-
Notifications
You must be signed in to change notification settings - Fork 2
/
ResetRepoSql.go
337 lines (268 loc) · 8.11 KB
/
ResetRepoSql.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
// Copyright 2019 Reaction Engineering International. All rights reserved.
// Use of this source code is governed by the MIT license in the file LICENSE.txt.
package passwords
import (
"github.com/reaction-eng/restlib/configuration"
"github.com/reaction-eng/restlib/email"
"database/sql"
"errors"
"log"
"time"
)
/**
Define a struct for Repo for use with users
*/
type ResetRepoSql struct {
//Hold on to the sql databased
db *sql.DB
//Also store the table name
tableName string
//We need the emailer
emailer email.Interface
resetEmailConfig PasswordResetConfig
activationEmailConfig PasswordResetConfig
//Store the required statements to reduce comput time
addRequestStatement *sql.Stmt
getRequestStatement *sql.Stmt
rmRequestStatement *sql.Stmt
}
/**
Store the type of token
*/
type tokenType int
const (
activation tokenType = 1
reset tokenType = 2
)
//Provide a method to make a new UserRepoSql
func NewRepoMySql(db *sql.DB, tableName string, emailer email.Interface, configFile string) *ResetRepoSql {
//Create a config
config, err := configuration.NewConfiguration(configFile)
//If there is no error
if err != nil {
log.Fatal(err)
}
//Build a reset and activation config
resetEmailConfig := PasswordResetConfig{}
activationEmailConfig := PasswordResetConfig{}
//Pull from the config
config.GetStruct("password_reset", &resetEmailConfig)
config.GetStruct("user_activation", &activationEmailConfig)
//Define a new repo
newRepo := ResetRepoSql{
db: db,
tableName: tableName,
emailer: emailer,
resetEmailConfig: resetEmailConfig,
activationEmailConfig: activationEmailConfig,
}
//Create the table if it is not already there
//Create a table
_, err = db.Exec("CREATE TABLE IF NOT EXISTS " + tableName + "(id int NOT NULL AUTO_INCREMENT, userId int, email TEXT, token TEXT, issued DATE, type INT, PRIMARY KEY (id) )")
if err != nil {
log.Fatal(err)
}
//Add request data to table
addRequest, err := db.Prepare("INSERT INTO " + tableName + "(userId,email, token, issued, type) VALUES (?, ?, ?, ?, ?)")
//Check for error
if err != nil {
log.Fatal(err)
}
//Store it
newRepo.addRequestStatement = addRequest
//pull the request from the table
getRequest, err := db.Prepare("SELECT * FROM " + tableName + " where userId = ? AND token = ? AND type = ?")
//Check for error
if err != nil {
log.Fatal(err)
}
//Store it
newRepo.getRequestStatement = getRequest
//pull the request from the table
rmRequest, err := db.Prepare("delete FROM " + tableName + " where id = ? limit 1")
//Check for error
if err != nil {
log.Fatal(err)
}
//Store it
newRepo.rmRequestStatement = rmRequest
//Return a point
return &newRepo
}
//Provide a method to make a new UserRepoSql
func NewRepoPostgresSql(db *sql.DB, tableName string, emailer email.Interface, configFile ...string) *ResetRepoSql {
//Create a config
config, err := configuration.NewConfiguration(configFile...)
//If there is no error
if err != nil {
log.Fatal(err)
}
//Build a reset and activation config
resetEmailConfig := PasswordResetConfig{}
activationEmailConfig := PasswordResetConfig{}
//Pull from the config
config.GetStruct("password_reset", &resetEmailConfig)
config.GetStruct("user_activation", &activationEmailConfig)
//Define a new repo
newRepo := ResetRepoSql{
db: db,
tableName: tableName,
emailer: emailer,
resetEmailConfig: resetEmailConfig,
activationEmailConfig: activationEmailConfig,
}
//Create the table if it is not already there
//Create a table
_, err = db.Exec("CREATE TABLE IF NOT EXISTS " + tableName + "(id SERIAL PRIMARY KEY, userId int NOT NULL, email TEXT NOT NULL, token TEXT NOT NULL,issued DATE NOT NULL, type int NOT NULL)")
if err != nil {
log.Fatal(err)
}
//Add request data to table
addRequest, err := db.Prepare("INSERT INTO " + tableName + "(userId,email, token, issued, type) VALUES ($1, $2, $3, $4, $5)")
//Check for error
if err != nil {
log.Fatal(err)
}
//Store it
newRepo.addRequestStatement = addRequest
//pull the request from the table
getRequest, err := db.Prepare("SELECT * FROM " + tableName + " where userId = $1 AND token = $2 AND type = $3")
//Check for error
if err != nil {
log.Fatal(err)
}
//Store it
newRepo.getRequestStatement = getRequest
//pull the request from the table
rmRequest, err := db.Prepare("delete FROM " + tableName + " where id = $1")
//Check for error
if err != nil {
log.Fatal(err)
}
//Store it
newRepo.rmRequestStatement = rmRequest
//Return a point
return &newRepo
}
/**
Look up the user and return if they were found
*/
func (repo *ResetRepoSql) IssueResetRequest(token string, userId int, emailAddress string) error {
//Now add it to the database
//Add the info
//execute the statement//(userId,name,input,flow)- "(userId,email, token, issued)
_, err := repo.addRequestStatement.Exec(userId, emailAddress, token, time.Now(), reset)
//Make the email header
header := email.HeaderInfo{
Subject: repo.resetEmailConfig.Subject,
To: []string{emailAddress},
}
//Build a reset token
resetInfo := PasswordResetInfo{
Token: token,
Email: emailAddress,
}
//Now email
err = repo.emailer.SendEmailTemplateFile(&header, repo.resetEmailConfig.Template, resetInfo, nil)
//Return the user calcs
return err
}
/**
Look up the user and return if they were found
*/
func (repo *ResetRepoSql) IssueActivationRequest(token string, userId int, emailAddress string) error {
//Now add it to the database
//Add the info
//execute the statement//(userId,name,input,flow)- "(userId,email, token, issued)
_, err := repo.addRequestStatement.Exec(userId, emailAddress, token, time.Now(), activation)
//Make the email header
header := email.HeaderInfo{
Subject: repo.activationEmailConfig.Subject,
To: []string{emailAddress},
}
//Build a reset token
resetInfo := PasswordResetInfo{
Token: token,
Email: emailAddress,
}
//Now email
err = repo.emailer.SendEmailTemplateFile(&header, repo.activationEmailConfig.Template, resetInfo, nil)
//Return the user calcs
return err
}
/**
Use the taken to validate
*/
func (repo *ResetRepoSql) CheckForResetToken(userId int, token string) (int, error) {
//Get the id and errors
id, err := repo.checkForToken(userId, token, reset)
//If there is an error customize it
if err != nil {
err = errors.New("password_change_forbidden")
}
return id, err
}
/**
Use the taken to validate
*/
func (repo *ResetRepoSql) CheckForActivationToken(userId int, token string) (int, error) {
//Get the id and errors
id, err := repo.checkForToken(userId, token, activation)
//If there is an error customize it
if err != nil {
err = errors.New("activation_forbidden")
}
return id, err
}
/**
Use the taken to validate
*/
func (repo *ResetRepoSql) checkForToken(userId int, token string, tkType tokenType) (int, error) {
//Prepare to get values
//id, userId int, email TEXT, token TEXT, issued DATE,
var id int
var userIdDB int
var emailDB string
var tokenDB string
var issued time.Time
var tokenDb tokenType
//Get the value
err := repo.getRequestStatement.QueryRow(userId, token, tkType).Scan(&id, &userIdDB, &emailDB, &tokenDB, &issued, &tokenDb)
//So it was correct, check the date
//TODO: check the date
//If there is an error, assume it can't be done
if err != nil {
return -1, errors.New("invalid_token")
}
//Make sure the user id and token match
if userId != userIdDB || tokenDB != token {
return -1, errors.New("invalid_token")
}
//Return the user calcs
return id, nil
}
func (repo *ResetRepoSql) UseToken(id int) error {
//Remove the token
_, err := repo.rmRequestStatement.Exec(id)
if err != nil {
return err
}
return nil
}
/**
Clean up the database, nothing much to do
*/
func (repo *ResetRepoSql) CleanUp() {
repo.getRequestStatement.Close()
repo.addRequestStatement.Close()
repo.rmRequestStatement.Close()
}
//func RepoDestroyCalc(id int) error {
// for i, t := range usersList {
// if t.Id == id {
// usersList = append(usersList[:i], usersList[i+1:]...)
// return nil
// }
// }
// return fmt.Errorf("Could not find Todo with id of %d to delete", id)
//}