miaopanel
1package store
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "time"
8)
9
10// ErrNotFound is returned when a row does not exist.
11var ErrNotFound = errors.New("记录不存在")
12
13// CountUsers returns the number of accounts (used for bootstrap).
14func (s *Store) CountUsers(ctx context.Context) (int, error) {
15 var n int
16 err := s.db.QueryRowContext(ctx, `SELECT COUNT(1) FROM users`).Scan(&n)
17 return n, err
18}
19
20// CreateUser inserts an account and returns it.
21func (s *Store) CreateUser(ctx context.Context, username, passHash, role string) (*User, error) {
22 now := time.Now().Unix()
23 res, err := s.db.ExecContext(ctx,
24 `INSERT INTO users(username, pass_hash, role, created_at) VALUES(?,?,?,?)`,
25 username, passHash, role, now)
26 if err != nil {
27 return nil, err
28 }
29 id, err := res.LastInsertId()
30 if err != nil {
31 return nil, err
32 }
33 return &User{ID: id, Username: username, PassHash: passHash, Role: role,
34 Status: 1, CreatedAt: now}, nil
35}
36
37const userColumns = `id, username, pass_hash, role, totp_secret, totp_enabled,
38 recovery, status, last_login_ip, last_login_at, created_at`
39
40func scanUser(row interface{ Scan(...any) error }) (*User, error) {
41 var u User
42 var enabled int
43 err := row.Scan(&u.ID, &u.Username, &u.PassHash, &u.Role, &u.TOTPSecret,
44 &enabled, &u.Recovery, &u.Status, &u.LastLoginIP, &u.LastLoginAt, &u.CreatedAt)
45 if errors.Is(err, sql.ErrNoRows) {
46 return nil, ErrNotFound
47 }
48 if err != nil {
49 return nil, err
50 }
51 u.TOTPEnabled = enabled == 1
52 return &u, nil
53}
54
55// UserByUsername looks an account up by name.
56func (s *Store) UserByUsername(ctx context.Context, username string) (*User, error) {
57 return scanUser(s.db.QueryRowContext(ctx,
58 `SELECT `+userColumns+` FROM users WHERE username = ?`, username))
59}
60
61// UserByID looks an account up by primary key.
62func (s *Store) UserByID(ctx context.Context, id int64) (*User, error) {
63 return scanUser(s.db.QueryRowContext(ctx,
64 `SELECT `+userColumns+` FROM users WHERE id = ?`, id))
65}
66
67// UpdatePassword replaces the password hash of an account.
68func (s *Store) UpdatePassword(ctx context.Context, id int64, hash string) error {
69 _, err := s.db.ExecContext(ctx, `UPDATE users SET pass_hash = ? WHERE id = ?`, hash, id)
70 return err
71}
72
73// SetTOTP stores the second factor state of an account.
74func (s *Store) SetTOTP(ctx context.Context, id int64, secret string, enabled bool, recovery string) error {
75 e := 0
76 if enabled {
77 e = 1
78 }
79 _, err := s.db.ExecContext(ctx,
80 `UPDATE users SET totp_secret = ?, totp_enabled = ?, recovery = ? WHERE id = ?`,
81 secret, e, recovery, id)
82 return err
83}
84
85// UseRecoveryCode consumes a one-time recovery code.
86func (s *Store) UseRecoveryCode(ctx context.Context, id int64, code string) (bool, error) {
87 u, err := s.UserByID(ctx, id)
88 if err != nil {
89 return false, err
90 }
91 codes := splitRecovery(u.Recovery)
92 kept := make([]string, 0, len(codes))
93 found := false
94 for _, c := range codes {
95 if c == code {
96 found = true
97 continue
98 }
99 kept = append(kept, c)
100 }
101 if !found {
102 return false, nil
103 }
104 _, err = s.db.ExecContext(ctx, `UPDATE users SET recovery = ? WHERE id = ?`, joinRecovery(kept), id)
105 return true, err
106}
107
108// MarkLogin records a successful login.
109func (s *Store) MarkLogin(ctx context.Context, id int64, ip string) error {
110 _, err := s.db.ExecContext(ctx,
111 `UPDATE users SET last_login_ip = ?, last_login_at = ? WHERE id = ?`,
112 ip, time.Now().Unix(), id)
113 return err
114}
115
116// ListUsers returns all accounts ordered by creation time.
117func (s *Store) ListUsers(ctx context.Context) ([]*User, error) {
118 rows, err := s.db.QueryContext(ctx, `SELECT `+userColumns+` FROM users ORDER BY id`)
119 if err != nil {
120 return nil, err
121 }
122 defer rows.Close()
123 var out []*User
124 for rows.Next() {
125 u, err := scanUser(rows)
126 if err != nil {
127 return nil, err
128 }
129 out = append(out, u)
130 }
131 return out, rows.Err()
132}