npm package: @plantandfood/kup.auth
Description: ## Installation
Latest version: 14.0.15

# kup.auth

## Installation

```sh
npm install --save-exact kup.auth
```

## Usage

You need to import the `KupAuthModule` by adding the following lines to your `app.module.ts` file.

```javascript
// app.module.ts
import { NgModule } from '@angular/core';
import { KupAuthModule } from '@plantandfood/kup.auth';

// You can get the options from other services,
// e.g. KupEnvService, by injecting them.
// Or you can use angular environment, or have it hard coded.

export function authFactory() {
  return {
    keycloakConfig: {
      url: 'https://keycloak-url',
      realm: 'keycloak-realm',
      clientId: 'client-id'
    },
    keycloakInitOptions: {
      onLoad: 'login-required',
      checkLoginIframe: false,
    },
  };
}

@NgModule({
  ...
  imports: [
    ...
    KupAuthModule.forRoot({
      useFactory: authFactory,
      deps: [
        // you can add services you need to access in factory function here
      ]
    }),
  ],
})
export class AppModule {}
```

Note that the `authFactory` is not an arrow function. This is due to AOT compiling. If you are not using AOT you can inline the `useFactory` as an arrow function but it is not recommended as you can run into issues later on if you switch to AOT (see https://angular.io/guide/aot-metadata-errors#function-calls-are-not-supported).

### Auth Guard

You can use angular router guards, to protect your routes from unauthorized users.

```javascript
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Router, Routes } from '@angular/router';
import { CanAuthenticationGuard } from '@plantandfood/kup.auth';

const routes: Routes = [
  ...{
    path: 'some-guarded-path',
    canActivate: [CanAuthenticationGuard],
    data: {
      roles: ['KUP_USER'],
    },
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [
    {
      provide: 'CanAuthenticationGuard',
      useValue: (router: Router) => true,
    },
  ],
})
export class AppRoutingModule {}
```

### `AuthService`

You can access the authentication information directly in any injectable using `AuthService`.

```javascript
// trial-permissions.service.ts
import { Injectable } from '@angular/core';
import { AuthService } from '@plantandfood/kup.auth';
...

@Injectable({ providedIn: 'root' })
export class TrialPermissionsService {
  constructor(
    private authService: AuthService,
  ) { }

  ...

  get canEditTrial$(): Observable<boolean> {
    const isTrialAdmin: boolean = this.authService.isUserInRole(
      UserRole.KUP_TRIAL_ADMIN
    );
    return combineLatest(
      of(isTrialAdmin),
      this.rightsSummary$.pipe(
        map(rightsSummary => rightsSummary && rightsSummary.canEdit)
      )
    ).pipe(map(([isTrialAdmin, canEdit]) => isTrialAdmin || canEdit));
  }
}
```

## API

#### `KupAuthModule`

```javascript
class KupAuthModule {}
```

| Methods                                                              | Description                                                                      |
| -------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `static forRoot(options: KupAuthModuleOptions): ModuleWithProviders` | Initializes the module with keycloack config provided using useFactory function. |

### Providers

#### `KupEnvService`

| Methods                                                       | Description                                                 |
| ------------------------------------------------------------- | ----------------------------------------------------------- |
| `getToken(): Observable<string>`                              | Returns observable which emits JWT                          |
| `loadProfileData(): Observable<any>`                          | Loads user profile                                          |
| `loadPermissions(): void`                                     | Loads user permissions                                      |
| `getUserRoles(): string[]`                                    | Returns an array of user roles for currently logged in user |
| `isUserInRole(role: any): boolean`                            | Returns true if user has specified role                     |
| `createPermissionsGuard(router: Router): NgxPermissionsGuard` | permissions                                                 |
| `logout(): void`                                              | Logs out the user                                           |

| Getters           | Description                           |
| ----------------- | ------------------------------------- |
| `isAuthenticated` | Returns true if user is authenticated |
| `displayName`     | Returns user name                     |

### Guards

See Usage section for more info.