Let's Go User authentication › User logout
Previous · Contents · Next
Chapter 10.5.

User logout

This brings us nicely to logging out a user. Implementing the user logout is straightforward in comparison to the signup and login — essentially all we need to do is remove the "authenticatedUserID" value from their session.

At the same time it’s good practice to renew the session ID again, and we’ll also add a flash message to the session data to confirm to the user that they’ve been logged out.

Let’s update the userLogoutPost handler to do exactly that.

File: cmd/web/handlers.go
package main

...

func (app *application) userLogoutPost(w http.ResponseWriter, r *http.Request) {
    // Use the RenewToken() method on the current session to change the session
    // ID again.
    err := app.sessionManager.RenewToken(r.Context())
    if err != nil {
        app.serverError(w, r, err)
        return
    }

    // Remove the authenticatedUserID from the session data so that the user is
    // 'logged out'.
    app.sessionManager.Remove(r.Context(), "authenticatedUserID")

    // Add a flash message to the session to confirm to the user that they've been
    // logged out.
    app.sessionManager.Put(r.Context(), "flash", "You've been logged out successfully!")

    // Redirect the user to the application home page.
    http.Redirect(w, r, "/", http.StatusSeeOther)
}

Save the file and restart the application. If you now click the ‘Logout’ link in the navigation bar you should be logged out and redirected to the homepage like so:

10.05-01.png