We'll firs start off by adding the route and the controller in.
GET /api/v1/users/auth
File: src/routes/user.route.js
constexpress=require('express')constrouter=express.Router()constisAuthenticated=require('../middleware/auth.middleware')const { registerUser,getAuthUser } =require('../controllers/auth')router.post('/', registerUser)router.post('/auth', getAuthUser) // This is our new routemodule.exports= router
File: src/controllers/user/getAuthUser.js
constcatchExceptions=require('../../utils/catchExceptions')/** * Gets the currently authenticated user in the current session. */constgetAuthUser=catchExceptions((req, res) => {// our code goes here...})module.exports= getAuthUser
2 - Input Request
None.
3 - Middleware
Now it's time to add our first middleware. This will essentially protect any route against unauthenticated users.
File: src/middleware/auth/auth.middleware.js
constglobalResponseDto=require('../responses/globalResponseDto')constisAuthenticated= (req, res, next) => {if (!req.session.user) {returnres.status(401).json(globalResponseDto({ 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.'] }) ) }next()}module.exports= isAuthenticated
We can then add this isAuthenticated middleware to our GET /users/auth route as follows. Remember that this is a reusable middleware, we'll be using this all throughout the next chapter.
None, but because we are using the express-session library, we can simply just retrieve the user from the req object given to us in our controller, see below.
6 - Events
None.
7 - Response
Putting it all together, we get the follow. Do note also that we are reusing our userResponseDto to help us out with outputting the correct user information to our client.
File: src/controllers/user/getAuthUser.js
constglobalResponseDto=require('../../responses/globalResponseDto')constuserResponseDto=require('../../responses/userResponseDto')constcatchExceptions=require('../../utils/catchExceptions')/** * Gets the currently authenticated user in the current session. */constgetAuthUser=catchExceptions((req, res) => {constuser=req.session.user // This is essentially our logged in userres.status(200).json(globalResponseDto({ status:'success', code:200, message:`The currently authenticated user's information.`, data:userResponseDto(user), errors:null }) )})module.exports= getAuthUser