blob: f09012323c43899ebd68f8bbbd581522a52eeef7 [file]
/********************************************************************************
* Copyright © 2018 Mettenmeier GmbH.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { UtilService } from '@core/services/util.service';
import { JwtHelperService } from '@auth0/angular-jwt';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
basePath: string = this.utilService.readConfig('basePath');
constructor(
private http: HttpClient,
private utilService: UtilService
) { }
login(token: string) {
localStorage.setItem('ACCESS_TOKEN', token);
const jwtHelper = new JwtHelperService();
const decodedToken = jwtHelper.decodeToken(token);
localStorage.setItem('USER_NAME', decodedToken.name);
localStorage.setItem('ROLES', decodedToken.realm_access.roles);
return this.http.get(`${this.basePath}/auth/login`);
}
logout() {
return this.http.get(`${this.basePath}/auth/logout`);
}
isLoggedIn() {
if (localStorage.getItem('ACCESS_TOKEN')) {
return true;
}
return false;
}
getUsername() {
return localStorage.getItem('USER_NAME') || 'noUsername';
}
getUserRoles() {
const roles = localStorage.getItem('ROLES');
if (roles) {
return roles.split(',');
}
return [];
}
/**
* Checks if user has the expected roles.
* @param expectedRoles The roles to check.
*/
userHasRoles(expectedRoles: string[]) {
return expectedRoles.some(v => this.getUserRoles().indexOf(v) > -1);
}
}