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, UserTokens } 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 { AuthStatus } from './auth-status.model'
13 import { AuthUser } from './auth-user.model'
15 interface UserLoginWithUsername extends UserLogin {
22 type UserLoginWithUserInformation = UserLoginWithUsername & User
25 export class AuthService {
26 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
27 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
28 private static BASE_REVOKE_TOKEN_URL = environment.apiUrl + '/api/v1/users/revoke-token'
29 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
30 private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
31 CLIENT_ID: 'client_id',
32 CLIENT_SECRET: 'client_secret'
35 loginChangedSource: Observable<AuthStatus>
36 userInformationLoaded = new ReplaySubject<boolean>(1)
37 tokensRefreshed = new ReplaySubject<void>(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()
58 new Hotkey('m s', (event: KeyboardEvent): boolean => {
59 this.router.navigate([ '/videos/subscriptions' ])
61 }, undefined, $localize`Go to my subscriptions`),
62 new Hotkey('m v', (event: KeyboardEvent): boolean => {
63 this.router.navigate([ '/my-library/videos' ])
65 }, undefined, $localize`Go to my videos`),
66 new Hotkey('m i', (event: KeyboardEvent): boolean => {
67 this.router.navigate([ '/my-library/video-imports' ])
69 }, undefined, $localize`Go to my imports`),
70 new Hotkey('m c', (event: KeyboardEvent): boolean => {
71 this.router.navigate([ '/my-library/video-channels' ])
73 }, undefined, $localize`Go to my channels`)
77 buildAuthUser (userInfo: Partial<User>, tokens: UserTokens) {
78 this.user = new AuthUser(userInfo, tokens)
81 loadClientCredentials () {
82 // Fetch the client_id/client_secret
83 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
84 .pipe(catchError(res => this.restExtractor.handleError(res)))
87 this.clientId = res.client_id
88 this.clientSecret = res.client_secret
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)
93 console.log('Client credentials loaded.')
97 let errorMessage = err.message
99 if (err.status === HttpStatusCode.FORBIDDEN_403) {
100 errorMessage = $localize`Cannot retrieve OAuth Client credentials: ${err.text}.
101 Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.`
104 // We put a bigger timeout: this is an important message
105 this.notifier.error(errorMessage, $localize`Error`, 7000)
111 if (this.user === null) return null
113 return this.user.getRefreshToken()
116 getRequestHeaderValue () {
117 const accessToken = this.getAccessToken()
119 if (accessToken === null) return null
121 return `${this.getTokenType()} ${accessToken}`
125 if (this.user === null) return null
127 return this.user.getAccessToken()
131 if (this.user === null) return null
133 return this.user.getTokenType()
141 return !!this.getAccessToken()
144 login (username: string, password: string, token?: string) {
147 client_id: this.clientId,
148 client_secret: this.clientSecret,
149 response_type: 'code',
150 grant_type: 'password',
156 if (token) Object.assign(body, { externalAuthToken: token })
158 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
159 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
161 map(res => Object.assign(res, { username })),
162 mergeMap(res => this.mergeUserInformation(res)),
163 map(res => this.handleLogin(res)),
164 catchError(res => this.restExtractor.handleError(res))
169 const authHeaderValue = this.getRequestHeaderValue()
170 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
172 this.http.post<{ redirectUrl?: string }>(AuthService.BASE_REVOKE_TOKEN_URL, {}, { headers })
175 if (res.redirectUrl) {
176 window.location.href = res.redirectUrl
180 error: err => console.error(err)
185 this.setStatus(AuthStatus.LoggedOut)
187 this.hotkeysService.remove(this.hotkeys)
190 refreshAccessToken () {
191 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
193 console.log('Refreshing token...')
195 const refreshToken = this.getRefreshToken()
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')
204 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
206 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
208 map(res => this.handleRefreshToken(res)),
210 this.refreshingTokenObservable = null
213 this.refreshingTokenObservable = null
216 console.log('Cannot refresh token -> logout...')
218 this.router.navigate([ '/login' ])
220 return observableThrowError(() => ({
221 error: $localize`You need to reconnect.`
227 return this.refreshingTokenObservable
230 refreshUserInformation () {
231 const obj: UserLoginWithUsername = {
232 access_token: this.user.getAccessToken(),
234 token_type: this.user.getTokenType(),
235 username: this.user.username
238 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)
265 this.setStatus(AuthStatus.LoggedIn)
266 this.userInformationLoaded.next(true)
268 this.hotkeysService.add(this.hotkeys)
271 private handleRefreshToken (obj: UserRefreshToken) {
272 this.user.refreshTokens(obj.access_token, obj.refresh_token)
273 this.tokensRefreshed.next()
276 private setStatus (status: AuthStatus) {
277 this.loginChanged.next(status)