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