aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/auth
diff options
context:
space:
mode:
Diffstat (limited to 'client/src/app/shared/auth')
-rw-r--r--client/src/app/shared/auth/auth-http.service.ts77
-rw-r--r--client/src/app/shared/auth/auth-status.model.ts4
-rw-r--r--client/src/app/shared/auth/auth.service.ts172
-rw-r--r--client/src/app/shared/auth/index.ts4
-rw-r--r--client/src/app/shared/auth/user.model.ts103
5 files changed, 360 insertions, 0 deletions
diff --git a/client/src/app/shared/auth/auth-http.service.ts b/client/src/app/shared/auth/auth-http.service.ts
new file mode 100644
index 000000000..ff8099a46
--- /dev/null
+++ b/client/src/app/shared/auth/auth-http.service.ts
@@ -0,0 +1,77 @@
1import { Injectable } from '@angular/core';
2import {
3 ConnectionBackend,
4 Headers,
5 Http,
6 Request,
7 RequestMethod,
8 RequestOptions,
9 RequestOptionsArgs,
10 Response
11} from '@angular/http';
12import { Observable } from 'rxjs/Observable';
13
14import { AuthService } from './auth.service';
15
16@Injectable()
17export class AuthHttp extends Http {
18 constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private authService: AuthService) {
19 super(backend, defaultOptions);
20 }
21
22 request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
23 if (!options) options = {};
24
25 options.headers = new Headers();
26 this.setAuthorizationHeader(options.headers);
27
28 return super.request(url, options)
29 .catch((err) => {
30 if (err.status === 401) {
31 return this.handleTokenExpired(err, url, options);
32 }
33
34 return Observable.throw(err);
35 });
36 }
37
38 delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
39 if (!options) options = {};
40 options.method = RequestMethod.Delete;
41
42 return this.request(url, options);
43 }
44
45 get(url: string, options?: RequestOptionsArgs): Observable<Response> {
46 if (!options) options = {};
47 options.method = RequestMethod.Get;
48
49 return this.request(url, options);
50 }
51
52 post(url: string, options?: RequestOptionsArgs): Observable<Response> {
53 if (!options) options = {};
54 options.method = RequestMethod.Post;
55
56 return this.request(url, options);
57 }
58
59 put(url: string, options?: RequestOptionsArgs): Observable<Response> {
60 if (!options) options = {};
61 options.method = RequestMethod.Put;
62
63 return this.request(url, options);
64 }
65
66 private handleTokenExpired(err: Response, url: string | Request, options: RequestOptionsArgs) {
67 return this.authService.refreshAccessToken().flatMap(() => {
68 this.setAuthorizationHeader(options.headers);
69
70 return super.request(url, options);
71 });
72 }
73
74 private setAuthorizationHeader(headers: Headers) {
75 headers.set('Authorization', `${this.authService.getTokenType()} ${this.authService.getToken()}`);
76 }
77}
diff --git a/client/src/app/shared/auth/auth-status.model.ts b/client/src/app/shared/auth/auth-status.model.ts
new file mode 100644
index 000000000..f646bd4cf
--- /dev/null
+++ b/client/src/app/shared/auth/auth-status.model.ts
@@ -0,0 +1,4 @@
1export enum AuthStatus {
2 LoggedIn,
3 LoggedOut
4}
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}
diff --git a/client/src/app/shared/auth/index.ts b/client/src/app/shared/auth/index.ts
new file mode 100644
index 000000000..aafaacbf1
--- /dev/null
+++ b/client/src/app/shared/auth/index.ts
@@ -0,0 +1,4 @@
1export * from './auth-http.service';
2export * from './auth-status.model';
3export * from './auth.service';
4export * from './user.model';
diff --git a/client/src/app/shared/auth/user.model.ts b/client/src/app/shared/auth/user.model.ts
new file mode 100644
index 000000000..98852f835
--- /dev/null
+++ b/client/src/app/shared/auth/user.model.ts
@@ -0,0 +1,103 @@
1export class User {
2 private static KEYS = {
3 USERNAME: 'username'
4 };
5
6 username: string;
7 tokens: Tokens;
8
9 static load() {
10 const usernameLocalStorage = localStorage.getItem(this.KEYS.USERNAME);
11 if (usernameLocalStorage) {
12 return new User(localStorage.getItem(this.KEYS.USERNAME), Tokens.load());
13 }
14
15 return null;
16 }
17
18 static flush() {
19 localStorage.removeItem(this.KEYS.USERNAME);
20 Tokens.flush();
21 }
22
23 constructor(username: string, hash_tokens: any) {
24 this.username = username;
25 this.tokens = new Tokens(hash_tokens);
26 }
27
28 getAccessToken() {
29 return this.tokens.access_token;
30 }
31
32 getRefreshToken() {
33 return this.tokens.refresh_token;
34 }
35
36 getTokenType() {
37 return this.tokens.token_type;
38 }
39
40 refreshTokens(access_token: string, refresh_token: string) {
41 this.tokens.access_token = access_token;
42 this.tokens.refresh_token = refresh_token;
43 }
44
45 save() {
46 localStorage.setItem('username', this.username);
47 this.tokens.save();
48 }
49}
50
51// Private class used only by User
52class Tokens {
53 private static KEYS = {
54 ACCESS_TOKEN: 'access_token',
55 REFRESH_TOKEN: 'refresh_token',
56 TOKEN_TYPE: 'token_type',
57 };
58
59 access_token: string;
60 refresh_token: string;
61 token_type: string;
62
63 static load() {
64 const accessTokenLocalStorage = localStorage.getItem(this.KEYS.ACCESS_TOKEN);
65 const refreshTokenLocalStorage = localStorage.getItem(this.KEYS.REFRESH_TOKEN);
66 const tokenTypeLocalStorage = localStorage.getItem(this.KEYS.TOKEN_TYPE);
67
68 if (accessTokenLocalStorage && refreshTokenLocalStorage && tokenTypeLocalStorage) {
69 return new Tokens({
70 access_token: accessTokenLocalStorage,
71 refresh_token: refreshTokenLocalStorage,
72 token_type: tokenTypeLocalStorage
73 });
74 }
75
76 return null;
77 }
78
79 static flush() {
80 localStorage.removeItem(this.KEYS.ACCESS_TOKEN);
81 localStorage.removeItem(this.KEYS.REFRESH_TOKEN);
82 localStorage.removeItem(this.KEYS.TOKEN_TYPE);
83 }
84
85 constructor(hash?: any) {
86 if (hash) {
87 this.access_token = hash.access_token;
88 this.refresh_token = hash.refresh_token;
89
90 if (hash.token_type === 'bearer') {
91 this.token_type = 'Bearer';
92 } else {
93 this.token_type = hash.token_type;
94 }
95 }
96 }
97
98 save() {
99 localStorage.setItem('access_token', this.access_token);
100 localStorage.setItem('refresh_token', this.refresh_token);
101 localStorage.setItem('token_type', this.token_type);
102 }
103}