aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app
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
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')
-rw-r--r--client/src/app/app.component.ts13
-rw-r--r--client/src/app/friends/friend.service.ts12
-rw-r--r--client/src/app/login/login.component.ts9
-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
-rw-r--r--client/src/app/videos/shared/video.service.ts10
-rw-r--r--client/src/app/videos/video-add/video-add.component.ts18
13 files changed, 291 insertions, 90 deletions
diff --git a/client/src/app/app.component.ts b/client/src/app/app.component.ts
index 354d00a7a..f53896bcf 100644
--- a/client/src/app/app.component.ts
+++ b/client/src/app/app.component.ts
@@ -1,5 +1,4 @@
1import { Component } from '@angular/core'; 1import { Component } from '@angular/core';
2import { HTTP_PROVIDERS } from '@angular/http';
3import { ActivatedRoute, Router, ROUTER_DIRECTIVES } from '@angular/router'; 2import { ActivatedRoute, Router, ROUTER_DIRECTIVES } from '@angular/router';
4 3
5import { FriendService } from './friends'; 4import { FriendService } from './friends';
@@ -16,7 +15,7 @@ import { VideoService } from './videos';
16 template: require('./app.component.html'), 15 template: require('./app.component.html'),
17 styles: [ require('./app.component.scss') ], 16 styles: [ require('./app.component.scss') ],
18 directives: [ ROUTER_DIRECTIVES, SearchComponent ], 17 directives: [ ROUTER_DIRECTIVES, SearchComponent ],
19 providers: [ AuthService, FriendService, HTTP_PROVIDERS, VideoService, SearchService ] 18 providers: [ FriendService, VideoService, SearchService ]
20}) 19})
21 20
22export class AppComponent { 21export class AppComponent {
@@ -35,14 +34,20 @@ export class AppComponent {
35 status => { 34 status => {
36 if (status === AuthStatus.LoggedIn) { 35 if (status === AuthStatus.LoggedIn) {
37 this.isLoggedIn = true; 36 this.isLoggedIn = true;
37 console.log('Logged in.');
38 } else if (status === AuthStatus.LoggedOut) {
39 this.isLoggedIn = false;
40 console.log('Logged out.');
41 } else {
42 console.error('Unknown auth status: ' + status);
38 } 43 }
39 } 44 }
40 ); 45 );
41 } 46 }
42 47
43 // FIXME
44 logout() { 48 logout() {
45 // this._authService.logout(); 49 this.authService.logout();
50 this.authService.setStatus(AuthStatus.LoggedOut);
46 } 51 }
47 52
48 makeFriends() { 53 makeFriends() {
diff --git a/client/src/app/friends/friend.service.ts b/client/src/app/friends/friend.service.ts
index f956a5ece..771046484 100644
--- a/client/src/app/friends/friend.service.ts
+++ b/client/src/app/friends/friend.service.ts
@@ -1,25 +1,23 @@
1import { Injectable } from '@angular/core'; 1import { Injectable } from '@angular/core';
2import { Http, Response } from '@angular/http'; 2import { Response } from '@angular/http';
3import { Observable } from 'rxjs/Observable'; 3import { Observable } from 'rxjs/Observable';
4 4
5import { AuthService } from '../shared'; 5import { AuthHttp, AuthService } from '../shared';
6 6
7@Injectable() 7@Injectable()
8export class FriendService { 8export class FriendService {
9 private static BASE_FRIEND_URL: string = '/api/v1/pods/'; 9 private static BASE_FRIEND_URL: string = '/api/v1/pods/';
10 10
11 constructor (private http: Http, private authService: AuthService) {} 11 constructor (private authHttp: AuthHttp, private authService: AuthService) {}
12 12
13 makeFriends() { 13 makeFriends() {
14 const headers = this.authService.getRequestHeader(); 14 return this.authHttp.get(FriendService.BASE_FRIEND_URL + 'makefriends')
15 return this.http.get(FriendService.BASE_FRIEND_URL + 'makefriends', { headers })
16 .map(res => res.status) 15 .map(res => res.status)
17 .catch(this.handleError); 16 .catch(this.handleError);
18 } 17 }
19 18
20 quitFriends() { 19 quitFriends() {
21 const headers = this.authService.getRequestHeader(); 20 return this.authHttp.get(FriendService.BASE_FRIEND_URL + 'quitfriends')
22 return this.http.get(FriendService.BASE_FRIEND_URL + 'quitfriends', { headers })
23 .map(res => res.status) 21 .map(res => res.status)
24 .catch(this.handleError); 22 .catch(this.handleError);
25 } 23 }
diff --git a/client/src/app/login/login.component.ts b/client/src/app/login/login.component.ts
index bcfa021fa..ddd62462e 100644
--- a/client/src/app/login/login.component.ts
+++ b/client/src/app/login/login.component.ts
@@ -1,7 +1,7 @@
1import { Component } from '@angular/core'; 1import { Component } from '@angular/core';
2import { Router } from '@angular/router'; 2import { Router } from '@angular/router';
3 3
4import { AuthService, AuthStatus, User } from '../shared'; 4import { AuthService } from '../shared';
5 5
6@Component({ 6@Component({
7 selector: 'my-login', 7 selector: 'my-login',
@@ -21,14 +21,11 @@ export class LoginComponent {
21 result => { 21 result => {
22 this.error = null; 22 this.error = null;
23 23
24 const user = new User(username, result);
25 user.save();
26
27 this.authService.setStatus(AuthStatus.LoggedIn);
28
29 this.router.navigate(['/videos/list']); 24 this.router.navigate(['/videos/list']);
30 }, 25 },
31 error => { 26 error => {
27 console.error(error);
28
32 if (error.error === 'invalid_grant') { 29 if (error.error === 'invalid_grant') {
33 this.error = 'Credentials are invalid.'; 30 this.error = 'Credentials are invalid.';
34 } else { 31 } else {
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}
diff --git a/client/src/app/videos/shared/video.service.ts b/client/src/app/videos/shared/video.service.ts
index dcbef7717..b4396f767 100644
--- a/client/src/app/videos/shared/video.service.ts
+++ b/client/src/app/videos/shared/video.service.ts
@@ -5,7 +5,7 @@ import { Observable } from 'rxjs/Observable';
5import { Pagination } from './pagination.model'; 5import { Pagination } from './pagination.model';
6import { Search } from '../../shared'; 6import { Search } from '../../shared';
7import { SortField } from './sort-field.type'; 7import { SortField } from './sort-field.type';
8import { AuthService } from '../../shared'; 8import { AuthHttp, AuthService } from '../../shared';
9import { Video } from './video.model'; 9import { Video } from './video.model';
10 10
11@Injectable() 11@Injectable()
@@ -14,6 +14,7 @@ export class VideoService {
14 14
15 constructor( 15 constructor(
16 private authService: AuthService, 16 private authService: AuthService,
17 private authHttp: AuthHttp,
17 private http: Http 18 private http: Http
18 ) {} 19 ) {}
19 20
@@ -35,10 +36,9 @@ export class VideoService {
35 } 36 }
36 37
37 removeVideo(id: string) { 38 removeVideo(id: string) {
38 const options = this.authService.getAuthRequestOptions(); 39 return this.authHttp.delete(VideoService.BASE_VIDEO_URL + id)
39 return this.http.delete(VideoService.BASE_VIDEO_URL + id, options) 40 .map(res => <number> res.status)
40 .map(res => <number> res.status) 41 .catch(this.handleError);
41 .catch(this.handleError);
42 } 42 }
43 43
44 searchVideos(search: Search, pagination: Pagination, sort: SortField) { 44 searchVideos(search: Search, pagination: Pagination, sort: SortField) {
diff --git a/client/src/app/videos/video-add/video-add.component.ts b/client/src/app/videos/video-add/video-add.component.ts
index 342935e36..c0f8cb9c4 100644
--- a/client/src/app/videos/video-add/video-add.component.ts
+++ b/client/src/app/videos/video-add/video-add.component.ts
@@ -130,8 +130,22 @@ export class VideoAddComponent implements OnInit {
130 }; 130 };
131 131
132 item.onError = (response: string, status: number) => { 132 item.onError = (response: string, status: number) => {
133 this.error = (status === 400) ? response : 'Unknow error'; 133 // We need to handle manually these cases beceause we use the FileUpload component
134 console.error(this.error); 134 if (status === 400) {
135 this.error = response;
136 } else if (status === 401) {
137 this.error = 'Access token was expired, refreshing token...';
138 this.authService.refreshAccessToken().subscribe(
139 () => {
140 // Update the uploader request header
141 this.uploader.authToken = this.authService.getRequestHeaderValue();
142 this.error += ' access token refreshed. Please retry your request.';
143 }
144 );
145 } else {
146 this.error = 'Unknow error';
147 console.error(this.error);
148 }
135 }; 149 };
136 150
137 151