38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
import jwt from 'jsonwebtoken';
|
|
import { JWT_SECRET } from '../constants/defaults';
|
|
|
|
export const getJwtSecret = () => process.env.JWT_SECRET || JWT_SECRET;
|
|
export interface TokenProps {
|
|
aud?: string;
|
|
exp?: number | Date;
|
|
iss?: string;
|
|
sub: string | null;
|
|
[key: string]: any;
|
|
}
|
|
|
|
export type SignProps = string | TokenProps | void;
|
|
|
|
export const sign = (props: SignProps) => {
|
|
const today = new Date();
|
|
const { sub = null, ...rest }: TokenProps =
|
|
typeof props === 'string' || typeof props === 'undefined' ? { sub: props || null } : props;
|
|
let { exp } = rest;
|
|
if (!exp) {
|
|
exp = new Date(today);
|
|
exp.setDate(today.getDate() + parseInt(process.env.JWT_DAYS_VALID as string));
|
|
exp = exp.getTime() / 1000;
|
|
}
|
|
return jwt.sign(
|
|
{
|
|
exp,
|
|
sub,
|
|
aud: rest.aud || process.env.JWT_AUDIENCE,
|
|
iat: today.getTime(),
|
|
iss: rest.iss || process.env.JWT_ISSUER,
|
|
},
|
|
getJwtSecret(),
|
|
);
|
|
};
|
|
|
|
export const verify = (token: string) => jwt.verify(token, getJwtSecret());
|