package store import ( "context" "errors" "time" "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" "github.com/jackc/pgx/v5" ) var ErrSessionNotFound = errors.New("session not found") func (s *PostgresStore) Credentials(ctx context.Context, username string) (model.User, string, error) { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() var user model.User var hash string err := s.pool.QueryRow(ctx, `SELECT id::text, username, display_name, created_at, password_hash FROM users WHERE username=$1`, username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash) if errors.Is(err, pgx.ErrNoRows) { return model.User{}, "", ErrUserNotFound } if err != nil { return model.User{}, "", ErrUnavailable } user.CreatedAt = user.CreatedAt.UTC() return user, hash, nil } func (s *PostgresStore) CreateSession(ctx context.Context, hash []byte, userID string, ttlSeconds int64) (time.Time, error) { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() var expires time.Time err := s.pool.QueryRow(ctx, `INSERT INTO sessions (token_hash, user_id, expires_at) VALUES ($1, $2, CURRENT_TIMESTAMP + $3::bigint * INTERVAL '1 second') RETURNING expires_at`, hash, userID, ttlSeconds).Scan(&expires) if err != nil { return time.Time{}, ErrUnavailable } return expires.UTC(), nil } func (s *PostgresStore) SessionUser(ctx context.Context, hash []byte) (model.User, error) { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() var userID string err := s.pool.QueryRow(ctx, `SELECT user_id::text FROM sessions WHERE token_hash=$1 AND expires_at > clock_timestamp()`, hash).Scan(&userID) if errors.Is(err, pgx.ErrNoRows) { return model.User{}, ErrSessionNotFound } if err != nil { return model.User{}, ErrUnavailable } return s.profile(ctx, userID) } func (s *PostgresStore) DeleteSession(ctx context.Context, hash []byte) error { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() tag, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash=$1 AND expires_at > clock_timestamp()`, hash) if err != nil { return ErrUnavailable } if tag.RowsAffected() == 0 { return ErrSessionNotFound } return nil }