-
Notifications
You must be signed in to change notification settings - Fork 6
chores: implemented jwt authentication middleware #21
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
Open
KodeSage
wants to merge
2
commits into
ShadeProtocol:main
Choose a base branch
from
KodeSage:feat/jwt_auth
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+186
−49
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,46 +1,62 @@ | ||
| import { Request, Response, NextFunction } from 'express'; | ||
| import jwt from 'jsonwebtoken'; | ||
| import prisma from '../config/prisma.js'; | ||
| import { environment } from '../config/environment.js'; | ||
|
|
||
| interface AccessTokenPayload extends jwt.JwtPayload { | ||
| sub: string; | ||
| address?: string; | ||
| } | ||
|
|
||
| /** | ||
| * Authenticates a merchant using a session bearer token. | ||
| * Authenticates a merchant from a JWT access token. | ||
| * | ||
| * Expects an `Authorization: Bearer <token>` header containing a JWT signed | ||
| * with `JWT_SECRET`. The token is verified and its `sub` claim is used to load | ||
| * the corresponding Merchant, which is attached to `req.merchant` on success. | ||
| * | ||
| * Expects an `Authorization: Bearer <token>` header that maps to a valid, | ||
| * non-expired MerchantSession. On success the resolved merchant is attached to | ||
| * `req.merchant`. Otherwise the request is rejected with 401. | ||
| * Responds with 401 when the header is missing/malformed, the token is invalid | ||
| * or expired, or the referenced merchant no longer exists. | ||
| */ | ||
| export const authenticateMerchant = async ( | ||
| req: Request, | ||
| res: Response, | ||
| next: NextFunction, | ||
| ): Promise<void> => { | ||
| try { | ||
| const authHeader = req.headers.authorization; | ||
| const authHeader = req.headers.authorization; | ||
|
|
||
| if (!authHeader || !authHeader.startsWith('Bearer ')) { | ||
| res.status(401).json({ error: 'Unauthorized' }); | ||
| return; | ||
| } | ||
| if (!authHeader || !authHeader.startsWith('Bearer ')) { | ||
| res.status(401).json({ error: 'Authentication required' }); | ||
| return; | ||
| } | ||
|
|
||
| const token = authHeader.slice('Bearer '.length).trim(); | ||
|
|
||
| const token = authHeader.slice('Bearer '.length).trim(); | ||
| if (!token) { | ||
| res.status(401).json({ error: 'Authentication required' }); | ||
| return; | ||
| } | ||
|
|
||
| if (!token) { | ||
| res.status(401).json({ error: 'Unauthorized' }); | ||
| return; | ||
| } | ||
| let payload: AccessTokenPayload; | ||
| try { | ||
| payload = jwt.verify(token, environment.jwtSecret) as AccessTokenPayload; | ||
| } catch { | ||
| res.status(401).json({ error: 'Invalid or expired token' }); | ||
| return; | ||
| } | ||
|
|
||
| const session = await prisma.refreshToken.findUnique({ | ||
| where: { token }, | ||
| include: { merchant: true }, | ||
| }); | ||
| if (!payload.sub) { | ||
| res.status(401).json({ error: 'Invalid or expired token' }); | ||
| return; | ||
| } | ||
|
|
||
| if (!session || session.expiresAt.getTime() < Date.now()) { | ||
| res.status(401).json({ error: 'Unauthorized' }); | ||
| return; | ||
| } | ||
| const merchant = await prisma.merchant.findUnique({ where: { id: payload.sub } }); | ||
|
|
||
| req.merchant = session.merchant; | ||
| next(); | ||
| } catch { | ||
| res.status(401).json({ error: 'Unauthorized' }); | ||
| if (!merchant) { | ||
| res.status(401).json({ error: 'Invalid or expired token' }); | ||
| return; | ||
| } | ||
|
|
||
| req.merchant = merchant; | ||
| next(); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| import { jest } from '@jest/globals'; | ||
| import jwt from 'jsonwebtoken'; | ||
| import type { Request, Response, NextFunction } from 'express'; | ||
|
|
||
| const { default: prismaMock } = (await import('../../src/config/prisma.js')) as any; | ||
| const { environment } = await import('../../src/config/environment.js'); | ||
| const { authenticateMerchant } = await import('../../src/middlewares/auth.middleware.js'); | ||
|
|
||
| const MERCHANT_ID = 'merchant-1'; | ||
|
|
||
| const merchant = { | ||
| id: MERCHANT_ID, | ||
| merchantId: 1, | ||
| address: '0x123', | ||
| registered: true, | ||
| }; | ||
|
|
||
| const buildReq = (authorization?: string): Request => | ||
| ({ headers: authorization ? { authorization } : {} }) as unknown as Request; | ||
|
|
||
| const buildRes = () => { | ||
| const res = {} as Response; | ||
| res.status = jest.fn().mockReturnValue(res) as unknown as Response['status']; | ||
| res.json = jest.fn().mockReturnValue(res) as unknown as Response['json']; | ||
| return res; | ||
| }; | ||
|
|
||
| const validToken = () => | ||
| jwt.sign({ sub: MERCHANT_ID, address: merchant.address }, environment.jwtSecret); | ||
|
|
||
| describe('authenticateMerchant', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| test('attaches the merchant and calls next() for a valid JWT', async () => { | ||
| prismaMock.merchant.findUnique.mockResolvedValue(merchant as any); | ||
| const req = buildReq(`Bearer ${validToken()}`); | ||
| const res = buildRes(); | ||
| const next = jest.fn() as unknown as NextFunction; | ||
|
|
||
| await authenticateMerchant(req, res, next); | ||
|
|
||
| expect(prismaMock.merchant.findUnique).toHaveBeenCalledWith({ where: { id: MERCHANT_ID } }); | ||
| expect(req.merchant).toEqual(merchant); | ||
| expect(next).toHaveBeenCalledTimes(1); | ||
| expect(res.status).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test('returns 401 "Authentication required" when the Authorization header is missing', async () => { | ||
| const req = buildReq(); | ||
| const res = buildRes(); | ||
| const next = jest.fn() as unknown as NextFunction; | ||
|
|
||
| await authenticateMerchant(req, res, next); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Authentication required' }); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test('returns 401 "Authentication required" when the scheme is not Bearer', async () => { | ||
| const req = buildReq('Basic abc123'); | ||
| const res = buildRes(); | ||
| const next = jest.fn() as unknown as NextFunction; | ||
|
|
||
| await authenticateMerchant(req, res, next); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Authentication required' }); | ||
| }); | ||
|
|
||
| test('returns 401 "Invalid or expired token" for a malformed token', async () => { | ||
| const req = buildReq('Bearer not-a-real-jwt'); | ||
| const res = buildRes(); | ||
| const next = jest.fn() as unknown as NextFunction; | ||
|
|
||
| await authenticateMerchant(req, res, next); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Invalid or expired token' }); | ||
| expect(prismaMock.merchant.findUnique).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test('returns 401 "Invalid or expired token" for an expired token', async () => { | ||
| const expired = jwt.sign({ sub: MERCHANT_ID }, environment.jwtSecret, { expiresIn: '-1s' }); | ||
| const req = buildReq(`Bearer ${expired}`); | ||
| const res = buildRes(); | ||
| const next = jest.fn() as unknown as NextFunction; | ||
|
|
||
| await authenticateMerchant(req, res, next); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Invalid or expired token' }); | ||
| }); | ||
|
|
||
| test('returns 401 "Invalid or expired token" when the token is signed with the wrong secret', async () => { | ||
| const forged = jwt.sign({ sub: MERCHANT_ID }, 'a-different-secret'); | ||
| const req = buildReq(`Bearer ${forged}`); | ||
| const res = buildRes(); | ||
| const next = jest.fn() as unknown as NextFunction; | ||
|
|
||
| await authenticateMerchant(req, res, next); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Invalid or expired token' }); | ||
| }); | ||
|
|
||
| test('returns 401 when the merchant no longer exists in the database', async () => { | ||
| prismaMock.merchant.findUnique.mockResolvedValue(null); | ||
| const req = buildReq(`Bearer ${validToken()}`); | ||
| const res = buildRes(); | ||
| const next = jest.fn() as unknown as NextFunction; | ||
|
|
||
| await authenticateMerchant(req, res, next); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith({ error: 'Invalid or expired token' }); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.