File

libs/auth/src/lib/basic-auth/basic-auth.service.ts

Description

Maintains all basic auth tokens and also do the authentication process.

Index

Properties
Methods

Constructor

constructor(http: HttpClient)
Parameters :
Name Type Optional
http HttpClient No

Methods

Public auth
auth(username: string, password: string, url: string)

Do the authentication.

Parameters :
Name Type Optional
username string No
password string No
url string No
Returns : Observable<string>
Public clearToken
clearToken(url: string)

Removes existing token.

Parameters :
Name Type Optional
url string No
Returns : void
Public getToken
getToken(url: string)

Gets the token for the given service url.

Parameters :
Name Type Optional
url string No
Returns : string
Public hasToken
hasToken(url: string)

Checks if a token exists.

Parameters :
Name Type Optional
url string No
Returns : boolean

Properties

Private basicAuthTokens
Type : Map<string | string>
Default value : new Map()
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

/**
 * Maintains all basic auth tokens and also do the authentication process.
 */
@Injectable()
export class BasicAuthService {

  private basicAuthTokens: Map<string, string> = new Map();

  constructor(
    private http: HttpClient
  ) { }

  /**
   * Do the authentication.
   */
  public auth(username: string, password: string, url: string): Observable<string> {
    const token = 'Basic ' + btoa(username + ':' + password);
    const headers = new HttpHeaders({ 'Authorization': token });
    return this.http.get(url, { headers })
      .pipe(
        map(res => {
          this.basicAuthTokens.set(url, token);
          return token;
        })
      );
  }

  /**
   * Removes existing token.
   */
  public clearToken(url: string): void {
    if (this.basicAuthTokens.has(url)) {
      this.basicAuthTokens.delete(url);
    }
  }

  /**
   * Checks if a token exists.
   */
  public hasToken(url: string): boolean {
    return this.basicAuthTokens.has(url);
  }

  /**
   * Gets the token for the given service url.
   */
  public getToken(url: string): string {
    return this.basicAuthTokens.has(url) ? this.basicAuthTokens.get(url) : null;
  }

}

result-matching ""

    No results matching ""