|
| 1 | +import jwt, { JwtPayload } from 'jsonwebtoken' |
| 2 | +import { Token } from '../types' |
| 3 | + |
| 4 | +export const issueAccessToken = (payload: {[key: string]: string | number}) => issueToken(payload, process.env.JWT_ACCESS_TOKEN as string, 10 * 60 * 1000) // 10 mins |
| 5 | +export const issueRefreshToken = (payload: {[key: string]: string | number}) => issueToken(payload, process.env.JWT_ACCESS_TOKEN as string, 14 * 24 * 60 * 60 * 1000) // 14 days |
| 6 | +export const verifyAccessToken = (token: string) => verifyToken(token, process.env.JWT_ACCESS_TOKEN as string) |
| 7 | +export const verifyRefreshToken = (token: string) => verifyToken(token, process.env.JWT_ACCESS_TOKEN as string) |
| 8 | + |
| 9 | +export async function issueToken(payload: {[key: string]: string | number}, secret: string, expiresIn: number): Promise<Token> { |
| 10 | + try { |
| 11 | + const token = await jwt.sign(payload, secret, { expiresIn }); |
| 12 | + const expirationDateValue = (addSeconds(new Date(), expiresIn/1000)).valueOf(); |
| 13 | + |
| 14 | + const fullToken = { token, expiresIn, expirationDateValue }; |
| 15 | + return Promise.resolve(fullToken); |
| 16 | + } |
| 17 | + catch(error) { |
| 18 | + return Promise.reject(error); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +export async function verifyToken(token: string, secret: string): Promise<JwtPayload | string> { |
| 23 | + try { |
| 24 | + const parsedToken = await jwt.verify(token, secret, {}); |
| 25 | + return Promise.resolve(parsedToken); |
| 26 | + } |
| 27 | + catch(error) { |
| 28 | + return Promise.reject(error); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +export function addSeconds(date: Date, seconds=0) { |
| 33 | + const newDate = new Date(date.valueOf()); |
| 34 | + newDate.setSeconds(newDate.getSeconds() + seconds); |
| 35 | + return newDate; |
| 36 | +} |
| 37 | + |
| 38 | +export function addDays(date: Date, days=0) { |
| 39 | + const newDate = new Date(date.valueOf()); |
| 40 | + newDate.setDate(newDate.getDate() + days); |
| 41 | + return newDate; |
| 42 | +} |
0 commit comments