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