1 import { HttpStatusCode, OAuth2ErrorCode, UserRefreshToken } from '../../../../../shared/models'
2 import { OAuthUserTokens, objectToUrlEncoded } from '../../../root-helpers'
3 import { peertubeLocalStorage } from '../../../root-helpers/peertube-web-storage'
5 export class AuthHTTP {
6 private readonly LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
7 CLIENT_ID: 'client_id',
8 CLIENT_SECRET: 'client_secret'
11 private userOAuthTokens: OAuthUserTokens
13 private headers = new Headers()
16 this.userOAuthTokens = OAuthUserTokens.getUserTokens(peertubeLocalStorage)
18 if (this.userOAuthTokens) this.setHeadersFromTokens()
21 fetch (url: string, { optionalAuth, method }: { optionalAuth: boolean, method?: string }) {
22 const refreshFetchOptions = optionalAuth
23 ? { headers: this.headers }
26 return this.refreshFetch(url.toString(), { ...refreshFetchOptions, method })
29 getHeaderTokenValue () {
30 return `${this.userOAuthTokens.tokenType} ${this.userOAuthTokens.accessToken}`
34 return !!this.userOAuthTokens
37 private refreshFetch (url: string, options?: RequestInit) {
38 return fetch(url, options)
39 .then((res: Response) => {
40 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
42 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
43 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
44 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
46 const headers = new Headers()
47 headers.set('Content-Type', 'application/x-www-form-urlencoded')
50 refresh_token: this.userOAuthTokens.refreshToken,
52 client_secret: clientSecret,
53 response_type: 'code',
54 grant_type: 'refresh_token'
57 fetch('/api/v1/users/token', {
60 body: objectToUrlEncoded(data)
62 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
65 }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => {
66 if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) {
67 OAuthUserTokens.flushLocalStorage(peertubeLocalStorage)
68 this.removeTokensFromHeaders()
73 this.userOAuthTokens.accessToken = obj.access_token
74 this.userOAuthTokens.refreshToken = obj.refresh_token
75 OAuthUserTokens.saveToLocalStorage(peertubeLocalStorage, this.userOAuthTokens)
77 this.setHeadersFromTokens()
80 }).catch((refreshTokenError: any) => {
81 reject(refreshTokenError)
85 return refreshingTokenPromise
87 OAuthUserTokens.flushLocalStorage(peertubeLocalStorage)
89 this.removeTokensFromHeaders()
90 }).then(() => fetch(url, {
98 private setHeadersFromTokens () {
99 this.headers.set('Authorization', this.getHeaderTokenValue())
102 private removeTokensFromHeaders () {
103 this.headers.delete('Authorization')