Files

105 lines
3.0 KiB
Go

package repository
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/panelhosting/panel/internal/httputil"
"github.com/panelhosting/panel/internal/models"
)
var ErrUserNotFound = errors.New("user not found")
func (r *UserRepository) GetByUsername(ctx context.Context, username string) (*models.User, error) {
const q = `
SELECT id, uuid, email, username, password_hash, role, status, locale, timezone, last_login_at, created_at, updated_at
FROM users WHERE LOWER(username) = LOWER($1)
`
var u models.User
err := r.pool.QueryRow(ctx, q, username).Scan(
&u.ID, &u.UUID, &u.Email, &u.Username, &u.PasswordHash, &u.Role, &u.Status,
&u.Locale, &u.Timezone, &u.LastLoginAt, &u.CreatedAt, &u.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrUserNotFound
}
if err != nil {
return nil, fmt.Errorf("get user by username: %w", err)
}
return &u, nil
}
func (r *UserRepository) GetByID(ctx context.Context, id int64) (*models.User, error) {
const q = `
SELECT id, uuid, email, username, password_hash, role, status, locale, timezone, last_login_at, created_at, updated_at
FROM users WHERE id = $1
`
var u models.User
err := r.pool.QueryRow(ctx, q, id).Scan(
&u.ID, &u.UUID, &u.Email, &u.Username, &u.PasswordHash, &u.Role, &u.Status,
&u.Locale, &u.Timezone, &u.LastLoginAt, &u.CreatedAt, &u.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrUserNotFound
}
if err != nil {
return nil, fmt.Errorf("get user by id: %w", err)
}
return &u, nil
}
func (r *UserRepository) UpdateLastLogin(ctx context.Context, id int64) error {
_, err := r.pool.Exec(ctx, `UPDATE users SET last_login_at = now() WHERE id = $1`, id)
return err
}
type SessionRepository struct {
pool *pgxpool.Pool
}
func NewSessionRepository(pool *pgxpool.Pool) *SessionRepository {
return &SessionRepository{pool: pool}
}
func (r *SessionRepository) Create(ctx context.Context, userID int64, tokenHash string, ip, userAgent string, expiresAt time.Time) error {
var ipArg any
if normalized, ok := httputil.ValidIP(ip); ok {
ipArg = normalized
}
const q = `
INSERT INTO sessions (user_id, token_hash, ip_address, user_agent, expires_at)
VALUES ($1, $2, $3, NULLIF($4, ''), $5)
`
_, err := r.pool.Exec(ctx, q, userID, tokenHash, ipArg, userAgent, expiresAt)
if err != nil {
return fmt.Errorf("create session: %w", err)
}
return nil
}
func (r *SessionRepository) GetUserIDByToken(ctx context.Context, tokenHash string) (int64, error) {
const q = `
SELECT user_id FROM sessions
WHERE token_hash = $1 AND expires_at > now()
`
var userID int64
err := r.pool.QueryRow(ctx, q, tokenHash).Scan(&userID)
if errors.Is(err, pgx.ErrNoRows) {
return 0, ErrUserNotFound
}
if err != nil {
return 0, fmt.Errorf("get session: %w", err)
}
return userID, nil
}
func (r *SessionRepository) DeleteByToken(ctx context.Context, tokenHash string) error {
_, err := r.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash = $1`, tokenHash)
return err
}