2021-08-14 21:39:37 +08:00
|
|
|
import assert from 'assert';
|
|
|
|
import RequestError from '@/errors/RequestError';
|
2021-08-15 23:39:03 +08:00
|
|
|
import { MiddlewareType } from 'koa';
|
|
|
|
import { jwtVerify } from 'jose/jwt/verify';
|
|
|
|
import { publicKey, issuer, adminResource } from '@/oidc/consts';
|
|
|
|
import { IRouterParamContext } from 'koa-router';
|
|
|
|
import { UserInfo, userInfoSelectFields } from '@logto/schemas';
|
|
|
|
import { findUserById } from '@/queries/user';
|
|
|
|
import pick from 'lodash.pick';
|
|
|
|
|
|
|
|
export type WithAuthContext<ContextT extends IRouterParamContext = IRouterParamContext> =
|
|
|
|
ContextT & {
|
|
|
|
user: UserInfo;
|
|
|
|
};
|
2021-08-14 21:39:37 +08:00
|
|
|
|
|
|
|
const bearerToken = 'Bearer';
|
|
|
|
|
2021-08-15 23:39:03 +08:00
|
|
|
export default function koaAuth<
|
2021-08-14 21:39:37 +08:00
|
|
|
StateT,
|
2021-08-15 23:39:03 +08:00
|
|
|
ContextT extends IRouterParamContext,
|
|
|
|
ResponseBodyT
|
|
|
|
>(): MiddlewareType<StateT, WithAuthContext<ContextT>, ResponseBodyT> {
|
2021-08-14 21:39:37 +08:00
|
|
|
return async (ctx, next) => {
|
|
|
|
const { authorization } = ctx.request.headers;
|
|
|
|
assert(
|
|
|
|
authorization,
|
|
|
|
new RequestError({ code: 'auth.authorization_header_missing', status: 401 })
|
|
|
|
);
|
|
|
|
assert(
|
|
|
|
authorization.startsWith(bearerToken),
|
|
|
|
new RequestError(
|
|
|
|
{ code: 'auth.authorization_type_not_supported', status: 401 },
|
|
|
|
{ supportedTypes: [bearerToken] }
|
|
|
|
)
|
|
|
|
);
|
2021-08-15 23:39:03 +08:00
|
|
|
const jwt = authorization.slice(bearerToken.length + 1);
|
|
|
|
|
|
|
|
try {
|
|
|
|
const {
|
|
|
|
payload: { sub },
|
|
|
|
} = await jwtVerify(jwt, publicKey, {
|
|
|
|
issuer,
|
|
|
|
audience: adminResource,
|
|
|
|
});
|
|
|
|
assert(sub);
|
|
|
|
const user = await findUserById(sub);
|
|
|
|
ctx.user = pick(user, ...userInfoSelectFields);
|
|
|
|
} catch {
|
|
|
|
throw new RequestError({ code: 'auth.unauthorized', status: 401 });
|
|
|
|
}
|
|
|
|
|
2021-08-14 21:39:37 +08:00
|
|
|
return next();
|
|
|
|
};
|
|
|
|
}
|