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