90 lines
1.7 KiB
Go
90 lines
1.7 KiB
Go
package authService
|
|
|
|
import (
|
|
"context"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"git.farahty.com/nimer/go-mongo/app"
|
|
"git.farahty.com/nimer/go-mongo/models"
|
|
"git.farahty.com/nimer/go-mongo/utils"
|
|
"github.com/google/uuid"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
)
|
|
|
|
func successLogin(ctx context.Context, user *models.User) (*models.LoginResponse, error) {
|
|
|
|
refresh_secret := app.Config.RefreshSecret
|
|
refresh_expiry := app.Config.RefreshExpiry
|
|
|
|
access_secret := app.Config.AccessSecret
|
|
access_expiry := app.Config.AccessExpiry
|
|
|
|
var identity string
|
|
if user.Email != nil {
|
|
identity = *user.Email
|
|
} else if user.Phone != nil {
|
|
identity = *user.Phone
|
|
} else {
|
|
return nil, fmt.Errorf("user identity not found")
|
|
}
|
|
|
|
refreshHandle := hex.EncodeToString([]byte(uuid.NewString()))
|
|
refreshToken, err := utils.CreateToken(
|
|
refreshHandle,
|
|
refresh_secret,
|
|
refresh_expiry,
|
|
models.UserJWT{
|
|
ID: user.ID.Hex(),
|
|
Identity: identity,
|
|
},
|
|
)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
accessToken, err := utils.CreateToken(
|
|
user.ID.Hex(),
|
|
access_secret,
|
|
access_expiry,
|
|
models.UserJWT{
|
|
ID: user.ID.Hex(),
|
|
Identity: identity,
|
|
},
|
|
)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
_, err = app.Collection("users").UpdateByID(ctx, user.ID, bson.D{
|
|
{Key: "$set", Value: bson.D{
|
|
{Key: "token", Value: refreshHandle},
|
|
}},
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
w := app.WriterFor(ctx)
|
|
|
|
http.SetCookie(*w, &http.Cookie{
|
|
Name: "access_token",
|
|
Value: *accessToken,
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
Secure: true,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
|
|
return &models.LoginResponse{
|
|
AccessToken: *accessToken,
|
|
RefreshToken: *refreshToken,
|
|
User: user,
|
|
}, nil
|
|
|
|
}
|