# tbs-auth

> Module for handling TBS authentication and authorization

Latest version **1.0.4** (published 2024-02-22) · UNLICENSED license · 0 weekly downloads

## Install

```sh
npm install tbs-auth
pnpm add tbs-auth
yarn add tbs-auth
bun add tbs-auth
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.4 |
| Published | 2024-02-22 |
| First published | 2023-11-10 |
| Weekly downloads | 0 |
| License | UNLICENSED |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 62 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Maintainers | abiel-tbs |
| Keywords | nestjs, tbs, typescript |

## Links

- npm: https://www.npmjs.com/package/tbs-auth
- Repository: https://github.com/The-Body-Shop-Indonesia/tbs-auth
- Issues: https://github.com/The-Body-Shop-Indonesia/tbs-auth/issues
- npm.io page: https://npm.io/package/tbs-auth

## Alternatives

- [@openai/codex-sdk](https://npm.io/package/@openai/codex-sdk.md) — 731.4K weekly downloads
- [babel-plugin-transform-react-jsx](https://npm.io/package/babel-plugin-transform-react-jsx.md) — 565.0K weekly downloads
- [babel-helper-remove-or-void](https://npm.io/package/babel-helper-remove-or-void.md) — 508.5K weekly downloads
- [@pnpm/store-controller-types](https://npm.io/package/@pnpm/store-controller-types.md) — 186.9K weekly downloads
- [react-native-signature-canvas](https://npm.io/package/react-native-signature-canvas.md) — 155.6K weekly downloads

## Recent versions

- 1.0.4 (latest) — 2024-02-22
- 1.0.3 — 2024-02-21
- 1.0.2 — 2024-02-20
- 1.0.1 — 2024-02-20
- 1.0.0 — 2024-01-29
- 0.0.1 — 2023-11-10

## README

# TBS Auth

Package for TBS authentication and authorization. Only support for casdoor.

## Features

1. Authentication check (token).
2. Authorization check based on casdoor enforcer.
3. Auto sync / populate for casdoor enforcer policy.

## Installation

### Yarn

```bash
yarn add tbs-auth
```

### NPM

```bash
npm install tbs-auth
```

## Getting Started

### Module registration

Registering the module:

```typescript
import { TbsAuthModule } from "tbs-auth";

TbsAuthModule.register({
  internal_urls: ['localhost', 'users'], // optional
  app_port: 3000, // required when internal_urls set
  casdoor: {
    host: "http:localhost:8000", // your casdoor api url
    client_id: "ada71jxcasd", // your casdoor client id
    private_key: "ajdkad81lkj123291nnsadjhsahj1", // your casdoor client secret
    organization: "tbs-icarus", // yout casdoor organization
    appName: 'tbs-app' // your casdoor app name 
  }
})
```

Auto Populate / Sync Policy. Put on `main.ts`.

```typescript
import { TbsAuthSyncService } from "tbs-auth";

await TbsAuthSyncService(
  app, 
  {
    host: process.env.CASDOOR_HOST,
    client_id: process.env.CASDOOR_CLIENT_ID,
    private_key: process.env.CASDOOR_PRIVATE_KEY,
  },
  "tbs",
  "products:",
  "tbs-icarus",
  "tbs-app",
);
```

### Guards

Register any of the guards either globally, or scoped in your controller.

#### Global registration using APP_GUARD token
***NOTE: These are in order, see https://docs.nestjs.com/guards#binding-guards for more information.***
```typescript
import { AuthenticationGuard } from "tbs-auth"

providers: [
  {
    provide: APP_GUARD,     
    useClass: AuthenticationGuard,
  },
]
```

#### Public API
This decorator can be applied at the controller or function level. Function-level application takes precedence over controller-level. The decorator accepts parameters:
- `false`  &rarr; If a token is provided, it will be checked for validity. If the token is revoked or expired, an unauthorized error will be thrown. However, if no token is provided, the client can still access this API. 
- `true` &rarr; skip everything even token provided. 
```typescript
import { Public } from "tbs-auth"

@Controller('cats')
@Public()
export class CatsController {}
```

#### Internal Access API
This decorator can be applied at the controller or function level. Function-level application takes precedence over controller-level. The decorator accepts parameters:
- `STRICT` &rarr; Requester domain must be registered on `internal_urls` config module registration above.
- `NOT_STRICT` &rarr; When the requester domain is not registered in internal_urls, a token must be provided for authorization. However, if the requester domain is registered, the token is bypassed.
```typescript
import { Public } from "tbs-auth"

@Controller('cats')
@Public() // fill true for skip the provided token, or false to skip everything
export class CatsController {}
```

## What does these providers do ?

### AuthenticationGuard
Adds an authentication guard, you can also have it scoped if you like (using regular `@UseGuards(AuthenticationGuard)` in your controllers). By default, it will throw a 401 unauthorized when it is unable to verify the JWT token or `Bearer` header is missing.

## Configuring controllers

In your controllers, simply do:

```typescript
import {Public, InternalAccess, InternalAccessMethod} from "tbs-auth";
import {Controller, Get, Delete, Put, Post, Param} from '@nestjs/common';
import {Product} from './product';
import {ProductService} from './product.service';
import {BypassEnforcer} from "./bypass-enforcer.decorator";

@Controller()
export class ProductController {
  constructor(private service: ProductService) {
  }

  @Get()
  @Public()
  async findAll() {
    return await this.service.findAll();
  }

  @Get()
  @InternalAccess()
  async findAllBarcodes() {
    return await this.service.findAllBarcodes();
  }

  @Get(':code')
  @BypassEnforcer()
  async findByCode(@Param('code') code: string) {
    return await this.service.findByCode(code);
  }

  @Post()
  @InternalAccess(InternalAccessMethod.STRICT)
  async create(@Body() product: Product) {
    return await this.service.create(product);
  }

  @Delete(':code')
  async deleteByCode(@Param('code') code: string) {
    return await this.service.deleteByCode(code);
  }

  @Put(':code')
  async update(@Param('code') code: string, @Body() product: Product) {
    return await this.service.update(code, product);
  }
}
```

## Decorators

Here is the decorators you can use in your controllers.

| Decorator          | Description                                                  | Default      |
|--------------------|--------------------------------------------------------------|--------------|
| @Public            | Allow any user to use the route.                             | `true`       |
| @InternalAccess    | Check if the request client IP is in the whitelist URL list. | `NOT_STRICT` |
| @PopulateEnforcer | Auto populate enforcer data for some role in an endpoint or controller | `null`
| @BypassEnforcer | Bypass the enforcer checking on an endpoint or controller | `true` |



## Configuration options

### Keycloak Options
For Keycloak options, refer to the official [keycloak-connect](https://github.com/keycloak/keycloak-nodejs-connect/blob/main/middleware/auth-utils/config.js) library.

### Nest Keycloak Options
| Option               | Description                                               | Required                    | Default      |
|----------------------|-----------------------------------------------------------|-----------------------------|--------------|
| internalUrls         | Sets the list of whitelist url keyword to access endpoint | no                          | -            |
| app_port             | Sets the port of your app server port                     | yes when `interalUrls` sets | -            |
| casdoor.host         | Casdoor API Url                                           | yes                         | -            |
| casdoor.client_id    | Casdoor Client ID                                         | yes                         | -            |
| casdoor.private_key  | Casdoor Client Secret                                     | yes                         | -            |
| casdoor.organization | Casdoor Organization                                      | yes                         | -            |
| casdoor.appName      | Casdoor App Name                                          | yes                         | -            |

---
_Source: https://npm.io/package/tbs-auth · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
