package store import ( "context" "database/sql" "errors" "time" ) // ErrNotFound is returned when a row does not exist. var ErrNotFound = errors.New("记录不存在") // CountUsers returns the number of accounts (used for bootstrap). func (s *Store) CountUsers(ctx context.Context) (int, error) { var n int err := s.db.QueryRowContext(ctx, `SELECT COUNT(1) FROM users`).Scan(&n) return n, err } // CreateUser inserts an account and returns it. func (s *Store) CreateUser(ctx context.Context, username, passHash, role string) (*User, error) { now := time.Now().Unix() res, err := s.db.ExecContext(ctx, `INSERT INTO users(username, pass_hash, role, created_at) VALUES(?,?,?,?)`, username, passHash, role, now) if err != nil { return nil, err } id, err := res.LastInsertId() if err != nil { return nil, err } return &User{ID: id, Username: username, PassHash: passHash, Role: role, Status: 1, CreatedAt: now}, nil } const userColumns = `id, username, pass_hash, role, totp_secret, totp_enabled, recovery, status, last_login_ip, last_login_at, created_at` func scanUser(row interface{ Scan(...any) error }) (*User, error) { var u User var enabled int err := row.Scan(&u.ID, &u.Username, &u.PassHash, &u.Role, &u.TOTPSecret, &enabled, &u.Recovery, &u.Status, &u.LastLoginIP, &u.LastLoginAt, &u.CreatedAt) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } if err != nil { return nil, err } u.TOTPEnabled = enabled == 1 return &u, nil } // UserByUsername looks an account up by name. func (s *Store) UserByUsername(ctx context.Context, username string) (*User, error) { return scanUser(s.db.QueryRowContext(ctx, `SELECT `+userColumns+` FROM users WHERE username = ?`, username)) } // UserByID looks an account up by primary key. func (s *Store) UserByID(ctx context.Context, id int64) (*User, error) { return scanUser(s.db.QueryRowContext(ctx, `SELECT `+userColumns+` FROM users WHERE id = ?`, id)) } // UpdatePassword replaces the password hash of an account. func (s *Store) UpdatePassword(ctx context.Context, id int64, hash string) error { _, err := s.db.ExecContext(ctx, `UPDATE users SET pass_hash = ? WHERE id = ?`, hash, id) return err } // SetTOTP stores the second factor state of an account. func (s *Store) SetTOTP(ctx context.Context, id int64, secret string, enabled bool, recovery string) error { e := 0 if enabled { e = 1 } _, err := s.db.ExecContext(ctx, `UPDATE users SET totp_secret = ?, totp_enabled = ?, recovery = ? WHERE id = ?`, secret, e, recovery, id) return err } // UseRecoveryCode consumes a one-time recovery code. func (s *Store) UseRecoveryCode(ctx context.Context, id int64, code string) (bool, error) { u, err := s.UserByID(ctx, id) if err != nil { return false, err } codes := splitRecovery(u.Recovery) kept := make([]string, 0, len(codes)) found := false for _, c := range codes { if c == code { found = true continue } kept = append(kept, c) } if !found { return false, nil } _, err = s.db.ExecContext(ctx, `UPDATE users SET recovery = ? WHERE id = ?`, joinRecovery(kept), id) return true, err } // MarkLogin records a successful login. func (s *Store) MarkLogin(ctx context.Context, id int64, ip string) error { _, err := s.db.ExecContext(ctx, `UPDATE users SET last_login_ip = ?, last_login_at = ? WHERE id = ?`, ip, time.Now().Unix(), id) return err } // ListUsers returns all accounts ordered by creation time. func (s *Store) ListUsers(ctx context.Context) ([]*User, error) { rows, err := s.db.QueryContext(ctx, `SELECT `+userColumns+` FROM users ORDER BY id`) 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() }