import unirest from 'unirest'; import { randomBytes } from 'crypto'; const temporaryLinks = new Map(); setInterval(() => { const now = Date.now(); for (const [linkId, linkData] of temporaryLinks.entries()) { if (linkData.expiresAt < now) temporaryLinks.delete(linkId); } }, parseInt(process.env.TEMP_LINKS_CLEANUP_INTERVAL_MS, 10)); export async function generateLoginLink(req, res) { try { const { secretKey, username } = req.body; if (secretKey !== process.env.ADMIN_SECRET_KEY) return res.status(401).json({ error: 'Invalid secret key' }); if (!username) return res.status(400).json({ error: 'Username is required' }); const tokenResponse = await unirest .post(process.env.AUTH_ENDPOINT) .headers({ 'Accept': 'application/json', 'Content-Type': 'application/json' }) .send({ username, password: process.env.AUTH_PASSWORD }); if (!tokenResponse.body.token) return res.status(500).json({ error: 'Failed to generate API key' }); const apiKey = tokenResponse.body.token; const linkId = randomBytes(parseInt(process.env.LINK_ID_BYTES, 10)).toString('hex'); const loginLink = `${process.env.AUTO_LOGIN_LINK_PREFIX}${linkId}`; temporaryLinks.set(linkId, { apiKey, username, expiresAt: Date.now() + parseInt(process.env.LINK_EXPIRY_SECONDS, 10) * 1000 }); setTimeout(() => temporaryLinks.delete(linkId), parseInt(process.env.LINK_EXPIRY_SECONDS, 10) * 1000); res.json({ loginLink }); } catch (error) { res.status(500).json({ error: 'Internal server error' }); } } export function handleAutoLogin(req, res) { const { linkId } = req.params; const linkData = temporaryLinks.get(linkId); if (!linkData || linkData.expiresAt < Date.now()) { temporaryLinks.delete(linkId); return res.send(`

Login Expired.

Redirecting...

`); } temporaryLinks.delete(linkId); res.send(` Auto Login

Logging in...

`); }