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 { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
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)
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)
42 private loginChanged: Subject<AuthStatus>
43 private user: AuthUser = null
44 private refreshingTokenObservable: Observable<any>
47 private http: HttpClient,
48 private notifier: Notifier,
49 private hotkeysService: HotkeysService,
50 private restExtractor: RestExtractor,
51 private router: Router
53 this.loginChanged = new Subject<AuthStatus>()
54 this.loginChangedSource = this.loginChanged.asObservable()
56 // Return null if there is nothing to load
57 this.user = AuthUser.load()
61 new Hotkey('m s', (event: KeyboardEvent): boolean => {
62 this.router.navigate([ '/videos/subscriptions' ])
64 }, undefined, $localize`Go to my subscriptions`),
65 new Hotkey('m v', (event: KeyboardEvent): boolean => {
66 this.router.navigate([ '/my-library/videos' ])
68 }, undefined, $localize`Go to my videos`),
69 new Hotkey('m i', (event: KeyboardEvent): boolean => {
70 this.router.navigate([ '/my-library/video-imports' ])
72 }, undefined, $localize`Go to my imports`),
73 new Hotkey('m c', (event: KeyboardEvent): boolean => {
74 this.router.navigate([ '/my-library/video-channels' ])
76 }, undefined, $localize`Go to my channels`)
80 loadClientCredentials () {
81 // Fetch the client_id/client_secret
82 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
83 .pipe(catchError(res => this.restExtractor.handleError(res)))
86 this.clientId = res.client_id
87 this.clientSecret = res.client_secret
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)
92 console.log('Client credentials loaded.')
96 let errorMessage = error.message
98 if (error.status === HttpStatusCode.FORBIDDEN_403) {
99 errorMessage = $localize`Cannot retrieve OAuth Client credentials: ${error.text}.
100 Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.`
103 // We put a bigger timeout: this is an important message
104 this.notifier.error(errorMessage, $localize`Error`, 7000)
110 if (this.user === null) return null
112 return this.user.getRefreshToken()
115 getRequestHeaderValue () {
116 const accessToken = this.getAccessToken()
118 if (accessToken === null) return null
120 return `${this.getTokenType()} ${accessToken}`
124 if (this.user === null) return null
126 return this.user.getAccessToken()
130 if (this.user === null) return null
132 return this.user.getTokenType()
140 return !!this.getAccessToken()
143 login (username: string, password: string, token?: string) {
146 client_id: this.clientId,
147 client_secret: this.clientSecret,
148 response_type: 'code',
149 grant_type: 'password',
155 if (token) Object.assign(body, { externalAuthToken: token })
157 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
158 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
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))
168 const authHeaderValue = this.getRequestHeaderValue()
169 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
171 this.http.post<{ redirectUrl?: string }>(AuthService.BASE_REVOKE_TOKEN_URL, {}, { headers })
174 if (res.redirectUrl) {
175 window.location.href = res.redirectUrl
179 err => console.error(err)
186 this.setStatus(AuthStatus.LoggedOut)
188 this.hotkeysService.remove(this.hotkeys)
191 refreshAccessToken () {
192 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
194 console.log('Refreshing token...')
196 const refreshToken = this.getRefreshToken()
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')
205 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
207 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
209 map(res => this.handleRefreshToken(res)),
210 tap(() => this.refreshingTokenObservable = null),
212 this.refreshingTokenObservable = null
215 console.log('Cannot refresh token -> logout...')
217 this.router.navigate([ '/login' ])
219 return observableThrowError({
220 error: $localize`You need to reconnect.`
226 return this.refreshingTokenObservable
229 refreshUserInformation () {
230 const obj: UserLoginWithUsername = {
231 access_token: this.user.getAccessToken(),
233 token_type: this.user.getTokenType(),
234 username: this.user.username
237 this.mergeUserInformation(obj)
243 this.userInformationLoaded.next(true)
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}`)
252 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
253 .pipe(map(res => Object.assign(obj, res)))
256 private handleLogin (obj: UserLoginWithUserInformation) {
258 accessToken: obj.access_token,
259 tokenType: obj.token_type,
260 refreshToken: obj.refresh_token
263 this.user = new AuthUser(obj, hashTokens)
266 this.setStatus(AuthStatus.LoggedIn)
267 this.userInformationLoaded.next(true)
269 this.hotkeysService.add(this.hotkeys)
272 private handleRefreshToken (obj: UserRefreshToken) {
273 this.user.refreshTokens(obj.access_token, obj.refresh_token)
277 private setStatus (status: AuthStatus) {
278 this.loginChanged.next(status)