aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/auth/auth.service.ts
diff options
context:
space:
mode:
Diffstat (limited to 'client/src/app/shared/auth/auth.service.ts')
-rw-r--r--client/src/app/shared/auth/auth.service.ts172
1 files changed, 172 insertions, 0 deletions
diff --git a/client/src/app/shared/auth/auth.service.ts b/client/src/app/shared/auth/auth.service.ts
new file mode 100644
index 000000000..47f7e1368
--- /dev/null
+++ b/client/src/app/shared/auth/auth.service.ts
@@ -0,0 +1,172 @@
1import { Injectable } from '@angular/core';
2import { Headers, Http, RequestOptions, Response, URLSearchParams } from '@angular/http';
3import { Observable } from 'rxjs/Observable';
4import { Subject } from 'rxjs/Subject';
5
6import { AuthStatus } from './auth-status.model';
7import { User } from './user.model';
8
9@Injectable()
10export class AuthService {
11 private static BASE_CLIENT_URL = '/api/v1/users/client';
12 private static BASE_TOKEN_URL = '/api/v1/users/token';
13
14 loginChangedSource: Observable<AuthStatus>;
15
16 private clientId: string;
17 private clientSecret: string;
18 private loginChanged: Subject<AuthStatus>;
19 private user: User = null;
20
21 constructor(private http: Http) {
22 this.loginChanged = new Subject<AuthStatus>();
23 this.loginChangedSource = this.loginChanged.asObservable();
24
25 // Fetch the client_id/client_secret
26 // FIXME: save in local storage?
27 this.http.get(AuthService.BASE_CLIENT_URL)
28 .map(res => res.json())
29 .catch(this.handleError)
30 .subscribe(
31 result => {
32 this.clientId = result.client_id;
33 this.clientSecret = result.client_secret;
34 console.log('Client credentials loaded.');
35 },
36 error => {
37 alert(error);
38 }
39 );
40
41 // Return null if there is nothing to load
42 this.user = User.load();
43 }
44
45 getAuthRequestOptions(): RequestOptions {
46 return new RequestOptions({ headers: this.getRequestHeader() });
47 }
48
49 getRefreshToken() {
50 if (this.user === null) return null;
51
52 return this.user.getRefreshToken();
53 }
54
55 getRequestHeader() {
56 return new Headers({ 'Authorization': this.getRequestHeaderValue() });
57 }
58
59 getRequestHeaderValue() {
60 return `${this.getTokenType()} ${this.getToken()}`;
61 }
62
63 getToken() {
64 if (this.user === null) return null;
65
66 return this.user.getAccessToken();
67 }
68
69 getTokenType() {
70 if (this.user === null) return null;
71
72 return this.user.getTokenType();
73 }
74
75 getUser(): User {
76 return this.user;
77 }
78
79 isLoggedIn() {
80 if (this.getToken()) {
81 return true;
82 } else {
83 return false;
84 }
85 }
86
87 login(username: string, password: string) {
88 let body = new URLSearchParams();
89 body.set('client_id', this.clientId);
90 body.set('client_secret', this.clientSecret);
91 body.set('response_type', 'code');
92 body.set('grant_type', 'password');
93 body.set('scope', 'upload');
94 body.set('username', username);
95 body.set('password', password);
96
97 let headers = new Headers();
98 headers.append('Content-Type', 'application/x-www-form-urlencoded');
99
100 let options = {
101 headers: headers
102 };
103
104 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
105 .map(res => res.json())
106 .map(res => {
107 res.username = username;
108 return res;
109 })
110 .map(res => this.handleLogin(res))
111 .catch(this.handleError);
112 }
113
114 logout() {
115 // TODO: make an HTTP request to revoke the tokens
116 this.user = null;
117 User.flush();
118 }
119
120 refreshAccessToken() {
121 console.log('Refreshing token...');
122
123 const refreshToken = this.getRefreshToken();
124
125 let body = new URLSearchParams();
126 body.set('refresh_token', refreshToken);
127 body.set('client_id', this.clientId);
128 body.set('client_secret', this.clientSecret);
129 body.set('response_type', 'code');
130 body.set('grant_type', 'refresh_token');
131
132 let headers = new Headers();
133 headers.append('Content-Type', 'application/x-www-form-urlencoded');
134
135 let options = {
136 headers: headers
137 };
138
139 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
140 .map(res => res.json())
141 .map(res => this.handleRefreshToken(res))
142 .catch(this.handleError);
143 }
144
145 setStatus(status: AuthStatus) {
146 this.loginChanged.next(status);
147 }
148
149 private handleLogin (obj: any) {
150 const username = obj.username;
151 const hash_tokens = {
152 access_token: obj.access_token,
153 token_type: obj.token_type,
154 refresh_token: obj.refresh_token
155 };
156
157 this.user = new User(username, hash_tokens);
158 this.user.save();
159
160 this.setStatus(AuthStatus.LoggedIn);
161 }
162
163 private handleError (error: Response) {
164 console.error(error);
165 return Observable.throw(error.json() || { error: 'Server error' });
166 }
167
168 private handleRefreshToken (obj: any) {
169 this.user.refreshTokens(obj.access_token, obj.refresh_token);
170 this.user.save();
171 }
172}