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'
16 interface UserLoginWithUsername extends UserLogin {
23 type UserLoginWithUserInformation = UserLoginWithUsername & User
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'
37 loginChangedSource: Observable<AuthStatus>
38 userInformationLoaded = new ReplaySubject<boolean>(1)
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
49 private http: HttpClient,
50 private notifier: Notifier,
51 private hotkeysService: HotkeysService,
52 private restExtractor: RestExtractor,
53 private router: Router
55 this.loginChanged = new Subject<AuthStatus>()
56 this.loginChangedSource = this.loginChanged.asObservable()
58 // Return null if there is nothing to load
59 this.user = AuthUser.load()
63 new Hotkey('m s', (event: KeyboardEvent): boolean => {
64 this.router.navigate([ '/videos/subscriptions' ])
66 }, undefined, $localize`Go to my subscriptions`),
67 new Hotkey('m v', (event: KeyboardEvent): boolean => {
68 this.router.navigate([ '/my-library/videos' ])
70 }, undefined, $localize`Go to my videos`),
71 new Hotkey('m i', (event: KeyboardEvent): boolean => {
72 this.router.navigate([ '/my-library/video-imports' ])
74 }, undefined, $localize`Go to my imports`),
75 new Hotkey('m c', (event: KeyboardEvent): boolean => {
76 this.router.navigate([ '/my-library/video-channels' ])
78 }, undefined, $localize`Go to my channels`)
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)))
88 this.clientId = res.client_id
89 this.clientSecret = res.client_secret
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)
94 console.log('Client credentials loaded.')
98 let errorMessage = error.message
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.`
105 // We put a bigger timeout: this is an important message
106 this.notifier.error(errorMessage, $localize`Error`, 7000)
112 if (this.user === null) return null
114 return this.user.getRefreshToken()
117 getRequestHeaderValue () {
118 const accessToken = this.getAccessToken()
120 if (accessToken === null) return null
122 return `${this.getTokenType()} ${accessToken}`
126 if (this.user === null) return null
128 return this.user.getAccessToken()
132 if (this.user === null) return null
134 return this.user.getTokenType()
142 return !!this.getAccessToken()
145 login (username: string, password: string, token?: string) {
148 client_id: this.clientId,
149 client_secret: this.clientSecret,
150 response_type: 'code',
151 grant_type: 'password',
157 if (token) Object.assign(body, { externalAuthToken: token })
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 })
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))
170 const authHeaderValue = this.getRequestHeaderValue()
171 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
173 this.http.post<{ redirectUrl?: string }>(AuthService.BASE_REVOKE_TOKEN_URL, {}, { headers })
176 if (res.redirectUrl) {
177 window.location.href = res.redirectUrl
181 err => console.error(err)
188 this.setStatus(AuthStatus.LoggedOut)
190 this.hotkeysService.remove(this.hotkeys)
193 refreshAccessToken () {
194 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
196 console.log('Refreshing token...')
198 const refreshToken = this.getRefreshToken()
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')
207 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
209 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
211 map(res => this.handleRefreshToken(res)),
212 tap(() => this.refreshingTokenObservable = null),
214 this.refreshingTokenObservable = null
217 console.log('Cannot refresh token -> logout...')
219 this.router.navigate([ '/login' ])
221 return observableThrowError({
222 error: $localize`You need to reconnect.`
228 return this.refreshingTokenObservable
231 refreshUserInformation () {
232 const obj: UserLoginWithUsername = {
233 access_token: this.user.getAccessToken(),
235 token_type: this.user.getTokenType(),
236 username: this.user.username
239 this.mergeUserInformation(obj)
245 this.userInformationLoaded.next(true)
250 getScopedTokens (): Promise<ScopedToken> {
251 return new Promise((res, rej) => {
252 if (this.scopedTokens) return res(this.scopedTokens)
254 const authHeaderValue = this.getRequestHeaderValue()
255 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
257 this.http.get<ScopedToken>(AuthService.BASE_SCOPED_TOKENS_URL, { headers })
260 this.scopedTokens = scopedTokens
261 res(this.scopedTokens)
272 renewScopedTokens (): Promise<ScopedToken> {
273 return new Promise((res, rej) => {
274 const authHeaderValue = this.getRequestHeaderValue()
275 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
277 this.http.post<ScopedToken>(AuthService.BASE_SCOPED_TOKENS_URL, {}, { headers })
280 this.scopedTokens = scopedTokens
281 res(this.scopedTokens)
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}`)
296 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
297 .pipe(map(res => Object.assign(obj, res)))
300 private handleLogin (obj: UserLoginWithUserInformation) {
302 accessToken: obj.access_token,
303 tokenType: obj.token_type,
304 refreshToken: obj.refresh_token
307 this.user = new AuthUser(obj, hashTokens)
310 this.setStatus(AuthStatus.LoggedIn)
311 this.userInformationLoaded.next(true)
313 this.hotkeysService.add(this.hotkeys)
316 private handleRefreshToken (obj: UserRefreshToken) {
317 this.user.refreshTokens(obj.access_token, obj.refresh_token)
321 private setStatus (status: AuthStatus) {
322 this.loginChanged.next(status)