1 import { Observable, ReplaySubject, Subject, throwError as observableThrowError } from 'rxjs'
2 import { catchError, map, mergeMap, share, tap } from 'rxjs/operators'
3 import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
4 import { Injectable } from '@angular/core'
5 import { Router } from '@angular/router'
6 import { NotificationsService } from 'angular2-notifications'
7 import { OAuthClientLocal, User as UserServerModel, UserRefreshToken } from '../../../../../shared'
8 import { User } from '../../../../../shared/models/users'
9 import { UserLogin } from '../../../../../shared/models/users/user-login.model'
10 import { environment } from '../../../environments/environment'
11 import { RestExtractor } from '../../shared/rest'
12 import { AuthStatus } from './auth-status.model'
13 import { AuthUser } from './auth-user.model'
14 import { objectToUrlEncoded } from '@app/shared/misc/utils'
15 import { peertubeLocalStorage } from '@app/shared/misc/peertube-local-storage'
16 import { I18n } from '@ngx-translate/i18n-polyfill'
17 import { HotkeysService, Hotkey } from 'angular2-hotkeys'
19 interface UserLoginWithUsername extends UserLogin {
26 type UserLoginWithUserInformation = UserLoginWithUsername & User
29 export class AuthService {
30 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
31 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
32 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
33 private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
34 CLIENT_ID: 'client_id',
35 CLIENT_SECRET: 'client_secret'
38 loginChangedSource: Observable<AuthStatus>
39 userInformationLoaded = new ReplaySubject<boolean>(1)
43 private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
44 private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
45 private loginChanged: Subject<AuthStatus>
46 private user: AuthUser = null
47 private refreshingTokenObservable: Observable<any>
50 private http: HttpClient,
51 private notificationsService: NotificationsService,
52 private hotkeysService: HotkeysService,
53 private restExtractor: RestExtractor,
54 private router: Router,
57 this.loginChanged = new Subject<AuthStatus>()
58 this.loginChangedSource = this.loginChanged.asObservable()
60 // Return null if there is nothing to load
61 this.user = AuthUser.load()
65 new Hotkey('m s', (event: KeyboardEvent): boolean => {
66 this.router.navigate([ '/videos/subscriptions' ])
68 }, undefined, 'Go to my subscriptions'),
69 new Hotkey('m v', (event: KeyboardEvent): boolean => {
70 this.router.navigate([ '/my-account/videos' ])
72 }, undefined, 'Go to my videos'),
73 new Hotkey('m i', (event: KeyboardEvent): boolean => {
74 this.router.navigate([ '/my-account/video-imports' ])
76 }, undefined, 'Go to my imports'),
77 new Hotkey('m c', (event: KeyboardEvent): boolean => {
78 this.router.navigate([ '/my-account/video-channels' ])
80 }, undefined, 'Go to my channels')
84 loadClientCredentials () {
85 // Fetch the client_id/client_secret
86 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
87 .pipe(catchError(res => this.restExtractor.handleError(res)))
90 this.clientId = res.client_id
91 this.clientSecret = res.client_secret
93 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
94 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
96 console.log('Client credentials loaded.')
100 let errorMessage = error.message
102 if (error.status === 403) {
103 errorMessage = this.i18n('Cannot retrieve OAuth Client credentials: {{errorText}}.\n', { errorText: error.text })
104 errorMessage += this.i18n(
105 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
109 // We put a bigger timeout
110 // This is an important message
111 this.notificationsService.error(this.i18n('Error'), errorMessage, { timeOut: 7000 })
117 if (this.user === null) return null
119 return this.user.getRefreshToken()
122 getRequestHeaderValue () {
123 const accessToken = this.getAccessToken()
125 if (accessToken === null) return null
127 return `${this.getTokenType()} ${accessToken}`
131 if (this.user === null) return null
133 return this.user.getAccessToken()
137 if (this.user === null) return null
139 return this.user.getTokenType()
147 return !!this.getAccessToken()
150 login (username: string, password: string) {
153 client_id: this.clientId,
154 client_secret: this.clientSecret,
155 response_type: 'code',
156 grant_type: 'password',
162 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
163 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
165 map(res => Object.assign(res, { username })),
166 mergeMap(res => this.mergeUserInformation(res)),
167 map(res => this.handleLogin(res)),
168 catchError(res => this.restExtractor.handleError(res))
173 // TODO: make an HTTP request to revoke the tokens
178 this.setStatus(AuthStatus.LoggedOut)
180 this.hotkeysService.remove(this.hotkeys)
182 this.redirectUrl = null
185 refreshAccessToken () {
186 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
188 console.log('Refreshing token...')
190 const refreshToken = this.getRefreshToken()
193 const body = new HttpParams().set('refresh_token', refreshToken)
194 .set('client_id', this.clientId)
195 .set('client_secret', this.clientSecret)
196 .set('response_type', 'code')
197 .set('grant_type', 'refresh_token')
199 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
201 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
203 map(res => this.handleRefreshToken(res)),
204 tap(() => this.refreshingTokenObservable = null),
206 this.refreshingTokenObservable = null
209 console.log('Cannot refresh token -> logout...')
211 this.router.navigate([ '/login' ])
213 return observableThrowError({
214 error: this.i18n('You need to reconnect.')
220 return this.refreshingTokenObservable
223 refreshUserInformation () {
225 access_token: this.user.getAccessToken(),
227 token_type: this.user.getTokenType(),
228 username: this.user.username
231 this.mergeUserInformation(obj)
237 this.userInformationLoaded.next(true)
242 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
243 // User is not loaded yet, set manually auth header
244 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
246 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
247 .pipe(map(res => Object.assign(obj, res)))
250 private handleLogin (obj: UserLoginWithUserInformation) {
252 accessToken: obj.access_token,
253 tokenType: obj.token_type,
254 refreshToken: obj.refresh_token
257 this.user = new AuthUser(obj, hashTokens)
260 this.setStatus(AuthStatus.LoggedIn)
261 this.userInformationLoaded.next(true)
263 this.hotkeysService.add(this.hotkeys)
266 private handleRefreshToken (obj: UserRefreshToken) {
267 this.user.refreshTokens(obj.access_token, obj.refresh_token)
271 private setStatus (status: AuthStatus) {
272 this.loginChanged.next(status)