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