1 import { Observable, ReplaySubject, Subject, throwError as observableThrowError } from 'rxjs'
2 import { catchError, map, mergeMap, tap, share } 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'
17 interface UserLoginWithUsername extends UserLogin {
24 type UserLoginWithUserInformation = UserLoginWithUsername & User
27 export class AuthService {
28 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
29 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/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)
39 private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
40 private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
41 private loginChanged: Subject<AuthStatus>
42 private user: AuthUser = null
43 private refreshingTokenObservable: Observable<any>
46 private http: HttpClient,
47 private notificationsService: NotificationsService,
48 private restExtractor: RestExtractor,
49 private router: Router
51 this.loginChanged = new Subject<AuthStatus>()
52 this.loginChangedSource = this.loginChanged.asObservable()
54 // Return null if there is nothing to load
55 this.user = AuthUser.load()
58 loadClientCredentials () {
59 // Fetch the client_id/client_secret
60 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
61 .pipe(catchError(res => this.restExtractor.handleError(res)))
64 this.clientId = res.client_id
65 this.clientSecret = res.client_secret
67 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
68 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
70 console.log('Client credentials loaded.')
74 let errorMessage = error.message
76 if (error.status === 403) {
77 errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
78 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), ' +
79 'in particular the "webserver" section.'
82 // We put a bigger timeout
83 // This is an important message
84 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
90 if (this.user === null) return null
92 return this.user.getRefreshToken()
95 getRequestHeaderValue () {
96 const accessToken = this.getAccessToken()
98 if (accessToken === null) return null
100 return `${this.getTokenType()} ${accessToken}`
104 if (this.user === null) return null
106 return this.user.getAccessToken()
110 if (this.user === null) return null
112 return this.user.getTokenType()
120 return !!this.getAccessToken()
123 login (username: string, password: string) {
126 client_id: this.clientId,
127 client_secret: this.clientSecret,
128 response_type: 'code',
129 grant_type: 'password',
135 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
136 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
138 map(res => Object.assign(res, { username })),
139 mergeMap(res => this.mergeUserInformation(res)),
140 map(res => this.handleLogin(res)),
141 catchError(res => this.restExtractor.handleError(res))
146 // TODO: make an HTTP request to revoke the tokens
151 this.setStatus(AuthStatus.LoggedOut)
154 refreshAccessToken () {
155 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
157 console.log('Refreshing token...')
159 const refreshToken = this.getRefreshToken()
162 const body = new HttpParams().set('refresh_token', refreshToken)
163 .set('client_id', this.clientId)
164 .set('client_secret', this.clientSecret)
165 .set('response_type', 'code')
166 .set('grant_type', 'refresh_token')
168 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
170 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
172 map(res => this.handleRefreshToken(res)),
173 tap(() => this.refreshingTokenObservable = null),
175 this.refreshingTokenObservable = null
178 console.log('Cannot refresh token -> logout...')
180 this.router.navigate([ '/login' ])
182 return observableThrowError({
183 error: 'You need to reconnect.'
189 return this.refreshingTokenObservable
192 refreshUserInformation () {
194 access_token: this.user.getAccessToken(),
196 token_type: this.user.getTokenType(),
197 username: this.user.username
200 this.mergeUserInformation(obj)
206 this.userInformationLoaded.next(true)
211 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
212 // User is not loaded yet, set manually auth header
213 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
215 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
216 .pipe(map(res => Object.assign(obj, res)))
219 private handleLogin (obj: UserLoginWithUserInformation) {
221 accessToken: obj.access_token,
222 tokenType: obj.token_type,
223 refreshToken: obj.refresh_token
226 this.user = new AuthUser(obj, hashTokens)
229 this.setStatus(AuthStatus.LoggedIn)
230 this.userInformationLoaded.next(true)
233 private handleRefreshToken (obj: UserRefreshToken) {
234 this.user.refreshTokens(obj.access_token, obj.refresh_token)
238 private setStatus (status: AuthStatus) {
239 this.loginChanged.next(status)