Branch: master
Find file Copy path
f864688 May 17, 2018
2 contributors

Users who have contributed to this file

@bajtos @joeytwiddle
59 lines (54 sloc) 2.06 KB
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/authentication
// This file is licensed under the MIT License.
// License text available at
import {Getter, Provider, Setter, inject} from '@loopback/context';
import {Request} from '@loopback/rest';
import {Strategy} from 'passport';
import {AuthenticationBindings} from '../keys';
import {StrategyAdapter} from '../strategy-adapter';
import {AuthenticateFn, UserProfile} from '../types';
* @description Provider of a function which authenticates
* @example `context.bind('authentication_key')
* .toProvider(AuthenticateActionProvider)`
export class AuthenticateActionProvider implements Provider<AuthenticateFn> {
// The provider is instantiated for Sequence constructor,
// at which time we don't have information about the current
// route yet. This information is needed to determine
// what auth strategy should be used.
// To solve this, we are injecting a getter function that will
// defer resolution of the strategy until authenticate() action
// is executed.
readonly getStrategy: Getter<Strategy>,
readonly setCurrentUser: Setter<UserProfile>,
) {}
* @returns authenticateFn
value(): AuthenticateFn {
return request => this.action(request);
* The implementation of authenticate() sequence action.
* @param request The incoming request provided by the REST layer
async action(request: Request): Promise<UserProfile | undefined> {
const strategy = await this.getStrategy();
if (!strategy) {
// The invoked operation does not require authentication.
return undefined;
if (!strategy.authenticate) {
throw new Error('invalid strategy parameter');
const strategyAdapter = new StrategyAdapter(strategy);
const user = await strategyAdapter.authenticate(request);
return user;