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
42 private refreshingTokenObservable: Observable<any>
45 private http: HttpClient,
46 private notificationsService: NotificationsService,
47 private restExtractor: RestExtractor,
48 private router: Router
50 this.loginChanged = new Subject<AuthStatus>()
51 this.loginChangedSource = this.loginChanged.asObservable()
53 // Return null if there is nothing to load
54 this.user = AuthUser.load()
57 loadClientCredentials () {
58 // Fetch the client_id/client_secret
59 // FIXME: save in local storage?
60 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
61 .catch(res => this.restExtractor.handleError(res))
64 this.clientId = res.client_id
65 this.clientSecret = res.client_secret
66 console.log('Client credentials loaded.')
70 let errorMessage = error.message
72 if (error.status === 403) {
73 errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
74 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), ' +
75 'in particular the "webserver" section.'
78 // We put a bigger timeout
79 // This is an important message
80 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
86 if (this.user === null) return null
88 return this.user.getRefreshToken()
91 getRequestHeaderValue () {
92 const accessToken = this.getAccessToken()
94 if (accessToken === null) return null
96 return `${this.getTokenType()} ${accessToken}`
100 if (this.user === null) return null
102 return this.user.getAccessToken()
106 if (this.user === null) return null
108 return this.user.getTokenType()
116 return !!this.getAccessToken()
119 login (username: string, password: string) {
121 const body = new URLSearchParams()
122 body.set('client_id', this.clientId)
123 body.set('client_secret', this.clientSecret)
124 body.set('response_type', 'code')
125 body.set('grant_type', 'password')
126 body.set('scope', 'upload')
127 body.set('username', username)
128 body.set('password', password)
130 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
131 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body.toString(), { headers })
132 .map(res => Object.assign(res, { username }))
133 .flatMap(res => this.mergeUserInformation(res))
134 .map(res => this.handleLogin(res))
135 .catch(res => this.restExtractor.handleError(res))
139 // TODO: make an HTTP request to revoke the tokens
144 this.setStatus(AuthStatus.LoggedOut)
147 refreshAccessToken () {
148 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
150 console.log('Refreshing token...')
152 const refreshToken = this.getRefreshToken()
155 const body = new HttpParams().set('refresh_token', refreshToken)
156 .set('client_id', this.clientId)
157 .set('client_secret', this.clientSecret)
158 .set('response_type', 'code')
159 .set('grant_type', 'refresh_token')
161 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
163 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
164 .map(res => this.handleRefreshToken(res))
165 .do(() => this.refreshingTokenObservable = null)
167 this.refreshingTokenObservable = null
170 console.log('Cannot refresh token -> logout...')
172 this.router.navigate([ '/login' ])
174 return Observable.throw({
175 error: 'You need to reconnect.'
179 return this.refreshingTokenObservable
182 refreshUserInformation () {
184 access_token: this.user.getAccessToken(),
186 token_type: this.user.getTokenType(),
187 username: this.user.username
190 this.mergeUserInformation(obj)
196 this.userInformationLoaded.next(true)
201 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
202 // User is not loaded yet, set manually auth header
203 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
205 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
206 .map(res => Object.assign(obj, res))
209 private handleLogin (obj: UserLoginWithUserInformation) {
211 accessToken: obj.access_token,
212 tokenType: obj.token_type,
213 refreshToken: obj.refresh_token
216 this.user = new AuthUser(obj, hashTokens)
219 this.setStatus(AuthStatus.LoggedIn)
220 this.userInformationLoaded.next(true)
223 private handleRefreshToken (obj: UserRefreshToken) {
224 this.user.refreshTokens(obj.access_token, obj.refresh_token)
228 private setStatus (status: AuthStatus) {
229 this.loginChanged.next(status)