Getting Authenticated User - Planning

Refer back to Chapter 6, The Bookstore API Endpoint Specifications, API Endpoint #4: Get Authenticated User section for the API endpoint specifications.

1 - Route Name

Now things are starting to get interesting, because recall that we just broke Guideline #4: Avoid actions and verbs in the URI in chapter 6, URI Design, URI Path Design for our login route. Is it time to do the same thing here as well?

Well if you were thinking of doing something like this... GET /api/v1/auth/user, you, would not be the only one.

Remember what talked about? Always think of the URIs as resources and entities that we can fetch. In this case, I think it's best to create the URI as follows.

GET /api/v1/users/auth

This would suffice many different guidelines we proposed in chapter 3. This would let us think of users as the resource, which means it would then be pluralized. This would also let us have the option of creating a dynamic URI such as this, GET /api/v1/users/:user_id in the future if we were to extend this endpoint.

2 - Input Request

None.

3 - Middleware

We are finally ready to write our first middleware!

For this endpoint, I'm thinking we should write a basic auth middleware that will check if there exists an authenticated user currently.

If the current user is not logged in, then return a response with a 401 status code. Otherwise, business as usual, the request will go through.

4 - Validation

None.

5 - Domain

You'll see in the next section that since we are using Express and the express-session library, fetching the currently authenticated user is quite simple, there's no real reason to make any database calls.

6 - Events

None.

7 - Response

There are two possible responses from this endpoint.

The first is if the user is not logged in. This will be caught somewhere in our middleware. For future use cases, we will be using the same middleware for creating, updating, and deleting a book listing.

{
  "status": "error",
  "code": 401,
  "message": "Access denied: you must be logged in to access this API endpoint.",
  "data": null,
  "errors": ["You must be logged in."]
}

And if the user is logged in, we will get the user's information in the response.

{
  "status": "success",
  "code": 200,
  "message": "The currently authenticated user's information.",
  "data": {
    "first_name": "Yichen",
    "last_name": "Zhu",
    "email": "yichen@yichen.com",
    "phone_number": "1234567890"
  },
  "errors": null
}

Last updated