All files / app/config jwt-config.ts

86.67% Statements 13/15
85.71% Branches 6/7
100% Functions 2/2
86.67% Lines 13/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90                                                                        1x 1x           1x               1x 913x 699x 214x 5x   209x       1x   1x         374x                                       1x  
import {Request} from 'express';
 
export interface JWTOptions {
  algorithm: 'HS512' | 'HS384' | 'HS256';
  expiresIn: string;
  issuer: string | undefined;
  subject?: string;
}
 
export interface JWTSecurityOptions {
  ignoredMethods: string[];
  tokenName: string;
  secretName: string;
}
 
export interface JWTCookieOptions {
  httpOnly: boolean;
  sameSite: boolean;
  secure: boolean;
  signed: boolean;
  maxAge: number;
}
 
export interface JWTConfig {
  notLoggedInSubject: string;
  name: string;
  secret: string;
  getToken(req: Request): string | null;
  getOptions(username?: string): JWTOptions;
  cookieOptions: JWTCookieOptions;
  securityOptions: JWTSecurityOptions;
}
 
// Get the secret for the jwt
// If no secret is provided exit with 1. #
// Server shouldn't start without the secret
const secret = process.env.JWT_SECRET;
Iif (secret === undefined) {
  console.error('Secret for jwt tokens is not provided. Please set the ' +
      'environment variable "JWT_SECRET" to the secret which should be used\n');
  process.exit(1);
}
 
const name = 'jwt';
 
/**
 * Gets the token from a request.
 *
 * The token should be stored in a cookie with
 * the name "jwt"
 */
const getToken = (req: Request): string | null => {
  if (req.cookies[name]) {
    return req.cookies[name];
  } else if (req.jwtToken) {
    return req.jwtToken;
  } else {
    return null;
  }
};
 
const notLoggedInSubject = '';
 
const jwt: JWTConfig = {
  notLoggedInSubject,
  name,
  secret,
  getToken,
  getOptions: (username: string = notLoggedInSubject) => ({
    algorithm: 'HS512',
    expiresIn: '30m', // 15 minutes
    issuer: 'my-group-car.de',
    subject: username,
  }),
  cookieOptions: {
    httpOnly: true,
    sameSite: process.env.NODE_ENV === 'production',
    secure: process.env.NODE_ENV === 'production',
    signed: false,
    maxAge: 1000 * 60 * 30, // 30 minutes
  },
  securityOptions: {
    ignoredMethods: ['GET', 'HEAD', 'OPTIONS'],
    tokenName: 'XSRF-TOKEN',
    secretName: 'secret',
  },
};
 
export default jwt;