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