Advertisement
Guest User

adada

a guest
Apr 26th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3.  
  4. @Injectable()
  5. export class AuthenticationService {
  6. public userRole: String = "default"; // Assume default user login
  7. public state: Number = 0;
  8. private httpClient: HttpClient;
  9. private url: string = "http://localhost:3000/v2/login";
  10.  
  11. constructor (httpClient: HttpClient) {
  12. this.httpClient = httpClient;
  13. }
  14.  
  15. login (user:string, pass:string):boolean {
  16. this.httpClient.post(this.url, {
  17. username: user,
  18. password: pass
  19. }, {observe: 'response'}).subscribe(
  20. data => {
  21. if (data.status == 200) {
  22. // Since the response is of object type HttpResponse<object> so that
  23. // I can read the status code from it, it needs to be casted this very
  24. // odd way in order to extract the json data from it.
  25. // If it's stupid but it works, it's not stupid I guess.
  26. this.userRole = JSON.parse(JSON.stringify(data.body)).role;
  27.  
  28. localStorage.setItem('username', user);
  29. this.state = 1;
  30. return true;
  31. }
  32. },
  33. error => {
  34. console.log("ERROR OBJECT: " + error);
  35. return false;
  36. }
  37. );
  38. return false;
  39. }
  40.  
  41. logout ():any {
  42. localStorage.removeItem('username');
  43. }
  44.  
  45. getUser ():any {
  46. return localStorage.getItem('username');
  47. }
  48.  
  49. isRole (role:string):boolean {
  50. if (this.userRole == role) {
  51. return true;
  52. } else {
  53. return false;
  54. }
  55. }
  56.  
  57. isLoggedIn ():boolean {
  58. return this.getUser() != null;
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement