-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add WebApiService to handle generic access and refresh token logic (#541
- Loading branch information
Showing
8 changed files
with
247 additions
and
76 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import React, { createContext, useContext } from 'react'; | ||
import { WebApiService } from '../services/WebApiService'; | ||
import { useAuth } from './AuthContext'; | ||
|
||
const WebApiContext = createContext<WebApiService | null>(null); | ||
|
||
export const WebApiProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { | ||
const { getAccessToken, getRefreshToken, login, logout } = useAuth(); | ||
|
||
const webApiService = new WebApiService( | ||
() => getAccessToken(), | ||
() => getRefreshToken(), | ||
(newAccessToken, newRefreshToken) => { | ||
login(username!, newAccessToken, newRefreshToken); | ||
}, | ||
logout | ||
); | ||
|
||
return ( | ||
<WebApiContext.Provider value={webApiService}> | ||
{children} | ||
</WebApiContext.Provider> | ||
); | ||
}; | ||
|
||
export const useWebApi = () => { | ||
const context = useContext(WebApiContext); | ||
if (!context) { | ||
throw new Error('useWebApi must be used within a WebApiProvider'); | ||
} | ||
return context; | ||
}; |
132 changes: 132 additions & 0 deletions
132
browser-extensions/chrome/src/services/WebApiService.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
import { Buffer } from 'buffer'; | ||
|
||
interface TokenResponse { | ||
token: string; | ||
refreshToken: string; | ||
} | ||
|
||
export class WebApiService { | ||
private baseUrl: string = 'https://localhost:7223/v1/'; // Should be configurable | ||
|
||
constructor( | ||
private getAccessToken: () => string | null, | ||
private getRefreshToken: () => string | null, | ||
private updateTokens: (accessToken: string, refreshToken: string) => void, | ||
private handleLogout: () => void | ||
) {} | ||
|
||
public async fetch<T>( | ||
endpoint: string, | ||
options: RequestInit = {} | ||
): Promise<T> { | ||
const url = this.baseUrl + endpoint; | ||
const headers = new Headers(options.headers || {}); | ||
|
||
// Add authorization header if we have an access token | ||
const accessToken = this.getAccessToken(); | ||
console.log('accessToken in webapi:', accessToken); | ||
if (accessToken) { | ||
headers.set('Authorization', `Bearer ${accessToken}`); | ||
} | ||
|
||
const requestOptions: RequestInit = { | ||
...options, | ||
headers, | ||
}; | ||
|
||
try { | ||
const response = await fetch(url, requestOptions); | ||
|
||
if (response.status === 401) { | ||
const newToken = await this.refreshAccessToken(); | ||
if (newToken) { | ||
headers.set('Authorization', `Bearer ${newToken}`); | ||
const retryResponse = await fetch(url, { | ||
...requestOptions, | ||
headers, | ||
}); | ||
|
||
if (!retryResponse.ok) { | ||
throw new Error('Request failed after token refresh'); | ||
} | ||
|
||
return retryResponse.json(); | ||
} else { | ||
this.handleLogout(); | ||
throw new Error('Session expired'); | ||
} | ||
} | ||
|
||
if (!response.ok) { | ||
throw new Error(`HTTP error! status: ${response.status}`); | ||
} | ||
|
||
return response.json(); | ||
} catch (error) { | ||
console.error('API request failed:', error); | ||
throw error; | ||
} | ||
} | ||
|
||
private async refreshAccessToken(): Promise<string | null> { | ||
const refreshToken = this.getRefreshToken(); | ||
if (!refreshToken) { | ||
return null; | ||
} | ||
|
||
try { | ||
const response = await fetch(`${this.baseUrl}Auth/refresh`, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
'X-Ignore-Failure': 'true', | ||
}, | ||
body: JSON.stringify({ | ||
token: this.getAccessToken(), | ||
refreshToken: refreshToken, | ||
}), | ||
}); | ||
|
||
if (!response.ok) { | ||
throw new Error('Failed to refresh token'); | ||
} | ||
|
||
const tokenResponse: TokenResponse = await response.json(); | ||
this.updateTokens(tokenResponse.token, tokenResponse.refreshToken); | ||
return tokenResponse.token; | ||
} catch (error) { | ||
console.error('Token refresh failed:', error); | ||
this.handleLogout(); | ||
return null; | ||
} | ||
} | ||
|
||
// Helper methods for common operations | ||
public async get<T>(endpoint: string): Promise<T> { | ||
return this.fetch<T>(endpoint, { method: 'GET' }); | ||
} | ||
|
||
public async post<T>(endpoint: string, data: any): Promise<T> { | ||
return this.fetch<T>(endpoint, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify(data), | ||
}); | ||
} | ||
|
||
public async put<T>(endpoint: string, data: any): Promise<T> { | ||
return this.fetch<T>(endpoint, { | ||
method: 'PUT', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify(data), | ||
}); | ||
} | ||
|
||
public async delete<T>(endpoint: string): Promise<T> { | ||
return this.fetch<T>(endpoint, { method: 'DELETE' }); | ||
} | ||
} |
Oops, something went wrong.