0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-13 21:30:30 -05:00
logto/packages/core/src/middleware/koa-auth.ts
Gao Sun 7c69896126
refactor: @logto/essentials -> @silverhand/essentials (#118)
* refactor: `@logto/essentials` -> `@silverhand/essentials`

* chore: remove useless comment
2021-09-16 23:48:06 +08:00

68 lines
2.1 KiB
TypeScript

import { IncomingHttpHeaders } from 'http';
import { UserInfo, userInfoSelectFields } from '@logto/schemas';
import { jwtVerify } from 'jose/jwt/verify';
import { MiddlewareType, Request } from 'koa';
import { IRouterParamContext } from 'koa-router';
import pick from 'lodash.pick';
import { developmentUserId, isProduction } from '@/env/consts';
import RequestError from '@/errors/RequestError';
import { publicKey, issuer, adminResource } from '@/oidc/consts';
import { findUserById } from '@/queries/user';
import assertThat from '@/utils/assert-that';
export type WithAuthContext<ContextT extends IRouterParamContext = IRouterParamContext> =
ContextT & {
user: UserInfo;
};
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_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);
const user = await findUserById(userId);
ctx.user = pick(user, ...userInfoSelectFields);
} catch {
throw new RequestError({ code: 'auth.unauthorized', status: 401 });
}
return next();
};
}