Files
mtusi2026lab2/src/user.go
T

77 lines
2.2 KiB
Go

package main
import (
"context"
"crypto/rand"
"crypto/subtle"
"errors"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/scrypt"
)
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt time.Time `json:"created_at"`
}
type userStore struct {
db *pgxpool.Pool
}
func newUserStore(db *pgxpool.Pool) *userStore {
return &userStore{db: db}
}
func derivePassword(password string, salt []byte) ([]byte, error) {
return scrypt.Key([]byte(password), salt, 32768, 8, 1, 32)
}
func (s *userStore) create(ctx context.Context, username, displayName, password string) (User, error) {
salt := make([]byte, 32)
if _, err := rand.Read(salt); err != nil {
return User{}, err
}
hash, err := derivePassword(password, salt)
if err != nil {
return User{}, err
}
user := User{
ID: uuid.New().String(),
Username: username,
DisplayName: displayName,
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
}
_, err = s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,password_salt,created_at) VALUES($1,$2,$3,$4,$5,$6)", user.ID, user.Username, user.DisplayName, hash, salt, user.CreatedAt)
return user, err
}
func (s *userStore) getByID(ctx context.Context, id string) (User, error) {
var user User
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at FROM users WHERE id=$1", id).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
return user, err
}
func (s *userStore) verifyPassword(ctx context.Context, username, password string) (User, bool, error) {
var user User
var hash, salt []byte
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash,password_salt FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash, &salt)
if errors.Is(err, pgx.ErrNoRows) {
return User{}, false, nil
}
if err != nil {
return User{}, false, err
}
actual, err := derivePassword(password, salt)
if err != nil {
return User{}, false, err
}
return user, subtle.ConstantTimeCompare(hash, actual) == 1, nil
}