Start learning free

LESSON 93 OF 173 · BACKEND: USERS AND SECURITY

Log Out in Go

Practice

Logging out has to happen on the server. If only the browser forgot the token, anyone who had copied it could still use it. So POST /logout deletes the request's token from the tokens table. After that the shop doesn't know that token, and it gets 401 everywhere.

To delete the token, the route needs the token itself, not just the user: a user who logged in twice has two tokens. So the lines that find it (the header first, then the cookie) move into a function of their own, currentToken(r), which both currentUser and logout call.

A DELETE is a query like the others, run with db.Exec. To clear a cookie, send it again with MaxAge: -1, which tells the browser to drop it. For example, a route that empties a user's cart and forgets a "cart" cookie could run:

db.Exec("DELETE FROM cart_items WHERE user_id = ?", user.ID)
http.SetCookie(w, &http.Cookie{Name: "cart", Value: "", Path: "/", MaxAge: -1})

In the tests, Ana logs in twice: first on her phone (token <phone>, sent in the header), then in the browser (token <token>, also kept in the session cookie). Logging out in the browser must not log the phone out:

GET /me  (cookie)  →  200  {"email": "ana@example.com", "id": 2, "role": "customer"}
POST /logout  (cookie)  →  200  {"message": "Logged out"}
GET /me  (cookie)  →  401  {"error": "Login required"}
GET /me  (Bearer <token>)  →  401  {"error": "Login required"}
GET /me  (Bearer <phone>)  →  200  {"email": "ana@example.com", "id": 2, "role": "customer"}
POST /logout  (Bearer <phone>)  →  200  {"message": "Logged out"}
GET /me  (Bearer <phone>)  →  401  {"error": "Login required"}

Your task: move the token-finding lines into currentToken(r), build currentUser's query on top of it, and add POST /logout behind loginRequired: logout deletes this request's token, clears the "session" cookie and answers {"message": "Logged out"}.


Assignment
Follow the Coding Tutorial to add a /logout route that really logs the user out.


Hint
Until currentToken ends with return token, Go answers missing return and the app doesn't start. logout takes w, r and user because loginRequired passes them, even though it doesn't use user. Answer last: once writeJSON has sent the status, a cookie set after it never reaches the browser.


STEP 1 OF 12
    Ctrl + Enter to check

    Auth Logout in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free