1 import { Injectable } from '@angular/core'
2 import { Router } from '@angular/router'
3 import { Observable } from 'rxjs/Observable'
4 import { Subject } from 'rxjs/Subject'
5 import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
6 import { ReplaySubject } from 'rxjs/ReplaySubject'
7 import 'rxjs/add/operator/do'
8 import 'rxjs/add/operator/map'
9 import 'rxjs/add/operator/mergeMap'
10 import 'rxjs/add/observable/throw'
12 import { NotificationsService } from 'angular2-notifications'
14 import { AuthStatus } from './auth-status.model'
15 import { AuthUser } from './auth-user.model'
21 User as UserServerModel
22 } from '../../../../../shared'
23 // Do not use the barrel (dependency loop)
24 import { RestExtractor } from '../../shared/rest'
25 import { UserLogin } from '../../../../../shared/models/users/user-login.model'
26 import { UserConstructorHash } from '../../shared/users/user.model'
28 interface UserLoginWithUsername extends UserLogin {
35 interface UserLoginWithUserInformation extends UserLogin {
49 videoChannels: VideoChannel[]
53 export class AuthService {
54 private static BASE_CLIENT_URL = API_URL + '/api/v1/oauth-clients/local'
55 private static BASE_TOKEN_URL = API_URL + '/api/v1/users/token'
56 private static BASE_USER_INFORMATION_URL = API_URL + '/api/v1/users/me'
58 loginChangedSource: Observable<AuthStatus>
59 userInformationLoaded = new ReplaySubject<boolean>(1)
61 private clientId: string
62 private clientSecret: string
63 private loginChanged: Subject<AuthStatus>
64 private user: AuthUser = null
67 private http: HttpClient,
68 private notificationsService: NotificationsService,
69 private restExtractor: RestExtractor,
70 private router: Router
72 this.loginChanged = new Subject<AuthStatus>()
73 this.loginChangedSource = this.loginChanged.asObservable()
75 // Return null if there is nothing to load
76 this.user = AuthUser.load()
79 loadClientCredentials () {
80 // Fetch the client_id/client_secret
81 // FIXME: save in local storage?
82 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
83 .catch(res => this.restExtractor.handleError(res))
86 this.clientId = res.client_id
87 this.clientSecret = res.client_secret
88 console.log('Client credentials loaded.')
92 let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
93 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
95 // We put a bigger timeout
96 // This is an important message
97 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
103 if (this.user === null) return null
105 return this.user.getRefreshToken()
108 getRequestHeaderValue () {
109 const accessToken = this.getAccessToken()
111 if (accessToken === null) return null
113 return `${this.getTokenType()} ${accessToken}`
117 if (this.user === null) return null
119 return this.user.getAccessToken()
123 if (this.user === null) return null
125 return this.user.getTokenType()
133 return !!this.getAccessToken()
136 login (username: string, password: string) {
138 const body = new HttpParams().set('client_id', this.clientId)
139 .set('client_secret', this.clientSecret)
140 .set('response_type', 'code')
141 .set('grant_type', 'password')
142 .set('scope', 'upload')
143 .set('username', username)
144 .set('password', password)
146 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
148 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers })
149 .map(res => Object.assign(res, { username }))
150 .flatMap(res => this.mergeUserInformation(res))
151 .map(res => this.handleLogin(res))
152 .catch(res => this.restExtractor.handleError(res))
156 // TODO: make an HTTP request to revoke the tokens
161 this.setStatus(AuthStatus.LoggedOut)
164 refreshAccessToken () {
165 console.log('Refreshing token...')
167 const refreshToken = this.getRefreshToken()
170 const body = new HttpParams().set('refresh_token', refreshToken)
171 .set('client_id', this.clientId)
172 .set('client_secret', this.clientSecret)
173 .set('response_type', 'code')
174 .set('grant_type', 'refresh_token')
176 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
178 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
179 .map(res => this.handleRefreshToken(res))
181 // The refresh token is invalid?
182 if (res.status === 400 && res.error.error === 'invalid_grant') {
183 console.error('Cannot refresh token -> logout...')
185 this.router.navigate(['/login'])
187 return Observable.throw({
188 error: 'You need to reconnect.'
192 return this.restExtractor.handleError(res)
196 refreshUserInformation () {
198 access_token: this.user.getAccessToken(),
200 token_type: this.user.getTokenType(),
201 username: this.user.username
204 this.mergeUserInformation(obj)
205 .do(() => this.userInformationLoaded.next(true))
208 this.user.displayNSFW = res.displayNSFW
209 this.user.role = res.role
210 this.user.videoChannels = res.videoChannels
211 this.user.account = res.account
218 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
219 // User is not loaded yet, set manually auth header
220 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
222 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
224 const newProperties = {
227 displayNSFW: res.displayNSFW,
229 videoQuota: res.videoQuota,
230 account: res.account,
231 videoChannels: res.videoChannels
234 return Object.assign(obj, newProperties)
239 private handleLogin (obj: UserLoginWithUserInformation) {
240 const hashUser: UserConstructorHash = {
242 username: obj.username,
245 displayNSFW: obj.displayNSFW,
246 videoQuota: obj.videoQuota,
247 videoChannels: obj.videoChannels,
251 accessToken: obj.access_token,
252 tokenType: obj.token_type,
253 refreshToken: obj.refresh_token
256 this.user = new AuthUser(hashUser, hashTokens)
259 this.setStatus(AuthStatus.LoggedIn)
262 private handleRefreshToken (obj: UserRefreshToken) {
263 this.user.refreshTokens(obj.access_token, obj.refresh_token)
267 private setStatus (status: AuthStatus) {
268 this.loginChanged.next(status)