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