]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/auth/auth.service.ts
Redirect to default login url on 401
[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'
d12b40fb 4import { HttpClient, HttpErrorResponse, 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'
2570fd9c 8import { logger, OAuthUserTokens, objectToUrlEncoded, peertubeLocalStorage, PluginsManager } 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'
2570fd9c 12import { ServerService } from '../server'
2295ce6c
C
13import { AuthStatus } from './auth-status.model'
14import { AuthUser } from './auth-user.model'
15
d592e0a9
C
16interface UserLoginWithUsername extends UserLogin {
17 access_token: string
18 refresh_token: string
19 token_type: string
20 username: string
21}
22
c5911fd3 23type UserLoginWithUserInformation = UserLoginWithUsername & User
b1794c53
C
24
25@Injectable()
26export class AuthService {
63c4db6d
C
27 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
28 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
dadc90bc 29 private static BASE_REVOKE_TOKEN_URL = environment.apiUrl + '/api/v1/users/revoke-token'
63c4db6d 30 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
a20776fc
C
31 private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
32 CLIENT_ID: 'client_id',
33 CLIENT_SECRET: 'client_secret'
34 }
b1794c53 35
df98563e 36 loginChangedSource: Observable<AuthStatus>
2de96f4d 37 userInformationLoaded = new ReplaySubject<boolean>(1)
a9bfa85d 38 tokensRefreshed = new ReplaySubject<void>(1)
c13e2bf3 39 hotkeys: Hotkey[]
b1794c53 40
a20776fc
C
41 private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
42 private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
df98563e
C
43 private loginChanged: Subject<AuthStatus>
44 private user: AuthUser = null
47f8de28 45 private refreshingTokenObservable: Observable<any>
ccf6ed16 46
df98563e 47 constructor (
2570fd9c 48 private serverService: ServerService,
d592e0a9 49 private http: HttpClient,
f8b2c1b4 50 private notifier: Notifier,
c13e2bf3 51 private hotkeysService: HotkeysService,
14ad0c27 52 private restExtractor: RestExtractor,
66357162 53 private router: Router
9df52d66 54 ) {
df98563e
C
55 this.loginChanged = new Subject<AuthStatus>()
56 this.loginChangedSource = this.loginChanged.asObservable()
23a5a916 57
c13e2bf3
RK
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
3545e72c 79 buildAuthUser (userInfo: Partial<User>, tokens: OAuthUserTokens) {
a9bfa85d
C
80 this.user = new AuthUser(userInfo, tokens)
81 }
82
d592e0a9
C
83 loadClientCredentials () {
84 // Fetch the client_id/client_secret
d592e0a9 85 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
db400f44 86 .pipe(catchError(res => this.restExtractor.handleError(res)))
1378c0d3
C
87 .subscribe({
88 next: res => {
db400f44
C
89 this.clientId = res.client_id
90 this.clientSecret = res.client_secret
a20776fc
C
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
42b40636 95 logger.info('Client credentials loaded.')
db400f44
C
96 },
97
1378c0d3
C
98 error: err => {
99 let errorMessage = err.message
db400f44 100
1378c0d3 101 if (err.status === HttpStatusCode.FORBIDDEN_403) {
255c0030 102 errorMessage = $localize`Cannot retrieve OAuth Client credentials: ${err.message}.
66357162 103Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.`
db400f44
C
104 }
105
f8b2c1b4 106 // We put a bigger timeout: this is an important message
66357162 107 this.notifier.error(errorMessage, $localize`Error`, 7000)
db400f44 108 }
1378c0d3 109 })
d592e0a9
C
110 }
111
df98563e
C
112 getRefreshToken () {
113 if (this.user === null) return null
bd5c83a8 114
df98563e 115 return this.user.getRefreshToken()
bd5c83a8
C
116 }
117
df98563e 118 getRequestHeaderValue () {
d592e0a9
C
119 const accessToken = this.getAccessToken()
120
121 if (accessToken === null) return null
122
123 return `${this.getTokenType()} ${accessToken}`
1553e15d
C
124 }
125
df98563e
C
126 getAccessToken () {
127 if (this.user === null) return null
bd5c83a8 128
df98563e 129 return this.user.getAccessToken()
1553e15d
C
130 }
131
df98563e
C
132 getTokenType () {
133 if (this.user === null) return null
bd5c83a8 134
df98563e 135 return this.user.getTokenType()
1553e15d
C
136 }
137
df98563e
C
138 getUser () {
139 return this.user
1553e15d
C
140 }
141
df98563e 142 isLoggedIn () {
d592e0a9 143 return !!this.getAccessToken()
1553e15d
C
144 }
145
d12b40fb
C
146 login (options: {
147 username: string
148 password: string
149 otpToken?: string
150 token?: string
151 }) {
152 const { username, password, token, otpToken } = options
153
d592e0a9 154 // Form url encoded
cd4d7a2c
C
155 const body = {
156 client_id: this.clientId,
157 client_secret: this.clientSecret,
158 response_type: 'code',
159 grant_type: 'password',
160 scope: 'upload',
50b4dcce 161 username,
cd4d7a2c 162 password
f954b5da 163 }
d592e0a9 164
4a8d113b
C
165 if (token) Object.assign(body, { externalAuthToken: token })
166
d12b40fb
C
167 let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
168 if (otpToken) headers = headers.set('x-peertube-otp', otpToken)
169
cd4d7a2c 170 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
db400f44
C
171 .pipe(
172 map(res => Object.assign(res, { username })),
173 mergeMap(res => this.mergeUserInformation(res)),
174 map(res => this.handleLogin(res)),
175 catchError(res => this.restExtractor.handleError(res))
176 )
4fd8aa32
C
177 }
178
df98563e 179 logout () {
dadc90bc
C
180 const authHeaderValue = this.getRequestHeaderValue()
181 const headers = new HttpHeaders().set('Authorization', authHeaderValue)
182
74fd2643 183 this.http.post<{ redirectUrl?: string }>(AuthService.BASE_REVOKE_TOKEN_URL, {}, { headers })
1378c0d3
C
184 .subscribe({
185 next: res => {
186 if (res.redirectUrl) {
187 window.location.href = res.redirectUrl
188 }
189 },
dadc90bc 190
42b40636 191 error: err => logger.error(err)
1378c0d3 192 })
dadc90bc 193
df98563e 194 this.user = null
724fed29 195
df98563e 196 this.setStatus(AuthStatus.LoggedOut)
c13e2bf3
RK
197
198 this.hotkeysService.remove(this.hotkeys)
bd5c83a8
C
199 }
200
df98563e 201 refreshAccessToken () {
47f8de28
C
202 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
203
42b40636 204 logger.info('Refreshing token...')
bd5c83a8 205
df98563e 206 const refreshToken = this.getRefreshToken()
bd5c83a8 207
d592e0a9
C
208 // Form url encoded
209 const body = new HttpParams().set('refresh_token', refreshToken)
210 .set('client_id', this.clientId)
211 .set('client_secret', this.clientSecret)
212 .set('response_type', 'code')
213 .set('grant_type', 'refresh_token')
bd5c83a8 214
d592e0a9 215 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
bd5c83a8 216
47f8de28 217 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
2570fd9c
C
218 .pipe(
219 map(res => this.handleRefreshToken(res)),
220 tap(() => {
221 this.refreshingTokenObservable = null
222 }),
223 catchError(err => {
224 this.refreshingTokenObservable = null
225
226 logger.error(err)
227 logger.info('Cannot refresh token -> logout...')
228 this.logout()
229
230 const externalLoginUrl = PluginsManager.getDefaultLoginHref(environment.apiUrl, this.serverService.getHTMLConfig())
231 if (externalLoginUrl) window.location.href = externalLoginUrl
232 else this.router.navigate([ '/login' ])
233
234 return observableThrowError(() => ({
235 error: $localize`You need to reconnect.`
236 }))
237 }),
238 share()
239 )
47f8de28
C
240
241 return this.refreshingTokenObservable
4fd8aa32
C
242 }
243
d592e0a9 244 refreshUserInformation () {
c199c427 245 const obj: UserLoginWithUsername = {
33c4972d
C
246 access_token: this.user.getAccessToken(),
247 refresh_token: null,
248 token_type: this.user.getTokenType(),
249 username: this.user.username
df98563e 250 }
af5e743b 251
d592e0a9 252 this.mergeUserInformation(obj)
1378c0d3
C
253 .subscribe({
254 next: res => {
db400f44 255 this.user.patch(res)
cadb46d8 256
db400f44
C
257 this.userInformationLoaded.next(true)
258 }
1378c0d3 259 })
af5e743b
C
260 }
261
d12b40fb
C
262 isOTPMissingError (err: HttpErrorResponse) {
263 if (err.status !== HttpStatusCode.UNAUTHORIZED_401) return false
264
265 if (err.headers.get('x-peertube-otp') !== 'required; app') return false
266
267 return true
268 }
269
d592e0a9
C
270 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
271 // User is not loaded yet, set manually auth header
272 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
273
bcd9f81e 274 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
db400f44 275 .pipe(map(res => Object.assign(obj, res)))
b1794c53
C
276 }
277
d592e0a9 278 private handleLogin (obj: UserLoginWithUserInformation) {
7da18e44 279 const hashTokens = {
df98563e
C
280 accessToken: obj.access_token,
281 tokenType: obj.token_type,
282 refreshToken: obj.refresh_token
283 }
bd5c83a8 284
ce5496d6 285 this.user = new AuthUser(obj, hashTokens)
bd5c83a8 286
df98563e 287 this.setStatus(AuthStatus.LoggedIn)
efc32059 288 this.userInformationLoaded.next(true)
c13e2bf3
RK
289
290 this.hotkeysService.add(this.hotkeys)
bd5c83a8
C
291 }
292
d592e0a9 293 private handleRefreshToken (obj: UserRefreshToken) {
df98563e 294 this.user.refreshTokens(obj.access_token, obj.refresh_token)
a9bfa85d 295 this.tokensRefreshed.next()
bd5c83a8 296 }
629d8d6f 297
df98563e
C
298 private setStatus (status: AuthStatus) {
299 this.loginChanged.next(status)
629d8d6f 300 }
b1794c53 301}