1 import { Observable, ReplaySubject, Subject, throwError as observableThrowError } from 'rxjs'
2 import { catchError, map, mergeMap, 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'
16 interface UserLoginWithUsername extends UserLogin {
23 type UserLoginWithUserInformation = UserLoginWithUsername & User
26 export class AuthService {
27 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
28 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
29 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
31 loginChangedSource: Observable<AuthStatus>
32 userInformationLoaded = new ReplaySubject<boolean>(1)
34 private clientId: string
35 private clientSecret: string
36 private loginChanged: Subject<AuthStatus>
37 private user: AuthUser = null
38 private refreshingTokenObservable: Observable<any>
41 private http: HttpClient,
42 private notificationsService: NotificationsService,
43 private restExtractor: RestExtractor,
44 private router: Router
46 this.loginChanged = new Subject<AuthStatus>()
47 this.loginChangedSource = this.loginChanged.asObservable()
49 // Return null if there is nothing to load
50 this.user = AuthUser.load()
53 loadClientCredentials () {
54 // Fetch the client_id/client_secret
55 // FIXME: save in local storage?
56 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
57 .pipe(catchError(res => this.restExtractor.handleError(res)))
60 this.clientId = res.client_id
61 this.clientSecret = res.client_secret
62 console.log('Client credentials loaded.')
66 let errorMessage = error.message
68 if (error.status === 403) {
69 errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
70 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), ' +
71 'in particular the "webserver" section.'
74 // We put a bigger timeout
75 // This is an important message
76 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
82 if (this.user === null) return null
84 return this.user.getRefreshToken()
87 getRequestHeaderValue () {
88 const accessToken = this.getAccessToken()
90 if (accessToken === null) return null
92 return `${this.getTokenType()} ${accessToken}`
96 if (this.user === null) return null
98 return this.user.getAccessToken()
102 if (this.user === null) return null
104 return this.user.getTokenType()
112 return !!this.getAccessToken()
115 login (username: string, password: string) {
118 client_id: this.clientId,
119 client_secret: this.clientSecret,
120 response_type: 'code',
121 grant_type: 'password',
127 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
128 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
130 map(res => Object.assign(res, { username })),
131 mergeMap(res => this.mergeUserInformation(res)),
132 map(res => this.handleLogin(res)),
133 catchError(res => this.restExtractor.handleError(res))
138 // TODO: make an HTTP request to revoke the tokens
143 this.setStatus(AuthStatus.LoggedOut)
146 refreshAccessToken () {
147 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
149 console.log('Refreshing token...')
151 const refreshToken = this.getRefreshToken()
154 const body = new HttpParams().set('refresh_token', refreshToken)
155 .set('client_id', this.clientId)
156 .set('client_secret', this.clientSecret)
157 .set('response_type', 'code')
158 .set('grant_type', 'refresh_token')
160 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
162 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
164 map(res => this.handleRefreshToken(res)),
165 tap(() => this.refreshingTokenObservable = null),
167 this.refreshingTokenObservable = null
170 console.log('Cannot refresh token -> logout...')
172 this.router.navigate([ '/login' ])
174 return observableThrowError({
175 error: 'You need to reconnect.'
180 return this.refreshingTokenObservable
183 refreshUserInformation () {
185 access_token: this.user.getAccessToken(),
187 token_type: this.user.getTokenType(),
188 username: this.user.username
191 this.mergeUserInformation(obj)
197 this.userInformationLoaded.next(true)
202 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
203 // User is not loaded yet, set manually auth header
204 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
206 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
207 .pipe(map(res => Object.assign(obj, res)))
210 private handleLogin (obj: UserLoginWithUserInformation) {
212 accessToken: obj.access_token,
213 tokenType: obj.token_type,
214 refreshToken: obj.refresh_token
217 this.user = new AuthUser(obj, hashTokens)
220 this.setStatus(AuthStatus.LoggedIn)
221 this.userInformationLoaded.next(true)
224 private handleRefreshToken (obj: UserRefreshToken) {
225 this.user.refreshTokens(obj.access_token, obj.refresh_token)
229 private setStatus (status: AuthStatus) {
230 this.loginChanged.next(status)