Skip to content

Commit

Permalink
feat: add activation token resend
Browse files Browse the repository at this point in the history
  • Loading branch information
WannaFight committed Apr 14, 2024
1 parent 6959a12 commit 49b0dfe
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmd/api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func (app *application) routes() http.Handler {
router.HandlerFunc(http.MethodPut, "/v1/users/password", app.updateUserPasswordHandler)

router.HandlerFunc(http.MethodPost, "/v1/tokens/authentication", app.createAuthenticationTokenHandler)
router.HandlerFunc(http.MethodPost, "/v1/tokens/activation", app.createActivationTokenHandler)
router.HandlerFunc(http.MethodPost, "/v1/tokens/password-reset", app.createPasswordResetTokenHandler)

router.Handler(http.MethodGet, "/debug/vars", expvar.Handler())
Expand Down
62 changes: 62 additions & 0 deletions cmd/api/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,65 @@ func (app *application) createPasswordResetTokenHandler(w http.ResponseWriter, r
app.serverErrorResponse(w, r, err)
}
}

func (app *application) createActivationTokenHandler(w http.ResponseWriter, r *http.Request) {
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
}

if user.Activated {
v.AddError("email", "user is already activated")
app.failedValidationResponse(w, r, v.Errors)
return
}

token, err := app.models.Tokens.New(user.ID, 3*24*time.Hour, data.ScopeActivation)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}

app.background(func() {
data := map[string]any{
"activationToken": token.PLaintext,
"userID": user.ID,
}
err = app.mailer.Send(user.Email, "user_welcome.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)
}
}

0 comments on commit 49b0dfe

Please sign in to comment.