Skip to content

Commit

Permalink
Merge branch 'main' into feat/workspace_setting
Browse files Browse the repository at this point in the history
  • Loading branch information
ZTongci authored Oct 16, 2024
2 parents 893a682 + e24b535 commit ac4d6ea
Show file tree
Hide file tree
Showing 191 changed files with 733 additions and 2,468 deletions.
3 changes: 3 additions & 0 deletions server/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ REEARTH_COGNITO_REGION=
REEARTH_COGNITO_USERPOOLID=
REEARTH_COGNITO_CLIENTID=

# Local Mock Auth
REEARTH_MOCKAUTH=

# Auth client
#REEARTH_AUTH_ISS=https://hoge.com
#REEARTH_AUTH_AUD=https://api.reearth.example.com
Expand Down
6 changes: 5 additions & 1 deletion server/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ help:
@echo " run-app Run the application"
@echo " run-db Run the MongoDB database using Docker Compose"
@echo " gql Generate GraphQL code"
@echo " mockuser Create a mock user by executing a curl request"

lint:
golangci-lint run --fix
Expand All @@ -38,4 +39,7 @@ run-db:
gql:
go generate ./internal/adapter/gql

.PHONY: lint test failcheck e2e build run-app run-db gql
mockuser:
curl -H 'Content-Type: application/json' -d '{"email": "mock@example.com", "username": "Mock User"}' http://localhost:8080/api/signup

.PHONY: lint test failcheck e2e build run-app run-db gql mockuser
57 changes: 57 additions & 0 deletions server/e2e/mock_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package e2e

import (
"net/http"
"testing"

"github.com/reearth/reearth/server/internal/app/config"
)

// go test -v -run TestMockAuth ./e2e/...

func TestMockAuth(t *testing.T) {
e := StartServer(t, &config.Config{
Dev: true,
MockAuth: true,
Origins: []string{"https://example.com"},
AuthSrv: config.AuthSrvConfig{
Disabled: true,
},
}, true, nil)

requestBody := map[string]interface{}{
"email": "mock@example.com",
"username": "Mock User",
}

response := e.POST("/api/signup").
WithJSON(requestBody).
Expect().
Status(http.StatusOK).
JSON()

response.Object().ContainsKey("id")
response.Object().ValueEqual("email", "mock@example.com")
response.Object().ValueEqual("name", "Mock User")
userId := response.Object().Value("id").String().Raw()

// checkj query GetMe
requestBody2 := GraphQLRequest{
OperationName: "GetMe",
Query: "query GetMe { \n me { \n id \n name \n email\n } \n}",
Variables: map[string]any{},
}
response2 := e.POST("/api/graphql").
WithHeader("Origin", "https://example.com").
WithHeader("X-Reearth-Debug-User", userId).
WithHeader("Content-Type", "application/json").
WithJSON(requestBody2).
Expect().
Status(http.StatusOK).
JSON().
Object()

response2.Value("data").Object().Value("me").Object().ContainsKey("id")
response2.Value("data").Object().Value("me").Object().Value("name").String().Equal("Mock User")
response2.Value("data").Object().Value("me").Object().Value("email").String().Equal("mock@example.com")
}
2 changes: 1 addition & 1 deletion server/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ require (
github.com/paulmach/go.geojson v1.4.0
github.com/pkg/errors v0.9.1
github.com/ravilushqa/otelgqlgen v0.15.0
github.com/reearth/reearthx v0.0.0-20240809105752-94879dbf747b
github.com/reearth/reearthx v0.0.0-20241016122433-351e92319d1c
github.com/samber/lo v1.39.0
github.com/spf13/afero v1.11.0
github.com/square/mongo-lock v0.0.0-20201208161834-4db518ed7fb2
Expand Down
4 changes: 2 additions & 2 deletions server/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -509,8 +509,8 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/ravilushqa/otelgqlgen v0.15.0 h1:U85nrlweMXTGaMChUViYM39/MXBZVeVVlpuHq+6eECQ=
github.com/ravilushqa/otelgqlgen v0.15.0/go.mod h1:o+1Eju0VySmgq2BP8Vupz2YrN21Bj7D7imBqu3m2uB8=
github.com/reearth/reearthx v0.0.0-20240809105752-94879dbf747b h1:Vt1oXaj7pntxlQoKi/zJwvMHovlM86sYweOOx2rlH7Q=
github.com/reearth/reearthx v0.0.0-20240809105752-94879dbf747b/go.mod h1:d1WXkdCVzSoc8pl3vW9/9yKfk4fdoZQZhX8Ot8jqgnc=
github.com/reearth/reearthx v0.0.0-20241016122433-351e92319d1c h1:T9gk3oxbgGsb8SasgjDpwtoxB/T8rdHbGUGymNhAvfc=
github.com/reearth/reearthx v0.0.0-20241016122433-351e92319d1c/go.mod h1:d1WXkdCVzSoc8pl3vW9/9yKfk4fdoZQZhX8Ot8jqgnc=
github.com/robertkrimen/godocdown v0.0.0-20130622164427-0bfa04905481/go.mod h1:C9WhFzY47SzYBIvzFqSvHIR6ROgDo4TtdTuRaOMjF/s=
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
Expand Down
21 changes: 21 additions & 0 deletions server/internal/adapter/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const (
contextOperator ContextKey = "operator"
ContextAuthInfo ContextKey = "authinfo"
contextUsecases ContextKey = "usecases"
contextMockAuth ContextKey = "mockauth"
)

var defaultLang = language.English
Expand All @@ -44,6 +45,10 @@ func AttachUsecases(ctx context.Context, u *interfaces.Container) context.Contex
return ctx
}

func AttachMockAuth(ctx context.Context, mockAuth bool) context.Context {
return context.WithValue(ctx, contextMockAuth, mockAuth)
}

func User(ctx context.Context) *user.User {
if v := ctx.Value(contextUser); v != nil {
if u, ok := v.(*user.User); ok {
Expand Down Expand Up @@ -90,6 +95,13 @@ func AcOperator(ctx context.Context) *accountusecase.Operator {
}

func GetAuthInfo(ctx context.Context) *appx.AuthInfo {
if IsMockAuth(ctx) {
return &appx.AuthInfo{
Sub: user.NewID().String(), // Use it if there is a Mock user in the DB
Name: "Mock User",
Email: "mock@example.com",
}
}
if v := ctx.Value(ContextAuthInfo); v != nil {
if v2, ok := v.(appx.AuthInfo); ok {
return &v2
Expand All @@ -101,3 +113,12 @@ func GetAuthInfo(ctx context.Context) *appx.AuthInfo {
func Usecases(ctx context.Context) *interfaces.Container {
return ctx.Value(contextUsecases).(*interfaces.Container)
}

func IsMockAuth(ctx context.Context) bool {
if v := ctx.Value(contextMockAuth); v != nil {
if mockAuth, ok := v.(bool); ok {
return mockAuth
}
}
return false
}
2 changes: 2 additions & 0 deletions server/internal/adapter/http/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package http
import (
"context"

"github.com/reearth/reearth/server/internal/adapter"
"github.com/reearth/reearthx/account/accountdomain"
"github.com/reearth/reearthx/account/accountdomain/user"
"github.com/reearth/reearthx/account/accountusecase/accountinterfaces"
Expand Down Expand Up @@ -90,6 +91,7 @@ func (c *UserController) Signup(ctx context.Context, input SignupInput) (SignupO
WorkspaceID: input.WorkspaceID,
Lang: input.Lang,
Theme: input.Theme,
MockAuth: adapter.IsMockAuth(ctx),
})

if err != nil {
Expand Down
21 changes: 17 additions & 4 deletions server/internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,23 @@ func initEcho(ctx context.Context, cfg *ServerConfig) *echo.Echo {
// auth
authConfig := cfg.Config.JWTProviders()
log.Infof("auth: config: %#v", authConfig)
e.Use(
echo.WrapMiddleware(lo.Must(appx.AuthMiddleware(authConfig, adapter.ContextAuthInfo, true))),
attachOpMiddleware(cfg),
)

var wrapHandler func(http.Handler) http.Handler
if cfg.Config.UseMockAuth() {
log.Infof("Using mock auth for local development")
wrapHandler = func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = adapter.AttachMockAuth(ctx, true)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
} else {
wrapHandler = lo.Must(appx.AuthMiddleware(authConfig, adapter.ContextAuthInfo, true))
}

e.Use(echo.WrapMiddleware(wrapHandler))
e.Use(attachOpMiddleware(cfg))

// enable pprof
if e.Debug {
Expand Down
74 changes: 45 additions & 29 deletions server/internal/app/auth_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,46 +42,62 @@ func attachOpMiddleware(cfg *ServerConfig) echo.MiddlewareFunc {
userID = u
}

// debug mode
if cfg.Debug {
if userID := c.Request().Header.Get(debugUserHeader); userID != "" {
if uId, err := accountdomain.UserIDFrom(userID); err == nil {
user2, err := multiUser.FetchByID(ctx, user.IDList{uId})
if err == nil && len(user2) == 1 {
u = user2[0]
if adapter.IsMockAuth(ctx) {
// Create a mock user based on the auth info
mockUser, err := cfg.AccountRepos.User.FindByNameOrEmail(ctx, "Mock User")
if err != nil {
// when creating the first mock user
uId, _ := user.IDFrom(au.Sub)
mockUser = user.New().
ID(uId).
Name(au.Name).
Email(au.Email).
MustBuild()
}
u = mockUser
} else {
// debug mode
if cfg.Debug {
if userID := c.Request().Header.Get(debugUserHeader); userID != "" {
if uId, err := accountdomain.UserIDFrom(userID); err == nil {
user2, err := multiUser.FetchByID(ctx, user.IDList{uId})
if err == nil && len(user2) == 1 {
u = user2[0]
}
}
}
}
}

if u == nil && userID != "" {
if userID2, err := accountdomain.UserIDFrom(userID); err == nil {
u2, err := multiUser.FetchByID(ctx, user.IDList{userID2})
if err != nil {
if u == nil && userID != "" {
if userID2, err := accountdomain.UserIDFrom(userID); err == nil {
u2, err := multiUser.FetchByID(ctx, user.IDList{userID2})
if err != nil {
return err
}
if len(u2) > 0 {
u = u2[0]
}
} else {
return err
}
if len(u2) > 0 {
u = u2[0]
}
} else {
return err
}
}

if u == nil && au != nil {
var err error
// find user
u, err = multiUser.FetchBySub(ctx, au.Sub)
if err != nil && err != rerror.ErrNotFound {
return err
if u == nil && au != nil {
var err error
// find user
u, err = multiUser.FetchBySub(ctx, au.Sub)
if err != nil && err != rerror.ErrNotFound {
return err
}
}
}

// save a new sub
if u != nil && au != nil {
if err := addAuth0SubToUser(ctx, u, user.AuthFrom(au.Sub), cfg); err != nil {
return err
// save a new sub
if u != nil && au != nil {
if err := addAuth0SubToUser(ctx, u, user.AuthFrom(au.Sub), cfg); err != nil {
return err
}
}

}

if u != nil {
Expand Down
33 changes: 33 additions & 0 deletions server/internal/app/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ type Config struct {

// system extensions
Ext_Plugin []string `pp:",omitempty"`

MockAuth bool `pp:",omitempty"`
}

func ReadConfig(debug bool) (*Config, error) {
Expand Down Expand Up @@ -124,6 +126,10 @@ func (c *Config) Print() string {
return s
}

func (c *Config) UseMockAuth() bool {
return c.Dev && c.MockAuth
}

func (c *Config) secrets() []string {
s := []string{c.DB, c.Auth0.ClientSecret}
for _, ac := range c.DB_Users {
Expand Down Expand Up @@ -175,10 +181,29 @@ func (c *Config) Auths() (res AuthConfigs) {
}

func (c *Config) JWTProviders() (res []appx.JWTProvider) {
if c.UseMockAuth() {
return []appx.JWTProvider{
{
ISS: "mock_issuer",
AUD: []string{"mock_audience"},
ALG: strPtr("RS256"),
TTL: intPtr(3600),
},
}
}
return c.Auths().JWTProviders()
}

func (c *Config) AuthForWeb() *AuthConfig {
if c.UseMockAuth() {
return &AuthConfig{
ISS: "mock_issuer",
AUD: []string{"mock_audience"},
ALG: strPtr("RS256"),
TTL: intPtr(3600),
}
}

if ac := c.Auth0.AuthConfigForWeb(); ac != nil {
return ac
}
Expand Down Expand Up @@ -223,3 +248,11 @@ func addHTTPScheme(host string) string {
}
return host
}

func strPtr(s string) *string {
return &s
}

func intPtr(i int) *int {
return &i
}
2 changes: 1 addition & 1 deletion server/internal/infrastructure/memory/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func (r *Project) FindByWorkspace(ctx context.Context, id accountdomain.Workspac

result := []*project.Project{}
for _, d := range r.data {
if d.Workspace() == id && (filter.Keyword == nil || strings.Contains(d.Name(), *filter.Keyword)) {
if d.Workspace() == id && !d.IsDeleted() && (filter.Keyword == nil || strings.Contains(d.Name(), *filter.Keyword)) {
result = append(result, d)
}
}
Expand Down
18 changes: 14 additions & 4 deletions server/internal/infrastructure/mongo/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,24 @@ func (r *Project) FindByWorkspace(ctx context.Context, id accountdomain.Workspac
return nil, usecasex.EmptyPageInfo(), nil
}

var filter any = bson.M{
filter := bson.M{
"team": id.String(),
"$or": []bson.M{
{"deleted": false},
{"deleted": bson.M{"$exists": false}},
},
}

if uFilter.Keyword != nil {
filter = mongox.And(filter, "name", bson.M{
"$regex": primitive.Regex{Pattern: fmt.Sprintf(".*%s.*", regexp.QuoteMeta(*uFilter.Keyword)), Options: "i"},
})
keywordFilter := bson.M{
"name": bson.M{
"$regex": primitive.Regex{
Pattern: fmt.Sprintf(".*%s.*", regexp.QuoteMeta(*uFilter.Keyword)),
Options: "i",
},
},
}
filter = bson.M{"$and": []bson.M{filter, keywordFilter}}
}

return r.paginate(ctx, filter, uFilter.Sort, uFilter.Pagination)
Expand Down
1 change: 1 addition & 0 deletions web/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ REEARTH_WEB_PLUGINS=http://localhost:8080/plugins
REEARTH_WEB_AUTH0_DOMAIN=
REEARTH_WEB_AUTH0_AUDIENCE=
REEARTH_WEB_AUTH0_CLIENT_ID=
REEARTH_WEB_AUTH_PROVIDER=

# Optional
REEARTH_WEB_CESIUM_ION_TOKEN_URL=
Expand Down
Loading

0 comments on commit ac4d6ea

Please sign in to comment.