1 | import { RequestHandler, Request, Response } from 'express';
|
2 | import { HookContext } from '@feathersjs/feathers';
|
3 | import { createDebug } from '@feathersjs/commons';
|
4 | import { authenticate as AuthenticateHook } from '@feathersjs/authentication';
|
5 |
|
6 | import { Application } from './declarations';
|
7 |
|
8 | const debug = createDebug('@feathersjs/express/authentication');
|
9 |
|
10 | const toHandler = (func: (req: Request, res: Response, next: () => void) => Promise<void>): RequestHandler => {
|
11 | return (req, res, next) => func(req, res, next).catch(error => next(error));
|
12 | };
|
13 |
|
14 | export type AuthenticationSettings = {
|
15 | service?: string;
|
16 | strategies?: string[];
|
17 | };
|
18 |
|
19 | export function parseAuthentication (settings: AuthenticationSettings = {}): RequestHandler {
|
20 | return toHandler(async (req, res, next) => {
|
21 | const app = req.app as any as Application;
|
22 | const service = app.defaultAuthentication?.(settings.service);
|
23 |
|
24 | if (!service) {
|
25 | return next();
|
26 | }
|
27 |
|
28 | const config = service.configuration;
|
29 | const authStrategies = settings.strategies || config.parseStrategies || config.authStrategies || [];
|
30 |
|
31 | if (authStrategies.length === 0) {
|
32 | debug('No `authStrategies` or `parseStrategies` found in authentication configuration');
|
33 | return next();
|
34 | }
|
35 |
|
36 | const authentication = await service.parse(req, res, ...authStrategies)
|
37 |
|
38 | if (authentication) {
|
39 | debug('Parsed authentication from HTTP header', authentication);
|
40 | req.feathers = { ...req.feathers, authentication };
|
41 | }
|
42 |
|
43 | return next();
|
44 | });
|
45 | }
|
46 |
|
47 | export function authenticate (settings: string | AuthenticationSettings, ...strategies: string[]): RequestHandler {
|
48 | const hook = AuthenticateHook(settings, ...strategies);
|
49 |
|
50 | return toHandler(async (req, _res, next) => {
|
51 | const app = req.app as any as Application;
|
52 | const params = req.feathers;
|
53 | const context = { app, params } as any as HookContext;
|
54 |
|
55 | await hook(context);
|
56 |
|
57 | req.feathers = context.params;
|
58 |
|
59 | return next();
|
60 | });
|
61 | }
|