]>
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' |
67ed6552 C |
8 | import { objectToUrlEncoded, peertubeLocalStorage } from '@app/helpers' |
9 | import { I18n } from '@ngx-translate/i18n-polyfill' | |
10 | import { MyUser as UserServerModel, OAuthClientLocal, User, UserLogin, UserRefreshToken } from '@shared/models' | |
63c4db6d | 11 | import { environment } from '../../../environments/environment' |
67ed6552 | 12 | import { RestExtractor } from '../rest/rest-extractor.service' |
2295ce6c C |
13 | import { AuthStatus } from './auth-status.model' |
14 | import { AuthUser } from './auth-user.model' | |
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, |
b1d40cff C |
51 | private router: Router, |
52 | private i18n: I18n | |
db400f44 | 53 | ) { |
df98563e C |
54 | this.loginChanged = new Subject<AuthStatus>() |
55 | this.loginChangedSource = this.loginChanged.asObservable() | |
23a5a916 | 56 | |
bd5c83a8 | 57 | // Return null if there is nothing to load |
df98563e | 58 | this.user = AuthUser.load() |
c13e2bf3 RK |
59 | |
60 | // Set HotKeys | |
61 | this.hotkeys = [ | |
62 | new Hotkey('m s', (event: KeyboardEvent): boolean => { | |
63 | this.router.navigate([ '/videos/subscriptions' ]) | |
64 | return false | |
e33f888b | 65 | }, undefined, this.i18n('Go to my subscriptions')), |
c13e2bf3 RK |
66 | new Hotkey('m v', (event: KeyboardEvent): boolean => { |
67 | this.router.navigate([ '/my-account/videos' ]) | |
68 | return false | |
e33f888b | 69 | }, undefined, this.i18n('Go to my videos')), |
c13e2bf3 RK |
70 | new Hotkey('m i', (event: KeyboardEvent): boolean => { |
71 | this.router.navigate([ '/my-account/video-imports' ]) | |
72 | return false | |
e33f888b | 73 | }, undefined, this.i18n('Go to my imports')), |
c13e2bf3 RK |
74 | new Hotkey('m c', (event: KeyboardEvent): boolean => { |
75 | this.router.navigate([ '/my-account/video-channels' ]) | |
76 | return false | |
e33f888b | 77 | }, undefined, this.i18n('Go to my channels')) |
c13e2bf3 | 78 | ] |
1553e15d | 79 | } |
b1794c53 | 80 | |
d592e0a9 C |
81 | loadClientCredentials () { |
82 | // Fetch the client_id/client_secret | |
d592e0a9 | 83 | this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL) |
db400f44 C |
84 | .pipe(catchError(res => this.restExtractor.handleError(res))) |
85 | .subscribe( | |
86 | res => { | |
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 | ||
db400f44 C |
93 | console.log('Client credentials loaded.') |
94 | }, | |
95 | ||
96 | error => { | |
97 | let errorMessage = error.message | |
98 | ||
99 | if (error.status === 403) { | |
25acef90 | 100 | errorMessage = this.i18n('Cannot retrieve OAuth Client credentials: {{errorText}}.\n', { errorText: error.text }) |
b1d40cff C |
101 | errorMessage += this.i18n( |
102 | 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.' | |
103 | ) | |
db400f44 C |
104 | } |
105 | ||
f8b2c1b4 C |
106 | // We put a bigger timeout: this is an important message |
107 | this.notifier.error(errorMessage, this.i18n('Error'), 7000) | |
db400f44 C |
108 | } |
109 | ) | |
d592e0a9 C |
110 | } |
111 | ||
df98563e C |
112 | getRefreshToken () { |
113 | if (this.user === null) return null | |
bd5c83a8 | 114 | |
df98563e | 115 | return this.user.getRefreshToken() |
bd5c83a8 C |
116 | } |
117 | ||
df98563e | 118 | getRequestHeaderValue () { |
d592e0a9 C |
119 | const accessToken = this.getAccessToken() |
120 | ||
121 | if (accessToken === null) return null | |
122 | ||
123 | return `${this.getTokenType()} ${accessToken}` | |
1553e15d C |
124 | } |
125 | ||
df98563e C |
126 | getAccessToken () { |
127 | if (this.user === null) return null | |
bd5c83a8 | 128 | |
df98563e | 129 | return this.user.getAccessToken() |
1553e15d C |
130 | } |
131 | ||
df98563e C |
132 | getTokenType () { |
133 | if (this.user === null) return null | |
bd5c83a8 | 134 | |
df98563e | 135 | return this.user.getTokenType() |
1553e15d C |
136 | } |
137 | ||
df98563e C |
138 | getUser () { |
139 | return this.user | |
1553e15d C |
140 | } |
141 | ||
df98563e | 142 | isLoggedIn () { |
d592e0a9 | 143 | return !!this.getAccessToken() |
1553e15d C |
144 | } |
145 | ||
4a8d113b | 146 | login (username: string, password: string, token?: string) { |
d592e0a9 | 147 | // Form url encoded |
cd4d7a2c C |
148 | const body = { |
149 | client_id: this.clientId, | |
150 | client_secret: this.clientSecret, | |
151 | response_type: 'code', | |
152 | grant_type: 'password', | |
153 | scope: 'upload', | |
50b4dcce | 154 | username, |
cd4d7a2c | 155 | password |
f954b5da | 156 | } |
d592e0a9 | 157 | |
4a8d113b C |
158 | if (token) Object.assign(body, { externalAuthToken: token }) |
159 | ||
d592e0a9 | 160 | const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') |
cd4d7a2c | 161 | return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers }) |
db400f44 C |
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 | ) | |
4fd8aa32 C |
168 | } |
169 | ||
df98563e | 170 | logout () { |
dadc90bc C |
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 | ||
df98563e | 181 | this.user = null |
724fed29 | 182 | |
df98563e | 183 | AuthUser.flush() |
e62f6ef7 | 184 | |
df98563e | 185 | this.setStatus(AuthStatus.LoggedOut) |
c13e2bf3 RK |
186 | |
187 | this.hotkeysService.remove(this.hotkeys) | |
bd5c83a8 C |
188 | } |
189 | ||
df98563e | 190 | refreshAccessToken () { |
47f8de28 C |
191 | if (this.refreshingTokenObservable) return this.refreshingTokenObservable |
192 | ||
df98563e | 193 | console.log('Refreshing token...') |
bd5c83a8 | 194 | |
df98563e | 195 | const refreshToken = this.getRefreshToken() |
bd5c83a8 | 196 | |
d592e0a9 C |
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') | |
bd5c83a8 | 203 | |
d592e0a9 | 204 | const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') |
bd5c83a8 | 205 | |
47f8de28 | 206 | this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers }) |
db400f44 C |
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({ | |
b1d40cff | 219 | error: this.i18n('You need to reconnect.') |
db400f44 | 220 | }) |
a20776fc C |
221 | }), |
222 | share() | |
db400f44 | 223 | ) |
47f8de28 C |
224 | |
225 | return this.refreshingTokenObservable | |
4fd8aa32 C |
226 | } |
227 | ||
d592e0a9 | 228 | refreshUserInformation () { |
c199c427 | 229 | const obj: UserLoginWithUsername = { |
33c4972d C |
230 | access_token: this.user.getAccessToken(), |
231 | refresh_token: null, | |
232 | token_type: this.user.getTokenType(), | |
233 | username: this.user.username | |
df98563e | 234 | } |
af5e743b | 235 | |
d592e0a9 | 236 | this.mergeUserInformation(obj) |
db400f44 C |
237 | .subscribe( |
238 | res => { | |
239 | this.user.patch(res) | |
240 | this.user.save() | |
cadb46d8 | 241 | |
db400f44 C |
242 | this.userInformationLoaded.next(true) |
243 | } | |
244 | ) | |
af5e743b C |
245 | } |
246 | ||
d592e0a9 C |
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 | ||
bcd9f81e | 251 | return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers }) |
db400f44 | 252 | .pipe(map(res => Object.assign(obj, res))) |
b1794c53 C |
253 | } |
254 | ||
d592e0a9 | 255 | private handleLogin (obj: UserLoginWithUserInformation) { |
7da18e44 | 256 | const hashTokens = { |
df98563e C |
257 | accessToken: obj.access_token, |
258 | tokenType: obj.token_type, | |
259 | refreshToken: obj.refresh_token | |
260 | } | |
bd5c83a8 | 261 | |
ce5496d6 | 262 | this.user = new AuthUser(obj, hashTokens) |
df98563e | 263 | this.user.save() |
bd5c83a8 | 264 | |
df98563e | 265 | this.setStatus(AuthStatus.LoggedIn) |
efc32059 | 266 | this.userInformationLoaded.next(true) |
c13e2bf3 RK |
267 | |
268 | this.hotkeysService.add(this.hotkeys) | |
bd5c83a8 C |
269 | } |
270 | ||
d592e0a9 | 271 | private handleRefreshToken (obj: UserRefreshToken) { |
df98563e C |
272 | this.user.refreshTokens(obj.access_token, obj.refresh_token) |
273 | this.user.save() | |
bd5c83a8 | 274 | } |
629d8d6f | 275 | |
df98563e C |
276 | private setStatus (status: AuthStatus) { |
277 | this.loginChanged.next(status) | |
629d8d6f | 278 | } |
b1794c53 | 279 | } |