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