npm package: @raptorjs/polizei
Description: A comprehensive NestJS module for authentication and authorization integration with the Polizei service. Provides decorators, guards, and services for seamless permission management and user authentication in NestJS applications.
Author: William Amed
Latest version: 1.2.0

# @raptorjs/polizei

A comprehensive NestJS module for authentication and authorization integration with the Polizei service. Provides decorators, guards, and services for seamless permission management and user authentication in NestJS applications.

## Features

- 🔐 **JWT Authentication** - Built-in JWT token validation
- 🛡️ **Permission Guards** - Route-level permission validation
- 🏢 **Multi-scope Support** - Handle multiple business scopes per user
- 🔑 **API Key Authentication** - Support for service-to-service authentication
- 🎯 **Decorator-based** - Clean, declarative permission system
- 🚀 **Production Ready** - TypeScript support and error handling
- 🔧 **Configurable** - Development mode for testing without external services

## Installation

```bash
npm install @raptorjs/polizei @nestjs/jwt @nestjs/axios axios
```

## Quick Start

### 1. Import and Configure Module

```typescript
import { Module } from '@nestjs/common';
import { PolizeiModule } from '@raptorjs/polizei';

@Module({
  imports: [
    PolizeiModule.register({
      serviceUrl: 'https://your-polizei-service.com',
      apiKey: 'your-workspace-api-key',
      jwtKey: 'your-jwt-secret-key',
      mode: 'development', // or 'production'
      logging: true
    })
  ],
})
export class AppModule {}
```

### 2. Use Permission Decorators in Controllers

```typescript
import { Controller, Get } from '@nestjs/common';
import { Permission, UserToken, GetScopes, GetCurrentScope } from '@raptorjs/polizei';

@Controller('users')
export class UsersController {
  
  @Get('profile')
  @Permission()
  getProfile(@UserToken() user) {
    return { user };
  }

  @Get('scopes')
  @Permission()
  getUserScopes(@GetScopes() scopes) {
    return { scopes };
  }

  @Get('current-scope')
  @Permission()
  getCurrentScope(@GetCurrentScope() currentScope) {
    return { currentScope };
  }
}
```

### 3. API Key Authentication (Service-to-Service)

```typescript
import { Controller, Post } from '@nestjs/common';
import { ApiPermission, RootScope } from '@raptorjs/polizei';

@Controller('api')
export class ApiController {
  
  @Post('data')
  @ApiPermission()
  getApiData(@RootScope() rootBusiness) {
    return { data: 'secure-api-data', business: rootBusiness };
  }
}
```

## Configuration Options

| Option | Type | Description | Default |
|--------|------|-------------|---------|
| `serviceUrl` | `string` | Polizei service URL | Required |
| `apiKey` | `string` | Workspace API key | Required |
| `jwtKey` | `string` | JWT secret for token validation | Optional |
| `mode` | `'production'\|'development'` | Operation mode | 'development' |
| `logging` | `boolean` | Enable request logging | `false` |

## Decorators

### @Permission(...permissions: string[])
Protects routes requiring specific permissions. Validates user has all specified permissions.

### @ApiPermission(...permissions: string[])
Protects API routes using API key authentication instead of JWT.

### @UserToken()
Extracts the authenticated user from the JWT token.

### @GetScopes(index?: number)
Retrieves user's associated scopes. Optional index for specific scope.

### @GetCurrentScope()
Gets the current active scope from headers or first available scope.

### @RootScope()
Retrieves root business information for API key authenticated requests.

## Service Methods

The `PolizeiService` provides various methods for user and scope management:

```typescript
// User management
await polizeiService.isAuthorize(username, routePath);
await polizeiService.getUserPayload(username);
await polizeiService.searchUser(username);

// Scope management
await polizeiService.getScopesOfApiKey(apiKey);
await polizeiService.getScope(scopeId);
await polizeiService.getScopesById(scopeIds);

// User-scope operations
await polizeiService.addUserToScope(username, scopeId);
await polizeiService.removeUserOfScope(username, scopeId);

// Authentication
await polizeiService.login(username, password);
await polizeiService.register(userData);
```

## Development Mode

In development mode (`mode: 'development'`), permission checks are bypassed but logged, allowing for easier development and testing without requiring a running Polizei service.

## Error Handling

The module throws appropriate NestJS exceptions:
- `UnauthorizedException` - Invalid or missing JWT token
- `ForbiddenException` - Insufficient permissions
- `NotAcceptableException` - Invalid scope or user data

## Dependencies

- `@nestjs/common`
- `@nestjs/core`
- `@nestjs/jwt`
- `@nestjs/axios`
- `axios`
- `@raptorjs/common`

## License

MIT © William Amed

## Support

For issues and feature requests, please create an issue in the GitHub repository.

---

Built with ❤️ for the NestJS community