npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

dharma-ui-security

v12.0.5

Published

[![NPM](https://nodei.co/npm/dharma-ui-security.png?downloads=true&downloadRank=true&stars=true)](https://www.npmjs.com/package/dharma-ui-security/)

Downloads

7

Readme

dharma-ui-security

NPM

Motivação:

O dharma UI security tem como objetivo garantir a segurança ao acessar as funções de autenticação e autorização nos serviços da Dotz.

O que o Dharma Security oferece:

  • Funções de autenticação e autorização
  • Auth Interceptor
  • Reload Token

Utilizar versão do angular de acordo com a versão do módulo.

Sumário:

Instale o módulo

$ npm install dharma-ui-security --save

após instalar o dharma-ui-security, instale o pacote oidc-client

$ npm install [email protected] --save-dev

Primeiro configure as variáveis de ambiente no environment do projeto

import { dynamicEnv } from 'dharma-ui-common';

export const environment = {
production: false,
URL_API: 'http://localhost:5000/v1/',
TOKEN_NAME: 'APP_NAME_TOKEN',
SSO_AUTHORITY: 'https://dev.dotznext.com/accounts/api/default/',
SSO_CLIENT_ID: 'ZVOHCENAZJDCNB6',
SSO_REDIRECT_URI: 'http://localhost:4200/auth-callback',
SSO_POST_LOGOUT_REDIRECT_URI: 'http://localhost:4200/',
SSO_RESPONSE_TYPE: 'id_token token',
SSO_SCOPE: 'openid profile accounts.api conciliation.api',
...dynamicEnv,
};

Na app.module importe da seguinte maneira o módulo securityModule:

import { SecurityModule, AuthInterceptor, UserManager, UserManagerSettings, SecurityConfig } from 'dharma-ui-security';
import { NgModule, LOCALE_ID } from  '@angular/core';
import { AppComponent } from  './app.component';
import { BrowserModule } from  '@angular/platform-browser';

const oauthSettings: UserManagerSettings = {
authority: environment.sso_authority,
client_id: environment.sso_client_id,
redirect_uri: environment.sso_redirect_uri,
post_logout_redirect_uri: environment.sso_post_logout_redirect_uri,
response_type: environment.sso_response_type,
scope: environment.sso_scope,
monitorSession: environment.sso_monitorSession,
checkSessionInterval: environment.sso_checkSessionInterval,
revokeAccessTokenOnSignout: environment.sso_revokeAccessTokenOnSignout,
clockSkew: environment.sso_clockSkew,
loadUserInfo: environment.sso_loadUserInfo
};

const userManager: any = new UserManager(oauthSettings);

const securityConfig: SecurityConfig = {
tokenName: environment.token_name, 
routerAfterAuthCallBack: environment.routerAfterAuthCallBack,
userManager: userManager,
useAuthorization: environment.useAuthorization,
aliasAuthorization: [environment.aliasAuthorization],
endpointsLogin: [environment.endpointsLogin],
};

@NgModule({
declarations: [
AppComponent
],
imports: [
CommonModule,
BrowserModule,
SecurityModule.forRoot(securityConfig),
],
providers: [
{ provide: UserManager, useValue: new UserManager(oauthSettings) },
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
{ provide: LOCALE_ID, useValue: 'pt-PT' },
],
bootstrap: [AppComponent]
})
export class AppModule { }

Descrição: A autenticação do dharma-ui-security consiste em proteger as rotas que o usuário deve estar logado, redirecionando para o login da Dotz (SSO). Após o usuário logar, o usuário será redirecionado para a url que foi configurada no environment com o nome: routerAfterAuthCallBack.

Após realizar as configurações iniciais do dharma-ui-securty, coloque um guard para proteger a rota desejada e adicione a rota auth-callback.

import { AuthCallbackComponent, AuthGuardService } from  'dharma-ui-security';

{
path:  '',
loadChildren:  '<caminho-do-modulo-protegido>#<nome-do-modulo>',
canActivate: [AuthGuardService]
},
{
path:  'auth-callback',
component:  AuthCallbackComponent
},

Após feito as configurações de rota

A Service base tem como objetivo ajudar o acesso dos seguintes endpoints:

  • getByFilter
  • getByID
  • getAll
  • getDataStore
  • insert
  • update
  • delete

Basta extender a classe ServiceBase no compoonent que você deseja fazer a chamada no endpoint, veja no exemplo abaixo:

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { LoaderService } from 'dharma-ui-components';
import { ServiceBase } from 'dharma-ui-security';

@Component({
  selector: 'app-base',
  template: '',
})
export class BaseComponent extends ServiceBase<any> implements OnInit, AfterViewInit {

  constructor(
    public loaderService: LoaderService) {
    super({
      endpoint: 'https://uat.dotznext.com/rewards/api/admin/v1/suppliergiftcards'
    });
  }

  ngOnInit() {
    this.getByFilter({ teste: 'oi' }).subscribe();
    this.loaderService.show();
  }
  ngAfterViewInit() {
    this.loaderService.hide();
  }
}

Para utilizar o auth interceptor basta adicionar a seguinte linha em no providers da app.module:

import { AuthInterceptor } from 'dharma-ui-security';

{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }

Veja o Exemplo.

O reload-token que antes fazia parte do core-module na versão anterior do dharma-ui agora faz parte do dharma-ui-security através da serviceBase. Veja um exemplo de como usar:

import { Injectable } from '@angular/core';
import { ServiceBase } from 'dharma-ui-security';
import { BrandView } from '../pages/brand/models/brand-view';
import { environment } from 'src/environments/environment';
import { Observable } from 'rxjs';
import { HttpParams } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';

@Injectable()
export class BrandService extends ServiceBase<BrandView> {
    constructor() {
        super({
        reloadTokenURL: environment.RELOAD_TOKEN_URL,
        endpoint: `${environment.URL_API}/brand`
    });
    }

    getAllBySupplierId(ID: string): Observable<BrandView[]> {
    let endpoint = this.servicesConfig.endpoint + '/getAllBySupplierId';
    const params = new HttpParams().set('id', ID.toString());
    return this.http.get(endpoint, { params }).pipe(
        map(this.extractData),
        catchError(this.serviceError.bind(this))
    );
    }
}

Veja no exemplo que passamos a variavel reloadTokenURL no super do componente:

    constructor() {
        super({
        reloadTokenURL: environment.RELOAD_TOKEN_URL,
        endpoint: `${environment.URL_API}/brand`
    });
    }
Sendo assim, o módulo core-module foi descontinuado (não existe mais no dharma-ui 2.0)

Todos os desenvolvedores são bem vindos em contribuir com a comunidade Dotz, basta abrir um pull request para os nossos arquitetos avaliarem e juntos encontrarem a melhor maneira de implementar sua ideia.

  • Commits atômicos, que resolvem no máximo uma tarefa do board.
  • Mensagem do commit deve seguir o que é sugerido no README.md do Dharma.Common
  • Em cada PR, devemos escrever nos comentários o motivo de cada arquivo alterado (ex: TransfersController recebe novo filtro no método Get()).
  • Só integrar PRs que tenham sido aprovadas no mínimo por 2 outros devs que não sejam o autor do PR, e preferencialmente todos nós devemos aprovar o PR para termos sempre certeza que todos estão cientes das mudanças e tenham feito ressalvas caso algum impacto tenha sido gerado.
  • Vamos manter a organização das branches no modelo parecido com gitflow (Master; Bugfix-[Numero bug]; Dev-[nome Release];), sempre sincronizadas com a master para caso precisarmos entregar na esteira.