Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

It defines an IsAuthenticated decorator that is applied to routes. #253

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,49 @@ class UserDetailsController extends BaseHttpController {
}
```

### Decorators
There are helpers for AuthProvider these are wrapped into decorators these are applied to action methods.
Copy link
Contributor

Choose a reason for hiding this comment

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

this English seems a bit shady, I am not a native speaker myself so can't really help with correct phrasing

Every decorator parameters correspond to method arguments with the equal name of the authenrication provider instance.
```ts
import { inRole, isAuthenticated, isResourceOwner } from 'inversify-express-utils';

@controller("/")
class TestController extends BaseHttpController {

@httpGet("isAuthenticated")
@isAuthenticated()
public async isAuthenticated() {
return this.ok("OK");
}

@httpGet("isResourceOwner")
@isResourceOwner("2301")
public async isResourceOwner() {
return this.ok("OK");
}

@httpGet("inRole")
@inRole("admin")
public async inRole() {
return this.ok("OK");
}
}
```

#### Custom HttpContext access decorator
if you need to define own access decorator that reuses the HttpContext reuse ```httpContextAccessDecoratorFactory```
as it is in an example under.

```ts
import { httpContextAccessDecoratorFactory } from 'inversify-express-utils';

function userExists (pass = true): any {
return httpContextAccessDecoratorFactory(async (context) => {
return (await context.user.isAuthenticated() && pass);
});
}
```

## BaseMiddleware

Extending `BaseMiddleware` allow us to inject dependencies
Expand Down
50 changes: 49 additions & 1 deletion src/decorators.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as express from "express";
import { inject, injectable, decorate } from "inversify";
import { interfaces } from "./interfaces";
import { TYPE, METADATA_KEY, PARAMETER_TYPE } from "./constants";
import { Handler, NextFunction, Request, Response } from "express";
import HttpContext = interfaces.HttpContext;

export const injectHttpContext = inject(TYPE.HttpContext);

Expand Down Expand Up @@ -130,3 +131,50 @@ export function params(type: PARAMETER_TYPE, parameterName?: string) {
Reflect.defineMetadata(METADATA_KEY.controllerParameter, metadataList, target.constructor);
};
}

export interface IContextAcessAdapterFn {
(context: HttpContext): Promise<boolean>;
}

export function httpContextAccessDecoratorFactory(implementation: IContextAcessAdapterFn) {
return function (target: any, key: string | symbol, descriptor: TypedPropertyDescriptor<Function>) {
const fn = descriptor.value as Handler;
descriptor.value = async function (_request: Request, _response: Response, _next: NextFunction) {
const context: HttpContext = Reflect.getMetadata(
METADATA_KEY.httpContext,
_request
);
const hasAccess = await implementation(context);
if (hasAccess) {
return fn.call(this, _request, _response);
} else {
_response
.status(403)
.send({ error: "The user is not authenticated." });

return _response;
}
};

return descriptor;
};
}

export function isAuthenticated (pass = true): any {
return httpContextAccessDecoratorFactory(async (context) => {
return (await context.user.isAuthenticated() && pass);
Copy link
Contributor

Choose a reason for hiding this comment

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

why do we need && pass here ?

});
}

export function inRole (role: string, pass = true): any {
return httpContextAccessDecoratorFactory(async (context) => {
return (await context.user.isInRole(role) && pass);
});
}

export function isResourceOwner (resorceId: string, pass = true): any {
return httpContextAccessDecoratorFactory(async (context) => {
return (await context.user.isResourceOwner(resorceId) && pass);
});
}

10 changes: 8 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { InversifyExpressServer } from "./server";
import { controller, httpMethod, httpGet, httpPut, httpPost, httpPatch,
httpHead, all, httpDelete, request, response, requestParam, queryParam,
requestBody, requestHeaders, cookies, next, principal, injectHttpContext } from "./decorators";
requestBody, requestHeaders, cookies, next, principal, injectHttpContext,
httpContextAccessDecoratorFactory, isAuthenticated, isResourceOwner, inRole } from "./decorators";
import { TYPE } from "./constants";
import { interfaces } from "./interfaces";
import * as results from "./results";
Expand All @@ -14,6 +15,7 @@ import { StringContent } from "./content/stringContent";
import { JsonContent } from "./content/jsonContent";
import { HttpContent } from "./content/httpContent";


export {
getRouteInfo,
getRawMetadata,
Expand Down Expand Up @@ -46,5 +48,9 @@ export {
HttpContent,
StringContent,
JsonContent,
results
results,
httpContextAccessDecoratorFactory,
inRole,
isAuthenticated,
isResourceOwner
};
193 changes: 191 additions & 2 deletions test/auth_provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
interfaces
} from "../src/index";
import { cleanUpMetadata } from "../src/utils";
import {httpContextAccessDecoratorFactory, inRole, isAuthenticated, isResourceOwner} from "../src/decorators";
import AuthProvider = interfaces.AuthProvider;

describe("AuthProvider", () => {

Expand Down Expand Up @@ -70,8 +72,8 @@ describe("AuthProvider", () => {
if (this.httpContext.user !== null) {
const email = this.httpContext.user.details.email;
const name = this._someDependency.name;
const isAuthenticated = await this.httpContext.user.isAuthenticated();
Copy link
Author

Choose a reason for hiding this comment

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

I did it because Travis had failed because a lint error: shadow variable.

expect(isAuthenticated).eq(true);
const _isAuthenticated = await this.httpContext.user.isAuthenticated();
expect(_isAuthenticated).eq(true);
return `${email} & ${name}`;
}
}
Expand All @@ -96,4 +98,191 @@ describe("AuthProvider", () => {

});

describe("Principal`s decorators", () => {
class Principal implements interfaces.Principal {
public details: any;
public constructor(details: any) {
this.details = details;
}
public isAuthenticated() {
return Promise.resolve<boolean>(!!this.details._id);
}
public isResourceOwner(resourceId: any) {
return Promise.resolve<boolean>(this.details.resourceIds.indexOf(resourceId) > -1);
}
public isInRole(role: string) {
return Promise.resolve<boolean>(this.details.roles.indexOf(role) > -1);
}
}

interface IUserDetails {
_id: number;
resourceIds?: string[];
roles?: string[];
}

@injectable()
class CustomAuthProvider implements interfaces.AuthProvider {

@inject("UserDetails") private readonly _details: IUserDetails;

public getUser(
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
const principal = new Principal(this._details);
return Promise.resolve(principal);
}
}

function userExists (pass = true): any {
return httpContextAccessDecoratorFactory(async (context) => {
return (await context.user.isAuthenticated() && pass);
});
}

@controller("/")
class TestController extends BaseHttpController {
@httpGet("userExists")
@userExists()
public async userExists() {
return this.ok("OK");
}

@httpGet("isAuthenticated")
@isAuthenticated()
public async isAuthenticated() {
return this.ok("OK");
}

@httpGet("isResourceOwner")
@isResourceOwner("2301")
public async isResourceOwner() {
return this.ok("OK");
}

@httpGet("inRole")
@inRole("admin")
public async inRole() {
return this.ok("OK");
}
}

const container = new Container();
container.bind<IUserDetails>("UserDetails")
.toConstantValue({ _id: 1 });


const server = new InversifyExpressServer(
container,
null,
null,
null,
CustomAuthProvider
);
const app = server.build();
const authProvider = container.get<CustomAuthProvider>(TYPE.AuthProvider);

describe("Custom decorator", () => {
it("Rejected", (done) => {
container.rebind<IUserDetails>("UserDetails")
.toConstantValue({ _id: 0});
expect(true).eq(true);

supertest(app)
.get("/userExists")
.expect(403)
.end(done);
});

it("Accepted", (done) => {
container.rebind<IUserDetails>("UserDetails")
.toConstantValue({ _id: 1});
expect(true).eq(true);

supertest(app)
.get("/userExists")
.expect(200, `"OK"`, done);
});
});

describe("IsAuthenticated", () => {
it("Rejected", (done) => {
container.rebind<IUserDetails>("UserDetails")
.toConstantValue({ _id: 0});
expect(true).eq(true);

supertest(app)
.get("/isAuthenticated")
.expect(403)
.end(done);
});

it("Accepted", (done) => {
container.rebind<IUserDetails>("UserDetails")
.toConstantValue({ _id: 1});
expect(true).eq(true);

supertest(app)
.get("/isAuthenticated")
.expect(200, `"OK"`, done);
});
});

describe("IsResorceOwner", () => {
it("Rejected", (done) => {
container.rebind<IUserDetails>("UserDetails").toConstantValue({
_id: 1,
resourceIds: ["2909"]
});
expect(true).eq(true);

supertest(app)
.get("/isResourceOwner")
.expect(403)
.end(done);
});

it("Accepted", (done) => {
container.rebind<IUserDetails>("UserDetails").toConstantValue({
_id: 1,
resourceIds: ["2301"]
});
expect(true).eq(true);

supertest(app)
.get("/isResourceOwner")
.expect(200, `"OK"`, done);
});
});

describe("IsRole", () => {
it("Rejected", (done) => {
container.rebind<IUserDetails>("UserDetails").toConstantValue({
_id: 1,
roles: ["manager"]
});
expect(true).eq(true);

supertest(app)
.get("/inRole")
.expect(403)
.end(done);
});

it("Accepted", (done) => {
container.rebind<IUserDetails>("UserDetails").toConstantValue({
_id: 1,
roles: ["admin"]
});
expect(true).eq(true);

supertest(app)
.get("/inRole")
.expect(200, `"OK"`, done);
});
});
});

});