1 import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
2 import { Injectable } from '@angular/core'
3 import { Router } from '@angular/router'
5 import { NotificationsService } from 'angular2-notifications'
6 import 'rxjs/add/observable/throw'
7 import 'rxjs/add/operator/do'
8 import 'rxjs/add/operator/map'
9 import 'rxjs/add/operator/mergeMap'
10 import { Observable } from 'rxjs/Observable'
11 import { ReplaySubject } from 'rxjs/ReplaySubject'
12 import { Subject } from 'rxjs/Subject'
13 import { OAuthClientLocal, User as UserServerModel, UserRefreshToken, UserRole, VideoChannel } from '../../../../../shared'
14 import { Account } from '../../../../../shared/models/accounts'
15 import { UserLogin } from '../../../../../shared/models/users/user-login.model'
16 // Do not use the barrel (dependency loop)
17 import { RestExtractor } from '../../shared/rest'
18 import { UserConstructorHash } from '../../shared/users/user.model'
20 import { AuthStatus } from './auth-status.model'
21 import { AuthUser } from './auth-user.model'
23 interface UserLoginWithUsername extends UserLogin {
30 interface UserLoginWithUserInformation extends UserLogin {
41 videoChannels: VideoChannel[]
45 export class AuthService {
46 private static BASE_CLIENT_URL = API_URL + '/api/v1/oauth-clients/local'
47 private static BASE_TOKEN_URL = API_URL + '/api/v1/users/token'
48 private static BASE_USER_INFORMATION_URL = API_URL + '/api/v1/users/me'
50 loginChangedSource: Observable<AuthStatus>
51 userInformationLoaded = new ReplaySubject<boolean>(1)
53 private clientId: string
54 private clientSecret: string
55 private loginChanged: Subject<AuthStatus>
56 private user: AuthUser = null
59 private http: HttpClient,
60 private notificationsService: NotificationsService,
61 private restExtractor: RestExtractor,
62 private router: Router
64 this.loginChanged = new Subject<AuthStatus>()
65 this.loginChangedSource = this.loginChanged.asObservable()
67 // Return null if there is nothing to load
68 this.user = AuthUser.load()
71 loadClientCredentials () {
72 // Fetch the client_id/client_secret
73 // FIXME: save in local storage?
74 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
75 .catch(res => this.restExtractor.handleError(res))
78 this.clientId = res.client_id
79 this.clientSecret = res.client_secret
80 console.log('Client credentials loaded.')
84 let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
85 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
87 // We put a bigger timeout
88 // This is an important message
89 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
95 if (this.user === null) return null
97 return this.user.getRefreshToken()
100 getRequestHeaderValue () {
101 const accessToken = this.getAccessToken()
103 if (accessToken === null) return null
105 return `${this.getTokenType()} ${accessToken}`
109 if (this.user === null) return null
111 return this.user.getAccessToken()
115 if (this.user === null) return null
117 return this.user.getTokenType()
125 return !!this.getAccessToken()
128 login (username: string, password: string) {
130 const body = new HttpParams().set('client_id', this.clientId)
131 .set('client_secret', this.clientSecret)
132 .set('response_type', 'code')
133 .set('grant_type', 'password')
134 .set('scope', 'upload')
135 .set('username', username)
136 .set('password', password)
138 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
140 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers })
141 .map(res => Object.assign(res, { username }))
142 .flatMap(res => this.mergeUserInformation(res))
143 .map(res => this.handleLogin(res))
144 .catch(res => this.restExtractor.handleError(res))
148 // TODO: make an HTTP request to revoke the tokens
153 this.setStatus(AuthStatus.LoggedOut)
156 refreshAccessToken () {
157 console.log('Refreshing token...')
159 const refreshToken = this.getRefreshToken()
162 const body = new HttpParams().set('refresh_token', refreshToken)
163 .set('client_id', this.clientId)
164 .set('client_secret', this.clientSecret)
165 .set('response_type', 'code')
166 .set('grant_type', 'refresh_token')
168 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
170 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
171 .map(res => this.handleRefreshToken(res))
174 console.log('Cannot refresh token -> logout...')
176 this.router.navigate(['/login'])
178 return Observable.throw({
179 error: 'You need to reconnect.'
184 refreshUserInformation () {
186 access_token: this.user.getAccessToken(),
188 token_type: this.user.getTokenType(),
189 username: this.user.username
192 this.mergeUserInformation(obj)
195 this.user.displayNSFW = res.displayNSFW
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,
218 videoQuota: res.videoQuota,
219 account: res.account,
220 videoChannels: res.videoChannels
223 return Object.assign(obj, newProperties)
228 private handleLogin (obj: UserLoginWithUserInformation) {
229 const hashUser: UserConstructorHash = {
231 username: obj.username,
234 displayNSFW: obj.displayNSFW,
235 videoQuota: obj.videoQuota,
236 videoChannels: obj.videoChannels,
240 accessToken: obj.access_token,
241 tokenType: obj.token_type,
242 refreshToken: obj.refresh_token
245 this.user = new AuthUser(hashUser, hashTokens)
248 this.setStatus(AuthStatus.LoggedIn)
249 this.userInformationLoaded.next(true)
252 private handleRefreshToken (obj: UserRefreshToken) {
253 this.user.refreshTokens(obj.access_token, obj.refresh_token)
257 private setStatus (status: AuthStatus) {
258 this.loginChanged.next(status)