UNPKG

1.95 kBPlain TextView Raw
1import { RequestHandler, Request, Response } from 'express'
2import { HookContext } from '@feathersjs/feathers'
3import { createDebug } from '@feathersjs/commons'
4import { authenticate as AuthenticateHook } from '@feathersjs/authentication'
5
6import { Application } from './declarations'
7
8const debug = createDebug('@feathersjs/express/authentication')
9
10const 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
16export type AuthenticationSettings = {
17 service?: string
18 strategies?: string[]
19}
20
21export 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
49export 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}