1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
package database
import (
"database/sql"
"time"
_ "github.com/mattn/go-sqlite3"
)
type Session struct {
ID string
UserID string
ExpireAt time.Time
}
func CreateSession(db *sql.DB, id, userID string, ttl time.Duration) (*Session, error) {
now := time.Now()
expire := now.Add(ttl)
_, err := db.Exec(
"INSERT INTO sessions (id, user_id, created_at, expire_at) VALUES (?, ?, ?, ?)",
id, userID, now, expire,
)
if err != nil {
return nil, err
}
return &Session{ID: id, UserID: userID, ExpireAt: expire}, nil
}
func GetSessionUser(db *sql.DB, id string) (*User, error) {
return scanUser(db.QueryRow(
"SELECT u.id, u.username, u.created_at, u.last_seen FROM users u JOIN sessions s ON s.user_id = u.id WHERE s.id = ? AND s.expire_at > ?",
id, time.Now(),
))
}
func DeleteExpiredSessions(db *sql.DB) error {
_, err := db.Exec("DELETE FROM sessions WHERE expire_at < ?", time.Now())
return err
}
func DeleteSession(db *sql.DB, id string) error {
_, err := db.Exec("DELETE FROM sessions WHERE id = ?", id)
return err
}
|