~evanj/cms

ref: afc228cb59683180b3b2957aceb6bf1aa0bf0d0e cms/internal/s/db/user.go -rw-r--r-- 6.8 KiB
afc228cbEvan J Feat(db): Tweaking db.SetMaxOpenConns, db.SetMaxIdleConns, and 1 year, 20 days ago
                                                                                
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
package db

import (
	"database/sql"
	"fmt"

	"git.sr.ht/~evanj/cms/internal/m/org"
	"git.sr.ht/~evanj/cms/internal/m/role"
	"git.sr.ht/~evanj/cms/internal/m/user"
	"git.sr.ht/~evanj/security"
)

type User struct {
	// Stored in DB.
	UserID    string
	UserName  string
	UserOrg   Org
	UserRole  Role
	userHash  string
	userEmail sql.NullString
	// Set on read.
	userToken string
}

// SQL QUERIES

var (
	queryCreateNewUser = `INSERT INTO cms_user (NAME, HASH, ORG_ID, ROLE_ID) VALUES (?, ?, ?, (SELECT cms_role.ID FROM cms_role WHERE VALUE=?))`

	queryFindUserByID = `
		SELECT cms_user.ID, NAME, HASH, EMAIL, cms_org.ID, cms_billing.TIER_NAME, cms_billing.PAYMENT_CUSTOMER, cms_role.ID, cms_role.VALUE
		FROM cms_user 
		JOIN cms_org ON cms_org.ID=cms_user.ORG_ID
		join cms_role ON cms_role.ID=cms_user.ROLE_ID
		LEFT JOIN cms_billing ON cms_billing.ORG_ID=cms_org.ID
		LEFT JOIN cms_email ON cms_email.USER_ID=cms_user.ID 
		WHERE cms_user.ID = ?
	`

	queryFindUserByName = `
		SELECT cms_user.ID, NAME, HASH, EMAIL, cms_org.ID, cms_billing.TIER_NAME, cms_billing.PAYMENT_CUSTOMER, cms_role.ID, cms_role.VALUE
		FROM cms_user 
		JOIN cms_org ON cms_org.ID=cms_user.ORG_ID
		join cms_role ON cms_role.ID=cms_user.ROLE_ID
		LEFT JOIN cms_billing ON cms_billing.ORG_ID=cms_org.ID
		LEFT JOIN cms_email ON cms_email.USER_ID=cms_user.ID 
		WHERE NAME = ?
	`
)

func (db *DB) UserNew(username, password, verifyPassword string) (user.User, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	user, err := db.userNew(t, username, password, verifyPassword)
	if err != nil {
		return nil, err
	}

	return user, t.Commit()
}

func (db *DB) userNewGeneratePassword(username, password, verifyPassword string) (string, error) {
	if password == "" {
		return "", fmt.Errorf("no password entered")
	}

	if password != verifyPassword {
		return "", fmt.Errorf("passwords do not match")
	}

	hash, err := db.sec.HashCreate(username, password)
	if err != nil {
		return "", fmt.Errorf("failed to create password hash")
	}

	return hash, nil
}

func (db *DB) userNew(t *sql.Tx, username, password, verifyPassword string) (user.User, error) {
	hash, err := db.userNewGeneratePassword(username, password, verifyPassword)
	if err != nil {
		return nil, err
	}

	org, err := db.orgNew(t)
	if err != nil {
		return nil, err
	}

	if _, err := t.Exec(queryCreateNewUser, username, hash, org.ID(), role.Admin.Name); err != nil {
		return nil, fmt.Errorf("user '%s' already exists", username)
	}

	return db.userGet(t, username, password)
}

func (db *DB) UserGet(username, password string) (user.User, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	user, err := db.userGet(t, username, password)
	if err != nil {
		return nil, err
	}

	return user, t.Commit()
}

func (db *DB) userGet(t *sql.Tx, username, password string) (user.User, error) {
	var user User
	if err := t.QueryRow(queryFindUserByName, username).Scan(
		&user.UserID, &user.UserName, &user.userHash, &user.userEmail,
		&user.UserOrg.OrgID, &user.UserOrg.OrgBillingTierName, &user.UserOrg.OrgPaymentCustomer,
		&user.UserRole.RoleID, &user.UserRole.RoleName,
	); err != nil {
		return nil, fmt.Errorf("failed to find user '%s'", username)
	}

	if err := db.sec.HashCompare(username, password, user.userHash); err != nil {
		return nil, fmt.Errorf("incorrect password")
	}

	tok, err := db.sec.TokenCreate(security.TokenMap{"ID": user.UserID})
	if err != nil {
		return nil, fmt.Errorf("failed to create token for user")
	}

	user.userToken = tok
	return &user, nil
}

func (db *DB) UserGetFromToken(token string) (user.User, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	user, err := db.userGetFromToken(t, token)
	if err != nil {
		return nil, err
	}

	return user, t.Commit()
}

func (db *DB) userGetFromToken(t *sql.Tx, token string) (user.User, error) {
	tmap, err := db.sec.TokenFrom(token)
	if err != nil {
		return nil, fmt.Errorf("failed to decode user token")
	}

	id, ok := tmap["ID"]
	if !ok {
		return nil, fmt.Errorf("corrupted user token")
	}

	var user User
	if err := t.QueryRow(queryFindUserByID, id).Scan(
		&user.UserID, &user.UserName, &user.userHash, &user.userEmail,
		&user.UserOrg.OrgID, &user.UserOrg.OrgBillingTierName, &user.UserOrg.OrgPaymentCustomer,
		&user.UserRole.RoleID, &user.UserRole.RoleName,
	); err != nil {

		fmt.Println(err)
		return nil, fmt.Errorf("failed to find user")
	}

	tok, err := db.sec.TokenCreate(security.TokenMap{"ID": user.UserID})
	if err != nil {
		return nil, fmt.Errorf("failed to create token for user")
	}

	user.userToken = tok
	return &user, nil
}

func (db *DB) UserSetEmail(u user.User, email string) (user.User, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	user, err := db.userSetEmail(t, u, email)
	if err != nil {
		return nil, err
	}

	return user, t.Commit()
}

func (db *DB) userSetEmail(t *sql.Tx, u user.User, email string) (user.User, error) {
	q := "INSERT INTO cms_email (EMAIL, USER_ID) VALUES (?, ?)"
	if _, err := t.Exec(q, email, u.ID()); err != nil {
		return nil, err
	}
	return db.userGetFromToken(t, u.Token())
}

func (db *DB) UserSetPassword(u user.User, current, password, verifyPassword string) (user.User, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	user, err := db.userSetPassword(t, u, current, password, verifyPassword)
	if err != nil {
		return nil, err
	}

	return user, t.Commit()
}

func (db *DB) userSetPassword(t *sql.Tx, u user.User, current, password, verifyPassword string) (user.User, error) {
	var currentHash string
	if err := t.QueryRow("SELECT HASH FROM cms_user WHERE ID=?", u.ID()).Scan(&currentHash); err != nil {
		return nil, err
	}

	if err := db.sec.HashCompare(u.Name(), current, currentHash); err != nil {
		return nil, fmt.Errorf("your previous password is incorrect")
	}

	if password == current {
		return nil, fmt.Errorf("this is already your password")
	}
	if password == "" {
		return nil, fmt.Errorf("no password entered")
	}
	if password != verifyPassword {
		return nil, fmt.Errorf("passwords do not match")
	}

	hash, err := db.sec.HashCreate(u.Name(), password)
	if err != nil {
		return nil, fmt.Errorf("failed to create password hash")
	}

	if _, err := t.Exec("UPDATE cms_user SET HASH=? WHERE ID=?", hash, u.ID()); err != nil {
		return nil, err
	}

	return db.userGet(t, u.Name(), password)
}

func (u *User) ID() string     { return u.UserID }
func (u *User) Name() string   { return u.UserName }
func (u *User) Token() string  { return u.userToken }
func (u *User) Org() org.Org   { return u.UserOrg }
func (u *User) HasEmail() bool { return u.userEmail.Valid }
func (u *User) Email() string  { return u.userEmail.String }

func (u *User) Role() role.Role {
	// NOTE: Guaranteed to have this set appropriately.
	r, _ := role.ByName(u.UserRole.RoleName)
	return r
}