Initial auth library commmit

This commit is contained in:
2023-05-02 01:14:23 -04:00
parent a1d60a5042
commit 3411ae1234
17 changed files with 585 additions and 0 deletions

31
lib/utils/jwt.ts Normal file
View File

@@ -0,0 +1,31 @@
import jwt, { JwtPayload } from 'jsonwebtoken';
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.exp;
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({
aud: rest.aud || process.env.JWT_AUDIENCE,
exp,
iat: today.getTime(),
iss: rest.iss || process.env.JWT_ISSUER,
sub,
}, process.env.JWT_SECRET || 'secret');
};
export const verify = (token: string) => jwt.verify(token, process.env.JWT_SECRET || 'secret');