]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/auth/auth.service.ts
Redirect to the last url on login
[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 { 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 { 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 notificationsService: NotificationsService,
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
109 // This is an important message
110 this.notificationsService.error(this.i18n('Error'), errorMessage, { timeOut: 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) {
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 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
162 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
163 .pipe(
164 map(res => Object.assign(res, { username })),
165 mergeMap(res => this.mergeUserInformation(res)),
166 map(res => this.handleLogin(res)),
167 catchError(res => this.restExtractor.handleError(res))
168 )
169 }
170
171 logout () {
172 // TODO: make an HTTP request to revoke the tokens
173 this.user = null
174
175 AuthUser.flush()
176
177 this.setStatus(AuthStatus.LoggedOut)
178
179 this.hotkeysService.remove(this.hotkeys)
180 }
181
182 refreshAccessToken () {
183 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
184
185 console.log('Refreshing token...')
186
187 const refreshToken = this.getRefreshToken()
188
189 // Form url encoded
190 const body = new HttpParams().set('refresh_token', refreshToken)
191 .set('client_id', this.clientId)
192 .set('client_secret', this.clientSecret)
193 .set('response_type', 'code')
194 .set('grant_type', 'refresh_token')
195
196 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
197
198 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
199 .pipe(
200 map(res => this.handleRefreshToken(res)),
201 tap(() => this.refreshingTokenObservable = null),
202 catchError(err => {
203 this.refreshingTokenObservable = null
204
205 console.error(err)
206 console.log('Cannot refresh token -> logout...')
207 this.logout()
208 this.router.navigate([ '/login' ])
209
210 return observableThrowError({
211 error: this.i18n('You need to reconnect.')
212 })
213 }),
214 share()
215 )
216
217 return this.refreshingTokenObservable
218 }
219
220 refreshUserInformation () {
221 const obj: UserLoginWithUsername = {
222 access_token: this.user.getAccessToken(),
223 refresh_token: null,
224 token_type: this.user.getTokenType(),
225 username: this.user.username
226 }
227
228 this.mergeUserInformation(obj)
229 .subscribe(
230 res => {
231 this.user.patch(res)
232 this.user.save()
233
234 this.userInformationLoaded.next(true)
235 }
236 )
237 }
238
239 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
240 // User is not loaded yet, set manually auth header
241 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
242
243 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
244 .pipe(map(res => Object.assign(obj, res)))
245 }
246
247 private handleLogin (obj: UserLoginWithUserInformation) {
248 const hashTokens = {
249 accessToken: obj.access_token,
250 tokenType: obj.token_type,
251 refreshToken: obj.refresh_token
252 }
253
254 this.user = new AuthUser(obj, hashTokens)
255 this.user.save()
256
257 this.setStatus(AuthStatus.LoggedIn)
258 this.userInformationLoaded.next(true)
259
260 this.hotkeysService.add(this.hotkeys)
261 }
262
263 private handleRefreshToken (obj: UserRefreshToken) {
264 this.user.refreshTokens(obj.access_token, obj.refresh_token)
265 this.user.save()
266 }
267
268 private setStatus (status: AuthStatus) {
269 this.loginChanged.next(status)
270 }
271 }