仰望星辰工作室

miaopanel

miaopanel/ internal/store/sessions.go 3.3 KB · 110 行 原始文件
1package store
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "strings"
8 "time"
9)
10
11func splitRecovery(s string) []string {
12 if strings.TrimSpace(s) == "" {
13 return nil
14 }
15 return strings.Split(s, ",")
16}
17
18func joinRecovery(codes []string) string { return strings.Join(codes, ",") }
19
20// CreateSession persists a new login session.
21func (s *Store) CreateSession(ctx context.Context, sess *Session) error {
22 _, err := s.db.ExecContext(ctx,
23 `INSERT INTO sessions(id, user_id, ip, ua, csrf, created_at, expires_at, last_seen)
24 VALUES(?,?,?,?,?,?,?,?)`,
25 sess.ID, sess.UserID, sess.IP, sess.UA, sess.CSRF,
26 sess.CreatedAt, sess.ExpiresAt, sess.CreatedAt)
27 return err
28}
29
30// SessionByID returns a session ignoring expiry (the caller checks it).
31func (s *Store) SessionByID(ctx context.Context, id string) (*Session, error) {
32 var sess Session
33 err := s.db.QueryRowContext(ctx,
34 `SELECT id, user_id, ip, ua, csrf, created_at, expires_at, last_seen
35 FROM sessions WHERE id = ?`, id).
36 Scan(&sess.ID, &sess.UserID, &sess.IP, &sess.UA, &sess.CSRF,
37 &sess.CreatedAt, &sess.ExpiresAt, &sess.LastSeen)
38 if errors.Is(err, sql.ErrNoRows) {
39 return nil, ErrNotFound
40 }
41 if err != nil {
42 return nil, err
43 }
44 return &sess, nil
45}
46
47// TouchSession extends a session after authenticated activity.
48func (s *Store) TouchSession(ctx context.Context, id string, expiresAt int64) error {
49 _, err := s.db.ExecContext(ctx,
50 `UPDATE sessions SET last_seen = ?, expires_at = ? WHERE id = ?`,
51 time.Now().Unix(), expiresAt, id)
52 return err
53}
54
55// DeleteSession removes a session.
56func (s *Store) DeleteSession(ctx context.Context, id string) error {
57 _, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE id = ?`, id)
58 return err
59}
60
61// DeleteOtherSessions invalidates every session of a user except keep.
62func (s *Store) DeleteOtherSessions(ctx context.Context, userID int64, keep string) (int64, error) {
63 res, err := s.db.ExecContext(ctx,
64 `DELETE FROM sessions WHERE user_id = ? AND id <> ?`, userID, keep)
65 if err != nil {
66 return 0, err
67 }
68 return res.RowsAffected()
69}
70
71// PurgeExpiredSessions drops stale sessions.
72func (s *Store) PurgeExpiredSessions(ctx context.Context) (int64, error) {
73 res, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE expires_at < ?`, time.Now().Unix())
74 if err != nil {
75 return 0, err
76 }
77 return res.RowsAffected()
78}
79
80// RecordLoginAttempt appends one authentication attempt.
81func (s *Store) RecordLoginAttempt(ctx context.Context, ip, username string, ok bool) error {
82 v := 0
83 if ok {
84 v = 1
85 }
86 _, err := s.db.ExecContext(ctx,
87 `INSERT INTO login_attempts(ip, username, success, at) VALUES(?,?,?,?)`,
88 ip, username, v, time.Now().Unix())
89 return err
90}
91
92// CountRecentFailures counts failed logins from an IP inside the window.
93func (s *Store) CountRecentFailures(ctx context.Context, ip string, window time.Duration) (int, error) {
94 since := time.Now().Add(-window).Unix()
95 var n int
96 err := s.db.QueryRowContext(ctx,
97 `SELECT COUNT(1) FROM login_attempts WHERE ip = ? AND success = 0 AND at >= ?`,
98 ip, since).Scan(&n)
99 return n, err
100}
101
102// CleanupAttempts removes attempts older than 24h.
103func (s *Store) CleanupAttempts(ctx context.Context) (int64, error) {
104 res, err := s.db.ExecContext(ctx,
105 `DELETE FROM login_attempts WHERE at < ?`, time.Now().Add(-24*time.Hour).Unix())
106 if err != nil {
107 return 0, err
108 }
109 return res.RowsAffected()
110}