Refactor added saving auth token to redis when successfully logged in

This commit is contained in:
PB
2025-10-20 19:58:14 +02:00
parent 52fc66e7a9
commit 50b2127bd7
8 changed files with 74 additions and 26 deletions

View File

@@ -3,40 +3,55 @@ package service
import (
"context"
"errors"
"fmt"
db "git.ego.freeddns.org/egommerce/identity-service/pkg/database"
"github.com/go-redis/redis/v8"
"github.com/jackc/pgx/v5/pgxpool"
)
var (
AuthService *Auth
JWTService *JWT
jwtSrv *JWT
ErrLoginIncorrect = errors.New("login incorrect")
ErrLoginIncorrect = errors.New("login incorrect")
ErrUnableToCacheToken = errors.New("unable to save token in cache")
)
func init() {
}
type Auth struct {
db *pgxpool.Pool
db *pgxpool.Pool
cache *redis.Client
}
func NewAuthService(db *pgxpool.Pool) *Auth {
return &Auth{db: db}
func NewAuthService(db *pgxpool.Pool, cache *redis.Client) *Auth {
return &Auth{
db: db,
cache: cache,
}
}
func (a *Auth) Login(login, passwd string) (string, error) {
if login == "admin" && passwd == "secret" { // FIXME hardcoded
token, err := JWTService.CreateToken()
if err != nil {
return "", err
}
var id string
return token, nil
sql := `SELECT id FROM identity.users WHERE username=$1 AND password=$2 LIMIT 1`
err := a.db.QueryRow(context.Background(), sql, login, passwd).Scan(&id)
if err != nil {
// if err = db.NoRowsInQuerySet(err); err != nil { // FIXME NoRowsInQuerySet error detect
// return "", errors.New("no user found")
// }
return "", ErrLoginIncorrect
}
return "", ErrLoginIncorrect
token, _ := jwtSrv.CreateToken(id)
if err = a.saveTokenToCache(token, id); err != nil {
return "", ErrUnableToCacheToken
}
return token, nil
}
func (a *Auth) Register(email, login, passwd string) (string, error) {
@@ -48,8 +63,18 @@ func (a *Auth) Register(email, login, passwd string) (string, error) {
if err = db.IsDuplicatedRow(err); err != nil {
return "", errors.New("username/email is already taken")
}
return "", errors.New("Failed to create new user: " + err.Error())
}
return id, nil
}
func (a *Auth) saveTokenToCache(token, id string) error {
res := a.cache.Set(context.Background(), "auth:token:"+id, token, tokenExpireTime)
if err := res.Err(); err != nil {
fmt.Println("failed to save token in redis: ", err.Error())
}
return nil
}