// Name: User Authentication // // Description: Authenticate a user has access the the api // // ============================================================================ import { config } from '../../config'; import * as jwt from 'jsonwebtoken'; import { User } from '../../app/user'; export interface JwtBase { aud: string; exp: number; // Expiration date iat: number; // Initial date iss: string; // Issuer sub: string; // Subject (userId) } export interface JwtPayload {} export type JWT = JwtBase & JwtPayload; /** * Given a user, return a new JWT. * This method is should be used by all authentication plugins (local, google, facebook, etc.) * after the user has been authenticated. * * @param user The active User * @param sessionSeconds The number of seconds this session should be active */ export function generateJWT( user: User, sessionSeconds?: number ): Promise { const payload = {}; return new Promise((resolve, reject) => { jwt.sign( payload, config.session.key, { algorithm: 'HS256', audience: '', issuer: 'Forage', subject: user.id, expiresIn: `${sessionSeconds || config.session.duration}s`, }, (err, encoded) => { if (err) reject('Unable to generate token'); resolve(encoded); } ); }); }