forked from mtusi2026/mtusi2026lab2
216 lines
4.3 KiB
Go
216 lines
4.3 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"mtusi2026lab2/internal/model"
|
|
)
|
|
|
|
var (
|
|
ErrUserNotFound = errors.New("user not found")
|
|
ErrUsernameTaken = errors.New("username already exists")
|
|
ErrSessionNotFound = errors.New("session not found")
|
|
)
|
|
|
|
type AuthStore struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewAuthStore(pool *pgxpool.Pool) *AuthStore {
|
|
return &AuthStore{pool: pool}
|
|
}
|
|
|
|
func (s *AuthStore) CreateUser(
|
|
ctx context.Context,
|
|
user model.User,
|
|
passwordHash string,
|
|
) error {
|
|
const query = `
|
|
INSERT INTO users
|
|
(id, username, display_name, password_hash, created_at)
|
|
VALUES ($1, $2, $3, $4, $5)
|
|
`
|
|
|
|
_, err := s.pool.Exec(ctx, query,
|
|
user.ID,
|
|
user.Username,
|
|
user.DisplayName,
|
|
passwordHash,
|
|
user.CreatedAt,
|
|
)
|
|
if err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
return ErrUsernameTaken
|
|
}
|
|
return fmt.Errorf("create user: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *AuthStore) GetUserByUsername(
|
|
ctx context.Context,
|
|
username string,
|
|
) (model.User, string, error) {
|
|
const query = `
|
|
SELECT id, username, display_name,
|
|
password_hash, created_at
|
|
FROM users
|
|
WHERE username = $1
|
|
`
|
|
|
|
var user model.User
|
|
var passwordHash string
|
|
|
|
err := s.pool.QueryRow(ctx, query, username).Scan(
|
|
&user.ID,
|
|
&user.Username,
|
|
&user.DisplayName,
|
|
&passwordHash,
|
|
&user.CreatedAt,
|
|
)
|
|
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return model.User{}, "", ErrUserNotFound
|
|
}
|
|
if err != nil {
|
|
return model.User{}, "", fmt.Errorf("get user: %w", err)
|
|
}
|
|
|
|
return user, passwordHash, nil
|
|
}
|
|
|
|
func (s *AuthStore) GetUserByID(
|
|
ctx context.Context,
|
|
id uuid.UUID,
|
|
) (model.User, error) {
|
|
const query = `
|
|
SELECT id, username, display_name, created_at
|
|
FROM users
|
|
WHERE id = $1
|
|
`
|
|
|
|
var user model.User
|
|
|
|
err := s.pool.QueryRow(ctx, query, id).Scan(
|
|
&user.ID,
|
|
&user.Username,
|
|
&user.DisplayName,
|
|
&user.CreatedAt,
|
|
)
|
|
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return model.User{}, ErrUserNotFound
|
|
}
|
|
if err != nil {
|
|
return model.User{}, fmt.Errorf("get user by id: %w", err)
|
|
}
|
|
|
|
return user, nil
|
|
}
|
|
|
|
func tokenHash(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
func (s *AuthStore) CreateSession(
|
|
ctx context.Context,
|
|
token string,
|
|
userID uuid.UUID,
|
|
createdAt time.Time,
|
|
expiresAt time.Time,
|
|
) error {
|
|
const query = `
|
|
INSERT INTO sessions
|
|
(token_hash, user_id, created_at, expires_at)
|
|
VALUES ($1, $2, $3, $4)
|
|
`
|
|
|
|
_, err := s.pool.Exec(ctx, query,
|
|
tokenHash(token),
|
|
userID,
|
|
createdAt,
|
|
expiresAt,
|
|
)
|
|
if err != nil {
|
|
return fmt.Errorf("create session: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *AuthStore) GetSessionUser(
|
|
ctx context.Context,
|
|
token string,
|
|
) (model.User, error) {
|
|
const query = `
|
|
SELECT u.id, u.username, u.display_name, u.created_at
|
|
FROM sessions s
|
|
JOIN users u ON u.id = s.user_id
|
|
WHERE s.token_hash = $1
|
|
AND s.expires_at > NOW()
|
|
`
|
|
|
|
var user model.User
|
|
|
|
err := s.pool.QueryRow(ctx, query, tokenHash(token)).Scan(
|
|
&user.ID,
|
|
&user.Username,
|
|
&user.DisplayName,
|
|
&user.CreatedAt,
|
|
)
|
|
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return model.User{}, ErrSessionNotFound
|
|
}
|
|
if err != nil {
|
|
return model.User{}, fmt.Errorf("get session: %w", err)
|
|
}
|
|
|
|
return user, nil
|
|
}
|
|
|
|
func (s *AuthStore) RevokeSession(
|
|
ctx context.Context,
|
|
token string,
|
|
) error {
|
|
const query = `
|
|
DELETE FROM sessions
|
|
WHERE token_hash = $1
|
|
AND expires_at > NOW()
|
|
`
|
|
|
|
result, err := s.pool.Exec(ctx, query, tokenHash(token))
|
|
if err != nil {
|
|
return fmt.Errorf("revoke session: %w", err)
|
|
}
|
|
if result.RowsAffected() == 0 {
|
|
return ErrSessionNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetActiveSessionUserID is the authoritative expiry/revocation check.
|
|
// Redis only caches the public user profile; it never grants access on its own.
|
|
func (s *AuthStore) GetActiveSessionUserID(ctx context.Context, token string) (uuid.UUID, error) {
|
|
var userID uuid.UUID
|
|
err := s.pool.QueryRow(ctx, `SELECT user_id FROM sessions WHERE token_hash=$1 AND expires_at>NOW()`, tokenHash(token)).Scan(&userID)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return uuid.Nil, ErrSessionNotFound
|
|
}
|
|
if err != nil {
|
|
return uuid.Nil, fmt.Errorf("validate session: %w", err)
|
|
}
|
|
return userID, nil
|
|
}
|