-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
273 lines (235 loc) · 6.3 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
// db.go
package main
import (
"database/sql"
"fmt"
"golang.org/x/crypto/bcrypt"
"crypto/rand"
"encoding/hex"
"log"
"net/http"
"net/url"
"runtime"
_ "github.com/mattn/go-sqlite3"
)
type DB struct {
*sql.DB
}
func SQLiteDbString(file string, readonly bool) string {
connectionParams := make(url.Values)
connectionParams.Add("_journal_mode", "WAL")
connectionParams.Add("_busy_timeout", "5000")
connectionParams.Add("_synchronous", "NORMAL")
connectionParams.Add("_cache_size", "-20000")
connectionParams.Add("_foreign_keys", "true")
if readonly {
connectionParams.Add("mode", "ro")
} else {
connectionParams.Add("_txlock", "IMMEDIATE")
connectionParams.Add("mode", "rwc")
}
return "file:" + file + "?" + connectionParams.Encode()
}
func InitDB(file string, readonly bool) (*DB, error) {
dbString := SQLiteDbString(file, readonly)
db, err := sql.Open("sqlite3", dbString)
if err != nil {
return nil, fmt.Errorf("error opening database: %w", err)
}
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("error connecting to database: %w", err)
}
pragmasToSet := []string{
"temp_store=memory",
}
for _, pragma := range pragmasToSet {
_, err = db.Exec("PRAGMA " + pragma + ";")
if err != nil {
return nil, err
}
}
if readonly {
db.SetMaxOpenConns(max(4, runtime.NumCPU()))
} else {
db.SetMaxOpenConns(1)
}
return &DB{db}, nil
}
func (db *DB) CreateTables() error {
tables := []string{
`CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
hashed_password TEXT NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
username TEXT NOT NULL,
FOREIGN KEY (username) REFERENCES users(username)
)`,
`CREATE TABLE IF NOT EXISTS rooms (
id TEXT PRIMARY KEY
)`,
`CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
room_id TEXT NOT NULL,
username TEXT NOT NULL,
content TEXT NOT NULL,
timestamp TEXT NOT NULL,
FOREIGN KEY (room_id) REFERENCES rooms(id),
FOREIGN KEY (username) REFERENCES users(username)
)`,
}
for _, table := range tables {
_, err := db.Exec(table)
if err != nil {
return fmt.Errorf("error creating table: %w", err)
}
}
return nil
}
func (db *DB) GetUser(username string) (*User, error) {
var user User
err := db.QueryRow("SELECT username, hashed_password FROM users WHERE username = ?", username).Scan(&user.Username, &user.HashedPassword)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, fmt.Errorf("error querying user: %w", err)
}
return &user, nil
}
func (db *DB) CreateUser(username, hashedPassword string) error {
_, err := db.Exec("INSERT INTO users (username, hashed_password) VALUES (?, ?)", username, hashedPassword)
if err != nil {
return fmt.Errorf("error creating user: %w", err)
}
return nil
}
func (db *DB) CreateSession(token, username string) error {
_, err := db.Exec("INSERT INTO sessions (token, username) VALUES (?, ?)", token, username)
if err != nil {
return fmt.Errorf("error creating session: %w", err)
}
return nil
}
func (db *DB) GetUserFromSession(token string) (*User, error) {
var username string
err := db.QueryRow("SELECT username FROM sessions WHERE token = ?", token).Scan(&username)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, fmt.Errorf("error querying session: %w", err)
}
return db.GetUser(username)
}
func (db *DB) CreateRoom(roomID string) error {
_, err := db.Exec("INSERT OR IGNORE INTO rooms (id) VALUES (?)", roomID)
if err != nil {
return fmt.Errorf("error creating room: %w", err)
}
return nil
}
func (db *DB) StoreMessage(roomID, username, content, timestamp string) error {
_, err := db.Exec("INSERT INTO messages (room_id, username, content, timestamp) VALUES (?, ?, ?, ?)",
roomID, username, content, timestamp)
if err != nil {
return fmt.Errorf("error storing message: %w", err)
}
return nil
}
func (db *DB) GetRoomMessages(roomID string) ([]Message, error) {
rows, err := db.Query("SELECT content, username, timestamp FROM messages WHERE room_id = ? ORDER BY timestamp", roomID)
if err != nil {
return nil, fmt.Errorf("error fetching room messages: %w", err)
}
defer rows.Close()
var messages []Message
for rows.Next() {
var msg Message
err := rows.Scan(&msg.Content, &msg.User, &msg.Timestamp)
if err != nil {
return nil, fmt.Errorf("error scanning message row: %w", err)
}
msg.Type = "message"
messages = append(messages, msg)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating message rows: %w", err)
}
return messages, nil
}
func (db *DB) GetRooms() (map[string]int, error) {
rows, err := db.Query(`
SELECT r.id, COUNT(DISTINCT m.username) as user_count
FROM rooms r
LEFT JOIN messages m ON r.id = m.room_id
GROUP BY r.id
`)
if err != nil {
return nil, err
}
defer rows.Close()
rooms := make(map[string]int)
for rows.Next() {
var roomID string
var userCount int
if err := rows.Scan(&roomID, &userCount); err != nil {
return nil, err
}
rooms[roomID] = userCount
}
return rooms, nil
}
func (db *DB) GetUserCount() (int, error) {
var count int
err := db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
return count, err
}
//
// Generate session token
//
func generateSessionToken() string {
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
log.Fatal(err)
}
return hex.EncodeToString(bytes)
}
//
// Get username from session
//
func getUserFromSession(rm *RoomManager, r *http.Request) *User {
cookie, err := r.Cookie("SessionToken")
if err != nil {
return nil
}
rm.mu.Lock()
defer rm.mu.Unlock()
user, err := rm.db.GetUserFromSession(cookie.Value)
if err != nil {
log.Printf("Error getting user from session: %v", err)
return nil
}
if user != nil {
user.SessionToken = cookie.Value
}
return user
}
//
// Hash Password
//
func hashPassword(password string) (string, error) {
hashedBytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hashedBytes), nil
}
//
// Verify Password
//
func verifyPassword(hashedPassword, password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
return err == nil
}