-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbaccessor.go
407 lines (324 loc) · 9.47 KB
/
dbaccessor.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package lib
import (
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/cloudflare/cfssl/log"
"github.com/hyperledger/fabric-ca/api"
"github.com/hyperledger/fabric-ca/lib/spi"
"github.com/jmoiron/sqlx"
"github.com/kisielk/sqlstruct"
_ "github.com/mattn/go-sqlite3" // Needed to support sqlite
)
// Match to sqlx
func init() {
sqlstruct.TagName = "db"
}
const (
insertUser = `
INSERT INTO users (id, token, type, affiliation, attributes, state, max_enrollments)
VALUES (:id, :token, :type, :affiliation, :attributes, :state, :max_enrollments);`
deleteUser = `
DELETE FROM users
WHERE (id = ?);`
updateUser = `
UPDATE users
SET token = :token, type = :type, affiliation = :affiliation, attributes = :attributes, state = :state
WHERE (id = :id);`
getUser = `
SELECT * FROM users
WHERE (id = ?)`
insertAffiliation = `
INSERT INTO affiliations (name, prekey)
VALUES (?, ?)`
deleteAffiliation = `
DELETE FROM affiliations
WHERE (name = ?)`
getAffiliation = `
SELECT name, prekey FROM affiliations
WHERE (name = ?)`
)
// UserRecord defines the properties of a user
type UserRecord struct {
Name string `db:"id"`
Pass string `db:"token"`
Type string `db:"type"`
Affiliation string `db:"affiliation"`
Attributes string `db:"attributes"`
State int `db:"state"`
MaxEnrollments int `db:"max_enrollments"`
}
// Accessor implements db.Accessor interface.
type Accessor struct {
db *sqlx.DB
}
// NewDBAccessor is a constructor for the database API
func NewDBAccessor() *Accessor {
return &Accessor{}
}
func (d *Accessor) checkDB() error {
if d.db == nil {
return errors.New("unknown db object, please check SetDB method")
}
return nil
}
// SetDB changes the underlying sql.DB object Accessor is manipulating.
func (d *Accessor) SetDB(db *sqlx.DB) {
d.db = db
}
// InsertUser inserts user into database
func (d *Accessor) InsertUser(user spi.UserInfo) error {
log.Debugf("DB: Add identity %s", user.Name)
err := d.checkDB()
if err != nil {
return err
}
attrBytes, err := json.Marshal(user.Attributes)
if err != nil {
return err
}
res, err := d.db.NamedExec(insertUser, &UserRecord{
Name: user.Name,
Pass: user.Pass,
Type: user.Type,
Affiliation: user.Affiliation,
Attributes: string(attrBytes),
State: user.State,
MaxEnrollments: user.MaxEnrollments,
})
if err != nil {
log.Errorf("Error adding identity %s to the database: %s", user.Name, err)
return err
}
numRowsAffected, err := res.RowsAffected()
if err != nil {
return err
}
if numRowsAffected == 0 {
return fmt.Errorf("Failed to add identity %s to the database", user.Name)
}
if numRowsAffected != 1 {
return fmt.Errorf("Expected to add one record to the database, but %d records were added", numRowsAffected)
}
log.Debugf("Successfully added Identity %s to the database", user.Name)
return nil
}
// DeleteUser deletes user from database
func (d *Accessor) DeleteUser(id string) error {
log.Debugf("DB: Delete identity %s", id)
err := d.checkDB()
if err != nil {
return err
}
_, err = d.db.Exec(deleteUser, id)
if err != nil {
return err
}
return nil
}
// UpdateUser updates user in database
func (d *Accessor) UpdateUser(user spi.UserInfo) error {
log.Debugf("DB: Update identity %s", user.Name)
err := d.checkDB()
if err != nil {
return err
}
attributes, err := json.Marshal(user.Attributes)
if err != nil {
return err
}
res, err := d.db.NamedExec(updateUser, &UserRecord{
Name: user.Name,
Pass: user.Pass,
Type: user.Type,
Affiliation: user.Affiliation,
Attributes: string(attributes),
State: user.State,
MaxEnrollments: user.MaxEnrollments,
})
if err != nil {
log.Errorf("Failed to update identity record [error: %s]", err)
return err
}
numRowsAffected, err := res.RowsAffected()
if numRowsAffected == 0 {
return fmt.Errorf("Failed to update the identity record")
}
if numRowsAffected != 1 {
return fmt.Errorf("Expected one identity record to be updated, but %d records were updated", numRowsAffected)
}
return err
}
// GetUser gets user from database
func (d *Accessor) GetUser(id string, attrs []string) (spi.User, error) {
log.Debugf("DB: Getting identity %s", id)
err := d.checkDB()
if err != nil {
return nil, err
}
var userRec UserRecord
err = d.db.Get(&userRec, d.db.Rebind(getUser), id)
if err != nil {
return nil, err
}
return d.newDBUser(&userRec), nil
}
// GetUserInfo gets user information from database
func (d *Accessor) GetUserInfo(id string) (spi.UserInfo, error) {
log.Debugf("DB: Getting information for identity %s", id)
var userInfo spi.UserInfo
err := d.checkDB()
if err != nil {
return userInfo, err
}
var userRec UserRecord
err = d.db.Get(&userRec, d.db.Rebind(getUser), id)
if err != nil {
return userInfo, err
}
var attributes []api.Attribute
json.Unmarshal([]byte(userRec.Attributes), &attributes)
userInfo.Name = userRec.Name
userInfo.Pass = userRec.Pass
userInfo.Type = userRec.Type
userInfo.Affiliation = userRec.Affiliation
userInfo.State = userRec.State
userInfo.MaxEnrollments = userRec.MaxEnrollments
userInfo.Attributes = attributes
return userInfo, nil
}
// InsertAffiliation inserts affiliation into database
func (d *Accessor) InsertAffiliation(name string, prekey string) error {
log.Debugf("DB: Add affiliation %s", name)
err := d.checkDB()
if err != nil {
return err
}
_, err = d.db.Exec(d.db.Rebind(insertAffiliation), name, prekey)
if err != nil {
return err
}
return nil
}
// DeleteAffiliation deletes affiliation from database
func (d *Accessor) DeleteAffiliation(name string) error {
log.Debugf("DB: Delete affiliation %s", name)
err := d.checkDB()
if err != nil {
return err
}
_, err = d.db.Exec(deleteAffiliation, name)
if err != nil {
return err
}
return nil
}
// GetAffiliation gets affiliation from database
func (d *Accessor) GetAffiliation(name string) (spi.Affiliation, error) {
log.Debugf("DB: Get affiliation %s", name)
err := d.checkDB()
if err != nil {
return nil, err
}
var affiliation spi.AffiliationImpl
err = d.db.Get(&affiliation, d.db.Rebind(getAffiliation), name)
if err != nil {
return nil, err
}
return &affiliation, nil
}
// Creates a DBUser object from the DB user record
func (d *Accessor) newDBUser(userRec *UserRecord) *DBUser {
var user = new(DBUser)
user.Name = userRec.Name
user.Pass = userRec.Pass
user.State = userRec.State
user.MaxEnrollments = userRec.MaxEnrollments
user.Affiliation = userRec.Affiliation
user.Type = userRec.Type
var attrs []api.Attribute
json.Unmarshal([]byte(userRec.Attributes), &attrs)
user.Attributes = attrs
user.attrs = make(map[string]string)
for _, attr := range attrs {
user.attrs[attr.Name] = attr.Value
}
user.db = d.db
return user
}
// DBUser is the databases representation of a user
type DBUser struct {
spi.UserInfo
attrs map[string]string
db *sqlx.DB
}
// GetName returns the enrollment ID of the user
func (u *DBUser) GetName() string {
return u.Name
}
// Login the user with a password
func (u *DBUser) Login(pass string) error {
log.Debugf("DB: Login identity %s with max enrollments of %d and state of %d",
u.Name, u.MaxEnrollments, u.State)
// Check the password
if u.Pass != pass {
return errors.New("Incorrect password")
}
// If the maxEnrollments is set (i.e. >= 0), make sure we haven't exceeded
// this number of logins. The state variable keeps track of the number of
// previously successful logins.
if u.MaxEnrollments >= 0 {
// If maxEnrollments is set to 0, user has unlimited enrollment
if u.MaxEnrollments != 0 {
if u.State >= u.MaxEnrollments {
return fmt.Errorf("No more enrollments left. The maximum number of enrollments is %d",
u.MaxEnrollments)
}
}
// Not exceeded, so attempt to increment the count
state := u.State + 1
res, err := u.db.Exec(u.db.Rebind("UPDATE users SET state = ? WHERE (id = ?)"), state, u.Name)
if err != nil {
return fmt.Errorf("Failed to update state of identity %s to %d: %s",
u.Name, state, err)
}
numRowsAffected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("db.RowsAffected failed: %s", err)
}
if numRowsAffected == 0 {
return fmt.Errorf("no rows were affected when updating the state of identity %s",
u.Name)
}
if numRowsAffected != 1 {
return fmt.Errorf("%d rows were affected when updating the state of identity %s",
numRowsAffected, u.Name)
}
log.Debugf("DB: Successfully incremented state for identity %s to %d",
u.Name, state)
}
log.Debugf("DB: identity %s successfully logged in", u.Name)
return nil
}
// GetAffiliationPath returns the complete path for the user's affiliation.
func (u *DBUser) GetAffiliationPath() []string {
affiliationPath := strings.Split(u.Affiliation, ".")
return affiliationPath
}
// GetAttribute returns the value for an attribute name
func (u *DBUser) GetAttribute(name string) string {
return u.attrs[name]
}