onasty/internal/service/authsrv/authsrv.go(view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
package authsrv
import (
"context"
"errors"
"log/slog"
"time"
"github.com/gofrs/uuid/v5"
"github.com/olexsmir/onasty/internal/dtos"
"github.com/olexsmir/onasty/internal/events/mailermq"
"github.com/olexsmir/onasty/internal/hasher"
"github.com/olexsmir/onasty/internal/jwtutil"
"github.com/olexsmir/onasty/internal/models"
"github.com/olexsmir/onasty/internal/oauth"
"github.com/olexsmir/onasty/internal/store/psql/sessionrepo"
"github.com/olexsmir/onasty/internal/store/psql/userepo"
"github.com/olexsmir/onasty/internal/store/psql/vertokrepo"
"github.com/olexsmir/onasty/internal/store/rdb/usercache"
)
type AuthServicer interface {
// SignUp creates a new user and sends a verification email.
//
// Uses [models.User.Validate] to validate credentials (see more possible returned errors).
//
// If provided email already in use returns [models.ErrUserEmailIsAlreadyInUse].
//
SignUp(ctx context.Context, credentials dtos.SignUp) error
// SignIn authenticates a user and returns access and refresh tokens.
//
// If user not found returns [models.ErrUserNotFound], and if credentials don't match [models.ErrUserWrongCredentials]
//
// If inactivated user tries to login, returns [models.ErrUserIsNotActivated]
//
SignIn(ctx context.Context, credentials dtos.SignIn) (dtos.Tokens, error)
// RefreshTokens refreshes the access and refresh tokens using the provided refresh token.
//
// If couldn't find a user liked with token, returns [models.ErrUserNotFound]
//
RefreshTokens(ctx context.Context, refreshToken string) (dtos.Tokens, error)
// Logout logs out a user by deleting the session associated with the provided refresh token.
Logout(ctx context.Context, userID uuid.UUID, refreshToken string) error
// LogoutAll logs out a user by deleting all sessions associated with the user ID.
LogoutAll(ctx context.Context, userID uuid.UUID) error
// GetOAuthURL retrieves the OAuth URL for the specified provider.
//
// If [providerName] is incorrect returns [ErrProviderNotSupported]
//
GetOAuthURL(providerName string) (dtos.OAuthRedirect, error)
// HandleOAuthLogin handles the OAuth login process by exchanging the code for tokens.
//
HandleOAuthLogin(ctx context.Context, providerName, code string) (dtos.Tokens, error)
// ParseJWTToken parses the JWT token and returns the payload.
//
// If token is expired, returns [jwtutil.ErrTokenExpired],
//
// If token is invalid returns: [jwturil.ErrTokenSignatureInvalid], [jwt.ErrUnexpectedSigningMethod]
//
ParseJWTToken(token string) (jwtutil.Payload, error)
// CheckIfUserExists checks if a user exists by user ID.
CheckIfUserExists(ctx context.Context, userID uuid.UUID) (bool, error)
// CheckIfUserIsActivated checks if a user is activated by user ID.
CheckIfUserIsActivated(ctx context.Context, userID uuid.UUID) (bool, error)
}
var _ AuthServicer = (*AuthSrv)(nil)
type AuthSrv struct {
userstore userepo.UserStorer
sessionstore sessionrepo.SessionStorer
vertokrepo vertokrepo.VerificationTokenStorer
cache usercache.UserCacheer
hasher hasher.Hasher
jwtTokenizer jwtutil.JWTTokenizer
mailermq mailermq.Mailer
googleOauth oauth.Provider
githubOauth oauth.Provider
refreshTokenTTL time.Duration
verificationTokenTTL time.Duration
}
func New(
userstore userepo.UserStorer,
sessionstore sessionrepo.SessionStorer,
vertokrepo vertokrepo.VerificationTokenStorer,
cache usercache.UserCacheer,
hasher hasher.Hasher,
jwtTokenizer jwtutil.JWTTokenizer,
mailermq mailermq.Mailer,
googleOauth, githubOauth oauth.Provider,
refreshTokenTTL, verificationTokenTTL time.Duration,
) *AuthSrv {
return &AuthSrv{
userstore: userstore,
sessionstore: sessionstore,
vertokrepo: vertokrepo,
cache: cache,
hasher: hasher,
jwtTokenizer: jwtTokenizer,
mailermq: mailermq,
googleOauth: googleOauth,
githubOauth: githubOauth,
refreshTokenTTL: refreshTokenTTL,
verificationTokenTTL: verificationTokenTTL,
}
}
func (a *AuthSrv) SignUp(ctx context.Context, inp dtos.SignUp) error {
user := models.User{
ID: uuid.Nil, // nil, since we do not know it yet
Email: inp.Email,
Activated: false,
Password: inp.Password,
CreatedAt: inp.CreatedAt,
LastLoginAt: inp.LastLoginAt,
}
if err := user.Validate(); err != nil {
return err
}
hashedPassword, err := a.hasher.Hash(inp.Password)
if err != nil {
return err
}
user.Password = hashedPassword
userID, err := a.userstore.Create(ctx, user)
if err != nil {
return err
}
verificationToken := uuid.Must(uuid.NewV4()).String()
if err := a.vertokrepo.Create(ctx, models.VerificationToken{
UserID: userID,
Token: verificationToken,
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(a.verificationTokenTTL),
}); err != nil {
return err
}
if err := a.mailermq.SendVerificationEmail(ctx, mailermq.SendVerificationEmailRequest{
Receiver: inp.Email,
Token: verificationToken,
}); err != nil {
return err
}
return nil
}
func (a *AuthSrv) SignIn(ctx context.Context, inp dtos.SignIn) (dtos.Tokens, error) {
user, err := a.userstore.GetByEmail(ctx, inp.Email)
if err != nil {
return dtos.Tokens{}, err
}
if err = a.hasher.Compare(user.Password, inp.Password); err != nil {
if errors.Is(err, hasher.ErrMismatchedHashes) {
return dtos.Tokens{}, models.ErrUserWrongCredentials
}
return dtos.Tokens{}, err
}
if !user.IsActivated() {
return dtos.Tokens{}, models.ErrUserIsNotActivated
}
return a.issueTokens(ctx, user.ID)
}
func (a *AuthSrv) RefreshTokens(ctx context.Context, rtoken string) (dtos.Tokens, error) {
userID, err := a.sessionstore.GetUserIDByRefreshToken(ctx, rtoken)
if err != nil {
return dtos.Tokens{}, err
}
tokens, err := a.createTokens(userID)
if err != nil {
return dtos.Tokens{}, err
}
if err := a.sessionstore.Update(ctx, userID, rtoken, tokens.Refresh); err != nil {
return dtos.Tokens{}, err
}
return dtos.Tokens{
Access: tokens.Access,
Refresh: tokens.Refresh,
}, nil
}
func (a *AuthSrv) Logout(ctx context.Context, userID uuid.UUID, refreshToken string) error {
return a.sessionstore.Delete(ctx, userID, refreshToken)
}
func (a *AuthSrv) LogoutAll(ctx context.Context, userID uuid.UUID) error {
return a.sessionstore.DeleteAllByUserID(ctx, userID)
}
func (a *AuthSrv) CheckIfUserExists(ctx context.Context, uid uuid.UUID) (bool, error) {
isExists, err := a.cache.GetIsExists(ctx, uid.String())
if err == nil {
return isExists, nil
}
slog.ErrorContext(ctx, "failed to fetch 'is user exists' cache", "err", err)
isExists, err = a.userstore.CheckIfUserExists(ctx, uid)
if err != nil {
return false, err
}
if err := a.cache.SetIsExists(ctx, uid.String(), isExists); err != nil {
slog.ErrorContext(ctx, "failed to update 'is user exists' cache", "err", err)
}
return isExists, nil
}
func (a *AuthSrv) CheckIfUserIsActivated(ctx context.Context, uid uuid.UUID) (bool, error) {
isActivated, err := a.cache.GetIsActivated(ctx, uid.String())
if err == nil {
return isActivated, nil
}
slog.ErrorContext(ctx, "failed to fetch 'is user activated' cache", "err", err)
isActivated, err = a.userstore.CheckIfUserIsActivated(ctx, uid)
if err != nil {
return false, err
}
if err := a.cache.SetIsActivated(ctx, uid.String(), isActivated); err != nil {
slog.ErrorContext(ctx, "failed to update 'is user activated' cache", "err", err)
}
return isActivated, nil
}
|