const jwt = require('jsonwebtoken'); const User = require('../models/user'); async function ssoHandler(req, res, next) { // 1. Check if the token is in the query parameters const { token } = req.query; if (token) { try { // 2. Decode the JWT to get the payload // In a real app, you MUST verify the token signature using jwt.verify() // For this demo, we'll just decode to inspect the payload. const decoded = jwt.decode(token); if (!decoded || !decoded.sub) { return res.status(400).send('Invalid token: "sub" claim is missing.'); } // 3. Find user by 'sub' claim let user = await User.findBySsoSub(decoded.sub); // 4. If user doesn't exist, create a new one (auto-registration) if (!user) { user = await User.createUser({ sso_sub: decoded.sub }); } // 5. Save user information in the session req.session.userId = user.id; // 6. Redirect to the same URL without the token parameter const redirectUrl = req.path; return res.redirect(redirectUrl); } catch (error) { console.error('SSO handling failed:', error); return res.status(500).send('An error occurred during SSO processing.'); } } // Attach user to request if session exists if (req.session.userId) { res.locals.user = await User.findById(req.session.userId); } else { res.locals.user = null; } return next(); } module.exports = ssoHandler;