/
users.go
208 lines (195 loc) · 6.96 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
package main
import (
"errors"
"net/http"
"time"
"github.com/shakilbd009/go-greenlight-api/internal/data"
"github.com/shakilbd009/go-greenlight-api/internal/validator"
)
// Verify 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"`
}
if err := app.readJSON(w, r, &input); 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)
}
}
// Set the new password for the user.
if err := user.Password.Set(input.Password); err != nil {
app.serverErrorResponse(w, r, err)
return
}
// Save the updated user record in our database, checking for any edit conflicts as // normal.
if err := app.models.Users.Update(user); 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.
if err := app.models.Tokens.DeleteAllForUser(data.ScopePasswordReset, user.ID); 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)
}
}
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"`
}
if err := app.readJSON(w, r, &input); err != nil {
app.badRequestResponse(w, r, err)
return
}
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 (which we will create in a minute). 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
}
user.Activated = true
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
}
err = app.models.Tokens.DeleteAllForUser(data.ScopeActivation, user.ID)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
err = app.writeJSON(w, http.StatusOK, envelope{"user": user}, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}
}
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 therequest 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
}
return
}
if err := app.models.Permissions.AddForUser(user.ID, "movies:read"); 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
}
// Call the Send() method on our Mailer, passing in the user's email address,
// name of the template file, and the User struct containing the new user's data.
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}
if err := app.mailer.Send(user.Email, "user_welcome.tmpl", data); 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)
}
})
//note that we also change this to send the client a 202 Accepted status code.
//this indicates, request has been accepted for processing.
//but the processing is not completed.
err = app.writeJSON(w, http.StatusAccepted, envelope{"user": user}, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}
}