-
Notifications
You must be signed in to change notification settings - Fork 10
/
database.go
112 lines (103 loc) · 1.8 KB
/
database.go
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"crypto/rsa"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"sync"
)
type DB struct {
ptr *sql.DB
mtx sync.Mutex
}
type User struct {
Id int
Access bool
Uid string
PrvKey string
}
func DBInit(filename string) *DB {
db, err := sql.Open("sqlite3", filename)
if err != nil {
return nil
}
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER,
access BOOLEAN,
uid VARCHAR(255) UNIQUE,
prvkey VARCHAR(4096),
PRIMARY KEY(id)
);
`)
if err != nil {
return nil
}
return &DB{
ptr: db,
}
}
func (db *DB) UpdateAccess(id string, mode bool) error {
db.mtx.Lock()
defer db.mtx.Unlock()
_, err := db.ptr.Exec(
"UPDATE users SET access=$1 WHERE id=$2",
mode,
id,
)
return err
}
func (db *DB) GetUserByID(id int) *User {
db.mtx.Lock()
defer db.mtx.Unlock()
var (
access bool
uid string
prvkey string
)
row := db.ptr.QueryRow(
"SELECT access, uid, prvkey FROM users WHERE id=$1",
id,
)
row.Scan(&access, &uid, &prvkey)
if prvkey == "" {
return nil
}
return &User{
Id: id,
Access: access,
Uid: uid,
PrvKey: string(HexDecode(prvkey)),
}
}
func (db *DB) Size() int {
db.mtx.Lock()
defer db.mtx.Unlock()
var id int
row := db.ptr.QueryRow(
"SELECT id FROM users ORDER BY id DESC LIMIT 1",
)
row.Scan(&id)
return id
}
func (db *DB) SetKey(uid string, key *rsa.PrivateKey) error {
db.mtx.Lock()
defer db.mtx.Unlock()
_, err := db.ptr.Exec(
"INSERT INTO users (access, uid, prvkey) VALUES ($1, $2, $3)",
0,
uid,
HexEncode(BytesPrivate(key)),
)
return err
}
func (db *DB) GetKey(uid string) *rsa.PrivateKey {
db.mtx.Lock()
defer db.mtx.Unlock()
var strprv string
row := db.ptr.QueryRow(
"SELECT prvkey FROM users WHERE access=1 AND uid=$1",
uid,
)
row.Scan(&strprv)
return ParsePrivate(HexDecode(strprv))
}