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