]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/auth/auth.service.ts
Client: add basic aot support
[github/Chocobozzz/PeerTube.git] / client / src / app / core / auth / auth.service.ts
1 import { Injectable } from '@angular/core';
2 import { Headers, Http, Response, URLSearchParams } from '@angular/http';
3 import { Router } from '@angular/router';
4 import { Observable } from 'rxjs/Observable';
5 import { Subject } from 'rxjs/Subject';
6 import 'rxjs/add/operator/map';
7 import 'rxjs/add/operator/mergeMap';
8
9 // Do not use the barrel (dependency loop)
10 import { AuthStatus } from '../../shared/auth/auth-status.model';
11 import { AuthUser } from '../../shared/auth/auth-user.model';
12 import { RestExtractor } from '../../shared/rest';
13
14 @Injectable()
15 export class AuthService {
16 private static BASE_CLIENT_URL = '/api/v1/clients/local';
17 private static BASE_TOKEN_URL = '/api/v1/users/token';
18 private static BASE_USER_INFORMATIONS_URL = '/api/v1/users/me';
19
20 loginChangedSource: Observable<AuthStatus>;
21
22 private clientId: string;
23 private clientSecret: string;
24 private loginChanged: Subject<AuthStatus>;
25 private user: AuthUser = null;
26
27 constructor(
28 private http: Http,
29 private restExtractor: RestExtractor,
30 private router: Router
31 ) {
32 this.loginChanged = new Subject<AuthStatus>();
33 this.loginChangedSource = this.loginChanged.asObservable();
34
35 // Fetch the client_id/client_secret
36 // FIXME: save in local storage?
37 this.http.get(AuthService.BASE_CLIENT_URL)
38 .map(this.restExtractor.extractDataGet)
39 .catch((res) => this.restExtractor.handleError(res))
40 .subscribe(
41 result => {
42 this.clientId = result.client_id;
43 this.clientSecret = result.client_secret;
44 console.log('Client credentials loaded.');
45 },
46 error => {
47 alert(
48 `Cannot retrieve OAuth Client credentials: ${error.text}. \n` +
49 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
50 );
51 }
52 );
53
54 // Return null if there is nothing to load
55 this.user = AuthUser.load();
56 }
57
58 getRefreshToken() {
59 if (this.user === null) return null;
60
61 return this.user.getRefreshToken();
62 }
63
64 getRequestHeaderValue() {
65 return `${this.getTokenType()} ${this.getAccessToken()}`;
66 }
67
68 getAccessToken() {
69 if (this.user === null) return null;
70
71 return this.user.getAccessToken();
72 }
73
74 getTokenType() {
75 if (this.user === null) return null;
76
77 return this.user.getTokenType();
78 }
79
80 getUser(): AuthUser {
81 return this.user;
82 }
83
84 isAdmin() {
85 if (this.user === null) return false;
86
87 return this.user.isAdmin();
88 }
89
90 isLoggedIn() {
91 if (this.getAccessToken()) {
92 return true;
93 } else {
94 return false;
95 }
96 }
97
98 login(username: string, password: string) {
99 let body = new URLSearchParams();
100 body.set('client_id', this.clientId);
101 body.set('client_secret', this.clientSecret);
102 body.set('response_type', 'code');
103 body.set('grant_type', 'password');
104 body.set('scope', 'upload');
105 body.set('username', username);
106 body.set('password', password);
107
108 let headers = new Headers();
109 headers.append('Content-Type', 'application/x-www-form-urlencoded');
110
111 let options = {
112 headers: headers
113 };
114
115 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
116 .map(this.restExtractor.extractDataGet)
117 .map(res => {
118 res.username = username;
119 return res;
120 })
121 .flatMap(res => this.fetchUserInformations(res))
122 .map(res => this.handleLogin(res))
123 .catch((res) => this.restExtractor.handleError(res));
124 }
125
126 logout() {
127 // TODO: make an HTTP request to revoke the tokens
128 this.user = null;
129
130 AuthUser.flush();
131
132 this.setStatus(AuthStatus.LoggedOut);
133 }
134
135 refreshAccessToken() {
136 console.log('Refreshing token...');
137
138 const refreshToken = this.getRefreshToken();
139
140 let body = new URLSearchParams();
141 body.set('refresh_token', refreshToken);
142 body.set('client_id', this.clientId);
143 body.set('client_secret', this.clientSecret);
144 body.set('response_type', 'code');
145 body.set('grant_type', 'refresh_token');
146
147 let headers = new Headers();
148 headers.append('Content-Type', 'application/x-www-form-urlencoded');
149
150 let options = {
151 headers: headers
152 };
153
154 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
155 .map(this.restExtractor.extractDataGet)
156 .map(res => this.handleRefreshToken(res))
157 .catch((res: Response) => {
158 // The refresh token is invalid?
159 if (res.status === 400 && res.json() && res.json().error === 'invalid_grant') {
160 console.error('Cannot refresh token -> logout...');
161 this.logout();
162 this.router.navigate(['/login']);
163
164 return Observable.throw({
165 json: () => '',
166 text: () => 'You need to reconnect.'
167 });
168 }
169
170 return this.restExtractor.handleError(res);
171 });
172 }
173
174 private fetchUserInformations (obj: any) {
175 // Do not call authHttp here to avoid circular dependencies headaches
176
177 const headers = new Headers();
178 headers.set('Authorization', `Bearer ${obj.access_token}`);
179
180 return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
181 .map(res => res.json())
182 .map(res => {
183 obj.id = res.id;
184 obj.role = res.role;
185 return obj;
186 }
187 );
188 }
189
190 private handleLogin (obj: any) {
191 const id = obj.id;
192 const username = obj.username;
193 const role = obj.role;
194 const hashTokens = {
195 access_token: obj.access_token,
196 token_type: obj.token_type,
197 refresh_token: obj.refresh_token
198 };
199
200 this.user = new AuthUser({ id, username, role }, hashTokens);
201 this.user.save();
202
203 this.setStatus(AuthStatus.LoggedIn);
204 }
205
206 private handleRefreshToken (obj: any) {
207 this.user.refreshTokens(obj.access_token, obj.refresh_token);
208 this.user.save();
209 }
210
211 private setStatus(status: AuthStatus) {
212 this.loginChanged.next(status);
213 }
214
215 }