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