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