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 { Notifier } from '@app/core/notification/notifier.service'
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/rest-extractor.service'
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 { Hotkey, HotkeysService } 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)
42 private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
43 private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
44 private loginChanged: Subject<AuthStatus>
45 private user: AuthUser = null
46 private refreshingTokenObservable: Observable<any>
49 private http: HttpClient,
50 private notifier: Notifier,
51 private hotkeysService: HotkeysService,
52 private restExtractor: RestExtractor,
53 private router: Router,
56 this.loginChanged = new Subject<AuthStatus>()
57 this.loginChangedSource = this.loginChanged.asObservable()
59 // Return null if there is nothing to load
60 this.user = AuthUser.load()
64 new Hotkey('m s', (event: KeyboardEvent): boolean => {
65 this.router.navigate([ '/videos/subscriptions' ])
67 }, undefined, this.i18n('Go to my subscriptions')),
68 new Hotkey('m v', (event: KeyboardEvent): boolean => {
69 this.router.navigate([ '/my-account/videos' ])
71 }, undefined, this.i18n('Go to my videos')),
72 new Hotkey('m i', (event: KeyboardEvent): boolean => {
73 this.router.navigate([ '/my-account/video-imports' ])
75 }, undefined, this.i18n('Go to my imports')),
76 new Hotkey('m c', (event: KeyboardEvent): boolean => {
77 this.router.navigate([ '/my-account/video-channels' ])
79 }, undefined, this.i18n('Go to my channels'))
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 console.log('Client credentials loaded.')
99 let errorMessage = error.message
101 if (error.status === 403) {
102 errorMessage = this.i18n('Cannot retrieve OAuth Client credentials: {{errorText}}.\n', { errorText: error.text })
103 errorMessage += this.i18n(
104 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
108 // We put a bigger timeout: this is an important message
109 this.notifier.error(errorMessage, this.i18n('Error'), 7000)
115 if (this.user === null) return null
117 return this.user.getRefreshToken()
120 getRequestHeaderValue () {
121 const accessToken = this.getAccessToken()
123 if (accessToken === null) return null
125 return `${this.getTokenType()} ${accessToken}`
129 if (this.user === null) return null
131 return this.user.getAccessToken()
135 if (this.user === null) return null
137 return this.user.getTokenType()
145 return !!this.getAccessToken()
148 login (username: string, password: string) {
151 client_id: this.clientId,
152 client_secret: this.clientSecret,
153 response_type: 'code',
154 grant_type: 'password',
160 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
161 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
163 map(res => Object.assign(res, { username })),
164 mergeMap(res => this.mergeUserInformation(res)),
165 map(res => this.handleLogin(res)),
166 catchError(res => this.restExtractor.handleError(res))
171 // TODO: make an HTTP request to revoke the tokens
176 this.setStatus(AuthStatus.LoggedOut)
178 this.hotkeysService.remove(this.hotkeys)
181 refreshAccessToken () {
182 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
184 console.log('Refreshing token...')
186 const refreshToken = this.getRefreshToken()
189 const body = new HttpParams().set('refresh_token', refreshToken)
190 .set('client_id', this.clientId)
191 .set('client_secret', this.clientSecret)
192 .set('response_type', 'code')
193 .set('grant_type', 'refresh_token')
195 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
197 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
199 map(res => this.handleRefreshToken(res)),
200 tap(() => this.refreshingTokenObservable = null),
202 this.refreshingTokenObservable = null
205 console.log('Cannot refresh token -> logout...')
207 this.router.navigate([ '/login' ])
209 return observableThrowError({
210 error: this.i18n('You need to reconnect.')
216 return this.refreshingTokenObservable
219 refreshUserInformation () {
220 const obj: UserLoginWithUsername = {
221 access_token: this.user.getAccessToken(),
223 token_type: this.user.getTokenType(),
224 username: this.user.username
227 this.mergeUserInformation(obj)
233 this.userInformationLoaded.next(true)
238 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
239 // User is not loaded yet, set manually auth header
240 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
242 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
243 .pipe(map(res => Object.assign(obj, res)))
246 private handleLogin (obj: UserLoginWithUserInformation) {
248 accessToken: obj.access_token,
249 tokenType: obj.token_type,
250 refreshToken: obj.refresh_token
253 this.user = new AuthUser(obj, hashTokens)
256 this.setStatus(AuthStatus.LoggedIn)
257 this.userInformationLoaded.next(true)
259 this.hotkeysService.add(this.hotkeys)
262 private handleRefreshToken (obj: UserRefreshToken) {
263 this.user.refreshTokens(obj.access_token, obj.refresh_token)
267 private setStatus (status: AuthStatus) {
268 this.loginChanged.next(status)