This commit is contained in:
Mephimeow
2026-06-13 17:30:14 +00:00
parent a26cd891e4
commit 17ffe35f5c
8 changed files with 163 additions and 158 deletions
+14 -16
View File
@@ -2,16 +2,14 @@ package auth
import (
"time"
"go.mongodb.org/mongo-driver/v2/bson"
)
type User struct {
ID bson.ObjectID `json:"id" bson:"_id"`
Username string `json:"username" bson:"username"`
Email string `json:"email" bson:"email"`
PasswordHash string `json:"-" bson:"password_hash"`
CreatedAt time.Time `json:"created_at" bson:"created_at"`
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
PasswordHash string `json:"-"`
CreatedAt time.Time `json:"created_at"`
}
type RegisterRequest struct {
@@ -40,18 +38,18 @@ type LogoutRequest struct {
}
type RefreshTokenDoc struct {
ID bson.ObjectID `json:"id" bson:"_id"`
UserID bson.ObjectID `json:"user_id" bson:"user_id"`
TokenHash string `json:"token_hash" bson:"token_hash"`
ExpiresAt time.Time `json:"expires_at" bson:"expires_at"`
CreatedAt time.Time `json:"created_at" bson:"created_at"`
ID string `json:"id"`
UserID string `json:"user_id"`
TokenHash string `json:"token_hash"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
}
type UserPublic struct {
ID bson.ObjectID `json:"id" bson:"_id"`
Username string `json:"username" bson:"username"`
Email string `json:"email" bson:"email"`
CreatedAt time.Time `json:"created_at" bson:"created_at"`
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
CreatedAt time.Time `json:"created_at"`
}
func NewUserPublic(u *User) UserPublic {
+56 -42
View File
@@ -4,97 +4,111 @@ import (
"context"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type Repository struct {
usersCollection *mongo.Collection
refreshTokensCollection *mongo.Collection
pool *pgxpool.Pool
}
func NewRepository(db *mongo.Database) *Repository {
return &Repository{
usersCollection: db.Collection("users"),
refreshTokensCollection: db.Collection("refresh_tokens"),
}
func NewRepository(pool *pgxpool.Pool) *Repository {
return &Repository{pool: pool}
}
func (r *Repository) EnsureIndexes(ctx context.Context) error {
_, err := r.usersCollection.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{Key: "email", Value: 1}},
Options: options.Index().SetUnique(true),
})
if err != nil {
return err
}
func (r *Repository) Migrate(ctx context.Context) error {
schema := `
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY,
username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
_, err = r.refreshTokensCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
{
Keys: bson.D{{Key: "token_hash", Value: 1}},
Options: options.Index().SetUnique(true),
},
{
Keys: bson.D{{Key: "expires_at", Value: 1}},
Options: options.Index().SetExpireAfterSeconds(0),
},
})
CREATE TABLE IF NOT EXISTS refresh_tokens (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires_at ON refresh_tokens(expires_at);
`
_, err := r.pool.Exec(ctx, schema)
return err
}
func (r *Repository) CreateUser(ctx context.Context, user *User) error {
user.ID = bson.NewObjectID()
user.ID = uuid.New().String()
user.CreatedAt = time.Now().UTC()
_, err := r.usersCollection.InsertOne(ctx, user)
_, err := r.pool.Exec(ctx,
`INSERT INTO users (id, username, email, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`,
user.ID, user.Username, user.Email, user.PasswordHash, user.CreatedAt,
)
return err
}
func (r *Repository) FindByEmail(ctx context.Context, email string) (*User, error) {
var user User
err := r.usersCollection.FindOne(ctx, bson.M{"email": email}).Decode(&user)
err := r.pool.QueryRow(ctx,
`SELECT id, username, email, password_hash, created_at FROM users WHERE email = $1`, email,
).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt)
if err != nil {
return nil, err
}
return &user, nil
}
func (r *Repository) FindByID(ctx context.Context, id bson.ObjectID) (*User, error) {
func (r *Repository) FindByID(ctx context.Context, id string) (*User, error) {
var user User
err := r.usersCollection.FindOne(ctx, bson.M{"_id": id}).Decode(&user)
err := r.pool.QueryRow(ctx,
`SELECT id, username, email, password_hash, created_at FROM users WHERE id = $1`, id,
).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt)
if err != nil {
return nil, err
}
return &user, nil
}
//Refresh
func (r *Repository) CreateRefreshToken(ctx context.Context, doc *RefreshTokenDoc) error {
doc.ID = bson.NewObjectID()
doc.ID = uuid.New().String()
doc.CreatedAt = time.Now().UTC()
_, err := r.refreshTokensCollection.InsertOne(ctx, doc)
_, err := r.pool.Exec(ctx,
`INSERT INTO refresh_tokens (id, user_id, token_hash, expires_at, created_at) VALUES ($1, $2, $3, $4, $5)`,
doc.ID, doc.UserID, doc.TokenHash, doc.ExpiresAt, doc.CreatedAt,
)
return err
}
func (r *Repository) FindRefreshTokenByHash(ctx context.Context, hash string) (*RefreshTokenDoc, error) {
var doc RefreshTokenDoc
err := r.refreshTokensCollection.FindOne(ctx, bson.M{"token_hash": hash}).Decode(&doc)
err := r.pool.QueryRow(ctx,
`SELECT id, user_id, token_hash, expires_at, created_at FROM refresh_tokens WHERE token_hash = $1`, hash,
).Scan(&doc.ID, &doc.UserID, &doc.TokenHash, &doc.ExpiresAt, &doc.CreatedAt)
if err != nil {
return nil, err
}
return &doc, nil
}
func (r *Repository) DeleteRefreshToken(ctx context.Context, id bson.ObjectID) error {
_, err := r.refreshTokensCollection.DeleteOne(ctx, bson.M{"_id": id})
func (r *Repository) DeleteRefreshToken(ctx context.Context, id string) error {
_, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE id = $1`, id)
return err
}
func (r *Repository) DeleteRefreshTokenByHash(ctx context.Context, hash string) (bool, error) {
res, err := r.refreshTokensCollection.DeleteOne(ctx, bson.M{"token_hash": hash})
tag, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE token_hash = $1`, hash)
if err != nil {
return false, err
}
return res.DeletedCount > 0, nil
return tag.RowsAffected() > 0, nil
}
func (r *Repository) EnsureIndexes(ctx context.Context) error {
return r.Migrate(ctx)
}
var ErrNoRows = pgx.ErrNoRows
+7 -10
View File
@@ -11,8 +11,6 @@ import (
"strings"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"golang.org/x/crypto/bcrypt"
)
@@ -56,7 +54,7 @@ func generateRandomToken() (string, error) {
}
func (s *Service) issueTokenPair(ctx context.Context, user *User) (*AuthResponse, error) {
accessToken, err := GenerateToken(user.ID.Hex(), user.Email, s.jwtSecret, s.jwtExp)
accessToken, err := GenerateToken(user.ID, user.Email, s.jwtSecret, s.jwtExp)
if err != nil {
return nil, fmt.Errorf("failed to generate access token: %w", err)
}
@@ -86,7 +84,7 @@ func (s *Service) issueTokenPair(ctx context.Context, user *User) (*AuthResponse
func (s *Service) Register(ctx context.Context, req RegisterRequest) (*UserPublic, error) {
req.Email = strings.ToLower(req.Email)
existing, err := s.repo.FindByEmail(ctx, req.Email)
if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
if err != nil && !errors.Is(err, ErrNoRows) {
return nil, fmt.Errorf("failed to check existing user: %w", err)
}
if existing != nil {
@@ -116,7 +114,7 @@ func (s *Service) Login(ctx context.Context, req LoginRequest) (*AuthResponse, e
req.Email = strings.ToLower(req.Email)
user, err := s.repo.FindByEmail(ctx, req.Email)
if err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
if errors.Is(err, ErrNoRows) {
return nil, ErrInvalidCreds
}
return nil, fmt.Errorf("failed to find user: %w", err)
@@ -134,7 +132,7 @@ func (s *Service) Refresh(ctx context.Context, rawRefresh string) (*AuthResponse
doc, err := s.repo.FindRefreshTokenByHash(ctx, hash)
if err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
if errors.Is(err, ErrNoRows) {
return nil, ErrInvalidRefresh
}
return nil, fmt.Errorf("failed to find refresh token: %w", err)
@@ -174,14 +172,13 @@ func (s *Service) Logout(ctx context.Context, rawRefresh string) error {
}
func (s *Service) GetUserByID(ctx context.Context, userID string) (*UserPublic, error) {
id, err := bson.ObjectIDFromHex(userID)
if err != nil {
if userID == "" {
return nil, ErrInvalidUserID
}
user, err := s.repo.FindByID(ctx, id)
user, err := s.repo.FindByID(ctx, userID)
if err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
if errors.Is(err, ErrNoRows) {
return nil, ErrUserNotFound
}
return nil, fmt.Errorf("failed to find user: %w", err)