Skip to content

Commit

Permalink
feat(authentication wip): get refresh token
Browse files Browse the repository at this point in the history
  • Loading branch information
MatsJohansen87 committed Apr 30, 2024
1 parent d558973 commit e32ecba
Show file tree
Hide file tree
Showing 2 changed files with 260 additions and 201 deletions.
137 changes: 72 additions & 65 deletions packages/lib/src/stores/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,96 +4,103 @@
*/
import { writable } from "svelte/store";

export const authStore = writable<string | null>("");
export const authStore = writable<string>("");

fetchAccessToken();

export async function fetchAccessToken() {
/**
* Fetches the access token from the backend service
*/
export async function fetchAccessToken(): Promise<void> {
const response = await fetch(`/oauth2/auth`, {
method: "GET",
credentials: "include",

})

});

const temporaryToken = response.headers.get("Authorization");

if (!temporaryToken) {
console.error("No temporary token found in response headers");
return;
}
console.log('temporaryToken', temporaryToken);
exchangeCodeForToken(temporaryToken)

console.log("temporaryToken", temporaryToken);
exchangeCodeForToken(temporaryToken);
}

// Placeholder values, replace these with your actual configurations
const clientId = 'bridgehead-test-private';
const clientSecret = 'mmDjwfaoLeTzdRUeGZRDEIaYXgY3zL6r';
const redirectUri = window.location.origin
const tokenEndpoint = 'https://login.verbis.dkfz.de/realms/test-realm-01/protocol/openid-connect/auth';
const clientId = "bridgehead-test-private";
const clientSecret = "mmDjwfaoLeTzdRUeGZRDEIaYXgY3zL6r";
// const redirectUri = window.location.origin
const tokenEndpoint =
"https://login.verbis.dkfz.de/realms/test-realm-01/protocol/openid-connect/auth";
const refreshTokenTimeInSeconds = 300; // 5 minutes

let accessToken = '';
let refreshToken = '';
let accessToken = "";
let refreshToken = "";

// Function to perform the OAuth2 token exchange
async function exchangeCodeForToken(code) {
const requestBody = new URLSearchParams();
requestBody.append('grant_type', 'authorization_code');
requestBody.append('client_id', clientId);
// requestBody.append('redirect_uri', redirectUri);
requestBody.append('code', code);
/**
* exchanges the temporary code received from the OAuth2 provider for an access token
* @param code the temporary code received from the OAuth2 provider
*/
async function exchangeCodeForToken(code: string): Promise<void> {
const requestBody = new URLSearchParams();
requestBody.append("grant_type", "refresh_token");
requestBody.append("client_id", clientId);
// requestBody.append('redirect_uri', redirectUri);
requestBody.append("code", code);

try {
const response = await fetch(tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: requestBody,
});
try {
const response = await fetch(tokenEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: requestBody,
});

const responseData = await response.json();
accessToken = responseData.access_token;
refreshToken = responseData.refresh_token;
const responseData = await response.json();
accessToken = responseData.access_token;
refreshToken = responseData.refresh_token;

console.log('refreshToken', refreshToken);
console.log('accessToken', accessToken);
startTokenRefreshTimer();
return true;
} catch (error) {
console.error('Token exchange failed:', error);
return false;
}
console.log("refreshToken", refreshToken);
console.log("accessToken", accessToken);
startTokenRefreshTimer();
} catch (error) {
console.error("Token exchange failed:", error);
}
}

// Function to refresh the access token using the refresh token
async function refreshAccessToken() {
const requestBody = new URLSearchParams();
requestBody.append('grant_type', 'refresh_token');
requestBody.append('client_id', clientId);
requestBody.append('client_secret', clientSecret);
requestBody.append('refresh_token', refreshToken);
/**
* Function to refresh the access token using the refresh token
*/
async function refreshAccessToken(): Promise<void> {
const requestBody = new URLSearchParams();
requestBody.append("grant_type", "refresh_token");
requestBody.append("client_id", clientId);
requestBody.append("client_secret", clientSecret);
requestBody.append("refresh_token", refreshToken);

try {
const response = await fetch(tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: requestBody,
});
try {
const response = await fetch(tokenEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: requestBody,
});

const responseData = await response.json();
accessToken = responseData.access_token;
startTokenRefreshTimer();
console.log('Token refreshed');
} catch (error) {
console.error('Token refresh failed:', error);
}
const responseData = await response.json();
accessToken = responseData.access_token;
startTokenRefreshTimer();
console.log("Token refreshed");
} catch (error) {
console.error("Token refresh failed:", error);
}
}

// Function to start the token refresh timer
function startTokenRefreshTimer() {
setInterval(refreshAccessToken, refreshTokenTimeInSeconds * 1000);
/**
* Function to start the token refresh timer
*/
function startTokenRefreshTimer(): void {
setInterval(refreshAccessToken, refreshTokenTimeInSeconds * 1000);
}
Loading

0 comments on commit e32ecba

Please sign in to comment.