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/actors'
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 {
36 autoPlayVideo: boolean
40 videoChannels: VideoChannel[]
44 export class AuthService {
45 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
46 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
47 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
49 loginChangedSource: Observable<AuthStatus>
50 userInformationLoaded = new ReplaySubject<boolean>(1)
52 private clientId: string
53 private clientSecret: string
54 private loginChanged: Subject<AuthStatus>
55 private user: AuthUser = null
58 private http: HttpClient,
59 private notificationsService: NotificationsService,
60 private restExtractor: RestExtractor,
61 private router: Router
63 this.loginChanged = new Subject<AuthStatus>()
64 this.loginChangedSource = this.loginChanged.asObservable()
66 // Return null if there is nothing to load
67 this.user = AuthUser.load()
70 loadClientCredentials () {
71 // Fetch the client_id/client_secret
72 // FIXME: save in local storage?
73 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
74 .catch(res => this.restExtractor.handleError(res))
77 this.clientId = res.client_id
78 this.clientSecret = res.client_secret
79 console.log('Client credentials loaded.')
83 let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
84 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
86 // We put a bigger timeout
87 // This is an important message
88 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
94 if (this.user === null) return null
96 return this.user.getRefreshToken()
99 getRequestHeaderValue () {
100 const accessToken = this.getAccessToken()
102 if (accessToken === null) return null
104 return `${this.getTokenType()} ${accessToken}`
108 if (this.user === null) return null
110 return this.user.getAccessToken()
114 if (this.user === null) return null
116 return this.user.getTokenType()
124 return !!this.getAccessToken()
127 login (username: string, password: string) {
129 const body = new HttpParams().set('client_id', this.clientId)
130 .set('client_secret', this.clientSecret)
131 .set('response_type', 'code')
132 .set('grant_type', 'password')
133 .set('scope', 'upload')
134 .set('username', username)
135 .set('password', password)
137 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
139 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers })
140 .map(res => Object.assign(res, { username }))
141 .flatMap(res => this.mergeUserInformation(res))
142 .map(res => this.handleLogin(res))
143 .catch(res => this.restExtractor.handleError(res))
147 // TODO: make an HTTP request to revoke the tokens
152 this.setStatus(AuthStatus.LoggedOut)
155 refreshAccessToken () {
156 console.log('Refreshing token...')
158 const refreshToken = this.getRefreshToken()
161 const body = new HttpParams().set('refresh_token', refreshToken)
162 .set('client_id', this.clientId)
163 .set('client_secret', this.clientSecret)
164 .set('response_type', 'code')
165 .set('grant_type', 'refresh_token')
167 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
169 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
170 .map(res => this.handleRefreshToken(res))
173 console.log('Cannot refresh token -> logout...')
175 this.router.navigate(['/login'])
177 return Observable.throw({
178 error: 'You need to reconnect.'
183 refreshUserInformation () {
185 access_token: this.user.getAccessToken(),
187 token_type: this.user.getTokenType(),
188 username: this.user.username
191 this.mergeUserInformation(obj)
194 this.user.displayNSFW = res.displayNSFW
195 this.user.autoPlayVideo = res.autoPlayVideo
196 this.user.role = res.role
197 this.user.videoChannels = res.videoChannels
198 this.user.account = res.account
202 this.userInformationLoaded.next(true)
207 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
208 // User is not loaded yet, set manually auth header
209 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
211 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
213 const newProperties = {
216 displayNSFW: res.displayNSFW,
217 autoPlayVideo: res.autoPlayVideo,
219 videoQuota: res.videoQuota,
220 account: res.account,
221 videoChannels: res.videoChannels
224 return Object.assign(obj, newProperties)
229 private handleLogin (obj: UserLoginWithUserInformation) {
230 const hashUser: UserConstructorHash = {
232 username: obj.username,
235 displayNSFW: obj.displayNSFW,
236 autoPlayVideo: obj.autoPlayVideo,
237 videoQuota: obj.videoQuota,
238 videoChannels: obj.videoChannels,
242 accessToken: obj.access_token,
243 tokenType: obj.token_type,
244 refreshToken: obj.refresh_token
247 this.user = new AuthUser(hashUser, hashTokens)
250 this.setStatus(AuthStatus.LoggedIn)
251 this.userInformationLoaded.next(true)
254 private handleRefreshToken (obj: UserRefreshToken) {
255 this.user.refreshTokens(obj.access_token, obj.refresh_token)
259 private setStatus (status: AuthStatus) {
260 this.loginChanged.next(status)