Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- @Injectable()
- export class AuthenticationService {
- public userRole: String = "default"; // Assume default user login
- public state: Number = 0;
- private httpClient: HttpClient;
- private url: string = "http://localhost:3000/v2/login";
- constructor (httpClient: HttpClient) {
- this.httpClient = httpClient;
- }
- login (user:string, pass:string):boolean {
- this.httpClient.post(this.url, {
- username: user,
- password: pass
- }, {observe: 'response'}).subscribe(
- data => {
- if (data.status == 200) {
- // Since the response is of object type HttpResponse<object> so that
- // I can read the status code from it, it needs to be casted this very
- // odd way in order to extract the json data from it.
- // If it's stupid but it works, it's not stupid I guess.
- this.userRole = JSON.parse(JSON.stringify(data.body)).role;
- localStorage.setItem('username', user);
- this.state = 1;
- return true;
- }
- },
- error => {
- console.log("ERROR OBJECT: " + error);
- return false;
- }
- );
- return false;
- }
- logout ():any {
- localStorage.removeItem('username');
- }
- getUser ():any {
- return localStorage.getItem('username');
- }
- isRole (role:string):boolean {
- if (this.userRole == role) {
- return true;
- } else {
- return false;
- }
- }
- isLoggedIn ():boolean {
- return this.getUser() != null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement