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