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 3 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
27 changes: 26 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,27 @@ export function params(type: PARAMETER_TYPE, parameterName?: string) {
Reflect.defineMetadata(METADATA_KEY.controllerParameter, metadataList, target.constructor);
};
}

export function isAuthenticated (pass = true): any {
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 _isAuthenticated = (await context.user.isAuthenticated());
if (_isAuthenticated && pass) {
return fn.call(this, _request, _response);
} else {
_response
.status(403)
.send({ error: "The user is not authenticated." });

return _response;
}
};

return descriptor;
};
}
88 changes: 86 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 { isAuthenticated } 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,86 @@ 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>(resourceId === 1111);
}
public isInRole(role: string) {
return Promise.resolve<boolean>(role === "admin");
}
}

interface IUserDetails {
_id: number;
}

@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);
}
}

@controller("/")
class TestController extends BaseHttpController {
@httpGet("/")
@isAuthenticated()
public async getTest() {
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);

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

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

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

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

});