]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/auth/auth.service.ts
Refactor login redirection/button links
[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, HttpErrorResponse, 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 { logger, OAuthUserTokens, objectToUrlEncoded, peertubeLocalStorage } from '@root-helpers/index'
9 import { HttpStatusCode, 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 { RedirectService } from '../routing'
13 import { AuthStatus } from './auth-status.model'
14 import { AuthUser } from './auth-user.model'
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 tokensRefreshed = new ReplaySubject<void>(1)
39 hotkeys: Hotkey[]
40
41 private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
42 private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
43 private loginChanged: Subject<AuthStatus>
44 private user: AuthUser = null
45 private refreshingTokenObservable: Observable<any>
46
47 constructor (
48 private redirectService: RedirectService,
49 private http: HttpClient,
50 private notifier: Notifier,
51 private hotkeysService: HotkeysService,
52 private restExtractor: RestExtractor,
53 private router: Router
54 ) {
55 this.loginChanged = new Subject<AuthStatus>()
56 this.loginChangedSource = this.loginChanged.asObservable()
57
58 // Set HotKeys
59 this.hotkeys = [
60 new Hotkey('m s', (event: KeyboardEvent): boolean => {
61 this.router.navigate([ '/videos/subscriptions' ])
62 return false
63 }, undefined, $localize`Go to my subscriptions`),
64 new Hotkey('m v', (event: KeyboardEvent): boolean => {
65 this.router.navigate([ '/my-library/videos' ])
66 return false
67 }, undefined, $localize`Go to my videos`),
68 new Hotkey('m i', (event: KeyboardEvent): boolean => {
69 this.router.navigate([ '/my-library/video-imports' ])
70 return false
71 }, undefined, $localize`Go to my imports`),
72 new Hotkey('m c', (event: KeyboardEvent): boolean => {
73 this.router.navigate([ '/my-library/video-channels' ])
74 return false
75 }, undefined, $localize`Go to my channels`)
76 ]
77 }
78
79 buildAuthUser (userInfo: Partial<User>, tokens: OAuthUserTokens) {
80 this.user = new AuthUser(userInfo, tokens)
81 }
82
83 loadClientCredentials () {
84 // Fetch the client_id/client_secret
85 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
86 .pipe(catchError(res => this.restExtractor.handleError(res)))
87 .subscribe({
88 next: res => {
89 this.clientId = res.client_id
90 this.clientSecret = res.client_secret
91
92 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
93 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
94
95 logger.info('Client credentials loaded.')
96 },
97
98 error: err => {
99 let errorMessage = err.message
100
101 if (err.status === HttpStatusCode.FORBIDDEN_403) {
102 errorMessage = $localize`Cannot retrieve OAuth Client credentials: ${err.message}.
103 Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.`
104 }
105
106 // We put a bigger timeout: this is an important message
107 this.notifier.error(errorMessage, $localize`Error`, 7000)
108 }
109 })
110 }
111
112 getRefreshToken () {
113 if (this.user === null) return null
114
115 return this.user.getRefreshToken()
116 }
117
118 getRequestHeaderValue () {
119 const accessToken = this.getAccessToken()
120
121 if (accessToken === null) return null
122
123 return `${this.getTokenType()} ${accessToken}`
124 }
125
126 getAccessToken () {
127 if (this.user === null) return null
128
129 return this.user.getAccessToken()
130 }
131
132 getTokenType () {
133 if (this.user === null) return null
134
135 return this.user.getTokenType()
136 }
137
138 getUser () {
139 return this.user
140 }
141
142 isLoggedIn () {
143 return !!this.getAccessToken()
144 }
145
146 login (options: {
147 username: string
148 password: string
149 otpToken?: string
150 token?: string
151 }) {
152 const { username, password, token, otpToken } = options
153
154 // Form url encoded
155 const body = {
156 client_id: this.clientId,
157 client_secret: this.clientSecret,
158 response_type: 'code',
159 grant_type: 'password',
160 scope: 'upload',
161 username,
162 password
163 }
164
165 if (token) Object.assign(body, { externalAuthToken: token })
166
167 let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
168 if (otpToken) headers = headers.set('x-peertube-otp', otpToken)
169
170 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
171 .pipe(
172 map(res => Object.assign(res, { username })),
173 mergeMap(res => this.mergeUserInformation(res)),
174 map(res => this.handleLogin(res)),
175 catchError(res => this.restExtractor.handleError(res))
176 )
177 }
178
179 logout () {
180 const authHeaderValue = this.getRequestHeaderValue()
181 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
182
183 this.http.post<{ redirectUrl?: string }>(AuthService.BASE_REVOKE_TOKEN_URL, {}, { headers })
184 .subscribe({
185 next: res => {
186 if (res.redirectUrl) {
187 window.location.href = res.redirectUrl
188 }
189 },
190
191 error: err => logger.error(err)
192 })
193
194 this.user = null
195
196 this.setStatus(AuthStatus.LoggedOut)
197
198 this.hotkeysService.remove(this.hotkeys)
199 }
200
201 refreshAccessToken () {
202 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
203
204 logger.info('Refreshing token...')
205
206 const refreshToken = this.getRefreshToken()
207
208 // Form url encoded
209 const body = new HttpParams().set('refresh_token', refreshToken)
210 .set('client_id', this.clientId)
211 .set('client_secret', this.clientSecret)
212 .set('response_type', 'code')
213 .set('grant_type', 'refresh_token')
214
215 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
216
217 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
218 .pipe(
219 map(res => this.handleRefreshToken(res)),
220 tap(() => {
221 this.refreshingTokenObservable = null
222 }),
223 catchError(err => {
224 this.refreshingTokenObservable = null
225
226 logger.error(err)
227 logger.info('Cannot refresh token -> logout...')
228 this.logout()
229
230 this.redirectService.redirectToLogin()
231
232 return observableThrowError(() => ({
233 error: $localize`You need to reconnect.`
234 }))
235 }),
236 share()
237 )
238
239 return this.refreshingTokenObservable
240 }
241
242 refreshUserInformation () {
243 const obj: UserLoginWithUsername = {
244 access_token: this.user.getAccessToken(),
245 refresh_token: null,
246 token_type: this.user.getTokenType(),
247 username: this.user.username
248 }
249
250 this.mergeUserInformation(obj)
251 .subscribe({
252 next: res => {
253 this.user.patch(res)
254
255 this.userInformationLoaded.next(true)
256 }
257 })
258 }
259
260 isOTPMissingError (err: HttpErrorResponse) {
261 if (err.status !== HttpStatusCode.UNAUTHORIZED_401) return false
262
263 if (err.headers.get('x-peertube-otp') !== 'required; app') return false
264
265 return true
266 }
267
268 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
269 // User is not loaded yet, set manually auth header
270 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
271
272 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
273 .pipe(map(res => Object.assign(obj, res)))
274 }
275
276 private handleLogin (obj: UserLoginWithUserInformation) {
277 const hashTokens = {
278 accessToken: obj.access_token,
279 tokenType: obj.token_type,
280 refreshToken: obj.refresh_token
281 }
282
283 this.user = new AuthUser(obj, hashTokens)
284
285 this.setStatus(AuthStatus.LoggedIn)
286 this.userInformationLoaded.next(true)
287
288 this.hotkeysService.add(this.hotkeys)
289 }
290
291 private handleRefreshToken (obj: UserRefreshToken) {
292 this.user.refreshTokens(obj.access_token, obj.refresh_token)
293 this.tokensRefreshed.next()
294 }
295
296 private setStatus (status: AuthStatus) {
297 this.loginChanged.next(status)
298 }
299 }