Skip to content

Commit

Permalink
Refactor JWT verification and type usage
Browse files Browse the repository at this point in the history
- Replaced direct jwt.verify calls with a new verifyAccessToken function in JWT.ts for better abstraction and reusability.
- Updated isAuthorized function in auth.ts
  • Loading branch information
ryota-murakami committed Jan 2, 2025
1 parent 9349e1d commit fcd7cef
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 7 deletions.
7 changes: 2 additions & 5 deletions server/auth.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type { Request, Response } from 'express'
import jwt from 'jsonwebtoken'

import { assertIsDefined } from '../lib/assertIsDefined'
import shallowEqualScalar from '../lib/shallowEqualScalar'

import deleteJWTattribute from './lib/deleteJWTattribute'
import Logger from './lib/Logger'
import { verifyAccessToken } from './lib/JWT'

export const isAuthorized = (req: Request, res: Response): true | void => {
const token = req.cookies.token as JWTtoken
Expand All @@ -18,10 +18,7 @@ export const isAuthorized = (req: Request, res: Response): true | void => {
Logger.info('req.cookies.token: ' + req.cookies.token)

try {
decripted = jwt.verify(
token,
process.env.REFRESH_TOKEN_SECRET as string,
) as IndexSignature<JWTpayload>
decripted = verifyAccessToken(token)
} catch (error) {
Logger.error('failed jwt.verify()')
Logger.error('decripted ' + JSON.stringify(decripted))
Expand Down
11 changes: 10 additions & 1 deletion server/lib/JWT.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import jwt from 'jsonwebtoken'
import jwt, { type JwtPayload } from 'jsonwebtoken'
import type { authors } from '@prisma/client'

// Generate Access Token
Expand All @@ -15,3 +15,12 @@ export function generateRefreshToken(author: authors) {
expiresIn: '7d',
})
}

// Verify Access Token
export function verifyAccessToken(token: string): JwtPayload {
// @TODO replace REFRESH_TOKEN_SECRET with ACCESS_TOKEN_SECRET
return jwt.verify(
token,
process.env.REFRESH_TOKEN_SECRET as string,
) as JwtPayload
}
4 changes: 3 additions & 1 deletion server/lib/deleteJWTattribute.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export default function deleteJWTattribute(payload: JsonObject): JsonObject {
import type { JwtPayload } from 'jsonwebtoken'

export default function deleteJWTattribute(payload: JwtPayload) {
delete payload.iat
delete payload.exp
delete payload.nbf
Expand Down

0 comments on commit fcd7cef

Please sign in to comment.