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, UserRole, VideoChannel } from '../../../../../shared'
13 import { Account } from '../../../../../shared/models/accounts'
14 import { UserLogin } from '../../../../../shared/models/users/user-login.model'
15 import { environment } from '../../../environments/environment'
16 import { RestExtractor } from '../../shared/rest'
17 import { UserConstructorHash } from '../../shared/users/user.model'
18 import { AuthStatus } from './auth-status.model'
19 import { AuthUser } from './auth-user.model'
21 interface UserLoginWithUsername extends UserLogin {
28 interface UserLoginWithUserInformation extends UserLogin {
39 videoChannels: VideoChannel[]
43 export class AuthService {
44 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
45 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
46 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
48 loginChangedSource: Observable<AuthStatus>
49 userInformationLoaded = new ReplaySubject<boolean>(1)
51 private clientId: string
52 private clientSecret: string
53 private loginChanged: Subject<AuthStatus>
54 private user: AuthUser = null
57 private http: HttpClient,
58 private notificationsService: NotificationsService,
59 private restExtractor: RestExtractor,
60 private router: Router
62 this.loginChanged = new Subject<AuthStatus>()
63 this.loginChangedSource = this.loginChanged.asObservable()
65 // Return null if there is nothing to load
66 this.user = AuthUser.load()
69 loadClientCredentials () {
70 // Fetch the client_id/client_secret
71 // FIXME: save in local storage?
72 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
73 .catch(res => this.restExtractor.handleError(res))
76 this.clientId = res.client_id
77 this.clientSecret = res.client_secret
78 console.log('Client credentials loaded.')
82 let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
83 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
85 // We put a bigger timeout
86 // This is an important message
87 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
93 if (this.user === null) return null
95 return this.user.getRefreshToken()
98 getRequestHeaderValue () {
99 const accessToken = this.getAccessToken()
101 if (accessToken === null) return null
103 return `${this.getTokenType()} ${accessToken}`
107 if (this.user === null) return null
109 return this.user.getAccessToken()
113 if (this.user === null) return null
115 return this.user.getTokenType()
123 return !!this.getAccessToken()
126 login (username: string, password: string) {
128 const body = new HttpParams().set('client_id', this.clientId)
129 .set('client_secret', this.clientSecret)
130 .set('response_type', 'code')
131 .set('grant_type', 'password')
132 .set('scope', 'upload')
133 .set('username', username)
134 .set('password', password)
136 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
138 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers })
139 .map(res => Object.assign(res, { username }))
140 .flatMap(res => this.mergeUserInformation(res))
141 .map(res => this.handleLogin(res))
142 .catch(res => this.restExtractor.handleError(res))
146 // TODO: make an HTTP request to revoke the tokens
151 this.setStatus(AuthStatus.LoggedOut)
154 refreshAccessToken () {
155 console.log('Refreshing token...')
157 const refreshToken = this.getRefreshToken()
160 const body = new HttpParams().set('refresh_token', refreshToken)
161 .set('client_id', this.clientId)
162 .set('client_secret', this.clientSecret)
163 .set('response_type', 'code')
164 .set('grant_type', 'refresh_token')
166 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
168 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
169 .map(res => this.handleRefreshToken(res))
172 console.log('Cannot refresh token -> logout...')
174 this.router.navigate(['/login'])
176 return Observable.throw({
177 error: 'You need to reconnect.'
182 refreshUserInformation () {
184 access_token: this.user.getAccessToken(),
186 token_type: this.user.getTokenType(),
187 username: this.user.username
190 this.mergeUserInformation(obj)
193 this.user.displayNSFW = res.displayNSFW
194 this.user.role = res.role
195 this.user.videoChannels = res.videoChannels
196 this.user.account = res.account
200 this.userInformationLoaded.next(true)
205 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
206 // User is not loaded yet, set manually auth header
207 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
209 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
211 const newProperties = {
214 displayNSFW: res.displayNSFW,
216 videoQuota: res.videoQuota,
217 account: res.account,
218 videoChannels: res.videoChannels
221 return Object.assign(obj, newProperties)
226 private handleLogin (obj: UserLoginWithUserInformation) {
227 const hashUser: UserConstructorHash = {
229 username: obj.username,
232 displayNSFW: obj.displayNSFW,
233 videoQuota: obj.videoQuota,
234 videoChannels: obj.videoChannels,
238 accessToken: obj.access_token,
239 tokenType: obj.token_type,
240 refreshToken: obj.refresh_token
243 this.user = new AuthUser(hashUser, hashTokens)
246 this.setStatus(AuthStatus.LoggedIn)
247 this.userInformationLoaded.next(true)
250 private handleRefreshToken (obj: UserRefreshToken) {
251 this.user.refreshTokens(obj.access_token, obj.refresh_token)
255 private setStatus (status: AuthStatus) {
256 this.loginChanged.next(status)