]>
Commit | Line | Data |
---|---|---|
1 | import { Hotkey, HotkeysService } from 'angular2-hotkeys' | |
2 | import { Observable, ReplaySubject, Subject, throwError as observableThrowError } from 'rxjs' | |
3 | import { catchError, map, mergeMap, share, tap } from 'rxjs/operators' | |
4 | import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http' | |
5 | import { Injectable } from '@angular/core' | |
6 | import { Router } from '@angular/router' | |
7 | import { Notifier } from '@app/core/notification/notifier.service' | |
8 | import { objectToUrlEncoded, peertubeLocalStorage } from '@root-helpers/index' | |
9 | import { I18n } from '@ngx-translate/i18n-polyfill' | |
10 | import { MyUser as UserServerModel, OAuthClientLocal, User, UserLogin, UserRefreshToken } from '@shared/models' | |
11 | import { environment } from '../../../environments/environment' | |
12 | import { RestExtractor } from '../rest/rest-extractor.service' | |
13 | import { AuthStatus } from './auth-status.model' | |
14 | import { AuthUser } from './auth-user.model' | |
15 | ||
16 | interface UserLoginWithUsername extends UserLogin { | |
17 | access_token: string | |
18 | refresh_token: string | |
19 | token_type: string | |
20 | username: string | |
21 | } | |
22 | ||
23 | type UserLoginWithUserInformation = UserLoginWithUsername & User | |
24 | ||
25 | @Injectable() | |
26 | export class AuthService { | |
27 | private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local' | |
28 | private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token' | |
29 | private static BASE_REVOKE_TOKEN_URL = environment.apiUrl + '/api/v1/users/revoke-token' | |
30 | private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me' | |
31 | private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = { | |
32 | CLIENT_ID: 'client_id', | |
33 | CLIENT_SECRET: 'client_secret' | |
34 | } | |
35 | ||
36 | loginChangedSource: Observable<AuthStatus> | |
37 | userInformationLoaded = new ReplaySubject<boolean>(1) | |
38 | hotkeys: Hotkey[] | |
39 | ||
40 | private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID) | |
41 | private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET) | |
42 | private loginChanged: Subject<AuthStatus> | |
43 | private user: AuthUser = null | |
44 | private refreshingTokenObservable: Observable<any> | |
45 | ||
46 | constructor ( | |
47 | private http: HttpClient, | |
48 | private notifier: Notifier, | |
49 | private hotkeysService: HotkeysService, | |
50 | private restExtractor: RestExtractor, | |
51 | private router: Router, | |
52 | private i18n: I18n | |
53 | ) { | |
54 | this.loginChanged = new Subject<AuthStatus>() | |
55 | this.loginChangedSource = this.loginChanged.asObservable() | |
56 | ||
57 | // Return null if there is nothing to load | |
58 | this.user = AuthUser.load() | |
59 | ||
60 | // Set HotKeys | |
61 | this.hotkeys = [ | |
62 | new Hotkey('m s', (event: KeyboardEvent): boolean => { | |
63 | this.router.navigate([ '/videos/subscriptions' ]) | |
64 | return false | |
65 | }, undefined, this.i18n('Go to my subscriptions')), | |
66 | new Hotkey('m v', (event: KeyboardEvent): boolean => { | |
67 | this.router.navigate([ '/my-account/videos' ]) | |
68 | return false | |
69 | }, undefined, this.i18n('Go to my videos')), | |
70 | new Hotkey('m i', (event: KeyboardEvent): boolean => { | |
71 | this.router.navigate([ '/my-account/video-imports' ]) | |
72 | return false | |
73 | }, undefined, this.i18n('Go to my imports')), | |
74 | new Hotkey('m c', (event: KeyboardEvent): boolean => { | |
75 | this.router.navigate([ '/my-account/video-channels' ]) | |
76 | return false | |
77 | }, undefined, this.i18n('Go to my channels')) | |
78 | ] | |
79 | } | |
80 | ||
81 | loadClientCredentials () { | |
82 | // Fetch the client_id/client_secret | |
83 | this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL) | |
84 | .pipe(catchError(res => this.restExtractor.handleError(res))) | |
85 | .subscribe( | |
86 | res => { | |
87 | this.clientId = res.client_id | |
88 | this.clientSecret = res.client_secret | |
89 | ||
90 | peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId) | |
91 | peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret) | |
92 | ||
93 | console.log('Client credentials loaded.') | |
94 | }, | |
95 | ||
96 | error => { | |
97 | let errorMessage = error.message | |
98 | ||
99 | if (error.status === 403) { | |
100 | errorMessage = this.i18n('Cannot retrieve OAuth Client credentials: {{errorText}}.\n', { errorText: error.text }) | |
101 | errorMessage += this.i18n( | |
102 | 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.' | |
103 | ) | |
104 | } | |
105 | ||
106 | // We put a bigger timeout: this is an important message | |
107 | this.notifier.error(errorMessage, this.i18n('Error'), 7000) | |
108 | } | |
109 | ) | |
110 | } | |
111 | ||
112 | getRefreshToken () { | |
113 | if (this.user === null) return null | |
114 | ||
115 | return this.user.getRefreshToken() | |
116 | } | |
117 | ||
118 | getRequestHeaderValue () { | |
119 | const accessToken = this.getAccessToken() | |
120 | ||
121 | if (accessToken === null) return null | |
122 | ||
123 | return `${this.getTokenType()} ${accessToken}` | |
124 | } | |
125 | ||
126 | getAccessToken () { | |
127 | if (this.user === null) return null | |
128 | ||
129 | return this.user.getAccessToken() | |
130 | } | |
131 | ||
132 | getTokenType () { | |
133 | if (this.user === null) return null | |
134 | ||
135 | return this.user.getTokenType() | |
136 | } | |
137 | ||
138 | getUser () { | |
139 | return this.user | |
140 | } | |
141 | ||
142 | isLoggedIn () { | |
143 | return !!this.getAccessToken() | |
144 | } | |
145 | ||
146 | login (username: string, password: string, token?: string) { | |
147 | // Form url encoded | |
148 | const body = { | |
149 | client_id: this.clientId, | |
150 | client_secret: this.clientSecret, | |
151 | response_type: 'code', | |
152 | grant_type: 'password', | |
153 | scope: 'upload', | |
154 | username, | |
155 | password | |
156 | } | |
157 | ||
158 | if (token) Object.assign(body, { externalAuthToken: token }) | |
159 | ||
160 | const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') | |
161 | return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers }) | |
162 | .pipe( | |
163 | map(res => Object.assign(res, { username })), | |
164 | mergeMap(res => this.mergeUserInformation(res)), | |
165 | map(res => this.handleLogin(res)), | |
166 | catchError(res => this.restExtractor.handleError(res)) | |
167 | ) | |
168 | } | |
169 | ||
170 | logout () { | |
171 | const authHeaderValue = this.getRequestHeaderValue() | |
172 | const headers = new HttpHeaders().set('Authorization', authHeaderValue) | |
173 | ||
174 | this.http.post<void>(AuthService.BASE_REVOKE_TOKEN_URL, {}, { headers }) | |
175 | .subscribe( | |
176 | () => { /* nothing to do */ }, | |
177 | ||
178 | err => console.error(err) | |
179 | ) | |
180 | ||
181 | this.user = null | |
182 | ||
183 | AuthUser.flush() | |
184 | ||
185 | this.setStatus(AuthStatus.LoggedOut) | |
186 | ||
187 | this.hotkeysService.remove(this.hotkeys) | |
188 | } | |
189 | ||
190 | refreshAccessToken () { | |
191 | if (this.refreshingTokenObservable) return this.refreshingTokenObservable | |
192 | ||
193 | console.log('Refreshing token...') | |
194 | ||
195 | const refreshToken = this.getRefreshToken() | |
196 | ||
197 | // Form url encoded | |
198 | const body = new HttpParams().set('refresh_token', refreshToken) | |
199 | .set('client_id', this.clientId) | |
200 | .set('client_secret', this.clientSecret) | |
201 | .set('response_type', 'code') | |
202 | .set('grant_type', 'refresh_token') | |
203 | ||
204 | const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') | |
205 | ||
206 | this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers }) | |
207 | .pipe( | |
208 | map(res => this.handleRefreshToken(res)), | |
209 | tap(() => this.refreshingTokenObservable = null), | |
210 | catchError(err => { | |
211 | this.refreshingTokenObservable = null | |
212 | ||
213 | console.error(err) | |
214 | console.log('Cannot refresh token -> logout...') | |
215 | this.logout() | |
216 | this.router.navigate([ '/login' ]) | |
217 | ||
218 | return observableThrowError({ | |
219 | error: this.i18n('You need to reconnect.') | |
220 | }) | |
221 | }), | |
222 | share() | |
223 | ) | |
224 | ||
225 | return this.refreshingTokenObservable | |
226 | } | |
227 | ||
228 | refreshUserInformation () { | |
229 | const obj: UserLoginWithUsername = { | |
230 | access_token: this.user.getAccessToken(), | |
231 | refresh_token: null, | |
232 | token_type: this.user.getTokenType(), | |
233 | username: this.user.username | |
234 | } | |
235 | ||
236 | this.mergeUserInformation(obj) | |
237 | .subscribe( | |
238 | res => { | |
239 | this.user.patch(res) | |
240 | this.user.save() | |
241 | ||
242 | this.userInformationLoaded.next(true) | |
243 | } | |
244 | ) | |
245 | } | |
246 | ||
247 | private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> { | |
248 | // User is not loaded yet, set manually auth header | |
249 | const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`) | |
250 | ||
251 | return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers }) | |
252 | .pipe(map(res => Object.assign(obj, res))) | |
253 | } | |
254 | ||
255 | private handleLogin (obj: UserLoginWithUserInformation) { | |
256 | const hashTokens = { | |
257 | accessToken: obj.access_token, | |
258 | tokenType: obj.token_type, | |
259 | refreshToken: obj.refresh_token | |
260 | } | |
261 | ||
262 | this.user = new AuthUser(obj, hashTokens) | |
263 | this.user.save() | |
264 | ||
265 | this.setStatus(AuthStatus.LoggedIn) | |
266 | this.userInformationLoaded.next(true) | |
267 | ||
268 | this.hotkeysService.add(this.hotkeys) | |
269 | } | |
270 | ||
271 | private handleRefreshToken (obj: UserRefreshToken) { | |
272 | this.user.refreshTokens(obj.access_token, obj.refresh_token) | |
273 | this.user.save() | |
274 | } | |
275 | ||
276 | private setStatus (status: AuthStatus) { | |
277 | this.loginChanged.next(status) | |
278 | } | |
279 | } |