This commit is contained in:
vipg
2026-02-09 17:43:42 +08:00
parent 25c4628b5f
commit c7b11dca35
5 changed files with 83 additions and 22 deletions

View File

@@ -4,6 +4,7 @@ import (
"database/sql"
"errors"
"common/auth"
"github.com/jackc/pgconn"
"golang.org/x/crypto/bcrypt"
"user/internal/repository"
@@ -23,64 +24,72 @@ func New(repo *repository.Repo) *Service {
return &Service{Repo: repo}
}
func (s *Service) Register(account, password string) (string, error) {
func (s *Service) Register(account, password string) (string, string, error) {
if !validAccount(account) || !validPassword(password) {
return "", ErrInvalidInput
return "", "", ErrInvalidInput
}
hashed, err := bcrypt.GenerateFromPassword([]byte(password), 12)
if err != nil {
return "", err
return "", "", err
}
tx, err := s.Repo.DB.Begin()
if err != nil {
return "", err
return "", "", err
}
defer func() { _ = tx.Rollback() }()
userID, err := s.Repo.CreateUser(tx)
if err != nil {
return "", err
return "", "", err
}
if err := s.Repo.CreateLoginAccount(tx, userID, account); err != nil {
if isUniqueViolation(err) {
return "", ErrAccountExists
return "", "", ErrAccountExists
}
return "", err
return "", "", err
}
if err := s.Repo.CreateLoginPassword(tx, userID, string(hashed)); err != nil {
return "", err
return "", "", err
}
if err := tx.Commit(); err != nil {
return "", err
return "", "", err
}
return userID, nil
tkn, err := auth.GenerateToken(userID)
if err != nil {
return "", "", err
}
return userID, tkn, nil
}
func (s *Service) Login(account, password string) (string, error) {
func (s *Service) Login(account, password string) (string, string, error) {
if !validAccount(account) || !validPassword(password) {
return "", ErrInvalidInput
return "", "", ErrInvalidInput
}
userID, err := s.Repo.GetUserIDByAccount(account)
if err != nil {
return "", ErrUnauthorized
return "", "", ErrUnauthorized
}
hashed, err := s.Repo.GetHashedPassword(userID)
if err != nil {
return "", ErrUnauthorized
return "", "", ErrUnauthorized
}
if bcrypt.CompareHashAndPassword([]byte(hashed), []byte(password)) != nil {
return "", ErrUnauthorized
return "", "", ErrUnauthorized
}
return userID, nil
tkn, err := auth.GenerateToken(userID)
if err != nil {
return "", "", err
}
return userID, tkn, nil
}
func validAccount(a string) bool {
n := len(a)
return n >= 3 && n <= 20
return n >= 3 && n <= 100
}
func validPassword(p string) bool {
n := len(p)
return n >= 8 && n <= 20
return n >= 8 && n <= 128
}
func isUniqueViolation(err error) bool {