navid/veinsforge / 6c726cf7659e637e1dc936688ae0c029fcf00a614ae35498bba56d72e31c949c / internal/data/users.go

users.go

← internal/data · 11350 bytes · raw · download

package data

import (
	"context"
	"database/sql"
	"strings"
	"time"
)

type User struct {
	ID           int64
	Username     string
	DisplayName  string
	Email        string
	PasswordHash string
	Bio          string
	AvatarFile   string
	IsAdmin      bool
	IsActive     bool
	SignupIP     string
	LastIP       string
	CreatedAt    time.Time
	UpdatedAt    time.Time
	LastLoginAt  *time.Time
}

func scanUser(sc interface{ Scan(...any) error }) (*User, error) {
	var u User
	var admin, active int
	var created, updated int64
	var last sql.NullInt64
	err := sc.Scan(&u.ID, &u.Username, &u.DisplayName, &u.Email, &u.PasswordHash,
		&u.Bio, &u.AvatarFile, &admin, &active, &u.SignupIP, &u.LastIP,
		&created, &updated, &last)
	if err != nil {
		return nil, err
	}
	u.IsAdmin = intBool(admin)
	u.IsActive = intBool(active)
	u.CreatedAt = fromUnix(created)
	u.UpdatedAt = fromUnix(updated)
	u.LastLoginAt = nullTime(last)
	return &u, nil
}

const userColumns = `id, username, display_name, email, password_hash, bio, avatar_file,
	is_admin, is_active, signup_ip, last_ip, created_at, updated_at, last_login_at`

func (s *Store) CreateUser(ctx context.Context, username, displayName, email, passwordHash, ip string, admin bool) (*User, error) {
	now := time.Now()
	res, err := s.db.ExecContext(ctx, `
		INSERT INTO users(username, display_name, email, password_hash, signup_ip, last_ip, is_admin, created_at, updated_at)
		VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		username, displayName, email, passwordHash, ip, ip, boolInt(admin), unix(now), unix(now))
	if err != nil {
		if isUnique(err) {
			return nil, ErrConflict
		}
		return nil, err
	}
	id, _ := res.LastInsertId()
	return s.GetUserByID(ctx, id)
}

// CreateUserAutoAdmin atomically creates a user and makes the very first
// account an administrator. The transaction prevents a signup race from
// producing two administrators.
func (s *Store) CreateUserAutoAdmin(ctx context.Context, username, displayName, email, passwordHash, ip string) (*User, error) {
	now := time.Now()
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return nil, err
	}
	defer tx.Rollback()
	var count int64
	if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&count); err != nil {
		return nil, err
	}
	admin := count == 0
	res, err := tx.ExecContext(ctx, `
		INSERT INTO users(username, display_name, email, password_hash, signup_ip, last_ip, is_admin, created_at, updated_at)
		VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		username, displayName, email, passwordHash, ip, ip, boolInt(admin), unix(now), unix(now))
	if err != nil {
		if isUnique(err) {
			return nil, ErrConflict
		}
		return nil, err
	}
	id, _ := res.LastInsertId()
	if err := tx.Commit(); err != nil {
		return nil, err
	}
	return s.GetUserByID(ctx, id)
}

func (s *Store) GetUserByID(ctx context.Context, id int64) (*User, error) {
	row := s.db.QueryRowContext(ctx, `SELECT `+userColumns+` FROM users WHERE id = ?`, id)
	u, err := scanUser(row)
	if err == sql.ErrNoRows {
		return nil, ErrNotFound
	}
	return u, err
}

func (s *Store) GetUserByUsername(ctx context.Context, username string) (*User, error) {
	row := s.db.QueryRowContext(ctx, `SELECT `+userColumns+` FROM users WHERE username = ? COLLATE NOCASE`, username)
	u, err := scanUser(row)
	if err == sql.ErrNoRows {
		return nil, ErrNotFound
	}
	return u, err
}

func (s *Store) CountUsers(ctx context.Context) (int64, error) {
	var n int64
	err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&n)
	return n, err
}

func (s *Store) UpdateUserProfile(ctx context.Context, id int64, displayName, email, bio string) error {
	_, err := s.db.ExecContext(ctx, `UPDATE users SET display_name = ?, email = ?, bio = ?, updated_at = ? WHERE id = ?`,
		displayName, email, bio, unix(time.Now()), id)
	return err
}

func (s *Store) UpdateUserPassword(ctx context.Context, id int64, hash string) error {
	_, err := s.db.ExecContext(ctx, `UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?`, hash, unix(time.Now()), id)
	return err
}

func (s *Store) SetUserAvatar(ctx context.Context, id int64, file string) error {
	_, err := s.db.ExecContext(ctx, `UPDATE users SET avatar_file = ?, updated_at = ? WHERE id = ?`, file, unix(time.Now()), id)
	return err
}

func (s *Store) SetUserActive(ctx context.Context, id int64, active bool) error {
	_, err := s.db.ExecContext(ctx, `UPDATE users SET is_active = ?, updated_at = ? WHERE id = ?`, boolInt(active), unix(time.Now()), id)
	if !active {
		_, _ = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE user_id = ?`, id)
	}
	return err
}

func (s *Store) SetUserAdmin(ctx context.Context, id int64, admin bool) error {
	_, err := s.db.ExecContext(ctx, `UPDATE users SET is_admin = ?, updated_at = ? WHERE id = ?`, boolInt(admin), unix(time.Now()), id)
	return err
}

func (s *Store) RecordLogin(ctx context.Context, id int64, ip string) error {
	now := unix(time.Now())
	_, err := s.db.ExecContext(ctx, `UPDATE users SET last_login_at = ?, last_ip = ?, updated_at = ? WHERE id = ?`, now, ip, now, id)
	return err
}

func (s *Store) ListUsers(ctx context.Context, offset, limit int) ([]*User, error) {
	rows, err := s.db.QueryContext(ctx, `SELECT `+userColumns+` FROM users ORDER BY username COLLATE NOCASE LIMIT ? OFFSET ?`, limit, offset)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []*User
	for rows.Next() {
		u, err := scanUser(rows)
		if err != nil {
			return nil, err
		}
		out = append(out, u)
	}
	return out, rows.Err()
}

func (s *Store) RecordLoginAttempt(ctx context.Context, username, ip string, success bool) {
	_, _ = s.db.ExecContext(ctx, `INSERT INTO login_attempts(username, ip, success, created_at) VALUES(?, ?, ?, ?)`,
		username, ip, boolInt(success), unix(time.Now()))
}

func (s *Store) RecentFailures(ctx context.Context, username, ip string, since time.Time) (int, error) {
	var n int
	err := s.db.QueryRowContext(ctx, `
		SELECT COUNT(*) FROM login_attempts
		WHERE success = 0 AND created_at >= ? AND ip = ?`,
		unix(since), ip).Scan(&n)
	return n, err
}

func (s *Store) ClearLoginFailures(ctx context.Context, ip string) {
	_, _ = s.db.ExecContext(ctx, `DELETE FROM login_attempts WHERE ip = ? AND success = 0`, ip)
}

func (s *Store) CountRecentAttempts(ctx context.Context, ip string, since time.Time) (int, error) {
	var n int
	err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM login_attempts WHERE ip = ? AND created_at >= ?`, ip, unix(since)).Scan(&n)
	return n, err
}

func (s *Store) CleanupLoginAttempts(ctx context.Context, before time.Time) {
	_, _ = s.db.ExecContext(ctx, `DELETE FROM login_attempts WHERE created_at < ?`, unix(before))
}

type SSHKey struct {
	ID          int64
	UserID      int64
	Name        string
	PublicKey   string
	Fingerprint string
	CreatedAt   time.Time
	LastUsedAt  *time.Time
}

func (s *Store) ListSSHKeys(ctx context.Context, userID int64) ([]*SSHKey, error) {
	rows, err := s.db.QueryContext(ctx, `SELECT id, user_id, name, public_key, fingerprint, created_at, last_used_at FROM ssh_keys WHERE user_id = ? ORDER BY created_at`, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []*SSHKey
	for rows.Next() {
		var k SSHKey
		var created int64
		var last sql.NullInt64
		if err := rows.Scan(&k.ID, &k.UserID, &k.Name, &k.PublicKey, &k.Fingerprint, &created, &last); err != nil {
			return nil, err
		}
		k.CreatedAt = fromUnix(created)
		k.LastUsedAt = nullTime(last)
		out = append(out, &k)
	}
	return out, rows.Err()
}

func (s *Store) AddSSHKey(ctx context.Context, userID int64, name, publicKey, fingerprint string) error {
	_, err := s.db.ExecContext(ctx, `INSERT INTO ssh_keys(user_id, name, public_key, fingerprint, created_at) VALUES(?, ?, ?, ?, ?)`,
		userID, name, publicKey, fingerprint, unix(time.Now()))
	if err != nil {
		if isUnique(err) {
			return ErrConflict
		}
		return err
	}
	return nil
}

func (s *Store) DeleteSSHKey(ctx context.Context, userID, keyID int64) error {
	res, err := s.db.ExecContext(ctx, `DELETE FROM ssh_keys WHERE id = ? AND user_id = ?`, keyID, userID)
	if err != nil {
		return err
	}
	n, _ := res.RowsAffected()
	if n == 0 {
		return ErrNotFound
	}
	return nil
}

func (s *Store) AllActiveSSHKeys(ctx context.Context) ([]*SSHKey, error) {
	rows, err := s.db.QueryContext(ctx, `
		SELECT k.id, k.user_id, k.name, k.public_key, k.fingerprint, k.created_at, k.last_used_at
		FROM ssh_keys k JOIN users u ON u.id = k.user_id
		WHERE u.is_active = 1 ORDER BY k.user_id, k.id`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []*SSHKey
	for rows.Next() {
		var k SSHKey
		var created int64
		var last sql.NullInt64
		if err := rows.Scan(&k.ID, &k.UserID, &k.Name, &k.PublicKey, &k.Fingerprint, &created, &last); err != nil {
			return nil, err
		}
		k.CreatedAt = fromUnix(created)
		k.LastUsedAt = nullTime(last)
		out = append(out, &k)
	}
	return out, rows.Err()
}

type Session struct {
	ID         string
	UserID     int64
	CSRF       string
	IP         string
	UserAgent  string
	CreatedAt  time.Time
	LastSeenAt time.Time
	ExpiresAt  time.Time
	User       *User
}

func (s *Store) CreateSession(ctx context.Context, id string, userID int64, csrf, ip, ua string, expires time.Time) error {
	now := time.Now()
	_, err := s.db.ExecContext(ctx, `INSERT INTO sessions(id, user_id, csrf, ip, user_agent, created_at, last_seen_at, expires_at)
		VALUES(?, ?, ?, ?, ?, ?, ?, ?)`, id, userID, csrf, ip, ua, unix(now), unix(now), unix(expires))
	return err
}

func (s *Store) GetSession(ctx context.Context, id string) (*Session, error) {
	row := s.db.QueryRowContext(ctx, `
		SELECT id, user_id, csrf, ip, user_agent, created_at, last_seen_at, expires_at
		FROM sessions WHERE id = ? AND expires_at > ?`, id, unix(time.Now()))
	var sess Session
	var created, seen, expires int64
	if err := row.Scan(&sess.ID, &sess.UserID, &sess.CSRF, &sess.IP, &sess.UserAgent, &created, &seen, &expires); err != nil {
		if err == sql.ErrNoRows {
			return nil, ErrNotFound
		}
		return nil, err
	}
	sess.CreatedAt = fromUnix(created)
	sess.LastSeenAt = fromUnix(seen)
	sess.ExpiresAt = fromUnix(expires)
	u, err := s.GetUserByID(ctx, sess.UserID)
	if err != nil {
		return nil, err
	}
	if !u.IsActive {
		return nil, ErrNotFound
	}
	sess.User = u
	return &sess, nil
}

func (s *Store) TouchSession(ctx context.Context, id string) {
	_, _ = s.db.ExecContext(ctx, `UPDATE sessions SET last_seen_at = ? WHERE id = ?`, unix(time.Now()), id)
}

func (s *Store) DeleteSession(ctx context.Context, id string) {
	_, _ = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE id = ?`, id)
}

func (s *Store) DeleteUserSessions(ctx context.Context, userID int64) {
	_, _ = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE user_id = ?`, userID)
}

func (s *Store) CleanupSessions(ctx context.Context) {
	_, _ = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE expires_at <= ?`, unix(time.Now()))
}

// UsernameAvailable checks the shared user/org namespace used in URLs.
func (s *Store) UsernameAvailable(ctx context.Context, username string) (bool, error) {
	var n int
	err := s.db.QueryRowContext(ctx, `
		SELECT (SELECT COUNT(*) FROM users WHERE username = ? COLLATE NOCASE)
		     + (SELECT COUNT(*) FROM orgs WHERE name = ? COLLATE NOCASE)`, username, username).Scan(&n)
	return n == 0, err
}

func NormalizeHandle(name string) string { return strings.TrimSpace(name) }