added transaction in registration
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 3m23s

This commit is contained in:
Dmitri 2026-04-21 10:21:16 +02:00
parent 3460b1ae87
commit af256b66b5
Signed by: kanopo
GPG Key ID: 759ADD40E3132AC7

View File

@ -4,6 +4,8 @@ import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"go.uber.org/zap"
"git.kanopo.dev/rhythm/rhythm-backend/internal/config"
@ -26,16 +28,18 @@ type Service interface {
}
type service struct {
pool *pgxpool.Pool
repo usersdb.Querier
cfg *config.Config
log *zap.SugaredLogger
}
func NewService(repo usersdb.Querier, cfg *config.Config, log *zap.SugaredLogger) Service {
func NewService(repo usersdb.Querier, cfg *config.Config, log *zap.SugaredLogger, pool *pgxpool.Pool) Service {
return &service{
repo: repo,
cfg: cfg,
log: log,
pool: pool,
}
}
@ -66,18 +70,29 @@ func (s *service) Login(ctx context.Context, email, passwordPlain string) (*Auth
}
func (s *service) Register(ctx context.Context, email, passwordPlain string) (*AuthResult, error) {
_, err := s.repo.GetUserByEmail(ctx, email)
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
txRepo := usersdb.New(tx)
_, err = txRepo.GetUserByEmail(ctx, email)
if err == nil {
s.log.Infof("registration failed: email already exists %v", email)
return nil, ErrInvalidCredentials
}
if !errors.Is(err, pgx.ErrNoRows) {
return nil, err
}
hash, err := password.HashPassword(passwordPlain)
if err != nil {
return nil, err
}
user, err := s.repo.CreateUser(ctx, usersdb.CreateUserParams{
user, err := txRepo.CreateUser(ctx, usersdb.CreateUserParams{
Email: email,
Password: hash,
})
@ -85,6 +100,10 @@ func (s *service) Register(ctx context.Context, email, passwordPlain string) (*A
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
tokenPair, err := jwt.GenerateTokenPair(user.ID.String(), s.cfg)
if err != nil {
s.log.Error("failed to generate token pair", "error", err)