/
users.go
260 lines (226 loc) · 7.48 KB
/
users.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
package main
import (
"errors"
"net/http"
"time"
"github.com/cedrickchee/skel/internal/data"
"github.com/cedrickchee/skel/internal/validator"
)
func (app *application) registerUserHandler(w http.ResponseWriter, r *http.Request) {
// Create an anonymous struct to hold the expected data from the request
// body.
var input struct {
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
}
// Parse the request body into the anonymous struct.
err := app.readJSON(w, r, &input)
if err != nil {
app.badRequestResponse(w, r, err)
return
}
// Copy the data from the request body into a new User struct. Notice also
// that we set the Activated field to false, which isn't strictly necessary
// because the Activated field will have the zero-value of false by default.
// But setting this explicitly helps to make our intentions clear to anyone
// reading the code.
user := &data.User{
Name: input.Name,
Email: input.Email,
Activated: false,
}
// Use the Password.Set() method to generate and store the hashed and
// plaintext passwords.
err = user.Password.Set(input.Password)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
v := validator.New()
// Validate the user struct and return the error messages to the client if
// any of the checks fail.
if data.ValidateUser(v, user); !v.Valid() {
app.failedValidationResponse(w, r, v.Errors)
return
}
// Insert the user data into the database.
err = app.models.Users.Insert(user)
if err != nil {
switch {
// If we get a ErrDuplicateEmail error, use the v.AddError() method to
// manually add a message to the validator instance, and then call our
// failedValidationResponse() helper.
case errors.Is(err, data.ErrDuplicateEmail):
v.AddError("email", "a user with this email address already exists")
app.failedValidationResponse(w, r, v.Errors)
default:
app.serverErrorResponse(w, r, err)
}
return
}
// Add the "movies:read" permission for the new user.
err = app.models.Permissions.AddForUser(user.ID, "movies:read")
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
// After the user record has been created in the database, generate a new
// activation token for the user.
token, err := app.models.Tokens.New(user.ID, 3*24*time.Hour, data.ScopeActivation)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
// Use the background helper to execute an anonymous function that sends the
// welcome email.
app.background(func() {
// As there are now multiple pieces of data that we want to pass to our
// email templates, we create a map to act as a 'holding structure' for
// the data. This contains the plaintext version of the activation token
// for the user, along with their ID.
data := map[string]interface{}{
"activationToken": token.Plaintext,
"userID": user.ID,
}
// Send the welcome email, passing in the map above as dynamic data.
err = app.mailer.Send(user.Email, "user_welcome.tmpl", data)
if err != nil {
// Importantly, if there is an error sending the email then we use
// the app.logger.PrintError() helper to manage it, instead of the
// app.serverErrorResponse() helper like before.
app.logger.PrintError(err, nil)
}
})
// Write a JSON response containing the user data along with a 202 Accepted
// status code. This status code indicates that the request has been
// accepted for processing, but the processing has not been completed.
err = app.writeJSON(w, http.StatusAccepted, envelope{"user": user}, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}
}
func (app *application) activateUserHandler(w http.ResponseWriter, r *http.Request) {
// Parse the plaintext activation token from the request body.
var input struct {
TokenPlaintext string `json:"token"`
}
err := app.readJSON(w, r, &input)
if err != nil {
app.badRequestResponse(w, r, err)
return
}
// Validate the plaintext token provided by the client.
v := validator.New()
if data.ValidateTokenPlaintext(v, input.TokenPlaintext); !v.Valid() {
app.failedValidationResponse(w, r, v.Errors)
return
}
// Retrieve the details of the user associated with the token using the
// GetForToken() method. If no matching record is found, then we let the
// client know that the token they provided is not valid.
user, err := app.models.Users.GetForToken(data.ScopeActivation, input.TokenPlaintext)
if err != nil {
switch {
case errors.Is(err, data.ErrRecordNotFound):
v.AddError("token", "invalid or expired activation token")
app.failedValidationResponse(w, r, v.Errors)
default:
app.serverErrorResponse(w, r, err)
}
return
}
// Update the user's activation status.
user.Activated = true
// Save the updated user record in our database, checking for any edit
// conflicts in the same way that we did for our movie records.
err = app.models.Users.Update(user)
if err != nil {
switch {
case errors.Is(err, data.ErrEditConflict):
app.editConflictResponse(w, r)
default:
app.serverErrorResponse(w, r, err)
}
return
}
// If everything went successfully, then we delete all activation tokens for
// the user.
err = app.models.Tokens.DeleteAllForUser(data.ScopeActivation, user.ID)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
// Send the updated user details to the client in a JSON response.
err = app.writeJSON(w, http.StatusOK, envelope{"user": user}, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}
}
// updateUserPasswordHandler verifies the password reset token and set a new
// password for the user.
func (app *application) updateUserPasswordHandler(w http.ResponseWriter, r *http.Request) {
// Parse and validate the user's new password and password reset token.
var input struct {
Password string `json:"password"`
TokenPlaintext string `json:"token"`
}
err := app.readJSON(w, r, &input)
if err != nil {
app.badRequestResponse(w, r, err)
return
}
v := validator.New()
data.ValidatePasswordPlaintext(v, input.Password)
data.ValidateTokenPlaintext(v, input.TokenPlaintext)
if !v.Valid() {
app.failedValidationResponse(w, r, v.Errors)
return
}
// Retrieve the details of the user associated with the password reset
// token, returning an error message if no matching record was found.
user, err := app.models.Users.GetForToken(data.ScopePasswordReset, input.TokenPlaintext)
if err != nil {
switch {
case errors.Is(err, data.ErrRecordNotFound):
v.AddError("token", "invalid or expired password reset token")
app.failedValidationResponse(w, r, v.Errors)
default:
app.serverErrorResponse(w, r, err)
}
return
}
// Set the new password for the user.
err = user.Password.Set(input.Password)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
// Save the updated user record in our database, checking for any edit
// conflicts as normal.
err = app.models.Users.Update(user)
if err != nil {
switch {
case errors.Is(err, data.ErrEditConflict):
app.editConflictResponse(w, r)
default:
app.serverErrorResponse(w, r, err)
}
return
}
// If everything was successful, then delete all password reset tokens for
// the user.
err = app.models.Tokens.DeleteAllForUser(data.ScopePasswordReset, user.ID)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
// Send the user a confirmation message.
env := envelope{
"message": "your password was successfully reset",
}
err = app.writeJSON(w, http.StatusOK, env, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}
}