]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/auth/auth.service.ts
224f35f82008711b846a23d5b7c5a58a0648b32f
[github/Chocobozzz/PeerTube.git] / client / src / app / core / auth / auth.service.ts
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 { MyUser as UserServerModel, OAuthClientLocal, User, UserLogin, UserRefreshToken } from '@shared/models'
10 import { environment } from '../../../environments/environment'
11 import { RestExtractor } from '../rest/rest-extractor.service'
12 import { AuthStatus } from './auth-status.model'
13 import { AuthUser } from './auth-user.model'
14 import { ScopedTokenType, ScopedToken } from '@shared/models/users/user-scoped-token'
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_SCOPED_TOKENS_URL = environment.apiUrl + '/api/v1/users/scoped-tokens'
31 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
32 private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
33 CLIENT_ID: 'client_id',
34 CLIENT_SECRET: 'client_secret'
35 }
36
37 loginChangedSource: Observable<AuthStatus>
38 userInformationLoaded = new ReplaySubject<boolean>(1)
39 hotkeys: Hotkey[]
40
41 private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
42 private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
43 private loginChanged: Subject<AuthStatus>
44 private user: AuthUser = null
45 private refreshingTokenObservable: Observable<any>
46 private scopedTokens: ScopedToken
47
48 constructor (
49 private http: HttpClient,
50 private notifier: Notifier,
51 private hotkeysService: HotkeysService,
52 private restExtractor: RestExtractor,
53 private router: Router
54 ) {
55 this.loginChanged = new Subject<AuthStatus>()
56 this.loginChangedSource = this.loginChanged.asObservable()
57
58 // Return null if there is nothing to load
59 this.user = AuthUser.load()
60
61 // Set HotKeys
62 this.hotkeys = [
63 new Hotkey('m s', (event: KeyboardEvent): boolean => {
64 this.router.navigate([ '/videos/subscriptions' ])
65 return false
66 }, undefined, $localize`Go to my subscriptions`),
67 new Hotkey('m v', (event: KeyboardEvent): boolean => {
68 this.router.navigate([ '/my-library/videos' ])
69 return false
70 }, undefined, $localize`Go to my videos`),
71 new Hotkey('m i', (event: KeyboardEvent): boolean => {
72 this.router.navigate([ '/my-library/video-imports' ])
73 return false
74 }, undefined, $localize`Go to my imports`),
75 new Hotkey('m c', (event: KeyboardEvent): boolean => {
76 this.router.navigate([ '/my-library/video-channels' ])
77 return false
78 }, undefined, $localize`Go to my channels`)
79 ]
80 }
81
82 loadClientCredentials () {
83 // Fetch the client_id/client_secret
84 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
85 .pipe(catchError(res => this.restExtractor.handleError(res)))
86 .subscribe(
87 res => {
88 this.clientId = res.client_id
89 this.clientSecret = res.client_secret
90
91 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
92 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
93
94 console.log('Client credentials loaded.')
95 },
96
97 error => {
98 let errorMessage = error.message
99
100 if (error.status === 403) {
101 errorMessage = $localize`Cannot retrieve OAuth Client credentials: ${error.text}.
102 Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.`
103 }
104
105 // We put a bigger timeout: this is an important message
106 this.notifier.error(errorMessage, $localize`Error`, 7000)
107 }
108 )
109 }
110
111 getRefreshToken () {
112 if (this.user === null) return null
113
114 return this.user.getRefreshToken()
115 }
116
117 getRequestHeaderValue () {
118 const accessToken = this.getAccessToken()
119
120 if (accessToken === null) return null
121
122 return `${this.getTokenType()} ${accessToken}`
123 }
124
125 getAccessToken () {
126 if (this.user === null) return null
127
128 return this.user.getAccessToken()
129 }
130
131 getTokenType () {
132 if (this.user === null) return null
133
134 return this.user.getTokenType()
135 }
136
137 getUser () {
138 return this.user
139 }
140
141 isLoggedIn () {
142 return !!this.getAccessToken()
143 }
144
145 login (username: string, password: string, token?: string) {
146 // Form url encoded
147 const body = {
148 client_id: this.clientId,
149 client_secret: this.clientSecret,
150 response_type: 'code',
151 grant_type: 'password',
152 scope: 'upload',
153 username,
154 password
155 }
156
157 if (token) Object.assign(body, { externalAuthToken: token })
158
159 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
160 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
161 .pipe(
162 map(res => Object.assign(res, { username })),
163 mergeMap(res => this.mergeUserInformation(res)),
164 map(res => this.handleLogin(res)),
165 catchError(res => this.restExtractor.handleError(res))
166 )
167 }
168
169 logout () {
170 const authHeaderValue = this.getRequestHeaderValue()
171 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
172
173 this.http.post<{ redirectUrl?: string }>(AuthService.BASE_REVOKE_TOKEN_URL, {}, { headers })
174 .subscribe(
175 res => {
176 if (res.redirectUrl) {
177 window.location.href = res.redirectUrl
178 }
179 },
180
181 err => console.error(err)
182 )
183
184 this.user = null
185
186 AuthUser.flush()
187
188 this.setStatus(AuthStatus.LoggedOut)
189
190 this.hotkeysService.remove(this.hotkeys)
191 }
192
193 refreshAccessToken () {
194 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
195
196 console.log('Refreshing token...')
197
198 const refreshToken = this.getRefreshToken()
199
200 // Form url encoded
201 const body = new HttpParams().set('refresh_token', refreshToken)
202 .set('client_id', this.clientId)
203 .set('client_secret', this.clientSecret)
204 .set('response_type', 'code')
205 .set('grant_type', 'refresh_token')
206
207 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
208
209 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
210 .pipe(
211 map(res => this.handleRefreshToken(res)),
212 tap(() => this.refreshingTokenObservable = null),
213 catchError(err => {
214 this.refreshingTokenObservable = null
215
216 console.error(err)
217 console.log('Cannot refresh token -> logout...')
218 this.logout()
219 this.router.navigate([ '/login' ])
220
221 return observableThrowError({
222 error: $localize`You need to reconnect.`
223 })
224 }),
225 share()
226 )
227
228 return this.refreshingTokenObservable
229 }
230
231 refreshUserInformation () {
232 const obj: UserLoginWithUsername = {
233 access_token: this.user.getAccessToken(),
234 refresh_token: null,
235 token_type: this.user.getTokenType(),
236 username: this.user.username
237 }
238
239 this.mergeUserInformation(obj)
240 .subscribe(
241 res => {
242 this.user.patch(res)
243 this.user.save()
244
245 this.userInformationLoaded.next(true)
246 }
247 )
248 }
249
250 getScopedTokens (): Promise<ScopedToken> {
251 return new Promise((res, rej) => {
252 if (this.scopedTokens) return res(this.scopedTokens)
253
254 const authHeaderValue = this.getRequestHeaderValue()
255 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
256
257 this.http.get<ScopedToken>(AuthService.BASE_SCOPED_TOKENS_URL, { headers })
258 .subscribe(
259 scopedTokens => {
260 this.scopedTokens = scopedTokens
261 res(this.scopedTokens)
262 },
263
264 err => {
265 console.error(err)
266 rej(err)
267 }
268 )
269 })
270 }
271
272 renewScopedTokens (): Promise<ScopedToken> {
273 return new Promise((res, rej) => {
274 const authHeaderValue = this.getRequestHeaderValue()
275 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
276
277 this.http.post<ScopedToken>(AuthService.BASE_SCOPED_TOKENS_URL, {}, { headers })
278 .subscribe(
279 scopedTokens => {
280 this.scopedTokens = scopedTokens
281 res(this.scopedTokens)
282 },
283
284 err => {
285 console.error(err)
286 rej(err)
287 }
288 )
289 })
290 }
291
292 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
293 // User is not loaded yet, set manually auth header
294 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
295
296 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
297 .pipe(map(res => Object.assign(obj, res)))
298 }
299
300 private handleLogin (obj: UserLoginWithUserInformation) {
301 const hashTokens = {
302 accessToken: obj.access_token,
303 tokenType: obj.token_type,
304 refreshToken: obj.refresh_token
305 }
306
307 this.user = new AuthUser(obj, hashTokens)
308 this.user.save()
309
310 this.setStatus(AuthStatus.LoggedIn)
311 this.userInformationLoaded.next(true)
312
313 this.hotkeysService.add(this.hotkeys)
314 }
315
316 private handleRefreshToken (obj: UserRefreshToken) {
317 this.user.refreshTokens(obj.access_token, obj.refresh_token)
318 this.user.save()
319 }
320
321 private setStatus (status: AuthStatus) {
322 this.loginChanged.next(status)
323 }
324 }