Skip to content

Commit

Permalink
implement middleware to attach the new tokens if the existing ones ar…
Browse files Browse the repository at this point in the history
…e expired
  • Loading branch information
dsmabulage committed Sep 3, 2024
1 parent 7c0bb94 commit 7509624
Showing 1 changed file with 29 additions and 13 deletions.
42 changes: 29 additions & 13 deletions src/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import type { Request, Response, NextFunction } from 'express'
import type { NextFunction, Request, Response } from 'express'
import jwt from 'jsonwebtoken'
import passport from 'passport'
import { JWT_SECRET, REFRESH_JWT_SECRET } from '../configs/envConfig'
import type Profile from '../entities/profile.entity'
import {
registerUser,
generateResetToken,
loginUser,
resetPassword,
generateResetToken
registerUser,
resetPassword
} from '../services/auth.service'
import passport from 'passport'
import type Profile from '../entities/profile.entity'
import jwt from 'jsonwebtoken'
import { JWT_SECRET } from '../configs/envConfig'
import type { ApiResponse } from '../types'
import { signAndSetCookie } from '../utils'

Expand Down Expand Up @@ -136,6 +136,7 @@ export const logout = async (
): Promise<ApiResponse<Profile>> => {
try {
res.clearCookie('jwt', { httpOnly: true })
res.clearCookie('refreshToken', { httpOnly: true })
return res.status(200).json({ message: 'Logged out successfully' })
} catch (err) {
if (err instanceof Error) {
Expand Down Expand Up @@ -164,17 +165,32 @@ export const requireAuth = (
}

const token = req.cookies.jwt
const refreshToken = req.cookies.refreshToken

if (!token) {
return res.status(401).json({ error: 'User is not authenticated' })
if (!token && !refreshToken) {
return res
.status(401)
.json({ error: 'Access Denied. No token provided.' })
}

try {
jwt.verify(token, JWT_SECRET)
} catch (err) {
return res
.status(401)
.json({ error: 'Invalid token, please log in again' })
if (!refreshToken) {
return res.status(401).send('Access Denied. Please Login again.')
}

try {
const decoded = jwt.verify(refreshToken, REFRESH_JWT_SECRET) as {
userId: string
}

signAndSetCookie(res, decoded.userId)
} catch (error) {
return res
.status(401)
.json({ error: 'Invalid token, please log in again' })
}
}

if (!user) {
Expand Down

0 comments on commit 7509624

Please sign in to comment.