Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix/issue 153 token revalidation #162

Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ SMTP_PASSWORD=your_smtp_password
LINKEDIN_CLIENT_ID=your_linkedin_client_id
LINKEDIN_CLIENT_SECRET=your_linkedin_client_secret
LINKEDIN_REDIRECT_URL=http://localhost:${SERVER_PORT}/api/auth/linkedin/callback
REFRESH_JWT_SECRET=your_refresh_jwt_secret_key
1 change: 1 addition & 0 deletions src/configs/envConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ export const SMTP_PASS = process.env.SMTP_PASS ?? ''
export const LINKEDIN_CLIENT_ID = process.env.LINKEDIN_CLIENT_ID ?? ''
export const LINKEDIN_CLIENT_SECRET = process.env.LINKEDIN_CLIENT_SECRET ?? ''
export const LINKEDIN_REDIRECT_URL = process.env.LINKEDIN_REDIRECT_URL ?? ''
export const REFRESH_JWT_SECRET = process.env.REFRESH_JWT_SECRET ?? ''
2 changes: 1 addition & 1 deletion src/configs/google-passport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ passport.deserializeUser(async (primary_email: string, done) => {
const cookieExtractor = (req: Request): string => {
let token = null
if (req?.cookies) {
token = req.cookies.jwt
token = req.cookies.accessToken
}
return token
}
Expand Down
2 changes: 1 addition & 1 deletion src/configs/linkedin-passport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ passport.deserializeUser(async (primary_email: string, done) => {
const cookieExtractor = (req: Request): string => {
let token = null
if (req?.cookies) {
token = req.cookies.jwt
token = req.cookies.accessToken
dsmabulage marked this conversation as resolved.
Show resolved Hide resolved
}
return token
}
Expand Down
65 changes: 50 additions & 15 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 @@ -135,7 +135,8 @@ export const logout = async (
res: Response
): Promise<ApiResponse<Profile>> => {
try {
res.clearCookie('jwt', { httpOnly: true })
res.clearCookie('accessToken', { 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 @@ -163,18 +164,33 @@ export const requireAuth = (
return
}

const token = req.cookies.jwt
const token = req.cookies.accessToken
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) {
dsmabulage marked this conversation as resolved.
Show resolved Hide resolved
return res
.status(401)
.json({ error: 'Invalid token, please log in again' })
}
}

if (!user) {
Expand Down Expand Up @@ -230,3 +246,22 @@ export const passwordReset = async (
})
}
}

export const refresh = async (req: Request, res: Response): Promise<void> => {
const refreshToken = req.cookies.refreshToken

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

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

signAndSetCookie(res, decoded.userId)
} catch (error) {
res.status(401).json({ error: 'Invalid token, please log in again' })
}
}
2 changes: 2 additions & 0 deletions src/routes/auth/auth.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
logout,
passwordReset,
passwordResetRequest,
refresh,
register
} from '../../controllers/auth.controller'
import { requestBodyValidator } from '../../middlewares/requestValidator'
Expand All @@ -15,6 +16,7 @@ import { loginSchema, registerSchema } from '../../schemas/auth-routes.schems'
const authRouter = express.Router()

authRouter.post('/register', requestBodyValidator(registerSchema), register)
authRouter.post('/refresh', refresh)
authRouter.post('/login', requestBodyValidator(loginSchema), login)
authRouter.get('/logout', logout)

Expand Down
29 changes: 19 additions & 10 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,33 @@
import { JWT_SECRET, CLIENT_URL } from './configs/envConfig'
import jwt from 'jsonwebtoken'
import { randomUUID } from 'crypto'
import ejs from 'ejs'
import type { Response } from 'express'
import type Mentor from './entities/mentor.entity'
import path from 'path'
import jwt from 'jsonwebtoken'
import multer from 'multer'
import ejs from 'ejs'
import { MenteeApplicationStatus, MentorApplicationStatus } from './enums'
import { generateCertificate } from './services/admin/generateCertificate'
import { randomUUID } from 'crypto'
import path from 'path'
import { certificatesDir } from './app'
import { CLIENT_URL, JWT_SECRET, REFRESH_JWT_SECRET } from './configs/envConfig'
import type Mentee from './entities/mentee.entity'
import type Mentor from './entities/mentor.entity'
import { MenteeApplicationStatus, MentorApplicationStatus } from './enums'
import { generateCertificate } from './services/admin/generateCertificate'

export const signAndSetCookie = (res: Response, uuid: string): void => {
const token = jwt.sign({ userId: uuid }, JWT_SECRET ?? '')
const accessToken = jwt.sign({ userId: uuid }, JWT_SECRET ?? '')
const refreshToken = jwt.sign({ userId: uuid }, REFRESH_JWT_SECRET ?? '', {
expiresIn: '10d'
})

res.cookie('jwt', token, {
res.cookie('accessToken', accessToken, {
httpOnly: true,
maxAge: 5 * 24 * 60 * 60 * 1000,
secure: false // TODO: Set to true when using HTTPS
})

res.cookie('refreshToken', refreshToken, {
httpOnly: true,
maxAge: 10 * 24 * 60 * 60 * 1000,
secure: false // TODO: Set to true when using HTTPS
})
}

export const getMentorPublicData = (mentor: Mentor): Mentor => {
Expand Down Expand Up @@ -100,7 +109,7 @@
subject: string
message: string
}
): any => {

Check warning on line 112 in src/utils.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
const templatePath = path.join(__dirname, 'templates', `${templateName}.ejs`)

return new Promise<string>((resolve, reject) => {
Expand Down
Loading