repository.go (2514B)
1 package repository 2 3 import ( 4 "crypto/sha512" 5 "database/sql" 6 "uuid" 7 8 _ "modernc.org/sqlite" 9 ) 10 11 type Credential struct { 12 Username string 13 Password [sha512.Size]byte 14 } 15 16 var db *sql.DB 17 18 // Open opens (creating if needed) the SQLite database at path. It must be 19 // called before any other function of this package. 20 func Open(path string) error { 21 conn, err := sql.Open("sqlite", path) 22 if err != nil { 23 return err 24 } 25 _, err = conn.Exec(` 26 CREATE TABLE IF NOT EXISTS credentials ( 27 username TEXT NOT NULL UNIQUE, 28 password BLOB NOT NULL CHECK (LENGTH(password) == 64) 29 )`) 30 if err != nil { 31 conn.Close() 32 return err 33 } 34 // Older databases have a sessions table without the owner of the 35 // session. Sessions are disposable, so the table is just recreated: the 36 // users have to log in again. 37 var hasUsername bool 38 err = conn.QueryRow( 39 `SELECT COUNT(*) > 0 FROM pragma_table_info('sessions') WHERE name = 'username'`, 40 ).Scan(&hasUsername) 41 if err == nil && !hasUsername { 42 _, err = conn.Exec(`DROP TABLE IF EXISTS sessions`) 43 } 44 if err != nil { 45 conn.Close() 46 return err 47 } 48 _, err = conn.Exec(` 49 CREATE TABLE IF NOT EXISTS sessions ( 50 token BLOB CHECK (LENGTH(token) == 16), 51 username TEXT NOT NULL 52 )`) 53 if err != nil { 54 conn.Close() 55 return err 56 } 57 db = conn 58 return nil 59 } 60 61 // Close closes the database opened by Open. 62 func Close() error { 63 return db.Close() 64 } 65 66 func NewCredential(c Credential) error { 67 _, err := db.Exec( 68 `INSERT INTO credentials (username, password) VALUES (?, ?)`, 69 c.Username, c.Password[:], 70 ) 71 return err 72 } 73 74 func GetByUsername(username string) (Credential, error) { 75 var c Credential 76 var password []byte 77 err := db.QueryRow( 78 `SELECT username, password FROM credentials WHERE username = ?`, 79 username, 80 ).Scan(&c.Username, &password) 81 copy(c.Password[:], password) 82 return c, err 83 } 84 85 // NewSession records token as a session of username. 86 func NewSession(token uuid.UUID, username string) error { 87 _, err := db.Exec( 88 `INSERT INTO sessions (token, username) VALUES (?, ?)`, 89 token[:], username, 90 ) 91 return err 92 } 93 94 // SessionUsername returns the user that owns the session, or sql.ErrNoRows if 95 // there is no such session. 96 func SessionUsername(token uuid.UUID) (string, error) { 97 var username string 98 err := db.QueryRow( 99 `SELECT username FROM sessions WHERE token = ?`, 100 token[:], 101 ).Scan(&username) 102 return username, err 103 } 104 105 func DeleteSession(token uuid.UUID) error { 106 _, err := db.Exec( 107 `DELETE FROM sessions WHERE token = ?`, token[:], 108 ) 109 return err 110 }