Added different redirect types.

This commit is contained in:
Tom Butcher 2025-08-24 11:06:10 +01:00
parent 509d74ad99
commit 3f22d1c731

View File

@ -32,6 +32,7 @@ const lookupUserByToken = async (token) => {
// Check cache first // Check cache first
const cachedUser = tokenUserCache.get(token); const cachedUser = tokenUserCache.get(token);
if (cachedUser) { if (cachedUser) {
console.log(cachedUser);
logger.debug(`User found in token cache for token: ${token.substring(0, 20)}...`); logger.debug(`User found in token cache for token: ${token.substring(0, 20)}...`);
return cachedUser; return cachedUser;
} }
@ -79,14 +80,14 @@ const removeUserFromTokenCache = (token) => {
}; };
// Login handler // Login handler
export const loginRouteHandler = (req, res, isApp = false) => { export const loginRouteHandler = (req, res, redirectType = 'web') => {
// Get the redirect URL from form data or default to production overview // Get the redirect URL from form data or default to production overview
const redirectUrl = req.query.redirect_uri || '/production/overview'; const redirectUrl = req.query.redirect_uri || '/production/overview';
// Store the original URL to redirect after login // Store the original URL to redirect after login
const authUrl = `${process.env.KEYCLOAK_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/auth`; const authUrl = `${process.env.KEYCLOAK_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/auth`;
const callBackState = isApp ? '/auth/app/callback' : '/auth/callback'; const callBackState = `/auth/${redirectType}/callback`;
const callbackUrl = encodeURIComponent(`${process.env.APP_URL_API}${callBackState}`); const callbackUrl = `${process.env.APP_URL_API}${callBackState}`;
const state = encodeURIComponent(redirectUrl); const state = encodeURIComponent(redirectUrl);
logger.warn(req.query.redirect_uri); logger.warn(req.query.redirect_uri);
@ -138,7 +139,7 @@ const fetchAndStoreUser = async (req, token) => {
}; };
// Function to exchange authorization code for tokens, fetch user, and set session // Function to exchange authorization code for tokens, fetch user, and set session
export const loginTokenRouteHandler = async (req, res, isApp = false) => { export const loginTokenRouteHandler = async (req, res, redirectType = 'web') => {
const code = req.query.code; const code = req.query.code;
if (!code) { if (!code) {
return res.status(400).json({ error: 'Authorization code missing' }); return res.status(400).json({ error: 'Authorization code missing' });
@ -153,7 +154,7 @@ export const loginTokenRouteHandler = async (req, res, isApp = false) => {
// Otherwise, start the request and store the promise // Otherwise, start the request and store the promise
const tokenPromise = (async () => { const tokenPromise = (async () => {
const callBackState = isApp ? '/auth/app/callback' : '/auth/callback'; const callBackState = `/auth/${redirectType}/callback`;
const callbackUrl = `${process.env.APP_URL_API}${callBackState}`; const callbackUrl = `${process.env.APP_URL_API}${callBackState}`;
const tokenUrl = `${process.env.KEYCLOAK_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`; const tokenUrl = `${process.env.KEYCLOAK_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`;
@ -191,12 +192,13 @@ export const loginTokenRouteHandler = async (req, res, isApp = false) => {
const userAndTokenData = await tokenPromise; const userAndTokenData = await tokenPromise;
res.status(200).json(userAndTokenData); res.status(200).json(userAndTokenData);
} catch (err) { } catch (err) {
res.status(500).json({ error: err.message }); var error = err?.response?.data?.error_description || err.message;
res.status(err?.status || 500).json({ error: error });
} }
}; };
// Login callback handler // Login callback handler
export const loginCallbackRouteHandler = async (req, res, isApp = false) => { export const loginCallbackRouteHandler = async (req, res, redirectType = 'web') => {
// Don't use keycloak.protect() here as it expects an already authenticated session // Don't use keycloak.protect() here as it expects an already authenticated session
// Extract the code and state from the query parameters // Extract the code and state from the query parameters
@ -207,9 +209,21 @@ export const loginCallbackRouteHandler = async (req, res, isApp = false) => {
return res.status(400).send('Authorization code missing'); return res.status(400).send('Authorization code missing');
} }
const appUrl = isApp var appUrl;
? 'farmcontrol://app' switch (redirectType) {
: process.env.APP_URL_CLIENT || 'http://localhost:3000'; case 'web':
appUrl = process.env.APP_URL_CLIENT || 'http://localhost:3000';
break;
case 'app-scheme':
appUrl = 'farmcontrol://app';
break;
case 'app-localhost':
appUrl = process.env.APP_DEV_AUTH_CLIENT || 'http://localhost:3500';
break;
default:
appUrl = process.env.APP_URL_CLIENT || 'http://localhost:3000';
break;
}
const redirectUriRaw = `${appUrl}${state}`; const redirectUriRaw = `${appUrl}${state}`;
let redirectUri; let redirectUri;
try { try {
@ -227,7 +241,7 @@ export const loginCallbackRouteHandler = async (req, res, isApp = false) => {
} }
// Save session and redirect to the original URL // Save session and redirect to the original URL
req.session.save(async () => { req.session.save(async () => {
if (isApp) { if (redirectType == 'app-scheme') {
// Read HTML template and inject redirectUri // Read HTML template and inject redirectUri
const templatePath = resolve(process.cwd(), 'src/services/misc/applaunch.html'); const templatePath = resolve(process.cwd(), 'src/services/misc/applaunch.html');
let html = readFileSync(templatePath, 'utf8'); let html = readFileSync(templatePath, 'utf8');