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

add token validation in qwik server #698

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
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
8 changes: 6 additions & 2 deletions apps/frontend/src/shared/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Cookie } from '@builder.io/qwik-city';
import jwt_decode from 'jwt-decode';
import { UserCtx } from '../routes/layout';
import { validateToken } from '../utils/api';

export const ACCESS_COOKIE_NAME = 'accessToken';
export const REFRESH_COOKIE_NAME = 'refreshToken';
Expand Down Expand Up @@ -33,8 +34,11 @@ export const validateAccessToken = async (cookies: Cookie): Promise<boolean> =>
setTokensAsCookies(newAccessToken, newRefreshToken, cookies);
return validateAccessToken(cookies);
}

return true;
const tokenIsValid = await validateToken(accessToken);
if (!tokenIsValid) {
setTokensAsCookies('', '', cookies);
}
return tokenIsValid;
};

export const setTokensAsCookies = (accessToken: string, refreshToken: string, cookie: Cookie) => {
Expand Down
26 changes: 26 additions & 0 deletions apps/frontend/src/utils/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { ACCESS_COOKIE_NAME } from '../shared/auth.service';

const cache = {
accessToken: '',
};
export const validateToken = async (accessToken: string): Promise<boolean> => {
if (accessToken === cache.accessToken) {
return true;
}
try {
const res = await fetch(`${process.env.API_DOMAIN}/api/v1/auth/check-auth`, {
method: 'GET',
credentials: 'include',
headers: {
cookie: `${ACCESS_COOKIE_NAME}=${accessToken}`,
},
});
if (res.ok) {
cache.accessToken = accessToken;
return true;
}
} catch (err) {
console.error('Failed to validate access token', err);
}
return false;
};