diff --git a/server/constants/env.go b/server/constants/env.go index dd0ed70..68131bf 100644 --- a/server/constants/env.go +++ b/server/constants/env.go @@ -9,8 +9,9 @@ import ( ) var ( - DB_TYPE = enum.Postgres - DB_URL = "postgresql://localhost:5432/postgres" + ENV = "" + DB_TYPE = "" + DB_URL = "" SMTP_HOST = "" SMTP_PORT = "" SENDER_EMAIL = "" @@ -20,6 +21,8 @@ var ( FRONTEND_URL = "" PORT = "8080" REDIS_URL = "" + IS_PROD = false + COOKIE_NAME = "" ) func init() { @@ -28,6 +31,9 @@ func init() { log.Println("Error loading .env file") } + ENV = os.Getenv("ENV") + DB_TYPE = os.Getenv("DB_TYPE") + DB_URL = os.Getenv("DB_URL") SMTP_HOST = os.Getenv("SMTP_HOST") SMTP_PORT = os.Getenv("SMTP_PORT") SENDER_EMAIL = os.Getenv("SENDER_EMAIL") @@ -37,8 +43,31 @@ func init() { FRONTEND_URL = os.Getenv("FRONTEND_URL") PORT = os.Getenv("PORT") REDIS_URL = os.Getenv("REDIS_URL") + COOKIE_NAME = os.Getenv("COOKIE_NAME") + + if ENV == "" { + ENV = "production" + } + + if ENV == "production" { + IS_PROD = true + } else { + IS_PROD = false + } + + if DB_TYPE == "" { + DB_TYPE = enum.Postgres.String() + } + + if DB_URL == "" { + DB_TYPE = "postgresql://localhost:5432/postgres" + } if JWT_TYPE == "" { JWT_TYPE = "HS256" } + + if COOKIE_NAME == "" { + COOKIE_NAME = "yauth" + } } diff --git a/server/db/db.go b/server/db/db.go index 21f81a2..4589dc6 100644 --- a/server/db/db.go +++ b/server/db/db.go @@ -36,13 +36,13 @@ func init() { TablePrefix: "yauth_", }, } - if constants.DB_TYPE == enum.Postgres { + if constants.DB_TYPE == enum.Postgres.String() { db, err = gorm.Open(postgres.Open(constants.DB_URL), ormConfig) } - if constants.DB_TYPE == enum.Mysql { + if constants.DB_TYPE == enum.Mysql.String() { db, err = gorm.Open(mysql.Open(constants.DB_URL), ormConfig) } - if constants.DB_TYPE == enum.Sqlite { + if constants.DB_TYPE == enum.Sqlite.String() { db, err = gorm.Open(sqlite.Open(constants.DB_URL), ormConfig) } diff --git a/server/db/user.go b/server/db/user.go index a5934e7..ccd2ab0 100644 --- a/server/db/user.go +++ b/server/db/user.go @@ -24,7 +24,7 @@ type User struct { func (user *User) BeforeSave(tx *gorm.DB) error { // Modify current operation through tx.Statement, e.g: - if pw, err := bcrypt.GenerateFromPassword([]byte(user.Password), 0); err == nil { + if pw, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost); err == nil { tx.Statement.SetColumn("Password", pw) } diff --git a/server/enum/tokenType.go b/server/enum/tokenType.go new file mode 100644 index 0000000..f97e1e2 --- /dev/null +++ b/server/enum/tokenType.go @@ -0,0 +1,15 @@ +package enum + +type TokenType int + +const ( + RefreshToken TokenType = iota + AccessToken +) + +func (d TokenType) String() string { + return [...]string{ + "refresh_token", + "access_token", + }[d] +} diff --git a/server/go.mod b/server/go.mod index 04fa350..de3bdde 100644 --- a/server/go.mod +++ b/server/go.mod @@ -10,6 +10,7 @@ require ( github.com/jackc/pgproto3/v2 v2.1.0 // indirect github.com/joho/godotenv v1.3.0 // indirect github.com/mattn/go-sqlite3 v1.14.7 // indirect + github.com/rs/cors v1.8.0 // indirect github.com/vektah/gqlparser/v2 v2.1.0 // indirect golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e // indirect golang.org/x/text v0.3.6 // indirect diff --git a/server/go.sum b/server/go.sum index c709ef9..17d07b1 100644 --- a/server/go.sum +++ b/server/go.sum @@ -71,6 +71,7 @@ github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4 github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do= github.com/gin-gonic/gin v1.7.2 h1:Tg03T9yM2xa8j6I3Z3oqLaQRSmKvxPd6g/2HJ6zICFA= github.com/gin-gonic/gin v1.7.2/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY= github.com/go-chi/chi v3.3.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= @@ -81,8 +82,10 @@ github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9 github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM= github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.16.0/go.mod h1:1AnU7NaIRDWWzGEKwgtJRd2xk99HeFyHw3yid4rvQIY= github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= @@ -243,6 +246,7 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/leodido/go-urn v1.1.0/go.mod h1:+cyI34gQWZcE1eQU7NVgKkkzdXDQHr1dBMtdAPozLkw= github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= @@ -351,6 +355,8 @@ github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqn github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rs/cors v1.6.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= +github.com/rs/cors v1.8.0 h1:P2KMzcFwrPoSjkF1WLRPsp3UMLyql8L4v9hQpVeK5so= +github.com/rs/cors v1.8.0/go.mod h1:EBwu+T5AvHOcXwvZIkQFjUN6s8Czyqw12GL/Y0tUyRM= github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= @@ -442,6 +448,7 @@ golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -529,12 +536,14 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200114235610-7ae403b6b589 h1:rjUrONFu4kLchcZTfp3/96bR8bW8dIa8uz3cR5n0cgM= golang.org/x/tools v0.0.0-20200114235610-7ae403b6b589/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e h1:4nW4NLDYnU28ojHaHO8OVxFHk/aQ33U01a9cjED+pzE= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= diff --git a/server/graph/generated/generated.go b/server/graph/generated/generated.go index b692998..b452c46 100644 --- a/server/graph/generated/generated.go +++ b/server/graph/generated/generated.go @@ -43,21 +43,9 @@ type DirectiveRoot struct { } type ComplexityRoot struct { - BasicAuthLoginResponse struct { - Errors func(childComplexity int) int - Message func(childComplexity int) int - RefreshToken func(childComplexity int) int - StatusCode func(childComplexity int) int - Success func(childComplexity int) int - User func(childComplexity int) int - } - BasicAuthSignupResponse struct { - Errors func(childComplexity int) int - Message func(childComplexity int) int - StatusCode func(childComplexity int) int - Success func(childComplexity int) int - User func(childComplexity int) int + Message func(childComplexity int) int + User func(childComplexity int) int } Error struct { @@ -65,21 +53,25 @@ type ComplexityRoot struct { Reason func(childComplexity int) int } + LoginResponse struct { + AccessToken func(childComplexity int) int + Message func(childComplexity int) int + User func(childComplexity int) int + } + Mutation struct { BasicAuthSignUp func(childComplexity int, params model.BasicAuthSignupInput) int - Login func(childComplexity int, params model.BasicAuthLoginInput) int + Login func(childComplexity int, params model.LoginInput) int VerifySignupToken func(childComplexity int, params model.VerifySignupTokenInput) int } Query struct { - Users func(childComplexity int) int + UpdateToken func(childComplexity int) int + Users func(childComplexity int) int } Response struct { - Errors func(childComplexity int) int - Message func(childComplexity int) int - StatusCode func(childComplexity int) int - Success func(childComplexity int) int + Message func(childComplexity int) int } User struct { @@ -109,10 +101,11 @@ type ComplexityRoot struct { type MutationResolver interface { VerifySignupToken(ctx context.Context, params model.VerifySignupTokenInput) (*model.Response, error) BasicAuthSignUp(ctx context.Context, params model.BasicAuthSignupInput) (*model.BasicAuthSignupResponse, error) - Login(ctx context.Context, params model.BasicAuthLoginInput) (*model.BasicAuthLoginResponse, error) + Login(ctx context.Context, params model.LoginInput) (*model.LoginResponse, error) } type QueryResolver interface { Users(ctx context.Context) ([]*model.User, error) + UpdateToken(ctx context.Context) (*model.LoginResponse, error) } type executableSchema struct { @@ -130,55 +123,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in _ = ec switch typeName + "." + field { - case "BasicAuthLoginResponse.errors": - if e.complexity.BasicAuthLoginResponse.Errors == nil { - break - } - - return e.complexity.BasicAuthLoginResponse.Errors(childComplexity), true - - case "BasicAuthLoginResponse.message": - if e.complexity.BasicAuthLoginResponse.Message == nil { - break - } - - return e.complexity.BasicAuthLoginResponse.Message(childComplexity), true - - case "BasicAuthLoginResponse.refreshToken": - if e.complexity.BasicAuthLoginResponse.RefreshToken == nil { - break - } - - return e.complexity.BasicAuthLoginResponse.RefreshToken(childComplexity), true - - case "BasicAuthLoginResponse.statusCode": - if e.complexity.BasicAuthLoginResponse.StatusCode == nil { - break - } - - return e.complexity.BasicAuthLoginResponse.StatusCode(childComplexity), true - - case "BasicAuthLoginResponse.success": - if e.complexity.BasicAuthLoginResponse.Success == nil { - break - } - - return e.complexity.BasicAuthLoginResponse.Success(childComplexity), true - - case "BasicAuthLoginResponse.user": - if e.complexity.BasicAuthLoginResponse.User == nil { - break - } - - return e.complexity.BasicAuthLoginResponse.User(childComplexity), true - - case "BasicAuthSignupResponse.errors": - if e.complexity.BasicAuthSignupResponse.Errors == nil { - break - } - - return e.complexity.BasicAuthSignupResponse.Errors(childComplexity), true - case "BasicAuthSignupResponse.message": if e.complexity.BasicAuthSignupResponse.Message == nil { break @@ -186,20 +130,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.BasicAuthSignupResponse.Message(childComplexity), true - case "BasicAuthSignupResponse.statusCode": - if e.complexity.BasicAuthSignupResponse.StatusCode == nil { - break - } - - return e.complexity.BasicAuthSignupResponse.StatusCode(childComplexity), true - - case "BasicAuthSignupResponse.success": - if e.complexity.BasicAuthSignupResponse.Success == nil { - break - } - - return e.complexity.BasicAuthSignupResponse.Success(childComplexity), true - case "BasicAuthSignupResponse.user": if e.complexity.BasicAuthSignupResponse.User == nil { break @@ -221,6 +151,27 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Error.Reason(childComplexity), true + case "LoginResponse.accessToken": + if e.complexity.LoginResponse.AccessToken == nil { + break + } + + return e.complexity.LoginResponse.AccessToken(childComplexity), true + + case "LoginResponse.message": + if e.complexity.LoginResponse.Message == nil { + break + } + + return e.complexity.LoginResponse.Message(childComplexity), true + + case "LoginResponse.user": + if e.complexity.LoginResponse.User == nil { + break + } + + return e.complexity.LoginResponse.User(childComplexity), true + case "Mutation.basicAuthSignUp": if e.complexity.Mutation.BasicAuthSignUp == nil { break @@ -243,7 +194,7 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return 0, false } - return e.complexity.Mutation.Login(childComplexity, args["params"].(model.BasicAuthLoginInput)), true + return e.complexity.Mutation.Login(childComplexity, args["params"].(model.LoginInput)), true case "Mutation.verifySignupToken": if e.complexity.Mutation.VerifySignupToken == nil { @@ -257,6 +208,13 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Mutation.VerifySignupToken(childComplexity, args["params"].(model.VerifySignupTokenInput)), true + case "Query.updateToken": + if e.complexity.Query.UpdateToken == nil { + break + } + + return e.complexity.Query.UpdateToken(childComplexity), true + case "Query.users": if e.complexity.Query.Users == nil { break @@ -264,13 +222,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Query.Users(childComplexity), true - case "Response.errors": - if e.complexity.Response.Errors == nil { - break - } - - return e.complexity.Response.Errors(childComplexity), true - case "Response.message": if e.complexity.Response.Message == nil { break @@ -278,20 +229,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Response.Message(childComplexity), true - case "Response.statusCode": - if e.complexity.Response.StatusCode == nil { - break - } - - return e.complexity.Response.StatusCode(childComplexity), true - - case "Response.success": - if e.complexity.Response.Success == nil { - break - } - - return e.complexity.Response.Success(childComplexity), true - case "User.createdAt": if e.complexity.User.CreatedAt == nil { break @@ -509,33 +446,20 @@ type Error { } type Response { - success: Boolean! message: String! - errors: [Error!] - statusCode: Int! } -type BasicAuthLoginResponse { - success: Boolean! +type LoginResponse { message: String! - errors: [Error!] - statusCode: Int! - refreshToken: String + accessToken: String user: User } type BasicAuthSignupResponse { - success: Boolean! message: String! - errors: [Error!] - statusCode: Int! user: User } -type Query { - users: [User!]! -} - input BasicAuthSignupInput { firstName: String lastName: String @@ -545,7 +469,7 @@ input BasicAuthSignupInput { image: String } -input BasicAuthLoginInput { +input LoginInput { email: String! password: String! } @@ -557,7 +481,12 @@ input VerifySignupTokenInput { type Mutation { verifySignupToken(params: VerifySignupTokenInput!): Response! basicAuthSignUp(params: BasicAuthSignupInput!): BasicAuthSignupResponse! - login(params: BasicAuthLoginInput!): BasicAuthLoginResponse! + login(params: LoginInput!): LoginResponse! +} + +type Query { + users: [User!]! + updateToken: LoginResponse } `, BuiltIn: false}, } @@ -585,10 +514,10 @@ func (ec *executionContext) field_Mutation_basicAuthSignUp_args(ctx context.Cont func (ec *executionContext) field_Mutation_login_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { var err error args := map[string]interface{}{} - var arg0 model.BasicAuthLoginInput + var arg0 model.LoginInput if tmp, ok := rawArgs["params"]; ok { ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("params")) - arg0, err = ec.unmarshalNBasicAuthLoginInput2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐBasicAuthLoginInput(ctx, tmp) + arg0, err = ec.unmarshalNLoginInput2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐLoginInput(ctx, tmp) if err != nil { return nil, err } @@ -665,242 +594,6 @@ func (ec *executionContext) field___Type_fields_args(ctx context.Context, rawArg // region **************************** field.gotpl ***************************** -func (ec *executionContext) _BasicAuthLoginResponse_success(ctx context.Context, field graphql.CollectedField, obj *model.BasicAuthLoginResponse) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "BasicAuthLoginResponse", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Success, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) _BasicAuthLoginResponse_message(ctx context.Context, field graphql.CollectedField, obj *model.BasicAuthLoginResponse) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "BasicAuthLoginResponse", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Message, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _BasicAuthLoginResponse_errors(ctx context.Context, field graphql.CollectedField, obj *model.BasicAuthLoginResponse) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "BasicAuthLoginResponse", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Errors, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.Error) - fc.Result = res - return ec.marshalOError2ᚕᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐErrorᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) _BasicAuthLoginResponse_statusCode(ctx context.Context, field graphql.CollectedField, obj *model.BasicAuthLoginResponse) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "BasicAuthLoginResponse", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.StatusCode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - -func (ec *executionContext) _BasicAuthLoginResponse_refreshToken(ctx context.Context, field graphql.CollectedField, obj *model.BasicAuthLoginResponse) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "BasicAuthLoginResponse", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RefreshToken, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) _BasicAuthLoginResponse_user(ctx context.Context, field graphql.CollectedField, obj *model.BasicAuthLoginResponse) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "BasicAuthLoginResponse", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.User, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.User) - fc.Result = res - return ec.marshalOUser2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐUser(ctx, field.Selections, res) -} - -func (ec *executionContext) _BasicAuthSignupResponse_success(ctx context.Context, field graphql.CollectedField, obj *model.BasicAuthSignupResponse) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "BasicAuthSignupResponse", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Success, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - func (ec *executionContext) _BasicAuthSignupResponse_message(ctx context.Context, field graphql.CollectedField, obj *model.BasicAuthSignupResponse) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { @@ -936,73 +629,6 @@ func (ec *executionContext) _BasicAuthSignupResponse_message(ctx context.Context return ec.marshalNString2string(ctx, field.Selections, res) } -func (ec *executionContext) _BasicAuthSignupResponse_errors(ctx context.Context, field graphql.CollectedField, obj *model.BasicAuthSignupResponse) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "BasicAuthSignupResponse", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Errors, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.Error) - fc.Result = res - return ec.marshalOError2ᚕᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐErrorᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) _BasicAuthSignupResponse_statusCode(ctx context.Context, field graphql.CollectedField, obj *model.BasicAuthSignupResponse) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "BasicAuthSignupResponse", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.StatusCode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - func (ec *executionContext) _BasicAuthSignupResponse_user(ctx context.Context, field graphql.CollectedField, obj *model.BasicAuthSignupResponse) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { @@ -1105,6 +731,105 @@ func (ec *executionContext) _Error_reason(ctx context.Context, field graphql.Col return ec.marshalNString2string(ctx, field.Selections, res) } +func (ec *executionContext) _LoginResponse_message(ctx context.Context, field graphql.CollectedField, obj *model.LoginResponse) (ret graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + fc := &graphql.FieldContext{ + Object: "LoginResponse", + Field: field, + Args: nil, + IsMethod: false, + IsResolver: false, + } + + ctx = graphql.WithFieldContext(ctx, fc) + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Message, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) _LoginResponse_accessToken(ctx context.Context, field graphql.CollectedField, obj *model.LoginResponse) (ret graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + fc := &graphql.FieldContext{ + Object: "LoginResponse", + Field: field, + Args: nil, + IsMethod: false, + IsResolver: false, + } + + ctx = graphql.WithFieldContext(ctx, fc) + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.AccessToken, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) _LoginResponse_user(ctx context.Context, field graphql.CollectedField, obj *model.LoginResponse) (ret graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + fc := &graphql.FieldContext{ + Object: "LoginResponse", + Field: field, + Args: nil, + IsMethod: false, + IsResolver: false, + } + + ctx = graphql.WithFieldContext(ctx, fc) + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.User, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*model.User) + fc.Result = res + return ec.marshalOUser2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐUser(ctx, field.Selections, res) +} + func (ec *executionContext) _Mutation_verifySignupToken(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { @@ -1214,7 +939,7 @@ func (ec *executionContext) _Mutation_login(ctx context.Context, field graphql.C fc.Args = args resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().Login(rctx, args["params"].(model.BasicAuthLoginInput)) + return ec.resolvers.Mutation().Login(rctx, args["params"].(model.LoginInput)) }) if err != nil { ec.Error(ctx, err) @@ -1226,9 +951,9 @@ func (ec *executionContext) _Mutation_login(ctx context.Context, field graphql.C } return graphql.Null } - res := resTmp.(*model.BasicAuthLoginResponse) + res := resTmp.(*model.LoginResponse) fc.Result = res - return ec.marshalNBasicAuthLoginResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐBasicAuthLoginResponse(ctx, field.Selections, res) + return ec.marshalNLoginResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐLoginResponse(ctx, field.Selections, res) } func (ec *executionContext) _Query_users(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { @@ -1266,6 +991,38 @@ func (ec *executionContext) _Query_users(ctx context.Context, field graphql.Coll return ec.marshalNUser2ᚕᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐUserᚄ(ctx, field.Selections, res) } +func (ec *executionContext) _Query_updateToken(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + fc := &graphql.FieldContext{ + Object: "Query", + Field: field, + Args: nil, + IsMethod: true, + IsResolver: true, + } + + ctx = graphql.WithFieldContext(ctx, fc) + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().UpdateToken(rctx) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*model.LoginResponse) + fc.Result = res + return ec.marshalOLoginResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐLoginResponse(ctx, field.Selections, res) +} + func (ec *executionContext) _Query___type(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { @@ -1337,41 +1094,6 @@ func (ec *executionContext) _Query___schema(ctx context.Context, field graphql.C return ec.marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx, field.Selections, res) } -func (ec *executionContext) _Response_success(ctx context.Context, field graphql.CollectedField, obj *model.Response) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Response", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Success, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - func (ec *executionContext) _Response_message(ctx context.Context, field graphql.CollectedField, obj *model.Response) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { @@ -1407,73 +1129,6 @@ func (ec *executionContext) _Response_message(ctx context.Context, field graphql return ec.marshalNString2string(ctx, field.Selections, res) } -func (ec *executionContext) _Response_errors(ctx context.Context, field graphql.CollectedField, obj *model.Response) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Response", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Errors, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.Error) - fc.Result = res - return ec.marshalOError2ᚕᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐErrorᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) _Response_statusCode(ctx context.Context, field graphql.CollectedField, obj *model.Response) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Response", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.StatusCode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) -} - func (ec *executionContext) _User_id(ctx context.Context, field graphql.CollectedField, obj *model.User) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { @@ -3117,34 +2772,6 @@ func (ec *executionContext) ___Type_ofType(ctx context.Context, field graphql.Co // region **************************** input.gotpl ***************************** -func (ec *executionContext) unmarshalInputBasicAuthLoginInput(ctx context.Context, obj interface{}) (model.BasicAuthLoginInput, error) { - var it model.BasicAuthLoginInput - var asMap = obj.(map[string]interface{}) - - for k, v := range asMap { - switch k { - case "email": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("email")) - it.Email, err = ec.unmarshalNString2string(ctx, v) - if err != nil { - return it, err - } - case "password": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("password")) - it.Password, err = ec.unmarshalNString2string(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - func (ec *executionContext) unmarshalInputBasicAuthSignupInput(ctx context.Context, obj interface{}) (model.BasicAuthSignupInput, error) { var it model.BasicAuthSignupInput var asMap = obj.(map[string]interface{}) @@ -3205,6 +2832,34 @@ func (ec *executionContext) unmarshalInputBasicAuthSignupInput(ctx context.Conte return it, nil } +func (ec *executionContext) unmarshalInputLoginInput(ctx context.Context, obj interface{}) (model.LoginInput, error) { + var it model.LoginInput + var asMap = obj.(map[string]interface{}) + + for k, v := range asMap { + switch k { + case "email": + var err error + + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("email")) + it.Email, err = ec.unmarshalNString2string(ctx, v) + if err != nil { + return it, err + } + case "password": + var err error + + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("password")) + it.Password, err = ec.unmarshalNString2string(ctx, v) + if err != nil { + return it, err + } + } + } + + return it, nil +} + func (ec *executionContext) unmarshalInputVerifySignupTokenInput(ctx context.Context, obj interface{}) (model.VerifySignupTokenInput, error) { var it model.VerifySignupTokenInput var asMap = obj.(map[string]interface{}) @@ -3233,49 +2888,6 @@ func (ec *executionContext) unmarshalInputVerifySignupTokenInput(ctx context.Con // region **************************** object.gotpl **************************** -var basicAuthLoginResponseImplementors = []string{"BasicAuthLoginResponse"} - -func (ec *executionContext) _BasicAuthLoginResponse(ctx context.Context, sel ast.SelectionSet, obj *model.BasicAuthLoginResponse) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, basicAuthLoginResponseImplementors) - - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("BasicAuthLoginResponse") - case "success": - out.Values[i] = ec._BasicAuthLoginResponse_success(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } - case "message": - out.Values[i] = ec._BasicAuthLoginResponse_message(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } - case "errors": - out.Values[i] = ec._BasicAuthLoginResponse_errors(ctx, field, obj) - case "statusCode": - out.Values[i] = ec._BasicAuthLoginResponse_statusCode(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } - case "refreshToken": - out.Values[i] = ec._BasicAuthLoginResponse_refreshToken(ctx, field, obj) - case "user": - out.Values[i] = ec._BasicAuthLoginResponse_user(ctx, field, obj) - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - var basicAuthSignupResponseImplementors = []string{"BasicAuthSignupResponse"} func (ec *executionContext) _BasicAuthSignupResponse(ctx context.Context, sel ast.SelectionSet, obj *model.BasicAuthSignupResponse) graphql.Marshaler { @@ -3287,23 +2899,11 @@ func (ec *executionContext) _BasicAuthSignupResponse(ctx context.Context, sel as switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("BasicAuthSignupResponse") - case "success": - out.Values[i] = ec._BasicAuthSignupResponse_success(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } case "message": out.Values[i] = ec._BasicAuthSignupResponse_message(ctx, field, obj) if out.Values[i] == graphql.Null { invalids++ } - case "errors": - out.Values[i] = ec._BasicAuthSignupResponse_errors(ctx, field, obj) - case "statusCode": - out.Values[i] = ec._BasicAuthSignupResponse_statusCode(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } case "user": out.Values[i] = ec._BasicAuthSignupResponse_user(ctx, field, obj) default: @@ -3349,6 +2949,37 @@ func (ec *executionContext) _Error(ctx context.Context, sel ast.SelectionSet, ob return out } +var loginResponseImplementors = []string{"LoginResponse"} + +func (ec *executionContext) _LoginResponse(ctx context.Context, sel ast.SelectionSet, obj *model.LoginResponse) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, loginResponseImplementors) + + out := graphql.NewFieldSet(fields) + var invalids uint32 + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("LoginResponse") + case "message": + out.Values[i] = ec._LoginResponse_message(ctx, field, obj) + if out.Values[i] == graphql.Null { + invalids++ + } + case "accessToken": + out.Values[i] = ec._LoginResponse_accessToken(ctx, field, obj) + case "user": + out.Values[i] = ec._LoginResponse_user(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch() + if invalids > 0 { + return graphql.Null + } + return out +} + var mutationImplementors = []string{"Mutation"} func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler { @@ -3419,6 +3050,17 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr } return res }) + case "updateToken": + field := field + out.Concurrently(i, func() (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_updateToken(ctx, field) + return res + }) case "__type": out.Values[i] = ec._Query___type(ctx, field) case "__schema": @@ -3445,23 +3087,11 @@ func (ec *executionContext) _Response(ctx context.Context, sel ast.SelectionSet, switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("Response") - case "success": - out.Values[i] = ec._Response_success(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } case "message": out.Values[i] = ec._Response_message(ctx, field, obj) if out.Values[i] == graphql.Null { invalids++ } - case "errors": - out.Values[i] = ec._Response_errors(ctx, field, obj) - case "statusCode": - out.Values[i] = ec._Response_statusCode(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } default: panic("unknown field " + strconv.Quote(field.Name)) } @@ -3808,25 +3438,6 @@ func (ec *executionContext) ___Type(ctx context.Context, sel ast.SelectionSet, o // region ***************************** type.gotpl ***************************** -func (ec *executionContext) unmarshalNBasicAuthLoginInput2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐBasicAuthLoginInput(ctx context.Context, v interface{}) (model.BasicAuthLoginInput, error) { - res, err := ec.unmarshalInputBasicAuthLoginInput(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNBasicAuthLoginResponse2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐBasicAuthLoginResponse(ctx context.Context, sel ast.SelectionSet, v model.BasicAuthLoginResponse) graphql.Marshaler { - return ec._BasicAuthLoginResponse(ctx, sel, &v) -} - -func (ec *executionContext) marshalNBasicAuthLoginResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐBasicAuthLoginResponse(ctx context.Context, sel ast.SelectionSet, v *model.BasicAuthLoginResponse) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - return ec._BasicAuthLoginResponse(ctx, sel, v) -} - func (ec *executionContext) unmarshalNBasicAuthSignupInput2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐBasicAuthSignupInput(ctx context.Context, v interface{}) (model.BasicAuthSignupInput, error) { res, err := ec.unmarshalInputBasicAuthSignupInput(ctx, v) return res, graphql.ErrorOnPath(ctx, err) @@ -3861,16 +3472,6 @@ func (ec *executionContext) marshalNBoolean2bool(ctx context.Context, sel ast.Se return res } -func (ec *executionContext) marshalNError2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐError(ctx context.Context, sel ast.SelectionSet, v *model.Error) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - return ec._Error(ctx, sel, v) -} - func (ec *executionContext) unmarshalNID2string(ctx context.Context, v interface{}) (string, error) { res, err := graphql.UnmarshalID(v) return res, graphql.ErrorOnPath(ctx, err) @@ -3886,19 +3487,23 @@ func (ec *executionContext) marshalNID2string(ctx context.Context, sel ast.Selec return res } -func (ec *executionContext) unmarshalNInt2int(ctx context.Context, v interface{}) (int, error) { - res, err := graphql.UnmarshalInt(v) +func (ec *executionContext) unmarshalNLoginInput2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐLoginInput(ctx context.Context, v interface{}) (model.LoginInput, error) { + res, err := ec.unmarshalInputLoginInput(ctx, v) return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalNInt2int(ctx context.Context, sel ast.SelectionSet, v int) graphql.Marshaler { - res := graphql.MarshalInt(v) - if res == graphql.Null { +func (ec *executionContext) marshalNLoginResponse2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐLoginResponse(ctx context.Context, sel ast.SelectionSet, v model.LoginResponse) graphql.Marshaler { + return ec._LoginResponse(ctx, sel, &v) +} + +func (ec *executionContext) marshalNLoginResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐLoginResponse(ctx context.Context, sel ast.SelectionSet, v *model.LoginResponse) graphql.Marshaler { + if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "must not be null") } + return graphql.Null } - return res + return ec._LoginResponse(ctx, sel, v) } func (ec *executionContext) marshalNResponse2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐResponse(ctx context.Context, sel ast.SelectionSet, v model.Response) graphql.Marshaler { @@ -4235,46 +3840,6 @@ func (ec *executionContext) marshalOBoolean2ᚖbool(ctx context.Context, sel ast return graphql.MarshalBoolean(*v) } -func (ec *executionContext) marshalOError2ᚕᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐErrorᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.Error) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNError2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐError(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - return ret -} - func (ec *executionContext) unmarshalOInt642ᚖint64(ctx context.Context, v interface{}) (*int64, error) { if v == nil { return nil, nil @@ -4290,6 +3855,13 @@ func (ec *executionContext) marshalOInt642ᚖint64(ctx context.Context, sel ast. return graphql.MarshalInt64(*v) } +func (ec *executionContext) marshalOLoginResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐLoginResponse(ctx context.Context, sel ast.SelectionSet, v *model.LoginResponse) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._LoginResponse(ctx, sel, v) +} + func (ec *executionContext) unmarshalOString2string(ctx context.Context, v interface{}) (string, error) { res, err := graphql.UnmarshalString(v) return res, graphql.ErrorOnPath(ctx, err) diff --git a/server/graph/model/models_gen.go b/server/graph/model/models_gen.go index d0e317b..032d473 100644 --- a/server/graph/model/models_gen.go +++ b/server/graph/model/models_gen.go @@ -2,20 +2,6 @@ package model -type BasicAuthLoginInput struct { - Email string `json:"email"` - Password string `json:"password"` -} - -type BasicAuthLoginResponse struct { - Success bool `json:"success"` - Message string `json:"message"` - Errors []*Error `json:"errors"` - StatusCode int `json:"statusCode"` - RefreshToken *string `json:"refreshToken"` - User *User `json:"user"` -} - type BasicAuthSignupInput struct { FirstName *string `json:"firstName"` LastName *string `json:"lastName"` @@ -26,11 +12,8 @@ type BasicAuthSignupInput struct { } type BasicAuthSignupResponse struct { - Success bool `json:"success"` - Message string `json:"message"` - Errors []*Error `json:"errors"` - StatusCode int `json:"statusCode"` - User *User `json:"user"` + Message string `json:"message"` + User *User `json:"user"` } type Error struct { @@ -38,11 +21,19 @@ type Error struct { Reason string `json:"reason"` } +type LoginInput struct { + Email string `json:"email"` + Password string `json:"password"` +} + +type LoginResponse struct { + Message string `json:"message"` + AccessToken *string `json:"accessToken"` + User *User `json:"user"` +} + type Response struct { - Success bool `json:"success"` - Message string `json:"message"` - Errors []*Error `json:"errors"` - StatusCode int `json:"statusCode"` + Message string `json:"message"` } type User struct { diff --git a/server/graph/schema.graphqls b/server/graph/schema.graphqls index 42a66e3..1061963 100644 --- a/server/graph/schema.graphqls +++ b/server/graph/schema.graphqls @@ -32,33 +32,20 @@ type Error { } type Response { - success: Boolean! message: String! - errors: [Error!] - statusCode: Int! } -type BasicAuthLoginResponse { - success: Boolean! +type LoginResponse { message: String! - errors: [Error!] - statusCode: Int! - refreshToken: String + accessToken: String user: User } type BasicAuthSignupResponse { - success: Boolean! message: String! - errors: [Error!] - statusCode: Int! user: User } -type Query { - users: [User!]! -} - input BasicAuthSignupInput { firstName: String lastName: String @@ -68,7 +55,7 @@ input BasicAuthSignupInput { image: String } -input BasicAuthLoginInput { +input LoginInput { email: String! password: String! } @@ -80,5 +67,10 @@ input VerifySignupTokenInput { type Mutation { verifySignupToken(params: VerifySignupTokenInput!): Response! basicAuthSignUp(params: BasicAuthSignupInput!): BasicAuthSignupResponse! - login(params: BasicAuthLoginInput!): BasicAuthLoginResponse! + login(params: LoginInput!): LoginResponse! +} + +type Query { + users: [User!]! + updateToken: LoginResponse } diff --git a/server/graph/schema.resolvers.go b/server/graph/schema.resolvers.go index 780b960..bbdd028 100644 --- a/server/graph/schema.resolvers.go +++ b/server/graph/schema.resolvers.go @@ -5,6 +5,7 @@ package graph import ( "context" + "errors" "fmt" "log" "strings" @@ -14,7 +15,9 @@ import ( "github.com/yauthdev/yauth/server/enum" "github.com/yauthdev/yauth/server/graph/generated" "github.com/yauthdev/yauth/server/graph/model" + "github.com/yauthdev/yauth/server/session" "github.com/yauthdev/yauth/server/utils" + "golang.org/x/crypto/bcrypt" ) func (r *mutationResolver) VerifySignupToken(ctx context.Context, params model.VerifySignupTokenInput) (*model.Response, error) { @@ -22,73 +25,36 @@ func (r *mutationResolver) VerifySignupToken(ctx context.Context, params model.V var res *model.Response _, err := db.Mgr.GetVerificationByToken(params.Token) if err != nil { - res = &model.Response{ - Success: false, - Message: `Invalid token`, - StatusCode: 400, - Errors: []*model.Error{&model.Error{ - Message: `Invalid token`, - Reason: `invalid token`, - }}, - } - } else { - - // verify if token exists in db - claim, err := utils.VerifyVerificationToken(params.Token) - if err != nil { - res = &model.Response{ - Success: false, - Message: `Invalid token`, - StatusCode: 400, - Errors: []*model.Error{&model.Error{ - Message: `Invalid token`, - Reason: `invalid token`, - }}, - } - } else { - res = &model.Response{ - Success: true, - Message: `Email verified successfully. Login to access the system.`, - StatusCode: 200, - } - - // update email_verified_at in users table - db.Mgr.UpdateVerificationTime(time.Now().Unix(), claim.Email) - // delete from verification table - db.Mgr.DeleteToken(claim.Email) - } - + return res, errors.New(`Invalid token`) } + // verify if token exists in db + claim, err := utils.VerifyVerificationToken(params.Token) + if err != nil { + return res, errors.New(`Invalid token`) + } + res = &model.Response{ + Message: `Email verified successfully. Login to access the system.`, + } + + // update email_verified_at in users table + db.Mgr.UpdateVerificationTime(time.Now().Unix(), claim.Email) + // delete from verification table + db.Mgr.DeleteToken(claim.Email) + return res, nil } func (r *mutationResolver) BasicAuthSignUp(ctx context.Context, params model.BasicAuthSignupInput) (*model.BasicAuthSignupResponse, error) { var res *model.BasicAuthSignupResponse if params.CofirmPassword != params.Password { - res = &model.BasicAuthSignupResponse{ - Success: false, - Message: `Passowrd and Confirm Password does not match`, - StatusCode: 400, - Errors: []*model.Error{&model.Error{ - Message: `Passowrd and Confirm Password does not match`, - Reason: `password and confirm_password fields should match`, - }}, - } + return res, errors.New(`Passowrd and Confirm Password does not match`) } params.Email = strings.ToLower(params.Email) if !utils.IsValidEmail(params.Email) { - res = &model.BasicAuthSignupResponse{ - Success: false, - Message: `Invalid email address`, - StatusCode: 400, - Errors: []*model.Error{&model.Error{ - Message: `Invalid email address`, - Reason: `invalid email address`, - }}, - } + return res, errors.New(`Invalid email address`) } // find user with email @@ -99,65 +65,107 @@ func (r *mutationResolver) BasicAuthSignUp(ctx context.Context, params model.Bas if existingUser.EmailVerifiedAt > 0 { // email is verified - res = &model.BasicAuthSignupResponse{ - Success: false, - Message: `You have already signed up. Please login`, - StatusCode: 400, - Errors: []*model.Error{&model.Error{ - Message: `Already signed up`, - Reason: `already signed up`, - }}, - } - } else { - user := db.User{ - Email: params.Email, - Password: params.Password, - } + return res, errors.New(`You have already signed up. Please login`) + } + user := db.User{ + Email: params.Email, + Password: params.Password, + } - if params.FirstName != nil { - user.FirstName = *params.FirstName - } + if params.FirstName != nil { + user.FirstName = *params.FirstName + } - if params.LastName != nil { - user.LastName = *params.LastName - } + if params.LastName != nil { + user.LastName = *params.LastName + } - user.SignUpMethod = enum.BasicAuth.String() - _, err = db.Mgr.AddUser(user) - if err != nil { - return res, err - } + user.SignUpMethod = enum.BasicAuth.String() + _, err = db.Mgr.AddUser(user) + if err != nil { + return res, err + } - // insert verification request - verificationType := enum.BasicAuth.String() - token, err := utils.CreateVerificationToken(params.Email, verificationType) - if err != nil { - log.Println(`Error generating token`, err) - } - db.Mgr.AddVerification(db.Verification{ - Token: token, - Identifier: verificationType, - ExpiresAt: time.Now().Add(time.Minute * 30).Unix(), - Email: params.Email, - }) + // insert verification request + verificationType := enum.BasicAuth.String() + token, err := utils.CreateVerificationToken(params.Email, verificationType) + if err != nil { + log.Println(`Error generating token`, err) + } + db.Mgr.AddVerification(db.Verification{ + Token: token, + Identifier: verificationType, + ExpiresAt: time.Now().Add(time.Minute * 30).Unix(), + Email: params.Email, + }) - // exec it as go routin so that we can reduce the api latency - go func() { - utils.SendVerificationMail(params.Email, token) - }() + // exec it as go routin so that we can reduce the api latency + go func() { + utils.SendVerificationMail(params.Email, token) + }() - res = &model.BasicAuthSignupResponse{ - Success: true, - Message: `Verification email sent successfully. Please check your inbox`, - StatusCode: 200, - } + res = &model.BasicAuthSignupResponse{ + Message: `Verification email sent successfully. Please check your inbox`, } return res, nil } -func (r *mutationResolver) Login(ctx context.Context, params model.BasicAuthLoginInput) (*model.BasicAuthLoginResponse, error) { - panic(fmt.Errorf("not implemented")) +func (r *mutationResolver) Login(ctx context.Context, params model.LoginInput) (*model.LoginResponse, error) { + gc, err := utils.GinContextFromContext(ctx) + var res *model.LoginResponse + if err != nil { + return res, err + } + + params.Email = strings.ToLower(params.Email) + user, err := db.Mgr.GetUserByEmail(params.Email) + if err != nil { + return res, errors.New(`User with this email not found`) + } + + if user.SignUpMethod != enum.BasicAuth.String() { + return res, errors.New(`User has not signed up email & password`) + } + + if user.EmailVerifiedAt <= 0 { + return res, errors.New(`Email not verified`) + } + // match password + err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(params.Password)) + if err != nil { + return res, errors.New(`Invalid Password`) + } + userIdStr := fmt.Sprintf("%d", user.ID) + log.Println("session object init -> ", session.GetToken(userIdStr)) + refreshToken, _ := utils.CreateAuthToken(utils.UserAuthInfo{ + ID: userIdStr, + Email: user.Email, + }, enum.RefreshToken) + + accessToken, _ := utils.CreateAuthToken(utils.UserAuthInfo{ + ID: userIdStr, + Email: user.Email, + }, enum.AccessToken) + + session.SetToken(userIdStr, refreshToken) + log.Println("session object -> ", session.GetToken(userIdStr)) + + res = &model.LoginResponse{ + Message: `Logged in successfully`, + AccessToken: &accessToken, + User: &model.User{ + ID: userIdStr, + Email: user.Email, + Image: &user.Image, + FirstName: &user.FirstName, + LastName: &user.LastName, + }, + } + + utils.SetCookie(gc, accessToken) + + return res, nil } func (r *queryResolver) Users(ctx context.Context) ([]*model.User, error) { @@ -182,6 +190,10 @@ func (r *queryResolver) Users(ctx context.Context) ([]*model.User, error) { return res, nil } +func (r *queryResolver) UpdateToken(ctx context.Context) (*model.LoginResponse, error) { + panic(fmt.Errorf("not implemented")) +} + // Mutation returns generated.MutationResolver implementation. func (r *Resolver) Mutation() generated.MutationResolver { return &mutationResolver{r} } diff --git a/server/session/session.go b/server/session/session.go index e146d75..85f6b25 100644 --- a/server/session/session.go +++ b/server/session/session.go @@ -15,7 +15,7 @@ type SessionStore struct { var SessionStoreObj SessionStore -func setToken(userId, token string) { +func SetToken(userId, token string) { if SessionStoreObj.redisMemoryStoreObj != nil { SessionStoreObj.redisMemoryStoreObj.AddToken(userId, token) } @@ -24,7 +24,7 @@ func setToken(userId, token string) { } } -func deleteToken(userId string) { +func DeleteToken(userId string) { if SessionStoreObj.redisMemoryStoreObj != nil { SessionStoreObj.redisMemoryStoreObj.DeleteToken(userId) } @@ -33,16 +33,18 @@ func deleteToken(userId string) { } } -func getToken(userId string) { +func GetToken(userId string) string { if SessionStoreObj.redisMemoryStoreObj != nil { - SessionStoreObj.redisMemoryStoreObj.GetToken(userId) + return SessionStoreObj.redisMemoryStoreObj.GetToken(userId) } if SessionStoreObj.inMemoryStoreObj != nil { - SessionStoreObj.inMemoryStoreObj.GetToken(userId) + return SessionStoreObj.inMemoryStoreObj.GetToken(userId) } + + return "" } -func clearStore() { +func ClearStore() { if SessionStoreObj.redisMemoryStoreObj != nil { SessionStoreObj.redisMemoryStoreObj.ClearStore() } diff --git a/server/utils/authToken.go b/server/utils/authToken.go new file mode 100644 index 0000000..0343855 --- /dev/null +++ b/server/utils/authToken.go @@ -0,0 +1,39 @@ +package utils + +import ( + "time" + + "github.com/golang-jwt/jwt" + "github.com/yauthdev/yauth/server/constants" + "github.com/yauthdev/yauth/server/enum" +) + +type UserAuthInfo struct { + Email string `json:"email"` + ID string `json:"id"` +} + +type UserAuthClaim struct { + *jwt.StandardClaims + TokenType string `json:"token_type"` + UserAuthInfo +} + +func CreateAuthToken(user UserAuthInfo, tokenType enum.TokenType) (string, error) { + t := jwt.New(jwt.GetSigningMethod(constants.JWT_TYPE)) + expiryBound := time.Hour + if tokenType == enum.RefreshToken { + // expires in 90 days + expiryBound = time.Hour * 2160 + } + + t.Claims = &UserAuthClaim{ + &jwt.StandardClaims{ + ExpiresAt: time.Now().Add(expiryBound).Unix(), + }, + tokenType.String(), + user, + } + + return t.SignedString([]byte(constants.JWT_SECRET)) +} diff --git a/server/utils/cookie.go b/server/utils/cookie.go new file mode 100644 index 0000000..03b2598 --- /dev/null +++ b/server/utils/cookie.go @@ -0,0 +1,17 @@ +package utils + +import ( + "github.com/gin-gonic/gin" + "github.com/yauthdev/yauth/server/constants" +) + +func SetCookie(gc *gin.Context, token string) { + secure := true + httpOnly := true + + if !constants.IS_PROD { + secure = false + } + + gc.SetCookie(constants.COOKIE_NAME, token, 3600, "/", GetFrontendHost(), secure, httpOnly) +} diff --git a/server/utils/urls.go b/server/utils/urls.go new file mode 100644 index 0000000..126b617 --- /dev/null +++ b/server/utils/urls.go @@ -0,0 +1,16 @@ +package utils + +import ( + "net/url" + + "github.com/yauthdev/yauth/server/constants" +) + +func GetFrontendHost() string { + u, err := url.Parse(constants.FRONTEND_URL) + if err != nil { + return `localhost` + } + + return u.Hostname() +}