templating api
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
# api/src/middlewares/README.md
|
||||
|
||||
Middleware are actions that run before or after every request.
|
||||
@@ -0,0 +1,53 @@
|
||||
import { type NextFunction, type Response } from "express"
|
||||
import { type Request as JwtRequest } from "express-jwt"
|
||||
import { isNil } from "lodash"
|
||||
|
||||
import { logger } from "@/utils/logger"
|
||||
import { Auth0PayloadError } from "@/integrations/auth0-integration"
|
||||
import { User } from "@/models"
|
||||
import { Users } from "@/services"
|
||||
|
||||
export type AuthorizationRequest = JwtRequest & {
|
||||
currentUser?: User | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Requires api/src/middlewares/jwt-middleware.ts to be run first
|
||||
*
|
||||
* I'd love to merge that code in here at some point, or make all this code a controller "before action"
|
||||
* I'm uncomfortable with creating users automatically here, I'd rather the front-end requested
|
||||
* user creation directly, and might switch to that in the future.
|
||||
*
|
||||
* NOTE: must be kept in sync with api/tests/support/mock-current-user.ts
|
||||
*/
|
||||
export async function findAndAuthorizeCurrentUserMiddleware(
|
||||
req: AuthorizationRequest,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const user = await User.withScope(["asCurrentUser"]).findOne({
|
||||
where: {
|
||||
auth0Subject: req.auth?.sub || "",
|
||||
},
|
||||
})
|
||||
|
||||
if (!isNil(user)) {
|
||||
req.currentUser = user
|
||||
return next()
|
||||
}
|
||||
|
||||
try {
|
||||
const token = req.headers.authorization || ""
|
||||
const user = await Users.FindFromAuth0TokenService.perform(token)
|
||||
req.currentUser = user
|
||||
return next()
|
||||
} catch (error) {
|
||||
logger.error(`Error ensuring user from Auth0 token ${error}`, { error })
|
||||
|
||||
if (error instanceof Auth0PayloadError) {
|
||||
return res.status(502).json({ message: "External authorization api failed." })
|
||||
} else {
|
||||
return res.status(401).json({ message: "User authentication failed." })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export { findAndAuthorizeCurrentUserMiddleware } from "./find-and-authorize-current-user-middleware"
|
||||
export { jwtMiddleware } from "./jwt-middleware"
|
||||
export { requestLoggerMiddleware } from "./request-logger-middleware"
|
||||
@@ -0,0 +1,26 @@
|
||||
import { expressjwt as jwt } from "express-jwt"
|
||||
import jwksRsa, { type GetVerificationKey } from "jwks-rsa"
|
||||
|
||||
import { AUTH0_DOMAIN, AUTH0_AUDIENCE, NODE_ENV } from "@/config"
|
||||
import { logger } from "@/utils/logger"
|
||||
|
||||
if (NODE_ENV !== "test") {
|
||||
logger.info(`AUTH0_DOMAIN - ${AUTH0_DOMAIN}/.well-known/jwks.json`)
|
||||
}
|
||||
|
||||
// TODO: investigate converting this to an integration or utility of the authorization middleware
|
||||
export const jwtMiddleware = jwt({
|
||||
secret: jwksRsa.expressJwtSecret({
|
||||
cache: true,
|
||||
rateLimit: true,
|
||||
jwksRequestsPerMinute: 5,
|
||||
jwksUri: `${AUTH0_DOMAIN}/.well-known/jwks.json`,
|
||||
}) as GetVerificationKey,
|
||||
|
||||
// Validate the audience and the issuer.
|
||||
audience: AUTH0_AUDIENCE,
|
||||
issuer: [`${AUTH0_DOMAIN}/`],
|
||||
algorithms: ["RS256"],
|
||||
})
|
||||
|
||||
export default jwtMiddleware
|
||||
@@ -0,0 +1,14 @@
|
||||
import morgan from "morgan"
|
||||
|
||||
import logger from "@/utils/logger"
|
||||
|
||||
export const requestLoggerMiddleware = morgan(
|
||||
":method :url :status :res[content-length] - :response-time ms",
|
||||
{
|
||||
stream: {
|
||||
write: (message) => logger.http(message.trim()),
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export default requestLoggerMiddleware
|
||||
Reference in New Issue
Block a user