Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Harden middleware for unenforced login #1091

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions website/src/middleware/authMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export async function getKeycloakClient() {
}

export const getAuthUrl = async (redirectUrl: string) => {
// redirectUrl = removeTokenCodeFromSearchParams(new URL(redirectUrl)).toString().replace('http://', 'https://');
const authUrl = (await getKeycloakClient()).authorizationUrl({
redirect_uri: redirectUrl,
scope: 'openid',
Expand All @@ -57,10 +58,44 @@ export const getAuthUrl = async (redirectUrl: string) => {
return authUrl;
};

async function getValidTokenFromCookies(context: APIContext) {
const token = await getTokenFromCookie(context);
if (token !== undefined) {
const userInfo = await getUserInfo(token);

if (userInfo.isErr()) {
logger.debug(`Cookie token found but could not get user info`);
deleteCookie(context);
return undefined;
}
setCookie(context, token);
return token;
}
return undefined;
}



async function getValidTokenFromParams(context: APIContext) {
const token = await getTokenFromParams(context);
if (token !== undefined) {
const userInfo = await getUserInfo(token);

if (userInfo.isErr()) {
logger.debug(`Token found in params but could not get user info`);
return undefined;
}

return token;
}
return undefined;
}


export const authMiddleware = defineMiddleware(async (context, next) => {
let token = await getTokenFromCookie(context);
let token = await getValidTokenFromCookies(context);
if (token === undefined) {
token = await getTokenFromParams(context);
token = await getValidTokenFromParams(context);
if (token !== undefined) {
logger.debug(`Token found in params, setting cookie`);
setCookie(context, token);
Expand All @@ -86,6 +121,9 @@ export const authMiddleware = defineMiddleware(async (context, next) => {
context.locals.session = {
isLoggedIn: false,
};
logger.debug(`Error getting user info: ${userInfo.error}`);
logger.debug(`Clearing auth cookies.`);
deleteCookie(context);
return next();
}

Expand Down
Loading