From 1d6191cbcb70323b8f83035bf26fa86dc10976a1 Mon Sep 17 00:00:00 2001 From: Lakhan Samani Date: Thu, 15 Jul 2021 15:13:00 +0530 Subject: [PATCH] Add logout resolver Resolves #8 --- server/graph/generated/generated.go | 559 +++++++++++++++++----------- server/graph/model/models_gen.go | 32 +- server/graph/schema.graphqls | 13 +- server/graph/schema.resolvers.go | 75 +++- server/utils/authToken.go | 35 ++ server/utils/cookie.go | 11 + 6 files changed, 491 insertions(+), 234 deletions(-) diff --git a/server/graph/generated/generated.go b/server/graph/generated/generated.go index a5cdc5e..c38b739 100644 --- a/server/graph/generated/generated.go +++ b/server/graph/generated/generated.go @@ -39,15 +39,9 @@ type ResolverRoot interface { Query() QueryResolver } -type DirectiveRoot struct { -} +type DirectiveRoot struct{} type ComplexityRoot struct { - BasicAuthSignupResponse struct { - Message func(childComplexity int) int - User func(childComplexity int) int - } - Error struct { Message func(childComplexity int) int Reason func(childComplexity int) int @@ -60,14 +54,24 @@ type ComplexityRoot struct { } Mutation struct { - BasicAuthSignUp func(childComplexity int, params model.BasicAuthSignupInput) int Login func(childComplexity int, params model.LoginInput) int + Logout func(childComplexity int) int + Signup func(childComplexity int, params model.SignUpInput) int VerifySignupToken func(childComplexity int, params model.VerifySignupTokenInput) int } Query struct { - UpdateToken func(childComplexity int) int - Users func(childComplexity int) int + Token func(childComplexity int) int + Users func(childComplexity int) int + } + + Response struct { + Message func(childComplexity int) int + } + + SignUpResponse struct { + Message func(childComplexity int) int + User func(childComplexity int) int } User struct { @@ -96,12 +100,14 @@ type ComplexityRoot struct { type MutationResolver interface { VerifySignupToken(ctx context.Context, params model.VerifySignupTokenInput) (*model.LoginResponse, error) - BasicAuthSignUp(ctx context.Context, params model.BasicAuthSignupInput) (*model.BasicAuthSignupResponse, error) + Signup(ctx context.Context, params model.SignUpInput) (*model.SignUpResponse, error) Login(ctx context.Context, params model.LoginInput) (*model.LoginResponse, error) + Logout(ctx context.Context) (*model.Response, error) } + type QueryResolver interface { Users(ctx context.Context) ([]*model.User, error) - UpdateToken(ctx context.Context) (*model.LoginResponse, error) + Token(ctx context.Context) (*model.LoginResponse, error) } type executableSchema struct { @@ -119,20 +125,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in _ = ec switch typeName + "." + field { - case "BasicAuthSignupResponse.message": - if e.complexity.BasicAuthSignupResponse.Message == nil { - break - } - - return e.complexity.BasicAuthSignupResponse.Message(childComplexity), true - - case "BasicAuthSignupResponse.user": - if e.complexity.BasicAuthSignupResponse.User == nil { - break - } - - return e.complexity.BasicAuthSignupResponse.User(childComplexity), true - case "Error.message": if e.complexity.Error.Message == nil { break @@ -168,18 +160,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.LoginResponse.User(childComplexity), true - case "Mutation.basicAuthSignUp": - if e.complexity.Mutation.BasicAuthSignUp == nil { - break - } - - args, err := ec.field_Mutation_basicAuthSignUp_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Mutation.BasicAuthSignUp(childComplexity, args["params"].(model.BasicAuthSignupInput)), true - case "Mutation.login": if e.complexity.Mutation.Login == nil { break @@ -192,6 +172,25 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Mutation.Login(childComplexity, args["params"].(model.LoginInput)), true + case "Mutation.logout": + if e.complexity.Mutation.Logout == nil { + break + } + + return e.complexity.Mutation.Logout(childComplexity), true + + case "Mutation.signup": + if e.complexity.Mutation.Signup == nil { + break + } + + args, err := ec.field_Mutation_signup_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.Signup(childComplexity, args["params"].(model.SignUpInput)), true + case "Mutation.verifySignupToken": if e.complexity.Mutation.VerifySignupToken == nil { break @@ -204,12 +203,12 @@ 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 { + case "Query.token": + if e.complexity.Query.Token == nil { break } - return e.complexity.Query.UpdateToken(childComplexity), true + return e.complexity.Query.Token(childComplexity), true case "Query.users": if e.complexity.Query.Users == nil { @@ -218,6 +217,27 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Query.Users(childComplexity), true + case "Response.message": + if e.complexity.Response.Message == nil { + break + } + + return e.complexity.Response.Message(childComplexity), true + + case "SignUpResponse.message": + if e.complexity.SignUpResponse.Message == nil { + break + } + + return e.complexity.SignUpResponse.Message(childComplexity), true + + case "SignUpResponse.user": + if e.complexity.SignUpResponse.User == nil { + break + } + + return e.complexity.SignUpResponse.User(childComplexity), true + case "User.createdAt": if e.complexity.User.CreatedAt == nil { break @@ -440,12 +460,16 @@ type LoginResponse { user: User } -type BasicAuthSignupResponse { +type SignUpResponse { message: String! user: User } -input BasicAuthSignupInput { +type Response { + message: String! +} + +input SignUpInput { firstName: String lastName: String email: String! @@ -465,13 +489,14 @@ input VerifySignupTokenInput { type Mutation { verifySignupToken(params: VerifySignupTokenInput!): LoginResponse! - basicAuthSignUp(params: BasicAuthSignupInput!): BasicAuthSignupResponse! + signup(params: SignUpInput!): SignUpResponse! login(params: LoginInput!): LoginResponse! + logout: Response! } type Query { users: [User!]! - updateToken: LoginResponse + token: LoginResponse } `, BuiltIn: false}, } @@ -481,13 +506,13 @@ var parsedSchema = gqlparser.MustLoadSchema(sources...) // region ***************************** args.gotpl ***************************** -func (ec *executionContext) field_Mutation_basicAuthSignUp_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +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.BasicAuthSignupInput + var arg0 model.LoginInput if tmp, ok := rawArgs["params"]; ok { ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("params")) - arg0, err = ec.unmarshalNBasicAuthSignupInput2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐBasicAuthSignupInput(ctx, tmp) + arg0, err = ec.unmarshalNLoginInput2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐLoginInput(ctx, tmp) if err != nil { return nil, err } @@ -496,13 +521,13 @@ func (ec *executionContext) field_Mutation_basicAuthSignUp_args(ctx context.Cont return args, nil } -func (ec *executionContext) field_Mutation_login_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_signup_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { var err error args := map[string]interface{}{} - var arg0 model.LoginInput + var arg0 model.SignUpInput if tmp, ok := rawArgs["params"]; ok { ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("params")) - arg0, err = ec.unmarshalNLoginInput2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐLoginInput(ctx, tmp) + arg0, err = ec.unmarshalNSignUpInput2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐSignUpInput(ctx, tmp) if err != nil { return nil, err } @@ -579,73 +604,6 @@ func (ec *executionContext) field___Type_fields_args(ctx context.Context, rawArg // region **************************** field.gotpl ***************************** -func (ec *executionContext) _BasicAuthSignupResponse_message(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.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) _BasicAuthSignupResponse_user(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.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) _Error_message(ctx context.Context, field graphql.CollectedField, obj *model.Error) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { @@ -857,7 +815,7 @@ func (ec *executionContext) _Mutation_verifySignupToken(ctx context.Context, fie return ec.marshalNLoginResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐLoginResponse(ctx, field.Selections, res) } -func (ec *executionContext) _Mutation_basicAuthSignUp(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { +func (ec *executionContext) _Mutation_signup(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -874,7 +832,7 @@ func (ec *executionContext) _Mutation_basicAuthSignUp(ctx context.Context, field ctx = graphql.WithFieldContext(ctx, fc) rawArgs := field.ArgumentMap(ec.Variables) - args, err := ec.field_Mutation_basicAuthSignUp_args(ctx, rawArgs) + args, err := ec.field_Mutation_signup_args(ctx, rawArgs) if err != nil { ec.Error(ctx, err) return graphql.Null @@ -882,7 +840,7 @@ func (ec *executionContext) _Mutation_basicAuthSignUp(ctx context.Context, field 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().BasicAuthSignUp(rctx, args["params"].(model.BasicAuthSignupInput)) + return ec.resolvers.Mutation().Signup(rctx, args["params"].(model.SignUpInput)) }) if err != nil { ec.Error(ctx, err) @@ -894,9 +852,9 @@ func (ec *executionContext) _Mutation_basicAuthSignUp(ctx context.Context, field } return graphql.Null } - res := resTmp.(*model.BasicAuthSignupResponse) + res := resTmp.(*model.SignUpResponse) fc.Result = res - return ec.marshalNBasicAuthSignupResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐBasicAuthSignupResponse(ctx, field.Selections, res) + return ec.marshalNSignUpResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐSignUpResponse(ctx, field.Selections, res) } func (ec *executionContext) _Mutation_login(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { @@ -941,6 +899,41 @@ func (ec *executionContext) _Mutation_login(ctx context.Context, field graphql.C return ec.marshalNLoginResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐLoginResponse(ctx, field.Selections, res) } +func (ec *executionContext) _Mutation_logout(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: "Mutation", + 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.Mutation().Logout(rctx) + }) + 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.(*model.Response) + fc.Result = res + return ec.marshalNResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐResponse(ctx, field.Selections, res) +} + func (ec *executionContext) _Query_users(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { @@ -976,7 +969,7 @@ 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) { +func (ec *executionContext) _Query_token(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -994,7 +987,7 @@ func (ec *executionContext) _Query_updateToken(ctx context.Context, field graphq 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) + return ec.resolvers.Query().Token(rctx) }) if err != nil { ec.Error(ctx, err) @@ -1079,6 +1072,108 @@ 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_message(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.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) _SignUpResponse_message(ctx context.Context, field graphql.CollectedField, obj *model.SignUpResponse) (ret graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + fc := &graphql.FieldContext{ + Object: "SignUpResponse", + 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) _SignUpResponse_user(ctx context.Context, field graphql.CollectedField, obj *model.SignUpResponse) (ret graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + fc := &graphql.FieldContext{ + Object: "SignUpResponse", + 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) _User_id(ctx context.Context, field graphql.CollectedField, obj *model.User) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { @@ -2722,9 +2817,37 @@ func (ec *executionContext) ___Type_ofType(ctx context.Context, field graphql.Co // region **************************** input.gotpl ***************************** -func (ec *executionContext) unmarshalInputBasicAuthSignupInput(ctx context.Context, obj interface{}) (model.BasicAuthSignupInput, error) { - var it model.BasicAuthSignupInput - var asMap = obj.(map[string]interface{}) +func (ec *executionContext) unmarshalInputLoginInput(ctx context.Context, obj interface{}) (model.LoginInput, error) { + var it model.LoginInput + 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) unmarshalInputSignUpInput(ctx context.Context, obj interface{}) (model.SignUpInput, error) { + var it model.SignUpInput + asMap := obj.(map[string]interface{}) for k, v := range asMap { switch k { @@ -2782,37 +2905,9 @@ 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{}) + asMap := obj.(map[string]interface{}) for k, v := range asMap { switch k { @@ -2838,35 +2933,6 @@ func (ec *executionContext) unmarshalInputVerifySignupTokenInput(ctx context.Con // region **************************** object.gotpl **************************** -var basicAuthSignupResponseImplementors = []string{"BasicAuthSignupResponse"} - -func (ec *executionContext) _BasicAuthSignupResponse(ctx context.Context, sel ast.SelectionSet, obj *model.BasicAuthSignupResponse) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, basicAuthSignupResponseImplementors) - - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("BasicAuthSignupResponse") - case "message": - out.Values[i] = ec._BasicAuthSignupResponse_message(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } - case "user": - out.Values[i] = ec._BasicAuthSignupResponse_user(ctx, field, obj) - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - var errorImplementors = []string{"Error"} func (ec *executionContext) _Error(ctx context.Context, sel ast.SelectionSet, obj *model.Error) graphql.Marshaler { @@ -2950,8 +3016,8 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) if out.Values[i] == graphql.Null { invalids++ } - case "basicAuthSignUp": - out.Values[i] = ec._Mutation_basicAuthSignUp(ctx, field) + case "signup": + out.Values[i] = ec._Mutation_signup(ctx, field) if out.Values[i] == graphql.Null { invalids++ } @@ -2960,6 +3026,11 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) if out.Values[i] == graphql.Null { invalids++ } + case "logout": + out.Values[i] = ec._Mutation_logout(ctx, field) + if out.Values[i] == graphql.Null { + invalids++ + } default: panic("unknown field " + strconv.Quote(field.Name)) } @@ -3000,7 +3071,7 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr } return res }) - case "updateToken": + case "token": field := field out.Concurrently(i, func() (res graphql.Marshaler) { defer func() { @@ -3008,7 +3079,7 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_updateToken(ctx, field) + res = ec._Query_token(ctx, field) return res }) case "__type": @@ -3026,6 +3097,62 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr return out } +var responseImplementors = []string{"Response"} + +func (ec *executionContext) _Response(ctx context.Context, sel ast.SelectionSet, obj *model.Response) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, responseImplementors) + + out := graphql.NewFieldSet(fields) + var invalids uint32 + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Response") + case "message": + out.Values[i] = ec._Response_message(ctx, field, obj) + if out.Values[i] == graphql.Null { + invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch() + if invalids > 0 { + return graphql.Null + } + return out +} + +var signUpResponseImplementors = []string{"SignUpResponse"} + +func (ec *executionContext) _SignUpResponse(ctx context.Context, sel ast.SelectionSet, obj *model.SignUpResponse) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, signUpResponseImplementors) + + out := graphql.NewFieldSet(fields) + var invalids uint32 + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("SignUpResponse") + case "message": + out.Values[i] = ec._SignUpResponse_message(ctx, field, obj) + if out.Values[i] == graphql.Null { + invalids++ + } + case "user": + out.Values[i] = ec._SignUpResponse_user(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch() + if invalids > 0 { + return graphql.Null + } + return out +} + var userImplementors = []string{"User"} func (ec *executionContext) _User(ctx context.Context, sel ast.SelectionSet, obj *model.User) graphql.Marshaler { @@ -3361,25 +3488,6 @@ func (ec *executionContext) ___Type(ctx context.Context, sel ast.SelectionSet, o // region ***************************** type.gotpl ***************************** -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) -} - -func (ec *executionContext) marshalNBasicAuthSignupResponse2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐBasicAuthSignupResponse(ctx context.Context, sel ast.SelectionSet, v model.BasicAuthSignupResponse) graphql.Marshaler { - return ec._BasicAuthSignupResponse(ctx, sel, &v) -} - -func (ec *executionContext) marshalNBasicAuthSignupResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐBasicAuthSignupResponse(ctx context.Context, sel ast.SelectionSet, v *model.BasicAuthSignupResponse) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - return ec._BasicAuthSignupResponse(ctx, sel, v) -} - func (ec *executionContext) unmarshalNBoolean2bool(ctx context.Context, v interface{}) (bool, error) { res, err := graphql.UnmarshalBoolean(v) return res, graphql.ErrorOnPath(ctx, err) @@ -3429,6 +3537,39 @@ func (ec *executionContext) marshalNLoginResponse2ᚖgithubᚗcomᚋyauthdevᚋy 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 { + return ec._Response(ctx, sel, &v) +} + +func (ec *executionContext) marshalNResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐResponse(ctx context.Context, sel ast.SelectionSet, v *model.Response) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + return ec._Response(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNSignUpInput2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐSignUpInput(ctx context.Context, v interface{}) (model.SignUpInput, error) { + res, err := ec.unmarshalInputSignUpInput(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNSignUpResponse2githubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐSignUpResponse(ctx context.Context, sel ast.SelectionSet, v model.SignUpResponse) graphql.Marshaler { + return ec._SignUpResponse(ctx, sel, &v) +} + +func (ec *executionContext) marshalNSignUpResponse2ᚖgithubᚗcomᚋyauthdevᚋyauthᚋserverᚋgraphᚋmodelᚐSignUpResponse(ctx context.Context, sel ast.SelectionSet, v *model.SignUpResponse) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + return ec._SignUpResponse(ctx, sel, v) +} + func (ec *executionContext) unmarshalNString2string(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 5f0320c..9d03a47 100644 --- a/server/graph/model/models_gen.go +++ b/server/graph/model/models_gen.go @@ -2,20 +2,6 @@ package model -type BasicAuthSignupInput struct { - FirstName *string `json:"firstName"` - LastName *string `json:"lastName"` - Email string `json:"email"` - Password string `json:"password"` - CofirmPassword string `json:"cofirmPassword"` - Image *string `json:"image"` -} - -type BasicAuthSignupResponse struct { - Message string `json:"message"` - User *User `json:"user"` -} - type Error struct { Message string `json:"message"` Reason string `json:"reason"` @@ -32,6 +18,24 @@ type LoginResponse struct { User *User `json:"user"` } +type Response struct { + Message string `json:"message"` +} + +type SignUpInput struct { + FirstName *string `json:"firstName"` + LastName *string `json:"lastName"` + Email string `json:"email"` + Password string `json:"password"` + CofirmPassword string `json:"cofirmPassword"` + Image *string `json:"image"` +} + +type SignUpResponse struct { + Message string `json:"message"` + User *User `json:"user"` +} + type User struct { ID string `json:"id"` Email string `json:"email"` diff --git a/server/graph/schema.graphqls b/server/graph/schema.graphqls index 97effeb..18e211b 100644 --- a/server/graph/schema.graphqls +++ b/server/graph/schema.graphqls @@ -37,12 +37,16 @@ type LoginResponse { user: User } -type BasicAuthSignupResponse { +type SignUpResponse { message: String! user: User } -input BasicAuthSignupInput { +type Response { + message: String! +} + +input SignUpInput { firstName: String lastName: String email: String! @@ -62,11 +66,12 @@ input VerifySignupTokenInput { type Mutation { verifySignupToken(params: VerifySignupTokenInput!): LoginResponse! - basicAuthSignUp(params: BasicAuthSignupInput!): BasicAuthSignupResponse! + signup(params: SignUpInput!): SignUpResponse! login(params: LoginInput!): LoginResponse! + logout: Response! } type Query { users: [User!]! - updateToken: LoginResponse + token: LoginResponse } diff --git a/server/graph/schema.resolvers.go b/server/graph/schema.resolvers.go index ead5b0a..67f9c3c 100644 --- a/server/graph/schema.resolvers.go +++ b/server/graph/schema.resolvers.go @@ -78,8 +78,8 @@ func (r *mutationResolver) VerifySignupToken(ctx context.Context, params model.V return res, nil } -func (r *mutationResolver) BasicAuthSignUp(ctx context.Context, params model.BasicAuthSignupInput) (*model.BasicAuthSignupResponse, error) { - var res *model.BasicAuthSignupResponse +func (r *mutationResolver) Signup(ctx context.Context, params model.SignUpInput) (*model.SignUpResponse, error) { + var res *model.SignUpResponse if params.CofirmPassword != params.Password { return res, errors.New(`Passowrd and Confirm Password does not match`) } @@ -137,7 +137,7 @@ func (r *mutationResolver) BasicAuthSignUp(ctx context.Context, params model.Bas utils.SendVerificationMail(params.Email, token) }() - res = &model.BasicAuthSignupResponse{ + res = &model.SignUpResponse{ Message: `Verification email sent successfully. Please check your inbox`, } @@ -167,6 +167,7 @@ func (r *mutationResolver) Login(ctx context.Context, params model.LoginInput) ( // match password err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(params.Password)) if err != nil { + log.Println("Compare password error:", err) return res, errors.New(`Invalid Password`) } userIdStr := fmt.Sprintf("%d", user.ID) @@ -199,6 +200,32 @@ func (r *mutationResolver) Login(ctx context.Context, params model.LoginInput) ( return res, nil } +func (r *mutationResolver) Logout(ctx context.Context) (*model.Response, error) { + gc, err := utils.GinContextFromContext(ctx) + var res *model.Response + if err != nil { + return res, err + } + + token, err := utils.GetAuthToken(gc) + if err != nil { + return res, err + } + + claim, err := utils.VerifyAuthToken(token) + if err != nil { + return res, err + } + + session.DeleteToken(claim.ID) + res = &model.Response{ + Message: "Logged out successfully", + } + + utils.DeleteCookie(gc) + return res, nil +} + func (r *queryResolver) Users(ctx context.Context) ([]*model.User, error) { var res []*model.User users, err := db.Mgr.GetUsers() @@ -221,8 +248,40 @@ 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")) +func (r *queryResolver) Token(ctx context.Context) (*model.LoginResponse, error) { + gc, err := utils.GinContextFromContext(ctx) + var res *model.LoginResponse + if err != nil { + return res, err + } + token, err := utils.GetAuthToken(gc) + if err != nil { + return res, err + } + + claim, err := utils.VerifyAuthToken(token) + if err != nil { + // generate new accessToken + return res, err + } + + user, err := db.Mgr.GetUserByEmail(claim.Email) + if err != nil { + return res, err + } + + res = &model.LoginResponse{ + Message: `Email verified successfully.`, + AccessToken: &token, + User: &model.User{ + ID: fmt.Sprintf("%d", user.ID), + Email: user.Email, + Image: &user.Image, + FirstName: &user.FirstName, + LastName: &user.LastName, + }, + } + return res, nil } // Mutation returns generated.MutationResolver implementation. @@ -231,5 +290,7 @@ func (r *Resolver) Mutation() generated.MutationResolver { return &mutationResol // Query returns generated.QueryResolver implementation. func (r *Resolver) Query() generated.QueryResolver { return &queryResolver{r} } -type mutationResolver struct{ *Resolver } -type queryResolver struct{ *Resolver } +type ( + mutationResolver struct{ *Resolver } + queryResolver struct{ *Resolver } +) diff --git a/server/utils/authToken.go b/server/utils/authToken.go index 0343855..d3fac37 100644 --- a/server/utils/authToken.go +++ b/server/utils/authToken.go @@ -1,8 +1,12 @@ package utils import ( + "errors" + "log" + "strings" "time" + "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt" "github.com/yauthdev/yauth/server/constants" "github.com/yauthdev/yauth/server/enum" @@ -37,3 +41,34 @@ func CreateAuthToken(user UserAuthInfo, tokenType enum.TokenType) (string, error return t.SignedString([]byte(constants.JWT_SECRET)) } + +func GetAuthToken(gc *gin.Context) (string, error) { + token := "" + cookie, err := gc.Request.Cookie(constants.COOKIE_NAME) + if err != nil { + // try to check in auth header for cookie + log.Println("cookie not found checking headers") + auth := gc.Request.Header.Get("Authorization") + if auth == "" { + return "", errors.New(`Unauthorized`) + } + + token = strings.TrimPrefix(auth, "Bearer ") + } else { + token = cookie.Value + } + + return token, nil +} + +func VerifyAuthToken(token string) (*UserAuthClaim, error) { + claims := &UserAuthClaim{} + _, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) { + return []byte(constants.JWT_SECRET), nil + }) + if err != nil { + return claims, err + } + + return claims, nil +} diff --git a/server/utils/cookie.go b/server/utils/cookie.go index 03b2598..0e83b23 100644 --- a/server/utils/cookie.go +++ b/server/utils/cookie.go @@ -15,3 +15,14 @@ func SetCookie(gc *gin.Context, token string) { gc.SetCookie(constants.COOKIE_NAME, token, 3600, "/", GetFrontendHost(), secure, httpOnly) } + +func DeleteCookie(gc *gin.Context) { + secure := true + httpOnly := true + + if !constants.IS_PROD { + secure = false + } + + gc.SetCookie(constants.COOKIE_NAME, "", -1, "/", GetFrontendHost(), secure, httpOnly) +}