Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/authentication/src/keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ export namespace BindingKeys {
export const STRATEGY = 'authentication.strategy';
export const AUTH_ACTION = 'authentication.actions.authenticate';
export const METADATA = 'authentication.operationMetadata';
export const CURRENT_USER = 'authentication.currentUser';
}
}
33 changes: 17 additions & 16 deletions packages/authentication/src/providers/authenticate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import * as http from 'http';
import {HttpErrors, inject, ParsedRequest} from '@loopback/core';
import {Provider} from '@loopback/context';
import {Provider, Getter, Setter} from '@loopback/context';
import {Strategy} from 'passport';
import {StrategyAdapter} from '../strategy-adapter';
import {BindingKeys} from '../keys';
Expand Down Expand Up @@ -44,41 +44,42 @@ export class AuthenticationProvider implements Provider<AuthenticateFn> {
// is executed.
@inject.getter(BindingKeys.Authentication.STRATEGY)
readonly getStrategy: () => Promise<Strategy>,
@inject.setter(BindingKeys.Authentication.CURRENT_USER)
readonly setCurrentUser: (value: UserProfile) => void,
) {}

/**
* @returns authenticateFn
*/
value(): AuthenticateFn {
return async (request: ParsedRequest) => {
const strategy = await this.getStrategy();
return await getAuthenticatedUser(strategy, request);
return await authenticateRequest(
this.getStrategy,
request,
this.setCurrentUser,
);
};
}
}

/**
* @description a function which accepts (passport-strategy, request)
* and returns a user
* The implementation of authenticate() sequence action.
* @param strategy Passport strategy
* @param request Parsed Request
*
* @example
* ```ts
* const strategy = new BasicStrategy(async (username, password) => {
* return await findUser(username, password);
* };
* getAuthenticatedUser(strategy, ParsedRequest);
* ```
* @param setCurrentUser The setter function to update the current user
* in the per-request Context
*/
export async function getAuthenticatedUser(
strategy: Strategy,
async function authenticateRequest(
getStrategy: Getter<Strategy>,
request: ParsedRequest,
setCurrentUser: Setter<UserProfile>,
): Promise<UserProfile> {
const strategy = await getStrategy();
if (!strategy.authenticate) {
return Promise.reject(new Error('invalid strategy parameter'));
}
const strategyAdapter = new StrategyAdapter(strategy);
const user: UserProfile = await strategyAdapter.authenticate(request);
const user = await strategyAdapter.authenticate(request);
setCurrentUser(user);
return user;
}
11 changes: 5 additions & 6 deletions packages/authentication/test/acceptance/basic-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ describe('Basic Authentication', () => {
users = new UserRepository({
joe : {profile: {id: 'joe'}, password: '12345'},
Simpson: {profile: {id: 'sim123'}, password: 'alpha'},
Flintstone: {profile: {id: 'Flint'}, password: 'beta'},
Flinstone: {profile: {id: 'Flint'}, password: 'beta'},
George: {profile: {id: 'Curious'}, password: 'gamma'},
});
}
Expand All @@ -96,7 +96,10 @@ describe('Basic Authentication', () => {

@api(apispec)
class MyController {
constructor(@inject('authentication.user') private user: UserProfile) {}
constructor(
@inject(BindingKeys.Authentication.CURRENT_USER)
private user: UserProfile,
) {}

@authenticate('BasicStrategy')
async whoAmI() : Promise<string> {
Expand Down Expand Up @@ -127,10 +130,6 @@ describe('Basic Authentication', () => {
// Authenticate
const user: UserProfile = await this.authenticateRequest(req);

// User is expected to be returned or an exception should be thrown
if (user) this.bindElement('authentication.user').to(user);
else throw new HttpErrors.InternalServerError('auth error');

// Authentication successful, proceed to invoke controller
const args = await this.parseParams(req, route);
const result = await this.invoke(route, args);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {Context, Provider, instantiateClass} from '@loopback/context';
import {ParsedRequest} from '@loopback/core';
import {
AuthenticationProvider,
getAuthenticatedUser,
AuthenticateFn,
UserProfile,
BindingKeys,
Expand All @@ -30,6 +29,7 @@ describe('AuthenticationProvider', () => {
describe('value()', () => {
let provider: AuthenticationProvider;
let strategy: MockStrategy;
let currentUser: UserProfile | undefined;

const mockUser: UserProfile = {name: 'user-name', id: 'mock-id'};

Expand All @@ -45,6 +45,13 @@ describe('AuthenticationProvider', () => {
expect(user).to.be.equal(mockUser);
});

it('updates current user', async () => {
const authenticate = await Promise.resolve(provider.value());
const request = <ParsedRequest> {};
await authenticate(request);
expect(currentUser).to.equal(mockUser);
});

describe('context.get(provider_key)', () => {
it('returns a function which authenticates a request and returns a user',
async () => {
Expand Down Expand Up @@ -106,7 +113,10 @@ describe('AuthenticationProvider', () => {
function givenAuthenticationProvider() {
strategy = new MockStrategy();
strategy.setMockUser(mockUser);
provider = new AuthenticationProvider(() => Promise.resolve(strategy));
provider = new AuthenticationProvider(
() => Promise.resolve(strategy),
u => currentUser = u);
currentUser = undefined;
}
});
});
2 changes: 1 addition & 1 deletion packages/context/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
export {Binding, BindingScope, BoundValue, ValueOrPromise} from './binding';
export {Context} from './context';
export {Constructor} from './resolver';
export {inject} from './inject';
export {inject, Setter, Getter} from './inject';
export {NamespacedReflect} from './reflect';
export {Provider} from './provider';
export {isPromise} from './is-promise';
Expand Down
53 changes: 52 additions & 1 deletion packages/context/src/inject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,17 +102,68 @@ export function inject(
};
}

/**
* The function injected by `@inject.getter(key)`.
*/
export type Getter<T> = () => Promise<T>;

/**
* The function injected by `@inject.setter(key)`.
*/
export type Setter<T> = (value: T) => void;

export namespace inject {
/**
* Inject a function for getting the actual bound value.
*
* This is useful when implementing Actions, where
* the action is instantiated for Sequence constructor, but some
* of action's dependencies become bound only after other actions
* have been executed by the sequence.
*
* See also `Getter<T>`.
*
* @param bindingKey The key of the value we want to eventually get.
* @param metadata Optional metadata to help the injection
*/
export const getter = function injectGetter(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it represent a deferred injection?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bindingKey: string,
metadata?: Object,
) {
return inject(bindingKey, metadata, resolveAsGetter);
};

/**
* Inject a function for setting (binding) the given key to a given
* value. (Only static/constant values are supported, it's not possible
* to bind a key to a class or a provider.)
*
* This is useful e.g. when implementing Actions that are contributing
* new Elements.
*
* See also `Setter<T>`.
*
* @param bindingKey The key of the value we want to set.
* @param metadata Optional metadata to help the injection
*/
export const setter = function injectSetter(
bindingKey: string,
metadata?: Object,
) {
return inject(bindingKey, metadata, resolveAsSetter);
};
}

function resolveAsGetter(ctx: Context, injection: Injection) {
return () => ctx.get(injection.bindingKey);
return function getter() {
return ctx.get(injection.bindingKey);
};
}

function resolveAsSetter(ctx: Context, injection: Injection) {
return function setter(value: BoundValue) {
ctx.bind(injection.bindingKey).to(value);
};
}

/**
Expand Down
20 changes: 18 additions & 2 deletions packages/context/test/acceptance/class-level-bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// License text available at https://opensource.org/licenses/MIT

import {expect} from '@loopback/testlab';
import {Context, inject, isPromise} from '../..';
import {Context, inject, isPromise, Setter, Getter} from '../..';

const INFO_CONTROLLER = 'controllers.info';

Expand Down Expand Up @@ -140,7 +140,7 @@ describe('Context bindings - Injecting dependencies of classes', () => {
class Store {
constructor(
@inject.getter('key')
public getter: Function,
public getter: Getter<string>,
) {}
}

Expand All @@ -155,6 +155,22 @@ describe('Context bindings - Injecting dependencies of classes', () => {
expect(await store.getter()).to.equal('new-value');
});

it('injects a setter function', async () => {
class Store {
constructor(
@inject.setter('key')
public setter: Setter<string>,
) {}
}

ctx.bind('store').toClass(Store);
const store = ctx.getSync('store');

expect(store.setter).to.be.Function();
store.setter('a-value');
expect(ctx.getSync('key')).to.equal('a-value');
});

function createContext() {
ctx = new Context();
}
Expand Down