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