1 import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
2 import { Injectable } from '@angular/core'
3 import { Router } from '@angular/router'
4 import { NotificationsService } from 'angular2-notifications'
5 import 'rxjs/add/observable/throw'
6 import 'rxjs/add/operator/do'
7 import 'rxjs/add/operator/map'
8 import 'rxjs/add/operator/mergeMap'
9 import { Observable } from 'rxjs/Observable'
10 import { ReplaySubject } from 'rxjs/ReplaySubject'
11 import { Subject } from 'rxjs/Subject'
12 import { OAuthClientLocal, User as UserServerModel, UserRefreshToken } from '../../../../../shared'
13 import { User } from '../../../../../shared/models/users'
14 import { UserLogin } from '../../../../../shared/models/users/user-login.model'
15 import { environment } from '../../../environments/environment'
16 import { RestExtractor } from '../../shared/rest'
17 import { AuthStatus } from './auth-status.model'
18 import { AuthUser } from './auth-user.model'
20 interface UserLoginWithUsername extends UserLogin {
27 type UserLoginWithUserInformation = UserLoginWithUsername & User
30 export class AuthService {
31 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
32 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
33 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
35 loginChangedSource: Observable<AuthStatus>
36 userInformationLoaded = new ReplaySubject<boolean>(1)
38 private clientId: string
39 private clientSecret: string
40 private loginChanged: Subject<AuthStatus>
41 private user: AuthUser = null
44 private http: HttpClient,
45 private notificationsService: NotificationsService,
46 private restExtractor: RestExtractor,
47 private router: Router
49 this.loginChanged = new Subject<AuthStatus>()
50 this.loginChangedSource = this.loginChanged.asObservable()
52 // Return null if there is nothing to load
53 this.user = AuthUser.load()
56 loadClientCredentials () {
57 // Fetch the client_id/client_secret
58 // FIXME: save in local storage?
59 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
60 .catch(res => this.restExtractor.handleError(res))
63 this.clientId = res.client_id
64 this.clientSecret = res.client_secret
65 console.log('Client credentials loaded.')
69 let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
70 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
72 // We put a bigger timeout
73 // This is an important message
74 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
80 if (this.user === null) return null
82 return this.user.getRefreshToken()
85 getRequestHeaderValue () {
86 const accessToken = this.getAccessToken()
88 if (accessToken === null) return null
90 return `${this.getTokenType()} ${accessToken}`
94 if (this.user === null) return null
96 return this.user.getAccessToken()
100 if (this.user === null) return null
102 return this.user.getTokenType()
110 return !!this.getAccessToken()
113 login (username: string, password: string) {
115 const body = new HttpParams().set('client_id', this.clientId)
116 .set('client_secret', this.clientSecret)
117 .set('response_type', 'code')
118 .set('grant_type', 'password')
119 .set('scope', 'upload')
120 .set('username', username)
121 .set('password', password)
123 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
125 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers })
126 .map(res => Object.assign(res, { username }))
127 .flatMap(res => this.mergeUserInformation(res))
128 .map(res => this.handleLogin(res))
129 .catch(res => this.restExtractor.handleError(res))
133 // TODO: make an HTTP request to revoke the tokens
138 this.setStatus(AuthStatus.LoggedOut)
141 refreshAccessToken () {
142 console.log('Refreshing token...')
144 const refreshToken = this.getRefreshToken()
147 const body = new HttpParams().set('refresh_token', refreshToken)
148 .set('client_id', this.clientId)
149 .set('client_secret', this.clientSecret)
150 .set('response_type', 'code')
151 .set('grant_type', 'refresh_token')
153 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
155 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
156 .map(res => this.handleRefreshToken(res))
159 console.log('Cannot refresh token -> logout...')
161 this.router.navigate(['/login'])
163 return Observable.throw({
164 error: 'You need to reconnect.'
169 refreshUserInformation () {
171 access_token: this.user.getAccessToken(),
173 token_type: this.user.getTokenType(),
174 username: this.user.username
177 this.mergeUserInformation(obj)
183 this.userInformationLoaded.next(true)
188 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
189 // User is not loaded yet, set manually auth header
190 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
192 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
193 .map(res => Object.assign(obj, res))
196 private handleLogin (obj: UserLoginWithUserInformation) {
198 accessToken: obj.access_token,
199 tokenType: obj.token_type,
200 refreshToken: obj.refresh_token
203 this.user = new AuthUser(obj, hashTokens)
206 this.setStatus(AuthStatus.LoggedIn)
207 this.userInformationLoaded.next(true)
210 private handleRefreshToken (obj: UserRefreshToken) {
211 this.user.refreshTokens(obj.access_token, obj.refresh_token)
215 private setStatus (status: AuthStatus) {
216 this.loginChanged.next(status)