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 4 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 ?? ''
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) {
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
25 changes: 17 additions & 8 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 refreshToken = jwt.sign({ userId: uuid }, REFRESH_JWT_SECRET ?? '', {
expiresIn: '10d'
})

res.cookie('jwt', token, {
dsmabulage marked this conversation as resolved.
Show resolved Hide resolved
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