feat: persist data in PostgreSQL and add Basic/Bearer sessions in Redis

This commit is contained in:
2026-10-30 01:34:50 +03:00
parent 196e118ede
commit f68710818d
27 changed files with 1229 additions and 214 deletions
+74
View File
@@ -0,0 +1,74 @@
package service
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"time"
"messenger/internal/domain"
)
const tokenBytes = 32
type AuthService struct {
users UserRepository
sessions SessionStore
ttl time.Duration
}
func NewAuthService(users UserRepository, sessions SessionStore, ttl time.Duration) *AuthService {
return &AuthService{users: users, sessions: sessions, ttl: ttl}
}
func (s *AuthService) Login(ctx context.Context, username, password string) (domain.Session, error) {
user, hash, err := s.users.GetUserByUsername(ctx, username)
if errors.Is(err, domain.ErrNotFound) {
return domain.Session{}, domain.ErrUnauthorized
}
if err != nil {
return domain.Session{}, err
}
ok, err := verifyPassword(password, hash)
if err != nil {
return domain.Session{}, err
}
if !ok {
return domain.Session{}, domain.ErrUnauthorized
}
raw := make([]byte, tokenBytes)
if _, err := rand.Read(raw); err != nil {
return domain.Session{}, err
}
token := base64.RawURLEncoding.EncodeToString(raw)
expiresAt := now().Add(s.ttl)
if err := s.sessions.Create(ctx, HashToken(token), user.ID, expiresAt); err != nil {
return domain.Session{}, err
}
return domain.Session{Token: token, ExpiresAt: expiresAt, User: user}, nil
}
func (s *AuthService) Authenticate(ctx context.Context, token string) (domain.User, error) {
userID, err := s.sessions.Get(ctx, HashToken(token))
if err != nil {
return domain.User{}, err
}
u, err := s.users.GetUser(ctx, userID)
if errors.Is(err, domain.ErrNotFound) {
return domain.User{}, domain.ErrUnauthorized
}
return u, err
}
func (s *AuthService) Logout(ctx context.Context, token string) error {
return s.sessions.Delete(ctx, HashToken(token))
}
func HashToken(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
+60
View File
@@ -0,0 +1,60 @@
package service
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argonMemory = 19 * 1024
argonTime = 2
argonThreads = 1
argonSaltLen = 16
argonKeyLen = 32
)
var errBadHash = errors.New("malformed password hash")
func hashPassword(password string) (string, error) {
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
return "", err
}
key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
b64 := base64.RawStdEncoding
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
}
func verifyPassword(password, encoded string) (bool, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false, errBadHash
}
var version int
var memory, time uint32
var threads uint8
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
return false, errBadHash
}
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &threads); err != nil {
return false, errBadHash
}
b64 := base64.RawStdEncoding
salt, err := b64.DecodeString(parts[4])
if err != nil {
return false, errBadHash
}
want, err := b64.DecodeString(parts[5])
if err != nil {
return false, errBadHash
}
got := argon2.IDKey([]byte(password), salt, time, memory, threads, uint32(len(want)))
return subtle.ConstantTimeCompare(got, want) == 1, nil
}
+8 -1
View File
@@ -9,8 +9,9 @@ import (
)
type UserRepository interface {
CreateUser(ctx context.Context, u domain.User) error
CreateUser(ctx context.Context, u domain.User, passwordHash string) error
GetUser(ctx context.Context, id uuid.UUID) (domain.User, error)
GetUserByUsername(ctx context.Context, username string) (domain.User, string, error)
}
type ChatRepository interface {
@@ -24,6 +25,12 @@ type MessageRepository interface {
ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error)
}
type SessionStore interface {
Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error
Get(ctx context.Context, tokenHash string) (uuid.UUID, error)
Delete(ctx context.Context, tokenHash string) error
}
func now() time.Time {
return time.Now().UTC().Truncate(time.Microsecond)
}
+18 -11
View File
@@ -2,9 +2,9 @@ package service
import (
"context"
"errors"
"fmt"
"regexp"
"unicode/utf8"
"uuid"
"messenger/internal/domain"
@@ -12,6 +12,11 @@ import (
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
const (
minPasswordLen = 12
maxPasswordLen = 128
)
type UserService struct {
repo UserRepository
}
@@ -20,29 +25,31 @@ func NewUserService(repo UserRepository) *UserService {
return &UserService{repo: repo}
}
func (s *UserService) Register(ctx context.Context, username, displayName string) (domain.User, error) {
func (s *UserService) Register(ctx context.Context, username, displayName, password string) (domain.User, error) {
if !usernameRe.MatchString(username) {
return domain.User{}, fmt.Errorf("%w: username must match [a-z0-9_]{3,32}", domain.ErrInvalidInput)
}
if err := checkText("display_name", displayName, 100); err != nil {
return domain.User{}, err
}
if err := checkText("password", password, maxPasswordLen); err != nil {
return domain.User{}, err
}
if utf8.RuneCountInString(password) < minPasswordLen {
return domain.User{}, fmt.Errorf("%w: password must be at least %d characters", domain.ErrInvalidInput, minPasswordLen)
}
hash, err := hashPassword(password)
if err != nil {
return domain.User{}, err
}
u := domain.User{
ID: uuid.New(),
Username: username,
DisplayName: displayName,
CreatedAt: now(),
}
if err := s.repo.CreateUser(ctx, u); err != nil {
if err := s.repo.CreateUser(ctx, u, hash); err != nil {
return domain.User{}, err
}
return u, nil
}
func (s *UserService) Authenticate(ctx context.Context, id uuid.UUID) (domain.User, error) {
u, err := s.repo.GetUser(ctx, id)
if errors.Is(err, domain.ErrNotFound) {
return domain.User{}, domain.ErrUnauthorized
}
return u, err
}