# user-grants

> 1. Go to https://gitlab.com/profile/keys and insert SSH key. If you don't have it, click on link "generate one" and paste the key on preview page 2. Open git bash and digit: ssh-keyscan -t rsa gitlab.com >> ~/.ssh/known_hosts

Latest version **1.0.0** (published 2018-08-17) · MIT license · 0 weekly downloads

## Install

```sh
npm install user-grants
pnpm add user-grants
yarn add user-grants
bun add user-grants
```

## Health

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

Positive: has types; esm support; no vulnerabilities.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.0 |
| Published | 2018-08-17 |
| First published | 2018-08-17 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 9 |
| Unpacked size | 49 KB |
| Known vulnerabilities | 0 (+21 in 3 direct dependencies) |
| Install scripts | no |
| Maintainers | smiccoli |

## Links

- npm: https://www.npmjs.com/package/user-grants
- npm.io page: https://npm.io/package/user-grants

## Dependencies (9)

- [rxjs](https://npm.io/package/rxjs.md) ^5.5.6
- [tslib](https://npm.io/package/tslib.md) ^1.7.1
- [core-js](https://npm.io/package/core-js.md) ^2.4.1
- [zone.js](https://npm.io/package/zone.js.md) ^0.8.19
- [@angular/core](https://npm.io/package/@angular/core.md) ^5.2.0
- [@angular/http](https://npm.io/package/@angular/http.md) ^5.2.0
- [@angular/common](https://npm.io/package/@angular/common.md) ^5.2.0
- [keycloak-angular](https://npm.io/package/keycloak-angular.md) 1.4.1
- [@angular/compiler](https://npm.io/package/@angular/compiler.md) ^5.2.0

## Recent versions

- 1.0.0 (latest) — 2018-08-17

## README

# HOW TO CONFIGURE INSTALL FROM GITLAB
1. Go to https://gitlab.com/profile/keys and insert SSH key. If you don't have it, click on link "generate one" and paste the key on preview page
2. Open git bash and digit:
ssh-keyscan -t rsa gitlab.com >> ~/.ssh/known_hosts

# HOW TO INSTALL APPLICATION
### install user grants module
`npm i -S git+ssh://git@gitlab.com:abcdj/auth-client-frontend.git#0.0.1`

### import UserGrantsModule and Keycloak inside app.module.ts
```
import { initializer } from './_config/app-init';
import { KeycloakService, KeycloakAngularModule } from 'keycloak-angular';
import { UserGrantsModule } from "./node_modules/user-grants/user-grants.module";
import { UserGrantsService } from './node_modules/user-grants/src/app/services/user-grants.service';
...
@NgModule({
  imports: [
    KeycloakAngularModule,
    UserGrantsModule
    ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initializer,
      multi: true,
       deps: [KeycloakService, UserGrantsService]
    },
    KeycloakService
  ]
    
)}
```
### inside app.init.ts import the service
```
import { KeycloakService } from 'keycloak-angular';
import { UserGrantsService } from '<root>/node_modules/user-grants/src/app/services/user-grants.service';

export function initializer(keycloak: KeycloakService, userGrants: UserGrantsService): () => Promise<any> {
  return (): Promise<any> => {
    return new Promise(async (resolve, reject) => {

        try {
          await keycloak.init(
            {
              config: {
                url: environment.keycloakRootUrl,
                realm: 'abcdj',
                clientId: 'mlm-ui-local'
              },
              initOptions: {
                onLoad: 'login-required',
                checkLoginIframe: false
              },
              bearerExcludedUrls: [ ]
            }
          );
          keycloak.getToken().then(token => {

            const grantJsonUrl = environment.endpoints.userCapabilities;

            localStorage.setItem('token', token);

            /* get all User grants */
            userGrants.init({
              urlJsonGrants: grantJsonUrl,
              token: environment.isKeycloakActivated ? localStorage.getItem('token') : null
            }).then(() => {
              resolve(token);
            }).catch(error => {
              reject(error);
            });

          }).catch(error => {
            reject(error);
          });

        } catch (error) {
          reject(error);
        }
    });
  };
}
```
### create an auth.guard.ts file and add this content
```
import { Injectable } from '@angular/core';
import {
  Router,
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';
import { KeycloakService, KeycloakAuthGuard } from 'keycloak-angular';


@Injectable()
export class AuthGuard extends KeycloakAuthGuard implements CanActivate {

  cancelledNavigation: string;

  constructor(
    protected router: Router,
    protected keycloakAngular: KeycloakService) {
    super(router, keycloakAngular);
    this.cancelledNavigation = undefined;
  }

  isAccessAllowed(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {

      return new Promise(async (resolve, reject) => {

          if (!this.authenticated) {
            this.keycloakAngular.login();
            return;
          }
          const requiredRoles = route.data.roles;
          if (!requiredRoles || requiredRoles.length === 0) {
            return resolve(true);
          } else {
            if (!this.roles || this.roles.length === 0) {
              resolve(false);
            }
            let granted: boolean = false;
            for (const requiredRole of requiredRoles) {
              if (this.roles.indexOf(requiredRole) > -1) {
                granted = true;
                break;
              }
            }
            resolve(granted);
          }


      });

  }
}
```
### in app.routes.ts add "canActivate: [AuthGuard]" for each route that require restricted access, as following
```
 { path: '', component: NameComponent, canActivate: [AuthGuard]}
```
 
### to check permissions inside a component, import UserGrantService inside your component.ts and use the hasPermission('resource', 'scope') method in ts and html files, as following
```
import { UserGrantsService } from '../../../../node_modules/user-grants/src/app/services/user-grants.service';
 
constructor(public userGrants: UserGrantsService) {}

userGrants.hasPermission( 'profile', 'create');

[...]
 
 <li *ngIf="userGrants.hasPermission( 'profile', 'create')">
```

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