]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/auth/auth.service.ts
9ac9ba7bb1fcd7a20b2f168af4253d779db998d4
[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 { User, 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 isAdmin () {
130 if (this.user === null) return false
131
132 return this.user.isAdmin()
133 }
134
135 isLoggedIn () {
136 return !!this.getAccessToken()
137 }
138
139 login (username: string, password: string) {
140 // Form url encoded
141 const body = new HttpParams().set('client_id', this.clientId)
142 .set('client_secret', this.clientSecret)
143 .set('response_type', 'code')
144 .set('grant_type', 'password')
145 .set('scope', 'upload')
146 .set('username', username)
147 .set('password', password)
148
149 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
150
151 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers })
152 .map(res => Object.assign(res, { username }))
153 .flatMap(res => this.mergeUserInformation(res))
154 .map(res => this.handleLogin(res))
155 .catch(res => this.restExtractor.handleError(res))
156 }
157
158 logout () {
159 // TODO: make an HTTP request to revoke the tokens
160 this.user = null
161
162 AuthUser.flush()
163
164 this.setStatus(AuthStatus.LoggedOut)
165 }
166
167 refreshAccessToken () {
168 console.log('Refreshing token...')
169
170 const refreshToken = this.getRefreshToken()
171
172 // Form url encoded
173 const body = new HttpParams().set('refresh_token', refreshToken)
174 .set('client_id', this.clientId)
175 .set('client_secret', this.clientSecret)
176 .set('response_type', 'code')
177 .set('grant_type', 'refresh_token')
178
179 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
180
181 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
182 .map(res => this.handleRefreshToken(res))
183 .catch(res => {
184 // The refresh token is invalid?
185 if (res.status === 400 && res.error.error === 'invalid_grant') {
186 console.error('Cannot refresh token -> logout...')
187 this.logout()
188 this.router.navigate(['/login'])
189
190 return Observable.throw({
191 error: 'You need to reconnect.'
192 })
193 }
194
195 return this.restExtractor.handleError(res)
196 })
197 }
198
199 refreshUserInformation () {
200 const obj = {
201 access_token: this.user.getAccessToken(),
202 refresh_token: null,
203 token_type: this.user.getTokenType(),
204 username: this.user.username
205 }
206
207 this.mergeUserInformation(obj)
208 .subscribe(
209 res => {
210 this.user.displayNSFW = res.displayNSFW
211 this.user.role = res.role
212 this.user.videoChannels = res.videoChannels
213 this.user.author = res.author
214
215 this.user.save()
216 }
217 )
218 }
219
220 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
221 // User is not loaded yet, set manually auth header
222 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
223
224 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
225 .map(res => {
226 const newProperties = {
227 id: res.id,
228 role: res.role,
229 displayNSFW: res.displayNSFW,
230 email: res.email,
231 videoQuota: res.videoQuota,
232 author: res.author,
233 videoChannels: res.videoChannels
234 }
235
236 return Object.assign(obj, newProperties)
237 }
238 )
239 }
240
241 private handleLogin (obj: UserLoginWithUserInformation) {
242 const hashUser: UserConstructorHash = {
243 id: obj.id,
244 username: obj.username,
245 role: obj.role,
246 email: obj.email,
247 displayNSFW: obj.displayNSFW,
248 videoQuota: obj.videoQuota,
249 videoChannels: obj.videoChannels,
250 author: obj.author
251 }
252 const hashTokens = {
253 accessToken: obj.access_token,
254 tokenType: obj.token_type,
255 refreshToken: obj.refresh_token
256 }
257
258 this.user = new AuthUser(hashUser, hashTokens)
259 this.user.save()
260
261 this.setStatus(AuthStatus.LoggedIn)
262 }
263
264 private handleRefreshToken (obj: UserRefreshToken) {
265 this.user.refreshTokens(obj.access_token, obj.refresh_token)
266 this.user.save()
267 }
268
269 private setStatus (status: AuthStatus) {
270 this.loginChanged.next(status)
271 }
272 }