-
Notifications
You must be signed in to change notification settings - Fork 100
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
victor-shelepen
wants to merge
5
commits into
inversify:master
Choose a base branch
from
victor-shelepen:vlikin-inversify-express-principle-decorators
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c6e41d1
It defines an IsAuthenticated decorator that is applied to routes.
victor-shelepen 681146a
Small fix. The disable test has been enabled.
victor-shelepen 6c11dc6
Lint fixing.
victor-shelepen 30f0b13
All decorators have been generated for Principal.
victor-shelepen 5e2bfd4
Authentication provider decorators documentation. Also some fixes.
victor-shelepen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
|
||
|
@@ -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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why do we need |
||
}); | ||
} | ||
|
||
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); | ||
}); | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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", () => { | ||
|
||
|
@@ -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(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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}`; | ||
} | ||
} | ||
|
@@ -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); | ||
}); | ||
}); | ||
}); | ||
|
||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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