Skip to content

Commit

Permalink
feat: add authorization component
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondfeng committed Aug 20, 2018
1 parent b23272f commit 1f6e799
Show file tree
Hide file tree
Showing 16 changed files with 410 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/authorization/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
25 changes: 25 additions & 0 deletions packages/authorization/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Copyright (c) IBM Corp. 2018. All Rights Reserved.
Node module: @loopback/authorization
This project is licensed under the MIT License, full text below.

--------

MIT license

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
56 changes: 56 additions & 0 deletions packages/authorization/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# @loopback/authorization

A LoopBack 4 component for authorization support.

**This is a reference implementation showing how to implement an authorization
component, it is not production ready.**

## Overview

## Installation

```shell
npm install --save @loopback/authorization
```

## Basic use

Start by decorating your controller methods with `@authorize` to require the
request to be authenticated.

In this example, we make the user profile available via dependency injection
using a key available from `@loopback/authorization` package.

```ts
import {inject} from '@loopback/context';
import {authorize} from '@loopback/authorization';
import {get} from '@loopback/rest';

export class MyController {
@authorize({allow: ['ADMIN']})
@get('/number-of-views')
numOfViews(): number {
return 100;
}
}
```

## Related resources

## Contributions

- [Guidelines](https://github.com/strongloop/loopback-next/blob/master/docs/CONTRIBUTING.md)
- [Join the team](https://github.com/strongloop/loopback-next/issues/110)

## Tests

run `npm test` from the root folder.

## Contributors

See
[all contributors](https://github.com/strongloop/loopback-next/graphs/contributors).

## License

MIT
12 changes: 12 additions & 0 deletions packages/authorization/docs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"content": [
"index.ts",
"src/index.ts",
"src/decorators/authorize.ts",
"src/providers/authorization-metadata.ts",
"src/providers/authorize.ts",
"src/authorization-component.ts",
"src/keys.ts"
],
"codeSectionDepth": 4
}
6 changes: 6 additions & 0 deletions packages/authorization/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/authorization
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './dist';
6 changes: 6 additions & 0 deletions packages/authorization/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/authorization
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

module.exports = require('./dist');
8 changes: 8 additions & 0 deletions packages/authorization/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/authorization
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

// DO NOT EDIT THIS FILE
// Add any additional (re)exports to src/index.ts instead.
export * from './src';
47 changes: 47 additions & 0 deletions packages/authorization/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"name": "@loopback/authorization",
"version": "0.1.0",
"description": "A LoopBack component for authorization support.",
"engines": {
"node": ">=8"
},
"scripts": {
"acceptance": "lb-mocha \"DIST/test/acceptance/**/*.js\"",
"build": "lb-tsc es2017",
"build:apidocs": "lb-apidocs",
"clean": "lb-clean loopback-authorization*.tgz dist package api-docs",
"integration": "lb-mocha \"DIST/test/integration/**/*.js\"",
"prepublishOnly": "npm run build && npm run build:apidocs",
"pretest": "npm run build",
"test": "lb-mocha \"DIST/test/unit/**/*.js\" \"DIST/test/integration/**/*.js\" \"DIST/test/acceptance/**/*.js\"",
"unit": "lb-mocha \"DIST/test/unit/**/*.js\"",
"verify": "npm pack && tar xf loopback-authorization*.tgz && tree package && npm run clean"
},
"author": "IBM",
"copyright.owner": "IBM Corp.",
"license": "MIT",
"dependencies": {
"@loopback/context": "^0.12.4",
"@loopback/core": "^0.11.4"
},
"devDependencies": {
"@loopback/build": "^0.3.3",
"@loopback/testlab": "^0.4.1"
},
"keywords": [
"LoopBack",
"Authorization"
],
"files": [
"README.md",
"index.js",
"index.d.ts",
"dist/src",
"api-docs",
"src"
],
"repository": {
"type": "git",
"url": "https://github.com/strongloop/loopback-next.git"
}
}
20 changes: 20 additions & 0 deletions packages/authorization/src/authorization-component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/authorization
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {AuthorizationBindings} from './keys';
import {Component, ProviderMap} from '@loopback/core';
import {AuthorizationProvider} from './providers/authorize';
import {AuthMetadataProvider} from './providers/authorization-metadata';

export class AuthenticationComponent implements Component {
providers?: ProviderMap;

constructor() {
this.providers = {
[AuthorizationBindings.AUTHORIZE_ACTION]: AuthorizationProvider,
[AuthorizationBindings.METADATA]: AuthMetadataProvider,
};
}
}
58 changes: 58 additions & 0 deletions packages/authorization/src/decorators/authorize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/authorization
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {
MetadataInspector,
Constructor,
MethodDecoratorFactory,
} from '@loopback/context';
import {AuthorizationBindings} from '../keys';

/**
* Authorization metadata stored via Reflection API
*/
export interface AuthorizationMetadata {
allow?: string[];
deny?: string[];
scopes?: string[];
}

/**
* Mark a controller method as requiring authorized user.
*
* @param spec Authorization metadata
*/
export function authorize(spec: AuthorizationMetadata) {
return MethodDecoratorFactory.createDecorator<AuthorizationMetadata>(
AuthorizationBindings.METADATA,
spec,
);
}

export namespace authorize {
export const allowAll = () => authorize({allow: ['$everyone']});
export const allowAuthenticated = () =>
authorize({allow: ['$authenticated']});
export const denyAll = () => authorize({deny: ['$everyone']});
export const denyUnauthenticated = () =>
authorize({deny: ['$anonymous', 'unauthenticated']});
}

/**
* Fetch authorization metadata stored by `@authorize` decorator.
*
* @param controllerClass Target controller
* @param methodName Target method
*/
export function getAuthorizeMetadata(
controllerClass: Constructor<{}>,
methodName: string,
): AuthorizationMetadata | undefined {
return MetadataInspector.getMethodMetadata<AuthorizationMetadata>(
AuthorizationBindings.METADATA,
controllerClass.prototype,
methodName,
);
}
12 changes: 12 additions & 0 deletions packages/authorization/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/authorization
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './authorization-component';
export * from './decorators/authorize';
export * from './keys';

// internals for tests
export * from './providers/authorization-metadata';
export * from './providers/authorize';
12 changes: 12 additions & 0 deletions packages/authorization/src/keys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/authorization
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

/**
* Binding keys used by this component.
*/
export namespace AuthorizationBindings {
export const AUTHORIZE_ACTION = 'authorization.actions.authorize';
export const METADATA = 'authorization.operationMetadata';
}
33 changes: 33 additions & 0 deletions packages/authorization/src/providers/authorization-metadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/authorization
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {CoreBindings} from '@loopback/core';
import {Constructor, Provider, inject} from '@loopback/context';
import {
AuthorizationMetadata,
getAuthorizeMetadata,
} from '../decorators/authorize';

/**
* @description Provides authorization metadata of a controller method
* @example `context.bind('authorization.meta')
* .toProvider(AuthMetadataProvider)`
*/
export class AuthMetadataProvider
implements Provider<AuthorizationMetadata | undefined> {
constructor(
@inject(CoreBindings.CONTROLLER_CLASS)
private readonly controllerClass: Constructor<{}>,
@inject(CoreBindings.CONTROLLER_METHOD_NAME)
private readonly methodName: string,
) {}

/**
* @returns AuthorizationMetadata
*/
value(): AuthorizationMetadata | undefined {
return getAuthorizeMetadata(this.controllerClass, this.methodName);
}
}
58 changes: 58 additions & 0 deletions packages/authorization/src/providers/authorize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/authorization
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {Provider} from '@loopback/context';
import {AuthorizationMetadata} from '..';

export enum AuthorizationDecision {
ALLOW = 'Allow',
DENY = 'Deny',
AUDIT = 'Audit',
}

export interface Principal {
name: string;
type: string;
// tslint:disable-next-line:no-any
[attribute: string]: any;
}

export interface Role {
name: string;
type: string;
// tslint:disable-next-line:no-any
[attribute: string]: any;
}

export interface SecurityContext {
principals: Principal[];
roles: Role[];
}

export type AuthorizeFn = (
caller: SecurityContext,
target: AuthorizationMetadata,
) => Promise<AuthorizationDecision>;

/**
* @description Provider of a function which authenticates
* @example `context.bind('authentication_key')
* .toProvider(AuthorizationProvider)`
*/
export class AuthorizationProvider implements Provider<AuthorizeFn> {
constructor() {}

/**
* @returns authenticateFn
*/
value(): AuthorizeFn {
return async (
securityContext: SecurityContext,
metadata: AuthorizationMetadata,
) => {
return AuthorizationDecision.ALLOW;
};
}
}
Loading

0 comments on commit 1f6e799

Please sign in to comment.