]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/auth/auth.service.ts
df6e5135b9aff824ecd35f626739b37d25934526
[github/Chocobozzz/PeerTube.git] / client / src / app / core / auth / auth.service.ts
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'
9
10 import { NotificationsService } from 'angular2-notifications'
11
12 import { AuthStatus } from './auth-status.model'
13 import { AuthUser } from './auth-user.model'
14 import {
15 OAuthClientLocal,
16 UserRole,
17 UserRefreshToken,
18 VideoChannel,
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 { UserConstructorHash } from '../../shared/users/user.model'
25
26 interface UserLoginWithUsername extends UserLogin {
27 access_token: string
28 refresh_token: string
29 token_type: string
30 username: string
31 }
32
33 interface UserLoginWithUserInformation extends UserLogin {
34 access_token: string
35 refresh_token: string
36 token_type: string
37 username: string
38 id: number
39 role: UserRole
40 displayNSFW: boolean
41 email: string
42 videoQuota: number
43 author: {
44 id: number
45 uuid: string
46 }
47 videoChannels: VideoChannel[]
48 }
49
50 @Injectable()
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'
55
56 loginChangedSource: Observable<AuthStatus>
57
58 private clientId: string
59 private clientSecret: string
60 private loginChanged: Subject<AuthStatus>
61 private user: AuthUser = null
62
63 constructor (
64 private http: HttpClient,
65 private notificationsService: NotificationsService,
66 private restExtractor: RestExtractor,
67 private router: Router
68 ) {
69 this.loginChanged = new Subject<AuthStatus>()
70 this.loginChangedSource = this.loginChanged.asObservable()
71
72 // Return null if there is nothing to load
73 this.user = AuthUser.load()
74 }
75
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))
81 .subscribe(
82 res => {
83 this.clientId = res.client_id
84 this.clientSecret = res.client_secret
85 console.log('Client credentials loaded.')
86 },
87
88 error => {
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.'
91
92 // We put a bigger timeout
93 // This is an important message
94 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
95 }
96 )
97 }
98
99 getRefreshToken () {
100 if (this.user === null) return null
101
102 return this.user.getRefreshToken()
103 }
104
105 getRequestHeaderValue () {
106 const accessToken = this.getAccessToken()
107
108 if (accessToken === null) return null
109
110 return `${this.getTokenType()} ${accessToken}`
111 }
112
113 getAccessToken () {
114 if (this.user === null) return null
115
116 return this.user.getAccessToken()
117 }
118
119 getTokenType () {
120 if (this.user === null) return null
121
122 return this.user.getTokenType()
123 }
124
125 getUser () {
126 return this.user
127 }
128
129 isLoggedIn () {
130 return !!this.getAccessToken()
131 }
132
133 login (username: string, password: string) {
134 // Form url encoded
135 const body = new HttpParams().set('client_id', this.clientId)
136 .set('client_secret', this.clientSecret)
137 .set('response_type', 'code')
138 .set('grant_type', 'password')
139 .set('scope', 'upload')
140 .set('username', username)
141 .set('password', password)
142
143 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
144
145 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers })
146 .map(res => Object.assign(res, { username }))
147 .flatMap(res => this.mergeUserInformation(res))
148 .map(res => this.handleLogin(res))
149 .catch(res => this.restExtractor.handleError(res))
150 }
151
152 logout () {
153 // TODO: make an HTTP request to revoke the tokens
154 this.user = null
155
156 AuthUser.flush()
157
158 this.setStatus(AuthStatus.LoggedOut)
159 }
160
161 refreshAccessToken () {
162 console.log('Refreshing token...')
163
164 const refreshToken = this.getRefreshToken()
165
166 // Form url encoded
167 const body = new HttpParams().set('refresh_token', refreshToken)
168 .set('client_id', this.clientId)
169 .set('client_secret', this.clientSecret)
170 .set('response_type', 'code')
171 .set('grant_type', 'refresh_token')
172
173 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
174
175 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
176 .map(res => this.handleRefreshToken(res))
177 .catch(res => {
178 // The refresh token is invalid?
179 if (res.status === 400 && res.error.error === 'invalid_grant') {
180 console.error('Cannot refresh token -> logout...')
181 this.logout()
182 this.router.navigate(['/login'])
183
184 return Observable.throw({
185 error: 'You need to reconnect.'
186 })
187 }
188
189 return this.restExtractor.handleError(res)
190 })
191 }
192
193 refreshUserInformation () {
194 const obj = {
195 access_token: this.user.getAccessToken(),
196 refresh_token: null,
197 token_type: this.user.getTokenType(),
198 username: this.user.username
199 }
200
201 this.mergeUserInformation(obj)
202 .subscribe(
203 res => {
204 this.user.displayNSFW = res.displayNSFW
205 this.user.role = res.role
206 this.user.videoChannels = res.videoChannels
207 this.user.author = res.author
208
209 this.user.save()
210 }
211 )
212 }
213
214 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
215 // User is not loaded yet, set manually auth header
216 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
217
218 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
219 .map(res => {
220 const newProperties = {
221 id: res.id,
222 role: res.role,
223 displayNSFW: res.displayNSFW,
224 email: res.email,
225 videoQuota: res.videoQuota,
226 author: res.author,
227 videoChannels: res.videoChannels
228 }
229
230 return Object.assign(obj, newProperties)
231 }
232 )
233 }
234
235 private handleLogin (obj: UserLoginWithUserInformation) {
236 const hashUser: UserConstructorHash = {
237 id: obj.id,
238 username: obj.username,
239 role: obj.role,
240 email: obj.email,
241 displayNSFW: obj.displayNSFW,
242 videoQuota: obj.videoQuota,
243 videoChannels: obj.videoChannels,
244 author: obj.author
245 }
246 const hashTokens = {
247 accessToken: obj.access_token,
248 tokenType: obj.token_type,
249 refreshToken: obj.refresh_token
250 }
251
252 this.user = new AuthUser(hashUser, hashTokens)
253 this.user.save()
254
255 this.setStatus(AuthStatus.LoggedIn)
256 }
257
258 private handleRefreshToken (obj: UserRefreshToken) {
259 this.user.refreshTokens(obj.access_token, obj.refresh_token)
260 this.user.save()
261 }
262
263 private setStatus (status: AuthStatus) {
264 this.loginChanged.next(status)
265 }
266 }