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