Skip to content

Commit

Permalink
feat(doc): passport (#75)
Browse files Browse the repository at this point in the history
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Romain Lenzotti <[email protected]>
  • Loading branch information
3 people committed Jul 9, 2024
1 parent 0e4b8ea commit 0d310b0
Show file tree
Hide file tree
Showing 20 changed files with 841 additions and 0 deletions.
229 changes: 229 additions & 0 deletions docs/tutorials/passport.md
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
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>
18 changes: 18 additions & 0 deletions docs/tutorials/snippets/passport/AcceptRolesMiddleware.ts
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");
}
}
}
}
36 changes: 36 additions & 0 deletions docs/tutorials/snippets/passport/AzureBearerProtocol.ts
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;
}
}
}
91 changes: 91 additions & 0 deletions docs/tutorials/snippets/passport/BasicProtocol.spec.ts
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);
});
});
});
Loading

0 comments on commit 0d310b0

Please sign in to comment.