aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared
diff options
context:
space:
mode:
authorChocobozzz <florian.bigard@gmail.com>2016-07-20 16:24:18 +0200
committerChocobozzz <florian.bigard@gmail.com>2016-07-20 16:25:06 +0200
commitbd5c83a8cb46eb6da2b25df3b1f6a2a5795d1869 (patch)
tree66df283a1554f27b92e392fca36b8e272d7535bc /client/src/app/shared
parent2f372a865487427ff97ad17edd0e6adfbb478c80 (diff)
downloadPeerTube-bd5c83a8cb46eb6da2b25df3b1f6a2a5795d1869.tar.gz
PeerTube-bd5c83a8cb46eb6da2b25df3b1f6a2a5795d1869.tar.zst
PeerTube-bd5c83a8cb46eb6da2b25df3b1f6a2a5795d1869.zip
Client: Add authHttp service that authentificates the http request and
optionally refresh the access token if needed
Diffstat (limited to 'client/src/app/shared')
-rw-r--r--client/src/app/shared/auth/auth-http.service.ts77
-rw-r--r--client/src/app/shared/auth/auth-status.model.ts (renamed from client/src/app/shared/users/auth-status.model.ts)0
-rw-r--r--client/src/app/shared/auth/auth.service.ts (renamed from client/src/app/shared/users/auth.service.ts)83
-rw-r--r--client/src/app/shared/auth/index.ts (renamed from client/src/app/shared/users/index.ts)2
-rw-r--r--client/src/app/shared/auth/user.model.ts103
-rw-r--r--client/src/app/shared/index.ts2
-rw-r--r--client/src/app/shared/users/token.model.ts32
-rw-r--r--client/src/app/shared/users/user.model.ts20
8 files changed, 253 insertions, 66 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/users/auth-status.model.ts b/client/src/app/shared/auth/auth-status.model.ts
index f646bd4cf..f646bd4cf 100644
--- a/client/src/app/shared/users/auth-status.model.ts
+++ b/client/src/app/shared/auth/auth-status.model.ts
diff --git a/client/src/app/shared/users/auth.service.ts b/client/src/app/shared/auth/auth.service.ts
index 1c822c1e1..47f7e1368 100644
--- a/client/src/app/shared/users/auth.service.ts
+++ b/client/src/app/shared/auth/auth.service.ts
@@ -9,13 +9,14 @@ import { User } from './user.model';
9@Injectable() 9@Injectable()
10export class AuthService { 10export class AuthService {
11 private static BASE_CLIENT_URL = '/api/v1/users/client'; 11 private static BASE_CLIENT_URL = '/api/v1/users/client';
12 private static BASE_LOGIN_URL = '/api/v1/users/token'; 12 private static BASE_TOKEN_URL = '/api/v1/users/token';
13 13
14 loginChangedSource: Observable<AuthStatus>; 14 loginChangedSource: Observable<AuthStatus>;
15 15
16 private clientId: string; 16 private clientId: string;
17 private clientSecret: string; 17 private clientSecret: string;
18 private loginChanged: Subject<AuthStatus>; 18 private loginChanged: Subject<AuthStatus>;
19 private user: User = null;
19 20
20 constructor(private http: Http) { 21 constructor(private http: Http) {
21 this.loginChanged = new Subject<AuthStatus>(); 22 this.loginChanged = new Subject<AuthStatus>();
@@ -36,12 +37,21 @@ export class AuthService {
36 alert(error); 37 alert(error);
37 } 38 }
38 ); 39 );
40
41 // Return null if there is nothing to load
42 this.user = User.load();
39 } 43 }
40 44
41 getAuthRequestOptions(): RequestOptions { 45 getAuthRequestOptions(): RequestOptions {
42 return new RequestOptions({ headers: this.getRequestHeader() }); 46 return new RequestOptions({ headers: this.getRequestHeader() });
43 } 47 }
44 48
49 getRefreshToken() {
50 if (this.user === null) return null;
51
52 return this.user.getRefreshToken();
53 }
54
45 getRequestHeader() { 55 getRequestHeader() {
46 return new Headers({ 'Authorization': this.getRequestHeaderValue() }); 56 return new Headers({ 'Authorization': this.getRequestHeaderValue() });
47 } 57 }
@@ -51,21 +61,19 @@ export class AuthService {
51 } 61 }
52 62
53 getToken() { 63 getToken() {
54 return localStorage.getItem('access_token'); 64 if (this.user === null) return null;
65
66 return this.user.getAccessToken();
55 } 67 }
56 68
57 getTokenType() { 69 getTokenType() {
58 return localStorage.getItem('token_type'); 70 if (this.user === null) return null;
71
72 return this.user.getTokenType();
59 } 73 }
60 74
61 getUser(): User { 75 getUser(): User {
62 if (this.isLoggedIn() === false) { 76 return this.user;
63 return null;
64 }
65
66 const user = User.load();
67
68 return user;
69 } 77 }
70 78
71 isLoggedIn() { 79 isLoggedIn() {
@@ -93,21 +101,72 @@ export class AuthService {
93 headers: headers 101 headers: headers
94 }; 102 };
95 103
96 return this.http.post(AuthService.BASE_LOGIN_URL, body.toString(), options) 104 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
97 .map(res => res.json()) 105 .map(res => res.json())
106 .map(res => {
107 res.username = username;
108 return res;
109 })
110 .map(res => this.handleLogin(res))
98 .catch(this.handleError); 111 .catch(this.handleError);
99 } 112 }
100 113
101 logout() { 114 logout() {
102 // TODO make HTTP request 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);
103 } 143 }
104 144
105 setStatus(status: AuthStatus) { 145 setStatus(status: AuthStatus) {
106 this.loginChanged.next(status); 146 this.loginChanged.next(status);
107 } 147 }
108 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
109 private handleError (error: Response) { 163 private handleError (error: Response) {
110 console.error(error); 164 console.error(error);
111 return Observable.throw(error.json() || { error: 'Server error' }); 165 return Observable.throw(error.json() || { error: 'Server error' });
112 } 166 }
167
168 private handleRefreshToken (obj: any) {
169 this.user.refreshTokens(obj.access_token, obj.refresh_token);
170 this.user.save();
171 }
113} 172}
diff --git a/client/src/app/shared/users/index.ts b/client/src/app/shared/auth/index.ts
index c6816b3c6..aafaacbf1 100644
--- a/client/src/app/shared/users/index.ts
+++ b/client/src/app/shared/auth/index.ts
@@ -1,4 +1,4 @@
1export * from './auth-http.service';
1export * from './auth-status.model'; 2export * from './auth-status.model';
2export * from './auth.service'; 3export * from './auth.service';
3export * from './token.model';
4export * from './user.model'; 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}
diff --git a/client/src/app/shared/index.ts b/client/src/app/shared/index.ts
index 0cab7dad0..dfea4c67c 100644
--- a/client/src/app/shared/index.ts
+++ b/client/src/app/shared/index.ts
@@ -1,2 +1,2 @@
1export * from './auth';
1export * from './search'; 2export * from './search';
2export * from './users'
diff --git a/client/src/app/shared/users/token.model.ts b/client/src/app/shared/users/token.model.ts
deleted file mode 100644
index 021c83fad..000000000
--- a/client/src/app/shared/users/token.model.ts
+++ /dev/null
@@ -1,32 +0,0 @@
1export class Token {
2 access_token: string;
3 refresh_token: string;
4 token_type: string;
5
6 static load() {
7 return new Token({
8 access_token: localStorage.getItem('access_token'),
9 refresh_token: localStorage.getItem('refresh_token'),
10 token_type: localStorage.getItem('token_type')
11 });
12 }
13
14 constructor(hash?: any) {
15 if (hash) {
16 this.access_token = hash.access_token;
17 this.refresh_token = hash.refresh_token;
18
19 if (hash.token_type === 'bearer') {
20 this.token_type = 'Bearer';
21 } else {
22 this.token_type = hash.token_type;
23 }
24 }
25 }
26
27 save() {
28 localStorage.setItem('access_token', this.access_token);
29 localStorage.setItem('refresh_token', this.refresh_token);
30 localStorage.setItem('token_type', this.token_type);
31 }
32}
diff --git a/client/src/app/shared/users/user.model.ts b/client/src/app/shared/users/user.model.ts
deleted file mode 100644
index ca0a5f26c..000000000
--- a/client/src/app/shared/users/user.model.ts
+++ /dev/null
@@ -1,20 +0,0 @@
1import { Token } from './token.model';
2
3export class User {
4 username: string;
5 token: Token;
6
7 static load() {
8 return new User(localStorage.getItem('username'), Token.load());
9 }
10
11 constructor(username: string, hash_token: any) {
12 this.username = username;
13 this.token = new Token(hash_token);
14 }
15
16 save() {
17 localStorage.setItem('username', this.username);
18 this.token.save();
19 }
20}