-
Notifications
You must be signed in to change notification settings - Fork 1
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
feat(doc): passport #75
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
10c9611
feat(doc): passport
souravdasslg 566afc1
Update docs/tutorials/snippets/passport/OriginalDiscordProtocol.js
souravdasslg 3ad99cd
Update docs/tutorials/snippets/passport/OriginalJwtPassport.js
souravdasslg 5b9354b
Update docs/tutorials/snippets/passport/server.ts
souravdasslg 9d6c003
Update docs/tutorials/passport.md
souravdasslg d22736d
Update docs/tutorials/passport.md
souravdasslg 9622b89
Update docs/tutorials/passport.md
souravdasslg ed7aa17
Update docs/tutorials/passport.md
souravdasslg cde76fa
Update passport.md
souravdasslg 4d358fa
Update docs/tutorials/snippets/passport/DiscordProtocol.ts
Romakita 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,229 @@ | ||
# Passport.js | ||
|
||
<Banner src="/passportjs.png" height="128" href="http://www.passportjs.org/"></Banner> | ||
|
||
> Passport is an authentication middleware for Node.js. | ||
|
||
Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. | ||
A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more. | ||
|
||
<Projects type="projects"/> | ||
|
||
## Installation | ||
|
||
Before using Passport, we need to install the [Passport.js](https://www.npmjs.com/package/passport) and the Passport-local. | ||
|
||
::: code-group | ||
|
||
```bash [npm] | ||
npm install --save passport | ||
``` | ||
|
||
```bash [yarn] | ||
yarn add passport | ||
``` | ||
|
||
::: | ||
|
||
## Configure your server | ||
|
||
Add this configuration to your server: | ||
|
||
<<< @/tutorials/snippets/passport/server.ts | ||
|
||
### UserInfo | ||
By default, Ts.ED uses a UserInfo model to serialize and deserialize users in sessions: | ||
|
||
```typescript | ||
import {Format, Property} from "@tsed/schema"; | ||
|
||
export class UserInfo { | ||
@Property() | ||
id: string; | ||
|
||
@Property() | ||
@Format("email") | ||
email: string; | ||
|
||
@Property() | ||
password: string; | ||
} | ||
``` | ||
|
||
You can set your own UserInfo model by changing the passport server configuration: | ||
|
||
```typescript | ||
class CustomUserInfoModel { | ||
@Property() | ||
id: string; | ||
|
||
@Property() | ||
token: string; | ||
} | ||
|
||
@Configuration({ | ||
passport: { | ||
userInfoModel: CustomUserInfoModel | ||
} | ||
}) | ||
``` | ||
|
||
It's also possible to disable model serialize/deserialize by setting a false value to `userInfoModel` options. | ||
|
||
## Create a new Protocol | ||
|
||
A Protocol is a special Ts.ED service which is used to declare a Passport Strategy and handle Passport lifecycle. | ||
|
||
Here is an example with the PassportLocal: | ||
|
||
::: code-group | ||
|
||
<<< @/tutorials/snippets/passport/LoginLocalProtocol.ts [LoginLocalProtocol.ts] | ||
|
||
<<< @/tutorials/snippets/passport/LoginLocalProtocol.spec.ts [LoginLocalProtocol.spec.ts] | ||
|
||
::: | ||
|
||
::: tip | ||
For signup and basic flow, you can check out one of our examples: | ||
|
||
<Projects type="projects"/> | ||
::: | ||
|
||
## Create the Passport controller | ||
|
||
Create a new Passport controller as following: | ||
|
||
<<< @/tutorials/snippets/passport/PassportCtrl.ts | ||
|
||
This controller will provide all required endpoints that will be used by the different protocols. | ||
|
||
## Protect a route | ||
|
||
@@Authorize@@ and @@Authenticate@@ decorators can be used as a Guard to protect your routes. | ||
|
||
<<< @/tutorials/snippets/passport/guard-ctrl.ts | ||
|
||
## Basic Auth | ||
|
||
It is also possible to use the Basic Auth. To do that, you have to create a Protocol based on `passport-http` strategy. | ||
|
||
<<< @/tutorials/snippets/passport/BasicProtocol.ts | ||
|
||
Then, add the protocol name on the @@Authorize@@ decorator: | ||
|
||
<<< @/tutorials/snippets/passport/guard-basic-auth.ts | ||
|
||
## Advanced Auth | ||
|
||
### JWT | ||
|
||
JWT auth scenario, for example, is different. The Strategy will produce a payload which contains data and JWT token. This information | ||
isn't attached to the request and cannot be retrieved using the default Ts.ED decorator. | ||
|
||
To solve it, the `@tsed/passport` has two decorators @@Arg@@ and @@Args@@ to get the argument given to the original verify function by the Strategy. | ||
|
||
For example, the official `passport-jwt` documentation gives this javascript code to configure the strategy: | ||
|
||
<<< @/tutorials/snippets/passport/OriginalJwtPassport.js | ||
|
||
The example code can be written with Ts.ED as following: | ||
|
||
<<< @/tutorials/snippets/passport/JwtProtocol.ts | ||
|
||
### Azure Bearer Auth | ||
|
||
Azure bearer uses another scenario which requires to return multiple arguments. The `$onVerify` method accepts an `Array` to return multiple values. | ||
|
||
<<< @/tutorials/snippets/passport/AzureBearerProtocol.ts | ||
|
||
### Discord Auth | ||
|
||
Discord passport gives an example to refresh the token. To do that, you have to create a new Strategy and register with the refresh function from `passport-oauth2-refresh` module. | ||
|
||
Here is the JavaScript code: | ||
|
||
<<< @/tutorials/snippets/passport/OriginalDiscordProtocol.js | ||
|
||
Ts.ED provides a way to handle the strategy built by the `@tsed/passport` by using the `$onInstall` hook. | ||
|
||
<<< @/tutorials/snippets/passport/DiscordProtocol.ts | ||
|
||
### Facebook Auth | ||
|
||
Facebook passport gives an example to use scope on routes (permissions). We'll see how we can configure a route with a mandatory `scope`. | ||
|
||
Here is the corresponding Facebook protocol: | ||
|
||
<<< @/tutorials/snippets/passport/FacebookProtocol.ts | ||
|
||
::: tip Note | ||
souravdasslg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
To use Facebook authentication, first create an app at Facebook Developers. | ||
In order to use Facebook authentication, you must first create an app at Facebook Developers. When created, an app is assigned an App ID and an App Secret. Your application must also implement a redirect URL, to which Facebook will redirect users after they have approved access for your application. | ||
|
||
The verify callback for Facebook authentication accepts `accessToken`, `refreshToken`, and `profile` arguments. `profile` will contain user profile information provided by Facebook; refer to User [Profile](http://www.passportjs.org/guide/profile/) for additional information. | ||
::: | ||
|
||
::: warning | ||
For security reasons, the redirection URL must reside on the same host that is registered with Facebook. | ||
::: | ||
|
||
Then we have to implement routes as following: | ||
|
||
<<< @/tutorials/snippets/passport/PassportFacebookCtrl.ts | ||
|
||
::: tip Note | ||
@@Authenticate@@ decorator accepts a second option to configure the `scope`. It is equivalent to `passport.authenticate('facebook', {scope: 'read_stream' })` | ||
::: | ||
|
||
## Roles | ||
|
||
Roles access management isn't a part of Passport.js and Ts.ED doesn't provide a way to handle this because it is specific for each application. | ||
|
||
This section will give basic examples to implement your own roles strategy access. | ||
|
||
To begin we have to implement a middleware which will be responsible to check the user role: | ||
|
||
<<< @/tutorials/snippets/passport/AcceptRolesMiddleware.ts | ||
|
||
Then, we have to create a decorator `AcceptRoles`. This decorator will store the given roles and register the AcceptRolesMiddleware created before. | ||
|
||
<<< @/tutorials/snippets/passport/acceptRoles.ts | ||
|
||
Finally, we can use this decorator on an Endpoint like this: | ||
|
||
<<< @/tutorials/snippets/passport/roles-usage.ts | ||
|
||
## Catch Passport Exception <Badge text="6.18.0+" /> | ||
|
||
```typescript | ||
import {Catch, ExceptionFilterMethods, PlatformContext} from "@tsed/common"; | ||
import {PassportException} from "@tsed/passport"; | ||
|
||
@Catch(PassportException) | ||
export class PassportExceptionFilter implements ExceptionFilterMethods { | ||
async catch(exception: PassportException, ctx: PlatformContext) { | ||
const {response} = ctx; | ||
|
||
console.log(exception.name); | ||
} | ||
} | ||
``` | ||
|
||
## Decorators | ||
|
||
<ApiList query="module == '@tsed/passport' && symbolType === 'decorator'" /> | ||
|
||
## Author | ||
|
||
<GithubContributors users="['Romakita']"/> | ||
|
||
## Maintainers <Badge text="Help wanted" /> | ||
|
||
<GithubContributors users="['Romakita']"/> | ||
|
||
<div class="flex items-center justify-center p-5"> | ||
<Button href="/contributing.html" class="rounded-medium"> | ||
Become maintainer | ||
</Button> | ||
</div> |
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 |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import {Middleware} from "@tsed/platform-middlewares"; | ||
import {Context} from "@tsed/platform-params"; | ||
import {Unauthorized} from "@tsed/exceptions"; | ||
|
||
@Middleware() | ||
export class AcceptRolesMiddleware { | ||
use(@Context() ctx: Context) { | ||
const request = ctx.getReq(); | ||
|
||
if (request.user && request.isAuthenticated()) { | ||
const roles = ctx.endpoint.get(AcceptRolesMiddleware); | ||
|
||
if (!roles.includes(request.user.role)) { | ||
throw new Unauthorized("Insufficient role"); | ||
} | ||
} | ||
} | ||
} |
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 |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import {Context} from "@tsed/platform-params"; | ||
import {Arg, OnVerify, PassportMiddleware, Protocol} from "@tsed/passport"; | ||
import {BearerStrategy, ITokenPayload} from "passport-azure-ad"; | ||
import {AuthService} from "../services/auth/AuthService"; | ||
|
||
@Protocol({ | ||
name: "azure-bearer", | ||
useStrategy: BearerStrategy | ||
}) | ||
export class AzureBearerProtocol implements OnVerify { | ||
constructor(private authService: AuthService) {} | ||
|
||
$onVerify(@Arg(0) token: ITokenPayload, @Context() ctx: Context) { | ||
// Verify is the right place to check given token and return UserInfo | ||
const {authService} = this; | ||
const {options = {}} = ctx.endpoint.get(PassportMiddleware) || {}; // retrieve options configured for the endpoint | ||
// check precondition and authenticate user by their token and given options | ||
try { | ||
const user = authService.verify(token, options); | ||
|
||
if (!user) { | ||
authService.add(token); | ||
ctx.logger.info({event: "BearerStrategy - token: ", token}); | ||
|
||
return token; | ||
} | ||
|
||
ctx.logger.info({event: "BearerStrategy - user: ", token}); | ||
|
||
return [user, token]; | ||
} catch (error) { | ||
ctx.logger.error({event: "BearerStrategy", token, error}); | ||
throw error; | ||
} | ||
} | ||
} |
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 |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import * as Sinon from "sinon"; | ||
import {User} from "../models/User"; | ||
import {UsersService} from "../services/users/UsersService"; | ||
import {BasicProtocol} from "./BasicProtocol"; | ||
import {PlatformTest} from "@tsed/common"; | ||
|
||
describe("BasicProtocol", () => { | ||
beforeEach(() => PlatformTest.create()); | ||
afterEach(() => PlatformTest.reset()); | ||
|
||
describe(".$onVerify()", () => { | ||
it("should return a user", async () => { | ||
// GIVEN | ||
const request = {}; | ||
const username = "[email protected]"; | ||
const password = "password"; | ||
const user = new User(); | ||
user.email = username; | ||
user.password = password; | ||
|
||
const usersService = { | ||
findOne: Sinon.stub().resolves(user) | ||
}; | ||
|
||
const protocol: BasicProtocol = await PlatformTest.invoke(BasicProtocol, [ | ||
{ | ||
token: UsersService, | ||
use: usersService | ||
} | ||
]); | ||
|
||
// WHEN | ||
const result = await protocol.$onVerify(request as any, username, password); | ||
|
||
// THEN | ||
usersService.findOne.should.be.calledWithExactly({email: "[email protected]"}); | ||
result.should.deep.equal(user); | ||
}); | ||
it("should return a user", async () => { | ||
// GIVEN | ||
const request = {}; | ||
const username = "[email protected]"; | ||
const password = "password"; | ||
const user = new User(); | ||
user.email = username; | ||
user.password = `${password}2`; | ||
|
||
const usersService = { | ||
findOne: Sinon.stub().resolves(user) | ||
}; | ||
|
||
const protocol: BasicProtocol = await PlatformTest.invoke(BasicProtocol, [ | ||
{ | ||
token: UsersService, | ||
use: usersService | ||
} | ||
]); | ||
|
||
// WHEN | ||
const result = await protocol.$onVerify(request as any, username, password); | ||
|
||
// THEN | ||
usersService.findOne.should.be.calledWithExactly({email: "[email protected]"}); | ||
result.should.deep.equal(false); | ||
}); | ||
it("should return a false when user isn't found", async () => { | ||
// GIVEN | ||
const request = {}; | ||
const username = "[email protected]"; | ||
const password = "password"; | ||
|
||
const usersService = { | ||
findOne: Sinon.stub().resolves(undefined) | ||
}; | ||
|
||
const protocol: BasicProtocol = await PlatformTest.invoke(BasicProtocol, [ | ||
{ | ||
token: UsersService, | ||
use: usersService | ||
} | ||
]); | ||
|
||
// WHEN | ||
const result = await protocol.$onVerify(request as any, username, password); | ||
|
||
// THEN | ||
usersService.findOne.should.be.calledWithExactly({email: "[email protected]"}); | ||
result.should.deep.equal(false); | ||
}); | ||
}); | ||
}); |
Oops, something went wrong.
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.
::: code-group
:::