1 import { Injectable } from '@angular/core'
2 import { Headers, Http, Response, URLSearchParams } from '@angular/http'
3 import { Router } from '@angular/router'
4 import { Observable } from 'rxjs/Observable'
5 import { Subject } from 'rxjs/Subject'
6 import 'rxjs/add/operator/map'
7 import 'rxjs/add/operator/mergeMap'
8 import 'rxjs/add/observable/throw'
10 import { NotificationsService } from 'angular2-notifications'
12 import { AuthStatus } from './auth-status.model'
13 import { AuthUser } from './auth-user.model'
14 // Do not use the barrel (dependency loop)
15 import { RestExtractor } from '../../shared/rest'
18 export class AuthService {
19 private static BASE_CLIENT_URL = API_URL + '/api/v1/clients/local'
20 private static BASE_TOKEN_URL = API_URL + '/api/v1/users/token'
21 private static BASE_USER_INFORMATIONS_URL = API_URL + '/api/v1/users/me'
23 loginChangedSource: Observable<AuthStatus>
25 private clientId: string
26 private clientSecret: string
27 private loginChanged: Subject<AuthStatus>
28 private user: AuthUser = null
32 private notificationsService: NotificationsService,
33 private restExtractor: RestExtractor,
34 private router: Router
36 this.loginChanged = new Subject<AuthStatus>()
37 this.loginChangedSource = this.loginChanged.asObservable()
39 // Fetch the client_id/client_secret
40 // FIXME: save in local storage?
41 this.http.get(AuthService.BASE_CLIENT_URL)
42 .map(this.restExtractor.extractDataGet)
43 .catch((res) => this.restExtractor.handleError(res))
46 this.clientId = result.client_id
47 this.clientSecret = result.client_secret
48 console.log('Client credentials loaded.')
52 let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
53 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
55 // We put a bigger timeout
56 // This is an important message
57 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
61 // Return null if there is nothing to load
62 this.user = AuthUser.load()
66 if (this.user === null) return null
68 return this.user.getRefreshToken()
71 getRequestHeaderValue () {
72 return `${this.getTokenType()} ${this.getAccessToken()}`
76 if (this.user === null) return null
78 return this.user.getAccessToken()
82 if (this.user === null) return null
84 return this.user.getTokenType()
92 if (this.user === null) return false
94 return this.user.isAdmin()
98 if (this.getAccessToken()) {
105 login (username: string, password: string) {
106 let body = new URLSearchParams()
107 body.set('client_id', this.clientId)
108 body.set('client_secret', this.clientSecret)
109 body.set('response_type', 'code')
110 body.set('grant_type', 'password')
111 body.set('scope', 'upload')
112 body.set('username', username)
113 body.set('password', password)
115 let headers = new Headers()
116 headers.append('Content-Type', 'application/x-www-form-urlencoded')
122 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
123 .map(this.restExtractor.extractDataGet)
125 res.username = username
128 .flatMap(res => this.mergeUserInformations(res))
129 .map(res => this.handleLogin(res))
130 .catch((res) => this.restExtractor.handleError(res))
134 // TODO: make an HTTP request to revoke the tokens
139 this.setStatus(AuthStatus.LoggedOut)
142 refreshAccessToken () {
143 console.log('Refreshing token...')
145 const refreshToken = this.getRefreshToken()
147 let body = new URLSearchParams()
148 body.set('refresh_token', refreshToken)
149 body.set('client_id', this.clientId)
150 body.set('client_secret', this.clientSecret)
151 body.set('response_type', 'code')
152 body.set('grant_type', 'refresh_token')
154 let headers = new Headers()
155 headers.append('Content-Type', 'application/x-www-form-urlencoded')
161 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
162 .map(this.restExtractor.extractDataGet)
163 .map(res => this.handleRefreshToken(res))
164 .catch((res: Response) => {
165 // The refresh token is invalid?
166 if (res.status === 400 && res.json() && res.json().error === 'invalid_grant') {
167 console.error('Cannot refresh token -> logout...')
169 this.router.navigate(['/login'])
171 return Observable.throw({
173 text: () => 'You need to reconnect.'
177 return this.restExtractor.handleError(res)
181 refreshUserInformations () {
183 access_token: this.user.getAccessToken()
186 this.mergeUserInformations (obj)
189 this.user.displayNSFW = res.displayNSFW
190 this.user.role = res.role
197 private mergeUserInformations (obj: { access_token: string }) {
198 // Do not call authHttp here to avoid circular dependencies headaches
200 const headers = new Headers()
201 headers.set('Authorization', `Bearer ${obj.access_token}`)
203 return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
204 .map(res => res.json())
206 const newProperties = {
209 displayNSFW: res.displayNSFW
212 return Object.assign(obj, newProperties)
217 private handleLogin (obj: any) {
219 const username = obj.username
220 const role = obj.role
221 const email = obj.email
222 const displayNSFW = obj.displayNSFW
224 accessToken: obj.access_token,
225 tokenType: obj.token_type,
226 refreshToken: obj.refresh_token
229 this.user = new AuthUser({ id, username, role, displayNSFW, email }, hashTokens)
232 this.setStatus(AuthStatus.LoggedIn)
235 private handleRefreshToken (obj: any) {
236 this.user.refreshTokens(obj.access_token, obj.refresh_token)
240 private setStatus (status: AuthStatus) {
241 this.loginChanged.next(status)