Release v0.20: регистрация, авторизация, личный кабинет
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type SessionRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewSessionRepository(pool *pgxpool.Pool) *SessionRepository {
|
||||
return &SessionRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Create(ctx context.Context, token string, userID int, expires time.Time) error {
|
||||
_, err := r.pool.Exec(ctx, `
|
||||
INSERT INTO sessions (id, user_id, expires_at) VALUES ($1, $2, $3)`,
|
||||
token, userID, expires)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *SessionRepository) UserID(ctx context.Context, token string) (int, error) {
|
||||
var userID int
|
||||
err := r.pool.QueryRow(ctx, `
|
||||
SELECT user_id FROM sessions
|
||||
WHERE id = $1 AND expires_at > NOW()`, token).Scan(&userID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return 0, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Delete(ctx context.Context, token string) error {
|
||||
_, err := r.pool.Exec(ctx, `DELETE FROM sessions WHERE id = $1`, token)
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user