Add resolver to update profile

Resolves #12 #11
This commit is contained in:
Lakhan Samani
2021-07-18 09:25:20 +05:30
parent 83b3149c0b
commit 7d17032fc2
14 changed files with 460 additions and 246 deletions

View File

@@ -2,7 +2,6 @@ package resolvers
import (
"context"
"errors"
"fmt"
"log"
"strings"
@@ -25,15 +24,15 @@ func Login(ctx context.Context, params model.LoginInput) (*model.LoginResponse,
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`)
return res, fmt.Errorf(`user with this email not found`)
}
if !strings.Contains(user.SignupMethod, enum.BasicAuth.String()) {
return res, errors.New(`User has not signed up email & password`)
return res, fmt.Errorf(`user has not signed up email & password`)
}
if user.EmailVerifiedAt <= 0 {
return res, errors.New(`Email not verified`)
return res, fmt.Errorf(`email not verified`)
}
// match password
cost, err := bcrypt.Cost([]byte(user.Password))
@@ -42,7 +41,7 @@ func Login(ctx context.Context, params model.LoginInput) (*model.LoginResponse,
if err != nil {
log.Println("Compare password error:", err)
return res, errors.New(`Invalid Password`)
return res, fmt.Errorf(`invalid password`)
}
userIdStr := fmt.Sprintf("%d", user.ID)
refreshToken, _, _ := utils.CreateAuthToken(utils.UserAuthInfo{

View File

@@ -6,6 +6,7 @@ import (
"github.com/yauthdev/yauth/server/db"
"github.com/yauthdev/yauth/server/graph/model"
"github.com/yauthdev/yauth/server/session"
"github.com/yauthdev/yauth/server/utils"
)
@@ -26,6 +27,12 @@ func Profile(ctx context.Context) (*model.User, error) {
return res, err
}
sessionToken := session.GetToken(claim.ID)
if sessionToken == "" {
return res, fmt.Errorf(`unauthorized`)
}
user, err := db.Mgr.GetUserByEmail(claim.Email)
if err != nil {
return res, err

View File

@@ -2,7 +2,7 @@ package resolvers
import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"
@@ -13,16 +13,16 @@ import (
"github.com/yauthdev/yauth/server/utils"
)
func Signup(ctx context.Context, params model.SignUpInput) (*model.SignUpResponse, error) {
var res *model.SignUpResponse
func Signup(ctx context.Context, params model.SignUpInput) (*model.Response, error) {
var res *model.Response
if params.CofirmPassword != params.Password {
return res, errors.New(`Passowrd and Confirm Password does not match`)
return res, fmt.Errorf(`passowrd and confirm password does not match`)
}
params.Email = strings.ToLower(params.Email)
if !utils.IsValidEmail(params.Email) {
return res, errors.New(`Invalid email address`)
return res, fmt.Errorf(`invalid email address`)
}
// find user with email
@@ -33,7 +33,7 @@ func Signup(ctx context.Context, params model.SignUpInput) (*model.SignUpRespons
if existingUser.EmailVerifiedAt > 0 {
// email is verified
return res, errors.New(`You have already signed up. Please login`)
return res, fmt.Errorf(`you have already signed up. Please login`)
}
user := db.User{
Email: params.Email,
@@ -57,7 +57,7 @@ func Signup(ctx context.Context, params model.SignUpInput) (*model.SignUpRespons
}
// insert verification request
verificationType := enum.BasicAuth.String()
verificationType := enum.BasicAuthSignup.String()
token, err := utils.CreateVerificationToken(params.Email, verificationType)
if err != nil {
log.Println(`Error generating token`, err)
@@ -74,8 +74,8 @@ func Signup(ctx context.Context, params model.SignUpInput) (*model.SignUpRespons
utils.SendVerificationMail(params.Email, token)
}()
res = &model.SignUpResponse{
Message: `Verification email sent successfully. Please check your inbox`,
res = &model.Response{
Message: `Verification email has been sent. Please check your inbox`,
}
return res, nil

View File

@@ -2,7 +2,6 @@ package resolvers
import (
"context"
"errors"
"fmt"
"github.com/yauthdev/yauth/server/db"
@@ -36,19 +35,17 @@ func Token(ctx context.Context) (*model.LoginResponse, error) {
sessionToken := session.GetToken(userIdStr)
if sessionToken == "" {
return res, errors.New(`Unauthorized`)
return res, fmt.Errorf(`unauthorized`)
}
// TODO check if session token has expired
if accessTokenErr != nil {
// if access token has expired and refresh/session token is valid
// generate new accessToken
fmt.Println(`here... getting new accesstoken`)
token, expiresAt, _ = utils.CreateAuthToken(utils.UserAuthInfo{
ID: userIdStr,
Email: user.Email,
}, enum.AccessToken)
}
utils.SetCookie(gc, token)
res = &model.LoginResponse{

View File

@@ -0,0 +1,136 @@
package resolvers
import (
"context"
"fmt"
"log"
"strings"
"time"
"github.com/yauthdev/yauth/server/db"
"github.com/yauthdev/yauth/server/enum"
"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 UpdateProfile(ctx context.Context, params model.UpdateProfileInput) (*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
}
sessionToken := session.GetToken(claim.ID)
if sessionToken == "" {
return res, fmt.Errorf(`unauthorized`)
}
// validate if all params are not empty
if params.FirstName == nil && params.LastName == nil && params.Image == nil && params.OldPassword == nil && params.Email == nil {
return res, fmt.Errorf("please enter atleast one param to update")
}
user, err := db.Mgr.GetUserByEmail(claim.Email)
if err != nil {
return res, err
}
if params.FirstName != nil && user.FirstName != *params.FirstName {
user.FirstName = *params.FirstName
}
if params.LastName != nil && user.LastName != *params.LastName {
user.LastName = *params.LastName
}
if params.Image != nil && user.Image != *params.Image {
user.Image = *params.Image
}
if params.OldPassword != nil {
if err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(*params.OldPassword)); err != nil {
return res, fmt.Errorf("incorrect old password")
}
if params.NewPassword == nil {
return res, fmt.Errorf("new password is required")
}
if params.ConfirmNewPassword == nil {
return res, fmt.Errorf("confirm password is required")
}
if *params.ConfirmNewPassword != *params.NewPassword {
return res, fmt.Errorf(`password and confirm password does not match`)
}
password, _ := utils.HashPassword(*params.NewPassword)
user.Password = password
}
hasEmailChanged := false
if params.Email != nil && user.Email != *params.Email {
// check if valid email
if !utils.IsValidEmail(*params.Email) {
return res, fmt.Errorf("invalid email address")
}
newEmail := strings.ToLower(*params.Email)
// check if user with new email exists
_, err = db.Mgr.GetUserByEmail(newEmail)
// err = nil means user exists
if err == nil {
return res, fmt.Errorf("user with this email address already exists")
}
session.DeleteToken(fmt.Sprintf("%d", user.ID))
utils.DeleteCookie(gc)
user.Email = newEmail
user.EmailVerifiedAt = 0
hasEmailChanged = true
// insert verification request
verificationType := enum.UpdateEmail.String()
token, err := utils.CreateVerificationToken(newEmail, 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: newEmail,
})
// exec it as go routin so that we can reduce the api latency
go func() {
utils.SendVerificationMail(newEmail, token)
}()
}
_, err = db.Mgr.UpdateUser(user)
message := `Profile details updated successfully.`
if hasEmailChanged {
message += `For the email change we have sent new verification email, please verify and continue`
}
res = &model.Response{
Message: message,
}
return res, nil
}

View File

@@ -2,7 +2,6 @@ package resolvers
import (
"context"
"errors"
"fmt"
"time"
@@ -13,7 +12,7 @@ import (
"github.com/yauthdev/yauth/server/utils"
)
func VerifySignupToken(ctx context.Context, params model.VerifySignupTokenInput) (*model.LoginResponse, error) {
func VerifyEmail(ctx context.Context, params model.VerifyEmailInput) (*model.LoginResponse, error) {
gc, err := utils.GinContextFromContext(ctx)
var res *model.LoginResponse
if err != nil {
@@ -22,13 +21,13 @@ func VerifySignupToken(ctx context.Context, params model.VerifySignupTokenInput)
_, err = db.Mgr.GetVerificationByToken(params.Token)
if err != nil {
return res, errors.New(`Invalid token`)
return res, fmt.Errorf(`invalid token`)
}
// verify if token exists in db
claim, err := utils.VerifyVerificationToken(params.Token)
if err != nil {
return res, errors.New(`Invalid token`)
return res, fmt.Errorf(`invalid token`)
}
user, err := db.Mgr.GetUserByEmail(claim.Email)