]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/auth/auth.service.ts
emit more specific status codes on video upload (#3423)
[github/Chocobozzz/PeerTube.git] / client / src / app / core / auth / auth.service.ts
1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { Observable, ReplaySubject, Subject, throwError as observableThrowError } from 'rxjs'
3 import { catchError, map, mergeMap, share, tap } from 'rxjs/operators'
4 import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
5 import { Injectable } from '@angular/core'
6 import { Router } from '@angular/router'
7 import { Notifier } from '@app/core/notification/notifier.service'
8 import { objectToUrlEncoded, peertubeLocalStorage } from '@root-helpers/index'
9 import { MyUser as UserServerModel, OAuthClientLocal, User, UserLogin, UserRefreshToken } from '@shared/models'
10 import { environment } from '../../../environments/environment'
11 import { RestExtractor } from '../rest/rest-extractor.service'
12 import { AuthStatus } from './auth-status.model'
13 import { AuthUser } from './auth-user.model'
14 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
15
16 interface UserLoginWithUsername extends UserLogin {
17 access_token: string
18 refresh_token: string
19 token_type: string
20 username: string
21 }
22
23 type UserLoginWithUserInformation = UserLoginWithUsername & User
24
25 @Injectable()
26 export class AuthService {
27 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
28 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
29 private static BASE_REVOKE_TOKEN_URL = environment.apiUrl + '/api/v1/users/revoke-token'
30 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
31 private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
32 CLIENT_ID: 'client_id',
33 CLIENT_SECRET: 'client_secret'
34 }
35
36 loginChangedSource: Observable<AuthStatus>
37 userInformationLoaded = new ReplaySubject<boolean>(1)
38 hotkeys: Hotkey[]
39
40 private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
41 private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
42 private loginChanged: Subject<AuthStatus>
43 private user: AuthUser = null
44 private refreshingTokenObservable: Observable<any>
45
46 constructor (
47 private http: HttpClient,
48 private notifier: Notifier,
49 private hotkeysService: HotkeysService,
50 private restExtractor: RestExtractor,
51 private router: Router
52 ) {
53 this.loginChanged = new Subject<AuthStatus>()
54 this.loginChangedSource = this.loginChanged.asObservable()
55
56 // Return null if there is nothing to load
57 this.user = AuthUser.load()
58
59 // Set HotKeys
60 this.hotkeys = [
61 new Hotkey('m s', (event: KeyboardEvent): boolean => {
62 this.router.navigate([ '/videos/subscriptions' ])
63 return false
64 }, undefined, $localize`Go to my subscriptions`),
65 new Hotkey('m v', (event: KeyboardEvent): boolean => {
66 this.router.navigate([ '/my-library/videos' ])
67 return false
68 }, undefined, $localize`Go to my videos`),
69 new Hotkey('m i', (event: KeyboardEvent): boolean => {
70 this.router.navigate([ '/my-library/video-imports' ])
71 return false
72 }, undefined, $localize`Go to my imports`),
73 new Hotkey('m c', (event: KeyboardEvent): boolean => {
74 this.router.navigate([ '/my-library/video-channels' ])
75 return false
76 }, undefined, $localize`Go to my channels`)
77 ]
78 }
79
80 loadClientCredentials () {
81 // Fetch the client_id/client_secret
82 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
83 .pipe(catchError(res => this.restExtractor.handleError(res)))
84 .subscribe(
85 res => {
86 this.clientId = res.client_id
87 this.clientSecret = res.client_secret
88
89 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
90 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
91
92 console.log('Client credentials loaded.')
93 },
94
95 error => {
96 let errorMessage = error.message
97
98 if (error.status === HttpStatusCode.FORBIDDEN_403) {
99 errorMessage = $localize`Cannot retrieve OAuth Client credentials: ${error.text}.
100 Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.`
101 }
102
103 // We put a bigger timeout: this is an important message
104 this.notifier.error(errorMessage, $localize`Error`, 7000)
105 }
106 )
107 }
108
109 getRefreshToken () {
110 if (this.user === null) return null
111
112 return this.user.getRefreshToken()
113 }
114
115 getRequestHeaderValue () {
116 const accessToken = this.getAccessToken()
117
118 if (accessToken === null) return null
119
120 return `${this.getTokenType()} ${accessToken}`
121 }
122
123 getAccessToken () {
124 if (this.user === null) return null
125
126 return this.user.getAccessToken()
127 }
128
129 getTokenType () {
130 if (this.user === null) return null
131
132 return this.user.getTokenType()
133 }
134
135 getUser () {
136 return this.user
137 }
138
139 isLoggedIn () {
140 return !!this.getAccessToken()
141 }
142
143 login (username: string, password: string, token?: string) {
144 // Form url encoded
145 const body = {
146 client_id: this.clientId,
147 client_secret: this.clientSecret,
148 response_type: 'code',
149 grant_type: 'password',
150 scope: 'upload',
151 username,
152 password
153 }
154
155 if (token) Object.assign(body, { externalAuthToken: token })
156
157 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
158 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
159 .pipe(
160 map(res => Object.assign(res, { username })),
161 mergeMap(res => this.mergeUserInformation(res)),
162 map(res => this.handleLogin(res)),
163 catchError(res => this.restExtractor.handleError(res))
164 )
165 }
166
167 logout () {
168 const authHeaderValue = this.getRequestHeaderValue()
169 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
170
171 this.http.post<{ redirectUrl?: string }>(AuthService.BASE_REVOKE_TOKEN_URL, {}, { headers })
172 .subscribe(
173 res => {
174 if (res.redirectUrl) {
175 window.location.href = res.redirectUrl
176 }
177 },
178
179 err => console.error(err)
180 )
181
182 this.user = null
183
184 AuthUser.flush()
185
186 this.setStatus(AuthStatus.LoggedOut)
187
188 this.hotkeysService.remove(this.hotkeys)
189 }
190
191 refreshAccessToken () {
192 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
193
194 console.log('Refreshing token...')
195
196 const refreshToken = this.getRefreshToken()
197
198 // Form url encoded
199 const body = new HttpParams().set('refresh_token', refreshToken)
200 .set('client_id', this.clientId)
201 .set('client_secret', this.clientSecret)
202 .set('response_type', 'code')
203 .set('grant_type', 'refresh_token')
204
205 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
206
207 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
208 .pipe(
209 map(res => this.handleRefreshToken(res)),
210 tap(() => this.refreshingTokenObservable = null),
211 catchError(err => {
212 this.refreshingTokenObservable = null
213
214 console.error(err)
215 console.log('Cannot refresh token -> logout...')
216 this.logout()
217 this.router.navigate([ '/login' ])
218
219 return observableThrowError({
220 error: $localize`You need to reconnect.`
221 })
222 }),
223 share()
224 )
225
226 return this.refreshingTokenObservable
227 }
228
229 refreshUserInformation () {
230 const obj: UserLoginWithUsername = {
231 access_token: this.user.getAccessToken(),
232 refresh_token: null,
233 token_type: this.user.getTokenType(),
234 username: this.user.username
235 }
236
237 this.mergeUserInformation(obj)
238 .subscribe(
239 res => {
240 this.user.patch(res)
241 this.user.save()
242
243 this.userInformationLoaded.next(true)
244 }
245 )
246 }
247
248 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
249 // User is not loaded yet, set manually auth header
250 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
251
252 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
253 .pipe(map(res => Object.assign(obj, res)))
254 }
255
256 private handleLogin (obj: UserLoginWithUserInformation) {
257 const hashTokens = {
258 accessToken: obj.access_token,
259 tokenType: obj.token_type,
260 refreshToken: obj.refresh_token
261 }
262
263 this.user = new AuthUser(obj, hashTokens)
264 this.user.save()
265
266 this.setStatus(AuthStatus.LoggedIn)
267 this.userInformationLoaded.next(true)
268
269 this.hotkeysService.add(this.hotkeys)
270 }
271
272 private handleRefreshToken (obj: UserRefreshToken) {
273 this.user.refreshTokens(obj.access_token, obj.refresh_token)
274 this.user.save()
275 }
276
277 private setStatus (status: AuthStatus) {
278 this.loginChanged.next(status)
279 }
280 }