-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
In order to verify a JWT and authorize access based on user roles. This assumes user roles will be stateless and included in the `aud` claim of the JWT
- Loading branch information
Pauline Vos
committed
Nov 15, 2024
1 parent
6620b04
commit 8aaa335
Showing
4 changed files
with
141 additions
and
4 deletions.
There are no files selected for viewing
This file contains 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,117 @@ | ||
import { | ||
ErrorType, | ||
BadgeHubApiError, | ||
NotAuthorizedError, | ||
NotAuthenticatedError, | ||
} from "../error"; | ||
import { isAdmin, isContributor, UserRole } from "./role"; | ||
import { JWTPayload, jwtVerify } from "jose"; | ||
import { NextFunction, Request, Response } from "express"; | ||
|
||
// Middleware for routes that require a contributor role | ||
const ensureAdminRouteMiddleware = async ( | ||
req: Request, | ||
res: Response, | ||
next: NextFunction | ||
) => { | ||
await handleMiddlewareCheck(req, res, ensureAdmin); | ||
|
||
next(); | ||
}; | ||
|
||
// Middleware for routes that require a contributor role | ||
const ensureContributorRouteMiddleware = ( | ||
req: Request, | ||
res: Response, | ||
next: NextFunction | ||
) => { | ||
handleMiddlewareCheck(req, res, ensureContributor).then(next); | ||
}; | ||
|
||
const handleMiddlewareCheck = async ( | ||
req: Request, | ||
res: Response, | ||
assertion: Function | ||
) => { | ||
try { | ||
const token = await decodeJwtFromRequest(req); | ||
const roles: UserRole[] = rolesFromJwtPayload(token); | ||
|
||
console.debug("Roles:", roles); | ||
if (roles.length == 0) { | ||
throw NotAuthorizedError(); | ||
} | ||
assertion(roles); | ||
} catch (e: any) { | ||
handleError(e, res); | ||
} | ||
}; | ||
|
||
const handleError = (err: Error, res: Response) => { | ||
if (err.name == ErrorType.NotAuthenticated) { | ||
res.status(403).json({ error: err.message }); | ||
} | ||
if (err.name == ErrorType.NotAuthorized) { | ||
res.status(401).json({ error: err.message }); | ||
} | ||
|
||
console.debug(err); | ||
res.status(500).json({ error: "Internal server error" }); | ||
Check failure on line 59 in src/auth/jwt.ts GitHub Actions / buildUnhandled error
|
||
}; | ||
|
||
const ensureAdmin = (roles: UserRole[]) => { | ||
roles.forEach((role) => { | ||
if (!isAdmin(role)) { | ||
throw NotAuthorizedError(); | ||
} | ||
}); | ||
}; | ||
|
||
const ensureContributor = (roles: UserRole[]) => { | ||
roles.forEach((role) => { | ||
if (!isContributor(role)) { | ||
throw NotAuthorizedError(); | ||
} | ||
}); | ||
}; | ||
|
||
const rolesFromJwtPayload = (payload: JWTPayload): UserRole[] => { | ||
const aud = payload.aud; | ||
|
||
if (!aud) { | ||
return []; | ||
} | ||
|
||
if (typeof aud == "string") { | ||
return [UserRole[aud as UserRole]]; | ||
} | ||
|
||
return (aud as string[]).map((i: string) => { | ||
return UserRole[i as UserRole]; | ||
}); | ||
}; | ||
|
||
const decodeJwtFromRequest = async (req: Request): Promise<JWTPayload> => { | ||
const token = req.headers.authorization; | ||
|
||
if (!token) { | ||
throw NotAuthenticatedError("missing API token"); | ||
} | ||
|
||
try { | ||
const result = await jwtVerify( | ||
token, | ||
new TextEncoder().encode(process.env.JWT_SIGNING_KEY) | ||
); | ||
const payload = result.payload; | ||
if (!Object.hasOwn(payload, "aud")) { | ||
throw NotAuthenticatedError("API token invalid"); | ||
} | ||
|
||
return payload; | ||
} catch (err) { | ||
throw NotAuthenticatedError("API token invalid"); | ||
} | ||
}; | ||
|
||
export { ensureAdminRouteMiddleware, ensureContributorRouteMiddleware }; |
This file contains 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,15 @@ | ||
enum UserRole { | ||
Admin = "Admin", | ||
Contributor = "Contributor", | ||
ReadOnlyUser = "ReadOnlyUser", | ||
} | ||
|
||
const isAdmin = (role: UserRole): boolean => { | ||
return role == UserRole.Admin; | ||
}; | ||
|
||
const isContributor = (role: UserRole): boolean => { | ||
return role == UserRole.Contributor || isAdmin(role); | ||
}; | ||
|
||
export { UserRole, isAdmin, isContributor }; |
This file contains 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 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