icynet-admin/lib/session.ts

34 lines
909 B
TypeScript
Raw Normal View History

2022-09-20 14:38:22 +00:00
import Cookies from 'cookies';
2022-08-29 18:09:28 +00:00
import { GetServerSidePropsContext, GetServerSidePropsResult } from 'next';
import { getUserInfo } from './api/remote';
2022-09-20 14:38:22 +00:00
import { COOKIE_KEYS } from './constants';
2022-08-29 18:09:28 +00:00
import { CurrentUserDto } from './types/user-response.interface';
2022-09-20 14:38:22 +00:00
const inProd = process.env.NODE_ENV === 'production';
2022-08-29 18:09:28 +00:00
function withUser(
handler: (
ctx: GetServerSidePropsContext,
user?: CurrentUserDto
) => Promise<GetServerSidePropsResult<any>>
) {
return async (ctx: GetServerSidePropsContext) => {
2022-09-20 14:38:22 +00:00
const cookies = new Cookies(ctx.req, ctx.res, {
secure: inProd,
keys: COOKIE_KEYS,
});
const accessToken = cookies.get('authorization', { signed: true });
2022-08-29 18:09:28 +00:00
let user: CurrentUserDto | undefined;
if (accessToken) {
try {
user = await getUserInfo(accessToken);
} catch (e) {}
}
return handler(ctx, user);
};
}
export default withUser;