feat: password reset, activate token resend

This commit is contained in:
2026-05-04 09:28:28 +02:00
parent 0bbc76be1d
commit 5eafa5c1d6
8 changed files with 185 additions and 1 deletions
+1
View File
@@ -29,6 +29,7 @@ func (app *application) routes() http.Handler {
router.HandlerFunc(http.MethodPost, "/v1/tokens/authentication", app.createAuthenticationTokenHandler)
router.HandlerFunc(http.MethodPost, "/v1/tokens/password-reset", app.createPasswordResetTokenHandler)
router.HandlerFunc(http.MethodPost, "/v1/tokens/activation", app.createActivationTokenHandler)
router.Handler(http.MethodGet, "/debug/vars", expvar.Handler())
+70
View File
@@ -148,3 +148,73 @@ func (app *application) createPasswordResetTokenHandler(w http.ResponseWriter, r
app.serverErrorResponse(w, r, err)
}
}
func (app *application) createActivationTokenHandler(w http.ResponseWriter, r *http.Request) {
// Parse and validate the user's email address.
var input struct {
Email string `json:"email"`
}
err := app.readJSON(w, r, &input)
if err != nil {
app.badRequestResponse(w, r, err)
return
}
v := validator.New()
if data.ValidateEmail(v, input.Email); !v.Valid() {
app.failedValidationResponse(w, r, v.Errors)
return
}
// Try to retrieve the corresponding user record for the email address. If it can't
// be found, return an error message to the client.
user, err := app.models.Users.GetByEmail(input.Email)
if err != nil {
switch {
case errors.Is(err, data.ErrRecordNotFound):
v.AddError("email", "no matching email address found")
app.failedValidationResponse(w, r, v.Errors)
default:
app.serverErrorResponse(w, r, err)
}
return
}
// Return an error if the user has already been activated.
if user.Activated {
v.AddError("email", "user has already been activated")
app.failedValidationResponse(w, r, v.Errors)
return
}
// Otherwise, create a new activation token.
token, err := app.models.Tokens.New(user.ID, 3*24*time.Hour, data.ScopeActivation)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
// Email the user with their additional activation token.
app.background(func() {
data := map[string]interface{}{
"activationToken": token.Plaintext,
}
// Since email addresses MAY be case sensitive, notice that we are sending this
// email using the address stored in our database for the user --- not to the
// input.Email address provided by the client in this request.
err = app.mailer.Send(user.Email, "token_activation.tmpl", data)
if err != nil {
app.logger.PrintError(err, nil)
}
})
// Send a 202 Accepted response and confirmation message to the client.
env := envelope{"message": "an email will be sent to you containing activation instructions"}
err = app.writeJSON(w, http.StatusAccepted, env, nil)
if err != nil {
app.serverErrorResponse(w, r, err)
}
}