Skip to content

Commit

Permalink
Merge pull request #18 from RafaelClaumann/chapter-17-5-redirect-user…
Browse files Browse the repository at this point in the history
…-approprietaly-after-login

Chapter 17.5 Redirect user appropriately after login
  • Loading branch information
RafaelClaumann authored Jun 13, 2024
2 parents d2b92f9 + 77d9ba7 commit de72262
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
10 changes: 9 additions & 1 deletion cmd/web/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,15 @@ func (app *application) userLoginPost(w http.ResponseWriter, r *http.Request) {
// Add the ID of the current user to the session, so that they are now 'logged in'.
app.sessionManager.Put(r.Context(), "authenticatedUserID", id)

// Redirect the user to the create snippet page.
// Use the PopString method to retrieve and remove a value from the session
// data in one step.
// If no matching key exists this will return the empty string.
path := app.sessionManager.PopString(r.Context(), "redirectPathAfterLogin")
if path != "" {
http.Redirect(w, r, path, http.StatusSeeOther)
return
}

http.Redirect(w, r, "/snippet/create", http.StatusSeeOther)
}

Expand Down
2 changes: 2 additions & 0 deletions cmd/web/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ func (app *application) requireAuthentication(next http.Handler) http.Handler {
// return from the middleware chain so that no subsequent handlers in
// the chain are executed.
if !app.isAuthenticated(r) {
// add redirectPathAfterLogin to redirect unauthenticated users correctly after login
app.sessionManager.Put(r.Context(), "redirectPathAfterLogin", r.URL.Path)
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
return
}
Expand Down

0 comments on commit de72262

Please sign in to comment.