forked from mtusi2026/mtusi2026lab3
109 lines
1.7 KiB
Go
109 lines
1.7 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"mtusi2026lab3/internal/domain"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
func (s *PostgreSQLStore) CreateSession(
|
|
ctx context.Context,
|
|
tokenHash []byte,
|
|
userID string,
|
|
expiresAt time.Time,
|
|
) error {
|
|
queryContext, cancel := s.withTimeout(ctx)
|
|
defer cancel()
|
|
|
|
_, err := s.pool.Exec(
|
|
queryContext,
|
|
`
|
|
INSERT INTO sessions (
|
|
token_hash,
|
|
user_id,
|
|
expires_at
|
|
)
|
|
VALUES ($1, $2, $3)
|
|
`,
|
|
tokenHash,
|
|
userID,
|
|
expiresAt,
|
|
)
|
|
if err != nil {
|
|
return fmt.Errorf("insert session: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *PostgreSQLStore) GetUserBySession(
|
|
ctx context.Context,
|
|
tokenHash []byte,
|
|
) (domain.User, error) {
|
|
queryContext, cancel := s.withTimeout(ctx)
|
|
defer cancel()
|
|
|
|
var user domain.User
|
|
|
|
err := s.pool.QueryRow(
|
|
queryContext,
|
|
`
|
|
SELECT
|
|
app_user.id::text,
|
|
app_user.username,
|
|
app_user.display_name,
|
|
app_user.created_at
|
|
FROM sessions AS session
|
|
JOIN users AS app_user
|
|
ON app_user.id = session.user_id
|
|
WHERE session.token_hash = $1
|
|
AND session.expires_at > CURRENT_TIMESTAMP
|
|
`,
|
|
tokenHash,
|
|
).Scan(
|
|
&user.ID,
|
|
&user.Username,
|
|
&user.DisplayName,
|
|
&user.CreatedAt,
|
|
)
|
|
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return domain.User{}, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return domain.User{}, fmt.Errorf(
|
|
"select user by session: %w",
|
|
err,
|
|
)
|
|
}
|
|
|
|
return user, nil
|
|
}
|
|
|
|
func (s *PostgreSQLStore) DeleteSession(
|
|
ctx context.Context,
|
|
tokenHash []byte,
|
|
) error {
|
|
queryContext, cancel := s.withTimeout(ctx)
|
|
defer cancel()
|
|
|
|
_, err := s.pool.Exec(
|
|
queryContext,
|
|
`
|
|
DELETE FROM sessions
|
|
WHERE token_hash = $1
|
|
`,
|
|
tokenHash,
|
|
)
|
|
if err != nil {
|
|
return fmt.Errorf("delete session: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|