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'
18 interface UserLoginWithUsername extends UserLogin {
25 type UserLoginWithUserInformation = UserLoginWithUsername & User
28 export class AuthService {
29 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
30 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
31 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
32 private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
33 CLIENT_ID: 'client_id',
34 CLIENT_SECRET: 'client_secret'
37 loginChangedSource: Observable<AuthStatus>
38 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 notificationsService: NotificationsService,
49 private restExtractor: RestExtractor,
50 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()
60 loadClientCredentials () {
61 // Fetch the client_id/client_secret
62 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
63 .pipe(catchError(res => this.restExtractor.handleError(res)))
66 this.clientId = res.client_id
67 this.clientSecret = res.client_secret
69 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
70 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
72 console.log('Client credentials loaded.')
76 let errorMessage = error.message
78 if (error.status === 403) {
79 errorMessage = this.i18n('Cannot retrieve OAuth Client credentials: {{errorText}}.\n', { errorText: error.text })
80 errorMessage += this.i18n(
81 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
85 // We put a bigger timeout
86 // This is an important message
87 this.notificationsService.error(this.i18n('Error'), errorMessage, { timeOut: 7000 })
93 if (this.user === null) return null
95 return this.user.getRefreshToken()
98 getRequestHeaderValue () {
99 const accessToken = this.getAccessToken()
101 if (accessToken === null) return null
103 return `${this.getTokenType()} ${accessToken}`
107 if (this.user === null) return null
109 return this.user.getAccessToken()
113 if (this.user === null) return null
115 return this.user.getTokenType()
123 return !!this.getAccessToken()
126 login (username: string, password: string) {
129 client_id: this.clientId,
130 client_secret: this.clientSecret,
131 response_type: 'code',
132 grant_type: 'password',
138 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
139 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
141 map(res => Object.assign(res, { username })),
142 mergeMap(res => this.mergeUserInformation(res)),
143 map(res => this.handleLogin(res)),
144 catchError(res => this.restExtractor.handleError(res))
149 // TODO: make an HTTP request to revoke the tokens
154 this.setStatus(AuthStatus.LoggedOut)
157 refreshAccessToken () {
158 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
160 console.log('Refreshing token...')
162 const refreshToken = this.getRefreshToken()
165 const body = new HttpParams().set('refresh_token', refreshToken)
166 .set('client_id', this.clientId)
167 .set('client_secret', this.clientSecret)
168 .set('response_type', 'code')
169 .set('grant_type', 'refresh_token')
171 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
173 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
175 map(res => this.handleRefreshToken(res)),
176 tap(() => this.refreshingTokenObservable = null),
178 this.refreshingTokenObservable = null
181 console.log('Cannot refresh token -> logout...')
183 this.router.navigate([ '/login' ])
185 return observableThrowError({
186 error: this.i18n('You need to reconnect.')
192 return this.refreshingTokenObservable
195 refreshUserInformation () {
197 access_token: this.user.getAccessToken(),
199 token_type: this.user.getTokenType(),
200 username: this.user.username
203 this.mergeUserInformation(obj)
209 this.userInformationLoaded.next(true)
214 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
215 // User is not loaded yet, set manually auth header
216 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
218 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
219 .pipe(map(res => Object.assign(obj, res)))
222 private handleLogin (obj: UserLoginWithUserInformation) {
224 accessToken: obj.access_token,
225 tokenType: obj.token_type,
226 refreshToken: obj.refresh_token
229 this.user = new AuthUser(obj, hashTokens)
232 this.setStatus(AuthStatus.LoggedIn)
233 this.userInformationLoaded.next(true)
236 private handleRefreshToken (obj: UserRefreshToken) {
237 this.user.refreshTokens(obj.access_token, obj.refresh_token)
241 private setStatus (status: AuthStatus) {
242 this.loginChanged.next(status)