add redirect after login (#1110)
[oweals/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 { NotificationsService } from 'angular2-notifications'
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 { HotkeysService, Hotkey } 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   redirectUrl: string
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 notificationsService: NotificationsService,
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, 'Go to my subscriptions'),
69       new Hotkey('m v', (event: KeyboardEvent): boolean => {
70         this.router.navigate([ '/my-account/videos' ])
71         return false
72       }, undefined, '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, '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, '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
110             // This is an important message
111             this.notificationsService.error(this.i18n('Error'), errorMessage, { timeOut: 7000 })
112           }
113         )
114   }
115
116   getRefreshToken () {
117     if (this.user === null) return null
118
119     return this.user.getRefreshToken()
120   }
121
122   getRequestHeaderValue () {
123     const accessToken = this.getAccessToken()
124
125     if (accessToken === null) return null
126
127     return `${this.getTokenType()} ${accessToken}`
128   }
129
130   getAccessToken () {
131     if (this.user === null) return null
132
133     return this.user.getAccessToken()
134   }
135
136   getTokenType () {
137     if (this.user === null) return null
138
139     return this.user.getTokenType()
140   }
141
142   getUser () {
143     return this.user
144   }
145
146   isLoggedIn () {
147     return !!this.getAccessToken()
148   }
149
150   login (username: string, password: string) {
151     // Form url encoded
152     const body = {
153       client_id: this.clientId,
154       client_secret: this.clientSecret,
155       response_type: 'code',
156       grant_type: 'password',
157       scope: 'upload',
158       username,
159       password
160     }
161
162     const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
163     return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
164                .pipe(
165                  map(res => Object.assign(res, { username })),
166                  mergeMap(res => this.mergeUserInformation(res)),
167                  map(res => this.handleLogin(res)),
168                  catchError(res => this.restExtractor.handleError(res))
169                )
170   }
171
172   logout () {
173     // TODO: make an HTTP request to revoke the tokens
174     this.user = null
175
176     AuthUser.flush()
177
178     this.setStatus(AuthStatus.LoggedOut)
179
180     this.hotkeysService.remove(this.hotkeys)
181
182     this.redirectUrl = null
183   }
184
185   refreshAccessToken () {
186     if (this.refreshingTokenObservable) return this.refreshingTokenObservable
187
188     console.log('Refreshing token...')
189
190     const refreshToken = this.getRefreshToken()
191
192     // Form url encoded
193     const body = new HttpParams().set('refresh_token', refreshToken)
194                                  .set('client_id', this.clientId)
195                                  .set('client_secret', this.clientSecret)
196                                  .set('response_type', 'code')
197                                  .set('grant_type', 'refresh_token')
198
199     const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
200
201     this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
202                                          .pipe(
203                                            map(res => this.handleRefreshToken(res)),
204                                            tap(() => this.refreshingTokenObservable = null),
205                                            catchError(err => {
206                                              this.refreshingTokenObservable = null
207
208                                              console.error(err)
209                                              console.log('Cannot refresh token -> logout...')
210                                              this.logout()
211                                              this.router.navigate([ '/login' ])
212
213                                              return observableThrowError({
214                                                error: this.i18n('You need to reconnect.')
215                                              })
216                                            }),
217                                            share()
218                                          )
219
220     return this.refreshingTokenObservable
221   }
222
223   refreshUserInformation () {
224     const obj = {
225       access_token: this.user.getAccessToken(),
226       refresh_token: null,
227       token_type: this.user.getTokenType(),
228       username: this.user.username
229     }
230
231     this.mergeUserInformation(obj)
232         .subscribe(
233           res => {
234             this.user.patch(res)
235             this.user.save()
236
237             this.userInformationLoaded.next(true)
238           }
239         )
240   }
241
242   private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
243     // User is not loaded yet, set manually auth header
244     const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
245
246     return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
247                .pipe(map(res => Object.assign(obj, res)))
248   }
249
250   private handleLogin (obj: UserLoginWithUserInformation) {
251     const hashTokens = {
252       accessToken: obj.access_token,
253       tokenType: obj.token_type,
254       refreshToken: obj.refresh_token
255     }
256
257     this.user = new AuthUser(obj, hashTokens)
258     this.user.save()
259
260     this.setStatus(AuthStatus.LoggedIn)
261     this.userInformationLoaded.next(true)
262
263     this.hotkeysService.add(this.hotkeys)
264   }
265
266   private handleRefreshToken (obj: UserRefreshToken) {
267     this.user.refreshTokens(obj.access_token, obj.refresh_token)
268     this.user.save()
269   }
270
271   private setStatus (status: AuthStatus) {
272     this.loginChanged.next(status)
273   }
274 }