0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-03-24 22:41:28 -05:00

refactor(core): add guards for authn routes (#3843)

This commit is contained in:
Gao Sun 2023-05-15 15:47:53 +08:00 committed by GitHub
parent a65bc9b13b
commit 176e70190f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -26,10 +26,18 @@ export default function authnRoutes<T extends AnonymousRouter>(
socials: { getConnector }, socials: { getConnector },
} = libraries; } = libraries;
const hasuraResponseGuard = z.object({
'X-Hasura-User-Id': z.string().optional(),
'X-Hasura-Role': z.string().optional(),
});
type HasuraResponse = z.infer<typeof hasuraResponseGuard>;
router.get( router.get(
'/authn/hasura', '/authn/hasura',
koaGuard({ koaGuard({
query: z.object({ resource: z.string().min(1), unauthorizedRole: z.string().optional() }), query: z.object({ resource: z.string().min(1), unauthorizedRole: z.string().optional() }),
response: hasuraResponseGuard,
status: [200, 401], status: [200, 401],
}), }),
async (ctx, next) => { async (ctx, next) => {
@ -59,7 +67,7 @@ export default function authnRoutes<T extends AnonymousRouter>(
// So we verify the token again with no resource provided. // So we verify the token again with no resource provided.
(await verifyToken().then(({ sub }) => sub)), (await verifyToken().then(({ sub }) => sub)),
'X-Hasura-Role': unauthorizedRole, 'X-Hasura-Role': unauthorizedRole,
}; } satisfies HasuraResponse;
ctx.status = 200; ctx.status = 200;
return next(); return next();
@ -75,7 +83,7 @@ export default function authnRoutes<T extends AnonymousRouter>(
ctx.body = { ctx.body = {
'X-Hasura-User-Id': sub, 'X-Hasura-User-Id': sub,
'X-Hasura-Role': expectedRole, 'X-Hasura-Role': expectedRole,
}; } satisfies HasuraResponse;
ctx.status = 200; ctx.status = 200;
return next(); return next();
@ -89,7 +97,11 @@ export default function authnRoutes<T extends AnonymousRouter>(
* The API does not care the type of the SAML assertion request body, simply pass this to * The API does not care the type of the SAML assertion request body, simply pass this to
* connector's built-in methods. * connector's built-in methods.
*/ */
koaGuard({ body: jsonObjectGuard, params: z.object({ connectorId: z.string().min(1) }) }), koaGuard({
body: jsonObjectGuard,
params: z.object({ connectorId: z.string().min(1) }),
status: 302,
}),
async (ctx, next) => { async (ctx, next) => {
const { const {
params: { connectorId }, params: { connectorId },