Start learning free

LESSON 89 OF 173 · BACKEND: USERS AND SECURITY

Who Am I? in Go

Practice

After logging in, a client holds a token. On every later request it sends the token back in the Authorization header, written as the word Bearer, a space, then the token. The shop looks the token up in the tokens table to find out who is calling.

Many handlers will need that answer, so the lookup goes in a helper function that any handler can call. Two tools help: r.Header.Get gives an empty string "" for a missing header, and a JOIN goes from a row in one table to the row it points to in another. Both on a made-up example:

lang := r.Header.Get("Accept-Language")      // "" when the header is missing
short := strings.ReplaceAll(lang, "-US", "")  // "en-US" becomes "en"
var name string
db.QueryRow("SELECT products.name FROM orders JOIN products ON products.id = orders.product_id WHERE orders.id = ?", 5).Scan(&name)

When no row matches, Scan changes nothing. A new User starts with ID 0, and no real user has that id, so a User with ID 0 means: nobody is logged in.

GET /me answers the logged-in user's id and email. With no token, or a token the shop never gave out, it answers 401. Below, <token> and <token2> stand for the random tokens the logins answered:

POST /register  {"email": "ana@example.com", "password": "secret123"}  →  201  {"email": "ana@example.com", "id": 1}
POST /register  {"email": "ben@example.com", "password": "tea4two"}    →  201  {"email": "ben@example.com", "id": 2}
POST /login  {"email": "ana@example.com", "password": "secret123"}  →  200  {"token": "<token>"}
POST /login  {"email": "ben@example.com", "password": "tea4two"}    →  200  {"token": "<token2>"}
GET /me  Authorization: Bearer <token>   →  200  {"email": "ana@example.com", "id": 1}
GET /me  Authorization: Bearer <token2>  →  200  {"email": "ben@example.com", "id": 2}
GET /me  (no header)  →  401  {"error": "Login required"}
GET /me  Authorization: Bearer 0123456789abcdef0123456789abcdef  →  401  {"error": "Login required"}

Your task: below newApp, write a helper currentUser(r *http.Request) User that reads the token from the Authorization header and returns its user's id and email, or a User with ID 0. Then add the GET /me handler: answer {"error": "Login required"} with 401 when user.ID is 0, otherwise the user as JSON.


Assignment
Follow the Coding Tutorial to write the currentUser helper and the GET /me handler that uses it.


Hint
A missing header gives "", so strings.ReplaceAll works on it too. An empty or unknown token matches no row, so user.ID stays 0: that is the 401 case. Put a return after the 401 so the handler stops there.


STEP 1 OF 12
    Ctrl + Enter to check

    Auth Me 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