- Create a
tokens
table in the database with two columns:token
text field, primary keyuser_id
foreign key to theusers
table
- In the
POST /login
request handler, after checking the user name and the password, generate a new token. It can be done using theuuid
Node module (https://github.com/uuidjs/uuid). The token will look something like1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed
. - Insert the new token into the
tokens
table. - Include the token in the JSON object in the HTTP response.
- The frontend should store the token in the global state (the same way it already stores other user parameters).
- When the frontend sends a HTTP request to a protected endpoint, it should include the token in the Authorization
header in the format
Authorization: Token 1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed
. Usingfetch
it looks something likefetch("/api/myresource/", { headers: {"Authorization": `Token ${token}`} })
- The request handler can access the Authorization header as
req.headers.authorization
. If the frontend doesn't send the header, the backend should respond with401 Unauthorized
status. - As the header's value is in the format
Token 1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed
, split the string at the white space character to get the token. If the header is in the wrong format, return400 Bad Request
status. - Create a function that selects the user from the database based on the received token. It can be done by joining
the
tokens
andusers
tables together. - If the query doesn't return a user then the backend should respond with
401 Unauthorized
status. Otherwise, the returned user ID can be used to proceed with the request and select the user's private data from the database.
- On the frontend, store the token in a cookie or in the local storage, and when the site is loading, check if a token has already been saved. This way users wouldn't have to log in every time they open the website.
- On the backend, add the token's creation date/time to the
tokens
table. When the frontend sends a HTTP request with a token, make sure that it hasn't expired. The expiry time can be e.g. one week. If the token expired, the frontend should redirect the user to the login page.