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, HttpErrorResponse, 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 { logger, OAuthUserTokens, objectToUrlEncoded, peertubeLocalStorage } from '@root-helpers/index'
9 import { HttpStatusCode, 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 { RedirectService } from '../routing'
13 import { AuthStatus } from './auth-status.model'
14 import { AuthUser } from './auth-user.model'
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_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
31 private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
32 CLIENT_ID: 'client_id',
33 CLIENT_SECRET: 'client_secret'
36 loginChangedSource: Observable<AuthStatus>
37 userInformationLoaded = new ReplaySubject<boolean>(1)
38 tokensRefreshed = new ReplaySubject<void>(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>
48 private redirectService: RedirectService,
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()
60 new Hotkey('m s', (event: KeyboardEvent): boolean => {
61 this.router.navigate([ '/videos/subscriptions' ])
63 }, undefined, $localize`Go to my subscriptions`),
64 new Hotkey('m v', (event: KeyboardEvent): boolean => {
65 this.router.navigate([ '/my-library/videos' ])
67 }, undefined, $localize`Go to my videos`),
68 new Hotkey('m i', (event: KeyboardEvent): boolean => {
69 this.router.navigate([ '/my-library/video-imports' ])
71 }, undefined, $localize`Go to my imports`),
72 new Hotkey('m c', (event: KeyboardEvent): boolean => {
73 this.router.navigate([ '/my-library/video-channels' ])
75 }, undefined, $localize`Go to my channels`)
79 buildAuthUser (userInfo: Partial<User>, tokens: OAuthUserTokens) {
80 this.user = new AuthUser(userInfo, tokens)
83 loadClientCredentials () {
84 // Fetch the client_id/client_secret
85 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
86 .pipe(catchError(res => this.restExtractor.handleError(res)))
89 this.clientId = res.client_id
90 this.clientSecret = res.client_secret
92 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
93 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
95 logger.info('Client credentials loaded.')
99 let errorMessage = err.message
101 if (err.status === HttpStatusCode.FORBIDDEN_403) {
102 errorMessage = $localize`Cannot retrieve OAuth Client credentials: ${err.message}.
103 Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.`
106 // We put a bigger timeout: this is an important message
107 this.notifier.error(errorMessage, $localize`Error`, 7000)
113 if (this.user === null) return null
115 return this.user.getRefreshToken()
118 getRequestHeaderValue () {
119 const accessToken = this.getAccessToken()
121 if (accessToken === null) return null
123 return `${this.getTokenType()} ${accessToken}`
127 if (this.user === null) return null
129 return this.user.getAccessToken()
133 if (this.user === null) return null
135 return this.user.getTokenType()
143 return !!this.getAccessToken()
152 const { username, password, token, otpToken } = options
156 client_id: this.clientId,
157 client_secret: this.clientSecret,
158 response_type: 'code',
159 grant_type: 'password',
165 if (token) Object.assign(body, { externalAuthToken: token })
167 let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
168 if (otpToken) headers = headers.set('x-peertube-otp', otpToken)
170 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
172 map(res => Object.assign(res, { username })),
173 mergeMap(res => this.mergeUserInformation(res)),
174 map(res => this.handleLogin(res)),
175 catchError(res => this.restExtractor.handleError(res))
180 const authHeaderValue = this.getRequestHeaderValue()
181 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
183 this.http.post<{ redirectUrl?: string }>(AuthService.BASE_REVOKE_TOKEN_URL, {}, { headers })
186 if (res.redirectUrl) {
187 window.location.href = res.redirectUrl
191 error: err => logger.error(err)
196 this.setStatus(AuthStatus.LoggedOut)
198 this.hotkeysService.remove(this.hotkeys)
201 refreshAccessToken () {
202 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
204 logger.info('Refreshing token...')
206 const refreshToken = this.getRefreshToken()
209 const body = new HttpParams().set('refresh_token', refreshToken)
210 .set('client_id', this.clientId)
211 .set('client_secret', this.clientSecret)
212 .set('response_type', 'code')
213 .set('grant_type', 'refresh_token')
215 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
217 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
219 map(res => this.handleRefreshToken(res)),
221 this.refreshingTokenObservable = null
224 this.refreshingTokenObservable = null
227 logger.info('Cannot refresh token -> logout...')
230 this.redirectService.redirectToLogin()
232 return observableThrowError(() => ({
233 error: $localize`You need to reconnect.`
239 return this.refreshingTokenObservable
242 refreshUserInformation () {
243 const obj: UserLoginWithUsername = {
244 access_token: this.user.getAccessToken(),
246 token_type: this.user.getTokenType(),
247 username: this.user.username
250 this.mergeUserInformation(obj)
255 this.userInformationLoaded.next(true)
260 isOTPMissingError (err: HttpErrorResponse) {
261 if (err.status !== HttpStatusCode.UNAUTHORIZED_401) return false
263 if (err.headers.get('x-peertube-otp') !== 'required; app') return false
268 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
269 // User is not loaded yet, set manually auth header
270 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
272 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
273 .pipe(map(res => Object.assign(obj, res)))
276 private handleLogin (obj: UserLoginWithUserInformation) {
278 accessToken: obj.access_token,
279 tokenType: obj.token_type,
280 refreshToken: obj.refresh_token
283 this.user = new AuthUser(obj, hashTokens)
285 this.setStatus(AuthStatus.LoggedIn)
286 this.userInformationLoaded.next(true)
288 this.hotkeysService.add(this.hotkeys)
291 private handleRefreshToken (obj: UserRefreshToken) {
292 this.user.refreshTokens(obj.access_token, obj.refresh_token)
293 this.tokensRefreshed.next()
296 private setStatus (status: AuthStatus) {
297 this.loginChanged.next(status)