0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-27 21:39:16 -05:00
logto/packages/core/src/middleware/koa-auth.ts
simeng-li cdcadb968f
refactor(core): refactor error handler logic (#220)
* refactor(core): refactor error handler logic

add oidc and slonik custom error handler

* fix(core): fix typo

fix type

* refactor: align core errors

align some old core error definitions
2022-02-14 11:50:47 +08:00

66 lines
1.9 KiB
TypeScript

import { IncomingHttpHeaders } from 'http';
import { jwtVerify } from 'jose/jwt/verify';
import { MiddlewareType, Request } from 'koa';
import { IRouterParamContext } from 'koa-router';
import { developmentUserId, isProduction } from '@/env/consts';
import RequestError from '@/errors/RequestError';
import { publicKey, issuer, adminResource } from '@/oidc/consts';
import assertThat from '@/utils/assert-that';
export type WithAuthContext<ContextT extends IRouterParamContext = IRouterParamContext> =
ContextT & {
auth: string;
};
const bearerTokenIdentifier = 'Bearer';
const extractBearerTokenFromHeaders = ({ authorization }: IncomingHttpHeaders) => {
assertThat(
authorization,
new RequestError({ code: 'auth.authorization_header_missing', status: 401 })
);
assertThat(
authorization.startsWith(bearerTokenIdentifier),
new RequestError(
{ code: 'auth.authorization_token_type_not_supported', status: 401 },
{ supportedTypes: [bearerTokenIdentifier] }
)
);
return authorization.slice(bearerTokenIdentifier.length + 1);
};
const getUserIdFromRequest = async (request: Request) => {
if (!isProduction && developmentUserId) {
return developmentUserId;
}
const {
payload: { sub },
} = await jwtVerify(extractBearerTokenFromHeaders(request.headers), publicKey, {
issuer,
audience: adminResource,
});
assertThat(sub, new RequestError({ code: 'auth.jwt_sub_missing', status: 401 }));
return sub;
};
export default function koaAuth<
StateT,
ContextT extends IRouterParamContext,
ResponseBodyT
>(): MiddlewareType<StateT, WithAuthContext<ContextT>, ResponseBodyT> {
return async (ctx, next) => {
try {
const userId = await getUserIdFromRequest(ctx.request);
ctx.auth = userId;
} catch {
throw new RequestError({ code: 'auth.unauthorized', status: 401 });
}
return next();
};
}