RESTful Node.js: A Structured Approach
  • Book Cover
  • About the Author
  • Links and Resources
  • Part I: The Why
    • Foreword
    • Preface
    • Chapter 1: Introduction
      • The Rise of REST and Distributed Systems
      • Problem #1: Structureless Design, Structureless REST
      • The Emergence of JavaScript and Node.js
      • Problem #2: Structureless JavaScript, Structureless Node.js
      • Behold, the Solution: A Structured Approach
      • Summary
  • Part 2: The Theory
    • Chapter 2: REST Origins
      • A Brief History of the Web and the Birth of REST
      • REST vs. HTTP
      • REST - The Abstract Web Architecture
      • HTTP - A Peak at REST's Concrete Implementation
      • What does it mean for an API to be RESTful?
      • Measuring "RESTfulness" with Richardson Maturity Model
      • Pragmatic REST vs Dogmatic REST
      • Summary
    • Chapter 3: RESTful API Design Guidelines and "Best Practices"
      • Theories vs. Principles vs. Guidelines
      • URI Design
      • Method Verbs
      • Status Codes
      • Representational Design
      • Metadata Design
      • Versioning Strategies
      • Security Considerations
      • Documentation
      • Case Study: GitHub
      • Summary
    • Chapter 4: Structured JavaScript Architecture
      • The Monstrous Monolith and Its Downfall
      • Layered/N-Tier Architecture: The Unpopular Proven Way
      • Microservices and Distributed Computing: A Popular Misdirection
      • Summary
    • Chapter 5: The 8 Step Recipe
      • Route Name (URI)
      • Input Request
      • Middleware
      • Validation
      • Domain
      • Events
      • Output Response
      • Test, Refactor, Document
      • Summary
  • Part 3: The Code
    • Chapter 6: Introduction to the Bookstore API
      • The Bookstore API Endpoint Specifications
      • API Design and Code Structure
      • Project Setup
      • Summary
    • Chapter 7: Retrieving Books from our API
      • Retrieving All Books - Planning
      • Retrieving All Books - Implementation
      • Retrieving A Book By ID - Planning
      • Retrieving A Book By ID - Implementation
      • Summary
    • Chapter 8: Adding Authentication to our API
      • Registering the User - Planning
      • Registering the User - Implementation
      • Logging the User In - Planning
      • Logging the User In - Implementation
      • Getting Authenticated User - Planning
      • Getting Authenticated User - Implementation
      • Summary
    • Chapter 9: Adding the Create, Update, and Delete Operations to our API
      • Creating A Book Listing - Planning
      • Creating A Book Listing - Implementation
      • Updating A Book Listing By ID - Planning
      • Updating A Book Listing By ID - Implementation
      • Deleting A Book Listing By ID - Planning
      • Deleting A Book Listing By ID - Implementation
      • Summary
    • Chapter 10: Testing our API
      • Testing the Request
      • Testing the Middleware
      • Testing the Validation
      • Testing the Domain
      • Testing the Event
      • Testing the Response
      • Testing the Controller
      • Integration Test
      • Summary
  • Conclusion
    • Final Words
  • Bonus!
    • Refactoring to HATEOAS
  • Appendix
    • Sources & References
Powered by GitBook
On this page
  • 1 - Route Name
  • 2 - Input Request
  • 3 - Middleware
  • 4 - Validation
  • 5 - Domain
  • 6 - Events
  • 7 - Response
Edit on GitHub
  1. Part 3: The Code
  2. Chapter 8: Adding Authentication to our API

Getting Authenticated User - Implementation

1 - Route Name

We'll firs start off by adding the route and the controller in.

GET /api/v1/users/auth

File: src/routes/user.route.js

const express = require('express')
const router = express.Router()

const isAuthenticated = require('../middleware/auth.middleware')
const { registerUser, getAuthUser } = require('../controllers/auth')

router.post('/', registerUser)
router.post('/auth', getAuthUser) // This is our new route

module.exports = router

File: src/controllers/user/getAuthUser.js

const catchExceptions = require('../../utils/catchExceptions')

/**
 * Gets the currently authenticated user in the current session.
 */
const getAuthUser = 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

const globalResponseDto = require('../responses/globalResponseDto')

const isAuthenticated = (req, res, next) => {
  if (!req.session.user) {
    return res.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.

File: src/controllers/auth/getAuthUser.controller.js

const { getAuthUser } = require('../controllers/auth')

router.get('/auth', isAuthenticated, getAuthUser)

4 - Validation

None.

5 - Domain

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

const globalResponseDto = require('../../responses/globalResponseDto')
const userResponseDto = require('../../responses/userResponseDto')

const catchExceptions = require('../../utils/catchExceptions')

/**
 * Gets the currently authenticated user in the current session.
 */
const getAuthUser = catchExceptions((req, res) => {
  const user = req.session.user // This is essentially our logged in user

  res.status(200).json(
    globalResponseDto({
      status: 'success',
      code: 200,
      message: `The currently authenticated user's information.`,
      data: userResponseDto(user),
      errors: null
    })
  )
})

module.exports = getAuthUser
PreviousGetting Authenticated User - PlanningNextSummary

Last updated 3 years ago