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'
14 import { OAuthClientLocal, UserRole, UserRefreshToken } from '../../../../../shared'
15 // Do not use the barrel (dependency loop)
16 import { RestExtractor } from '../../shared/rest'
17 import { UserLogin } from '../../../../../shared/models/users/user-login.model'
18 import { User } from '../../shared/users/user.model'
20 interface UserLoginWithUsername extends UserLogin {
27 interface UserLoginWithUserInformation extends UserLogin {
39 export class AuthService {
40 private static BASE_CLIENT_URL = API_URL + '/api/v1/oauth-clients/local'
41 private static BASE_TOKEN_URL = API_URL + '/api/v1/users/token'
42 private static BASE_USER_INFORMATION_URL = API_URL + '/api/v1/users/me'
44 loginChangedSource: Observable<AuthStatus>
46 private clientId: string
47 private clientSecret: string
48 private loginChanged: Subject<AuthStatus>
49 private user: AuthUser = null
52 private http: HttpClient,
53 private notificationsService: NotificationsService,
54 private restExtractor: RestExtractor,
55 private router: Router
57 this.loginChanged = new Subject<AuthStatus>()
58 this.loginChangedSource = this.loginChanged.asObservable()
60 // Return null if there is nothing to load
61 this.user = AuthUser.load()
64 loadClientCredentials () {
65 // Fetch the client_id/client_secret
66 // FIXME: save in local storage?
67 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
68 .catch(res => this.restExtractor.handleError(res))
71 this.clientId = res.client_id
72 this.clientSecret = res.client_secret
73 console.log('Client credentials loaded.')
77 let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
78 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
80 // We put a bigger timeout
81 // This is an important message
82 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
88 if (this.user === null) return null
90 return this.user.getRefreshToken()
93 getRequestHeaderValue () {
94 const accessToken = this.getAccessToken()
96 if (accessToken === null) return null
98 return `${this.getTokenType()} ${accessToken}`
102 if (this.user === null) return null
104 return this.user.getAccessToken()
108 if (this.user === null) return null
110 return this.user.getTokenType()
118 if (this.user === null) return false
120 return this.user.isAdmin()
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))
172 // The refresh token is invalid?
173 if (res.status === 400 && res.error === 'invalid_grant') {
174 console.error('Cannot refresh token -> logout...')
176 this.router.navigate(['/login'])
178 return Observable.throw({
179 error: 'You need to reconnect.'
183 return this.restExtractor.handleError(res)
187 refreshUserInformation () {
189 access_token: this.user.getAccessToken(),
191 token_type: this.user.getTokenType(),
192 username: this.user.username
195 this.mergeUserInformation(obj)
198 this.user.displayNSFW = res.displayNSFW
199 this.user.role = res.role
206 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
207 // User is not loaded yet, set manually auth header
208 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
210 return this.http.get<User>(AuthService.BASE_USER_INFORMATION_URL, { headers })
212 const newProperties = {
213 id: res.id as number,
214 role: res.role as UserRole,
215 displayNSFW: res.displayNSFW as boolean,
216 email: res.email as string
219 return Object.assign(obj, newProperties)
224 private handleLogin (obj: UserLoginWithUserInformation) {
226 const username = obj.username
227 const role = obj.role
228 const email = obj.email
229 const displayNSFW = obj.displayNSFW
231 accessToken: obj.access_token,
232 tokenType: obj.token_type,
233 refreshToken: obj.refresh_token
236 this.user = new AuthUser({ id, username, role, displayNSFW, email }, hashTokens)
239 this.setStatus(AuthStatus.LoggedIn)
242 private handleRefreshToken (obj: UserRefreshToken) {
243 this.user.refreshTokens(obj.access_token, obj.refresh_token)
247 private setStatus (status: AuthStatus) {
248 this.loginChanged.next(status)