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 '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'
19 User as UserServerModel
20 } from '../../../../../shared'
21 // Do not use the barrel (dependency loop)
22 import { RestExtractor } from '../../shared/rest'
23 import { UserLogin } from '../../../../../shared/models/users/user-login.model'
24 import { User, UserConstructorHash } from '../../shared/users/user.model'
26 interface UserLoginWithUsername extends UserLogin {
33 interface UserLoginWithUserInformation extends UserLogin {
47 videoChannels: VideoChannel[]
51 export class AuthService {
52 private static BASE_CLIENT_URL = API_URL + '/api/v1/oauth-clients/local'
53 private static BASE_TOKEN_URL = API_URL + '/api/v1/users/token'
54 private static BASE_USER_INFORMATION_URL = API_URL + '/api/v1/users/me'
56 loginChangedSource: Observable<AuthStatus>
58 private clientId: string
59 private clientSecret: string
60 private loginChanged: Subject<AuthStatus>
61 private user: AuthUser = null
64 private http: HttpClient,
65 private notificationsService: NotificationsService,
66 private restExtractor: RestExtractor,
67 private router: Router
69 this.loginChanged = new Subject<AuthStatus>()
70 this.loginChangedSource = this.loginChanged.asObservable()
72 // Return null if there is nothing to load
73 this.user = AuthUser.load()
76 loadClientCredentials () {
77 // Fetch the client_id/client_secret
78 // FIXME: save in local storage?
79 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
80 .catch(res => this.restExtractor.handleError(res))
83 this.clientId = res.client_id
84 this.clientSecret = res.client_secret
85 console.log('Client credentials loaded.')
89 let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
90 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
92 // We put a bigger timeout
93 // This is an important message
94 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
100 if (this.user === null) return null
102 return this.user.getRefreshToken()
105 getRequestHeaderValue () {
106 const accessToken = this.getAccessToken()
108 if (accessToken === null) return null
110 return `${this.getTokenType()} ${accessToken}`
114 if (this.user === null) return null
116 return this.user.getAccessToken()
120 if (this.user === null) return null
122 return this.user.getTokenType()
130 if (this.user === null) return false
132 return this.user.isAdmin()
136 return !!this.getAccessToken()
139 login (username: string, password: string) {
141 const body = new HttpParams().set('client_id', this.clientId)
142 .set('client_secret', this.clientSecret)
143 .set('response_type', 'code')
144 .set('grant_type', 'password')
145 .set('scope', 'upload')
146 .set('username', username)
147 .set('password', password)
149 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
151 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers })
152 .map(res => Object.assign(res, { username }))
153 .flatMap(res => this.mergeUserInformation(res))
154 .map(res => this.handleLogin(res))
155 .catch(res => this.restExtractor.handleError(res))
159 // TODO: make an HTTP request to revoke the tokens
164 this.setStatus(AuthStatus.LoggedOut)
167 refreshAccessToken () {
168 console.log('Refreshing token...')
170 const refreshToken = this.getRefreshToken()
173 const body = new HttpParams().set('refresh_token', refreshToken)
174 .set('client_id', this.clientId)
175 .set('client_secret', this.clientSecret)
176 .set('response_type', 'code')
177 .set('grant_type', 'refresh_token')
179 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
181 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
182 .map(res => this.handleRefreshToken(res))
184 // The refresh token is invalid?
185 if (res.status === 400 && res.error.error === 'invalid_grant') {
186 console.error('Cannot refresh token -> logout...')
188 this.router.navigate(['/login'])
190 return Observable.throw({
191 error: 'You need to reconnect.'
195 return this.restExtractor.handleError(res)
199 refreshUserInformation () {
201 access_token: this.user.getAccessToken(),
203 token_type: this.user.getTokenType(),
204 username: this.user.username
207 this.mergeUserInformation(obj)
210 this.user.displayNSFW = res.displayNSFW
211 this.user.role = res.role
212 this.user.videoChannels = res.videoChannels
213 this.user.author = res.author
220 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
221 // User is not loaded yet, set manually auth header
222 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
224 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
226 const newProperties = {
229 displayNSFW: res.displayNSFW,
231 videoQuota: res.videoQuota,
233 videoChannels: res.videoChannels
236 return Object.assign(obj, newProperties)
241 private handleLogin (obj: UserLoginWithUserInformation) {
242 const hashUser: UserConstructorHash = {
244 username: obj.username,
247 displayNSFW: obj.displayNSFW,
248 videoQuota: obj.videoQuota,
249 videoChannels: obj.videoChannels,
253 accessToken: obj.access_token,
254 tokenType: obj.token_type,
255 refreshToken: obj.refresh_token
258 this.user = new AuthUser(hashUser, hashTokens)
261 this.setStatus(AuthStatus.LoggedIn)
264 private handleRefreshToken (obj: UserRefreshToken) {
265 this.user.refreshTokens(obj.access_token, obj.refresh_token)
269 private setStatus (status: AuthStatus) {
270 this.loginChanged.next(status)