extract-session-token.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { Request } from 'express';
  2. import { AuthOptions } from '../../config/vendure-config';
  3. // Helper that gives us the content of the tokenmethod array so we dont duplicate options
  4. type ExtractArrayElement<T> = T extends ReadonlyArray<infer U> ? U : T;
  5. export type ExtractTokenResult = {
  6. method: Exclude<ExtractArrayElement<AuthOptions['tokenMethod']>, undefined>;
  7. token: string;
  8. };
  9. /**
  10. * Depending on the configured `tokenMethod`, tries to extract a session token in the order:
  11. *
  12. * 1. Cookie
  13. * 2. Authorization Header
  14. * 3. API-Key Header
  15. *
  16. * @see {@link AuthOptions}
  17. */
  18. export function extractSessionToken(
  19. req: Request,
  20. tokenMethod: Exclude<AuthOptions['tokenMethod'], undefined>,
  21. apiKeyHeaderKey: string,
  22. ): ExtractTokenResult | undefined {
  23. if (req.session?.token && (tokenMethod === 'cookie' || tokenMethod.includes('cookie'))) {
  24. return { method: 'cookie', token: req.session.token as string };
  25. }
  26. const authHeader = req.get('Authorization')?.trim();
  27. if (authHeader && (tokenMethod === 'bearer' || tokenMethod.includes('bearer'))) {
  28. const matchesBearer = authHeader.match(/^bearer\s(.+)$/i);
  29. if (matchesBearer) {
  30. return { method: 'bearer', token: matchesBearer[1] };
  31. }
  32. }
  33. // TODO: For some reason `apiKeyHeaderKey` is undefined on CI Server Smoke tests... (confirmed on 2025-12-07)
  34. // Maybe it has something to do with the package versions that get installed by the CI, I do not know.
  35. // Anyway, this simple check fixes this for now, let's try removing this again when versions change.
  36. if (!apiKeyHeaderKey) return;
  37. const apiKeyHeader = req.get(apiKeyHeaderKey)?.trim();
  38. if (apiKeyHeader && tokenMethod.includes('api-key')) {
  39. return { method: 'api-key', token: apiKeyHeader };
  40. }
  41. }