🤖

JWT Authentication【10Test Middleware】

2022/10/12に公開

JWT Authentication【10Test Middleware】

YouTube: https://youtu.be/neOPTnXwqBk

authMiddleware.ts
import {Request, Response, NextFunction} from 'express'
import jwt from 'jsonwebtoken'
import cookie from 'cookie'
import { jwtSecretKey } from '../utils/jwtSecretKey'

export const isAuthenticated = (req: Request, res: Response, next: NextFunction) => {
  const cookies = cookie.parse(req.headers.cookie || '')
  const token = cookies.jwt || false

  if (!token) {
    return res.status(401).json({
      message: "Unauthorized - Please login first",
      user: null
    })
  }

  jwt.verify(token, jwtSecretKey, (err, user) => {
    if (err) {
      res.setHeader('Set-Cookie', cookie.serialize('jwt', '', {
        httpOnly: true,
        secure: req.app.get('env') !== 'development',
        maxAge: Number(new Date(0)),
        // secure: true,
        // sameSite: "none"
      }))
      return res.status(400).json({
        message: 'Token is Invalid',
        user: null
      })
    }
    req.user = user
    next()
  })
}
auth.ts
import { Router } from "express";
import { login, logout, register } from "../controllers/authControllers";
import { isAuthenticated } from "../middlewares/authMiddleware";

const router = Router()

router.post('/register', register)
router.post('/login', login)
router.post('/logout', isAuthenticated, logout)

export default router

Discussion