-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
286 lines (254 loc) · 6.03 KB
/
db.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package pimbin
import (
"crypto/rand"
"database/sql"
"encoding/base64"
"errors"
"fmt"
"log"
"sync"
"github.com/mattn/go-sqlite3"
_ "github.com/mattn/go-sqlite3"
)
const schema = `
CREATE TABLE users (
username VARCHAR(255) PRIMARY KEY,
password VARCHAR(255) NOT NULL,
token CHAR(24) UNIQUE
);
CREATE TABLE pastes (
id CHAR(6) PRIMARY KEY NOT NULL,
owner VARCHAR(255) NOT NULL,
FOREIGN KEY(owner) REFERENCES users(username)
);
CREATE TABLE files (
paste CHAR(6) NOT NULL,
hash CHAR(44) NOT NULL,
name VARCHAR(128) NOT NULL,
FOREIGN KEY(paste) REFERENCES pastes(id) ON DELETE CASCADE
);`
var migrations = []string{""}
// User contains a user's data.
type User struct {
Password string
Name string
Token string
}
// Paste contains a paste's data.
type Paste struct {
ID string
Owner string
Files []File
}
// File describes a paste's file.
type File struct {
Hash string
Name string
}
// DB is a pimbin database.
type DB struct {
lock sync.RWMutex
db *sql.DB
}
// OpenSQLiteDB opens and returns an sqlite3 database from the path provided.
func OpenSQLiteDB(source string) (*DB, error) {
sqlDB, err := sql.Open("sqlite3", source)
if err != nil {
return nil, err
}
db := &DB{db: sqlDB}
if err := db.migrate(); err != nil {
return nil, err
}
return db, nil
}
func (db *DB) migrate() error {
db.lock.Lock()
defer db.lock.Unlock()
tx, err := db.db.Begin()
defer tx.Rollback()
if err != nil {
return fmt.Errorf("couldn't start db transaction: %v", err)
}
var version int
if err := db.db.QueryRow("PRAGMA user_version").Scan(&version); err != nil {
return fmt.Errorf("couldn't query schema version: %v", err)
}
if version > len(migrations) {
log.Fatalln("database is from a newer pimbin")
}
if version == 0 {
if _, err := tx.Exec(schema); err != nil {
return fmt.Errorf("failed while executing schema: %v", err)
}
version++
}
for version < len(migrations) {
tx.Exec(migrations[version])
version++
}
_, err = tx.Exec(fmt.Sprintf("PRAGMA user_version = %d", len(migrations)))
if err != nil {
return fmt.Errorf("failed to change schema version: %v", err)
}
return tx.Commit()
}
func fromStringPtr(ptr *string) string {
if ptr == nil {
return ""
}
return *ptr
}
func toStringPtr(s string) *string {
if s == "" {
return nil
}
return &s
}
// Users lists the users in the database.
func (db *DB) Users() ([]User, error) {
db.lock.RLock()
defer db.lock.RUnlock()
rows, err := db.db.Query("SELECT username, password, token FROM users")
if err != nil {
return nil, err
}
defer rows.Close()
var users []User
for rows.Next() {
var (
user User
password *string
token *string
)
if err := rows.Scan(&user.Name, &password, &token); err != nil {
return nil, err
}
user.Password = fromStringPtr(password)
user.Token = fromStringPtr(token)
users = append(users, user)
}
if err := rows.Err(); err != nil {
return nil, err
}
return users, nil
}
// User returns a user from their username, or an error if one occurs while trying to retrieve them.
func (db *DB) User(username string) (*User, error) {
db.lock.Lock()
defer db.lock.Unlock()
user := &User{Name: username}
var password *string
row := db.db.QueryRow("SELECT password FROM users WHERE username = ?", username)
if err := row.Scan(&password); err != nil {
return nil, err
}
user.Password = fromStringPtr(password)
return user, nil
}
// CreateUser inserts user into the database.
func (db *DB) CreateUser(user *User) error {
db.lock.Lock()
defer db.lock.Unlock()
password := toStringPtr(user.Password)
_, err := db.db.Exec("INSERT INTO users(username, password) VALUES (?, ?)", user.Name, password)
return err
}
// RefreshToken refreshes a user's token and returns the new token.
func (db *DB) RefreshToken(user *User) (string, error) {
db.lock.Lock()
defer db.lock.Unlock()
b := make([]byte, 24)
_, err := rand.Read(b)
if err != nil {
return "", err
}
token := base64.URLEncoding.EncodeToString(b)
_, err = db.db.Exec("UPDATE users SET token = ? WHERE username = ?", token, user.Name)
if errors.Is(err, sqlite3.ErrConstraintUnique) {
return db.RefreshToken(user)
}
return token, err
}
// UpdatePassword records changes to user's password in the database.
func (db *DB) UpdatePassword(user *User) error {
db.lock.Lock()
defer db.lock.Unlock()
password := toStringPtr(user.Password)
_, err := db.db.Exec(`UPDATE users SET password = ? WHERE username = ?`,
password, user.Name)
return err
}
// PutPaste inserts the given paste into the database.
func (db *DB) PutPaste(p Paste) error {
db.lock.Lock()
defer db.lock.Unlock()
_, err := db.db.Exec("INSERT INTO pastes(id,owner) VALUES(?, ?)", p.ID, p.Owner)
if err != nil {
return err
}
stmt, err := db.db.Prepare("INSERT INTO files(paste, hash, name) VALUES (?, ?, ?)")
if err != nil {
return err
}
defer stmt.Close()
for _, f := range p.Files {
if _, err = stmt.Exec(p.ID, f.Hash, f.Name); err != nil {
return err
}
}
return nil
}
// Paste returns a paste from its ID.
func (db *DB) Paste(id string) (*Paste, error) {
db.lock.RLock()
defer db.lock.RUnlock()
var owner string
row := db.db.QueryRow("SELECT owner FROM pastes WHERE id=?", id)
err := row.Scan(&owner)
if err != nil {
return nil, err
}
rows, err := db.db.Query("SELECT hash,name FROM files WHERE paste=?", id)
if err != nil {
return nil, err
}
paste := &Paste{
ID: id,
Owner: owner,
}
for rows.Next() {
var (
hash string
name string
)
if err := rows.Scan(&hash, &name); err != nil {
return nil, err
}
file := File{
Hash: hash,
Name: name,
}
paste.Files = append(paste.Files, file)
}
if err := rows.Err(); err != nil {
return nil, err
}
return paste, nil
}
// DeletePaste deletes a paste and its file entries by the id.
func (db *DB) DeletePaste(id string) error {
db.lock.Lock()
defer db.lock.Unlock()
_, err := db.db.Exec("DELETE FROM paste WHERE id = ?", id)
if err != nil {
return err
}
return nil
}
// Close closes the DB.
func (db *DB) Close() error {
db.lock.Lock()
defer db.lock.Unlock()
return db.Close()
}