forked from AlexMax/charon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
237 lines (205 loc) · 5.9 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
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
/*
* Charon: A game authentication server
* Copyright (C) 2014-2016 Alex Mayfield <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package charon
import (
"crypto/sha256"
"errors"
"io/ioutil"
"strings"
"sync"
"time"
"github.com/AlexMax/charon/srp"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3" // Database driver
)
// Database is an instance of our database connection and all necessary state
// used to manage said instance.
type Database struct {
db *sqlx.DB
mutex sync.Mutex
}
// Schema for sqlite3.
const schema = `
CREATE TABLE IF NOT EXISTS Users(
id INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(255),
email VARCHAR(255),
verifier BLOB,
salt BLOB,
access TEXT,
active TINYINT(1),
createdAt DATETIME NOT NULL,
updatedAt DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS Profiles(
id INTEGER PRIMARY KEY AUTOINCREMENT,
clan VARCHAR(255),
clantag VARCHAR(255),
contactinfo VARCHAR(255),
country VARCHAR(255),
gravatar TEXT,
location VARCHAR(255),
message VARCHAR(255),
username VARCHAR(255),
visible TINYINT(1) DEFAULT 1,
visible_lastseen TINYINT(1) DEFAULT 1,
createdAt DATETIME NOT NULL,
updatedAt DATETIME NOT NULL,
UserId INTEGER
);`
var connectMutex sync.Mutex
// NewDatabase creates a new Database instance.
func NewDatabase(config *Config) (database *Database, err error) {
// Create a database connection.
filename := config.Database.Filename
connectMutex.Lock()
db, err := sqlx.Connect("sqlite3", filename)
connectMutex.Unlock()
if err != nil {
return
}
// Create the database schema.
_ = db.MustExec("PRAGMA foreign_keys = ON;")
_ = db.MustExec(schema)
database = new(Database)
database.db = db
return
}
// Import executes a file containing SQL statements on the loaded database.
func (database *Database) Import(paths ...string) (err error) {
for _, path := range paths {
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
_, err = database.db.Exec(string(data))
if err != nil {
return err
}
}
return
}
// User is a representation of the `User` table in the database.
type User struct {
ID uint
Username string
Email string
Verifier []byte
Salt []byte
Access string
Active bool
CreatedAt time.Time `db:"createdAt"`
UpdatedAt time.Time `db:"updatedAt"`
}
// User access constants.
const (
UserAccessUnverified string = "UNVERIFIED"
UserAccessUser string = "USER"
UserAccessOp string = "OP"
UserAccessMaster string = "MASTER"
UserAccessOwner string = "OWNER"
)
// AddUser adds a new user.
func (database *Database) AddUser(username string, email string, password string) (err error) {
// Username and email are forced lowercase
username = strings.ToLower(username)
email = strings.ToLower(email)
// Must be unique
var count int
database.mutex.Lock()
err = database.db.Get(&count, "SELECT COUNT(*) FROM Users WHERE Username = ?", username)
database.mutex.Unlock()
if err != nil {
return err
}
if count > 0 {
return errors.New("charon: username is not unique")
}
srp, err := srp.NewSRP("rfc5054.2048", sha256.New, nil)
if err != nil {
return err
}
user := new(User)
user.Username = username
user.Email = email
user.Access = UserAccessUnverified
user.Active = false
user.CreatedAt = time.Now()
user.UpdatedAt = time.Now()
user.Salt, user.Verifier, err = srp.ComputeVerifier([]byte(username), []byte(password))
if err != nil {
return err
}
database.mutex.Lock()
_, err = database.db.NamedExec("INSERT INTO Users (Username, Email, Verifier, Salt, Access, Active, createdAt, updatedAt) VALUES (:username, :email, :verifier, :salt, :access, :active, :createdAt, :updatedAt)", user)
database.mutex.Unlock()
return
}
// FindUser tries to find a specific user by name or email address.
func (database *Database) FindUser(username string) (user *User, err error) {
// Username is forced lowercase
username = strings.ToLower(username)
user = &User{}
database.mutex.Lock()
err = database.db.Get(user, "SELECT * FROM users WHERE username = $1 OR email = $1", strings.ToLower(username))
database.mutex.Unlock()
return
}
// LoginUser tries to log a user in with the passed username and password.
func (database *Database) LoginUser(username string, password string) (user *User, err error) {
// Username is forced lowercase
username = strings.ToLower(username)
user, err = database.FindUser(username)
if err != nil {
return
}
srpo, err := srp.NewSRP("rfc5054.2048", sha256.New, nil)
if err != nil {
return
}
cs := srpo.NewClientSession([]byte(user.Username), []byte(password))
ss := srpo.NewServerSession([]byte(user.Username), user.Salt, user.Verifier)
_, err = cs.ComputeKey(user.Salt, ss.GetB())
if err != nil {
return
}
_, err = ss.ComputeKey(cs.GetA())
if err != nil {
return
}
cauth := cs.ComputeAuthenticator()
if !ss.VerifyClientAuthenticator(cauth) {
err = errors.New("Client Authenticator is not valid")
return
}
return
}
// Profile is representation of the `profile` table in the database.
type Profile struct {
ID uint
User_id uint
Clan string
Contactinfo string
Country string
Gravatar string
Location string
Message string
Username string
Visible bool
Visible_lastplayed bool
}