UNPKG

@foal/jwt

Version:

Authentication with JWT for FoalTS

37 lines (36 loc) 1.43 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RequestValidationError = void 0; exports.getJwtFromRequest = getJwtFromRequest; const core_1 = require("@foal/core"); const constants_1 = require("./constants"); class RequestValidationError extends Error { } exports.RequestValidationError = RequestValidationError; function getJwtFromRequest(request, location, required) { let token; switch (location) { case 'token-in-header': const headerContent = request.get('Authorization'); if (!headerContent) { if (required) { throw new RequestValidationError('Authorization header not found.'); } return; } token = headerContent?.split('Bearer ')[1]; if (!token) { throw new RequestValidationError('Expected a bearer token. Scheme is Authorization: Bearer <token>.'); } return token; case 'token-in-cookie': const cookieName = core_1.Config.get('settings.jwt.cookie.name', 'string', constants_1.JWT_DEFAULT_COOKIE_NAME); token = request.cookies[cookieName]; if (!token && required) { throw new RequestValidationError('Auth cookie not found.'); } return token; default: throw new Error('Invalid location.'); } }