update refresh

This commit is contained in:
2026-07-06 12:58:27 +07:00
parent e4007eb15a
commit 57687d1d62
15 changed files with 483 additions and 66 deletions
+39 -6
View File
@@ -2,6 +2,7 @@ package refresh_tokens_repo
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
@@ -19,25 +20,57 @@ func NewRefreshTokensRepo(pool *pgxpool.Pool) *RefreshTokensRepo {
func (s *RefreshTokensRepo) AddRefreshToken(
ctx context.Context,
userId int,
refreshToken string,
expiresAt time.Time,
jti string,
) error {
_, err := s.pool.Exec(
ctx,
`INSERT INTO refresh_tokens (user_id, refresh_token) VALUES ($1, $2)`,
`INSERT INTO refresh_tokens (user_id, expires_at, jti)
VALUES ($1, $2, $3)`,
userId,
refreshToken,
expiresAt,
jti,
)
return err
}
func (s *RefreshTokensRepo) DeleteRefreshTokensByUserId(
func (s *RefreshTokensRepo) ExistsRefreshToken(
ctx context.Context,
userId int,
jti string,
now time.Time,
) (bool, error) {
var exists bool
err := s.pool.QueryRow(
ctx,
`SELECT EXISTS(
SELECT 1
FROM refresh_tokens
WHERE user_id = $1
AND jti = $2
AND expires_at > $3
)`,
userId,
jti,
now,
).Scan(&exists)
if err != nil {
return false, err
}
return exists, nil
}
func (s *RefreshTokensRepo) DeleteRefreshTokenByJti(
ctx context.Context,
jti string,
) error {
_, err := s.pool.Exec(
ctx,
`DELETE FROM refresh_tokens WHERE user_id = $1`,
userId,
`DELETE FROM refresh_tokens
WHERE jti = $1`,
jti,
)
return err
}
+1 -1
View File
@@ -5,6 +5,6 @@ type User struct {
Username string
Email string
PasswordHash string
Role string
Roles []string
IsActive bool
}
+35 -5
View File
@@ -28,11 +28,11 @@ func (s *UsersRepo) AddUser(
username string,
email string,
passwordHash string,
role string,
roles []string,
) error {
tag, err := s.pool.Exec(
ctx,
`INSERT INTO users (username, email, password_hash, role)
`INSERT INTO users (username, email, password_hash, roles)
SELECT $1, $2, $3, $4
WHERE NOT EXISTS (
SELECT 1 FROM users
@@ -41,7 +41,7 @@ func (s *UsersRepo) AddUser(
username,
email,
passwordHash,
role,
roles,
username,
email,
@@ -85,7 +85,7 @@ func (s *UsersRepo) GetUserByEmail(
user := &repos.User{}
row := s.pool.QueryRow(
ctx,
`SELECT id, username, email, password_hash, role, is_active
`SELECT id, username, email, password_hash, roles, is_active
FROM users
WHERE email = $1`,
email,
@@ -95,7 +95,37 @@ func (s *UsersRepo) GetUserByEmail(
&user.Username,
&user.Email,
&user.PasswordHash,
&user.Role,
&user.Roles,
&user.IsActive,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrUserNotFound
}
return nil, err
}
return user, nil
}
func (s *UsersRepo) GetUserByID(
ctx context.Context,
id int,
) (*repos.User, error) {
user := &repos.User{}
row := s.pool.QueryRow(
ctx,
`SELECT id, username, email, password_hash, roles, is_active
FROM users
WHERE id = $1`,
id,
)
err := row.Scan(
&user.ID,
&user.Username,
&user.Email,
&user.PasswordHash,
&user.Roles,
&user.IsActive,
)
if err != nil {