· 5 years ago · Feb 28, 2020, 01:38 PM
1import * as moment from "moment";
2import { Observable } from "rxjs/Observable";
3
4import { User } from "../models/user";
5
6import "rxjs/add/observable/of";
7import "rxjs/add/operator/catch";
8import "rxjs/add/operator/map";
9
10import { of } from "rxjs/observable/of";
11
12import { HttpClient, HttpHeaders } from "@angular/common/http";
13import { Injectable } from "@angular/core";
14
15import { environment } from "../../../environments/environment";
16
17@Injectable()
18export class AuthService {
19 loggedIn = false;
20 guestUsername = "Guest";
21 user = null;
22
23 endpoint = environment.api.endpoint;
24
25 constructor(private httpClient: HttpClient) {
26 this.loggedIn = this.checkAccessToken();
27 }
28
29 /**
30 * Is the user currently logged in
31 *
32 * @returns boolean
33 */
34 isLoggedIn(): boolean {
35 return this.loggedIn;
36 }
37
38 /**
39 * Is the user currently a guest?
40 *
41 * @returns boolean
42 */
43 isGuest(): boolean {
44 return !this.loggedIn;
45 }
46
47 /**
48 * Logins in user based on email and username using OAuth password grant type
49 * @param email username/email of the user to login
50 * @param password Users password
51 *
52 * @returns any
53 */
54 login(email: string, password: string): any {
55 // TODO: stick these in env
56 const bodyData: string =
57 "username=" +
58 email +
59 "&password=" +
60 password +
61 "&grant_type=password&client_id=" +
62 environment.api.clientId +
63 "&client_secret=" +
64 environment.api.clientsecret;
65
66 const headers = new HttpHeaders()
67 .set("Content-Type", "application/x-www-form-urlencoded")
68 .set("Pass", "true");
69
70 const options = {
71 headers: headers
72 };
73
74 return this.httpClient
75 .post(this.endpoint + "oauth/token", bodyData, options)
76 .catch(err => {
77 alert(JSON.stringify(err));
78 return of(err);
79 })
80 .map((value: any) => {
81 // If bad request user is not vaild. value === fail is a hack to get around interceptor eating response object
82 if (value.status === 400 || value.status === 404 || value === "fail") {
83 this.loggedIn = false;
84 this.user = <User>{};
85 } else {
86 this.loggedIn = true;
87
88 const data: any = value;
89
90 this.user = <User>{};
91 this.user = data.user;
92
93 localStorage.setItem(
94 "NWH_Operations_App_AccessToken",
95 data.accessToken
96 );
97
98 // expire based on expiries_in time
99 localStorage.setItem(
100 "NWH_Operations_App_AccessToken_Expiry",
101 data.accessTokenExpiresAt
102 );
103 }
104 });
105 }
106
107 /**
108 * Checks to make sure access token has not expired
109 *
110 * @returns boolean
111 */
112 checkAccessToken(): boolean {
113 // Check if auth token has expired before each request
114 const timestamp: any = localStorage.getItem(
115 "NWH_Operations_App_AccessToken_Expiry"
116 );
117
118 if (timestamp !== "" && timestamp != null && timestamp !== undefined) {
119 const date: moment.Moment = moment(timestamp);
120
121 if (moment().unix() < date.unix()) {
122 return true;
123 }
124 }
125
126 return false;
127 }
128
129 /**
130 * Logs the current user out
131 *
132 * @returns void
133 */
134 logout() {
135 this.loggedIn = false;
136 this.user = null;
137
138 // Remove user settings from local storage
139 localStorage.removeItem("NWH_Operations_App_AccessToken");
140
141 localStorage.removeItem("NWH_Operations_App_AccessToken_Expiry");
142 }
143
144 /**
145 * Gets information about the user
146 * Caches it for duration of session
147 *
148 * Note: DO NOT use this information for populating either operatorId or userId fields in database
149 * This information can be changed "in transit" it is not secure.
150 *
151 * @returns User
152 */
153 getUser() {
154 if (this.user === null) {
155 return this.httpClient.get(this.endpoint + "me").map(data => {
156 this.user = <User>data;
157 return <User>data;
158 });
159 } else {
160 return of(this.user);
161 }
162 }
163}