基于Node.js+EJS的登录系统:安全重定向、权限验证与页面数据传递问题求助
Since you've struggled with Passport for 6 weeks and can't modify your existing login system, let's go with a simple, no-Passport approach using Express sessions and custom middleware. This will fix both your permission issue and data sharing problem.
Step 1: Set Up Express Session
First, we'll use express-session to store user data server-side after login. Install it first:
npm install express-session
Add this middleware to your app's main file (like app.js or server.js) before your routes:
const session = require('express-session'); app.use(session({ secret: 'your-strong-random-secret-key', // Replace with a unique secret (keep this safe in production!) resave: false, saveUninitialized: false, cookie: { secure: false, // Set to true if you're using HTTPS in production maxAge: 24 * 60 * 60 * 1000 // Session expires after 1 day (adjust as needed) } }));
Step 2: Store User Data in Session on Login
Modify your existing login success code to save the name and uid to the session. This way, the data persists across page loads:
if (code.data == "201") { let uid = req.body.uid; // Save user data to session req.session.user = { name, uid }; // Pass the session data to your dashboard template (same as before, but now it's from session) res.render('dashboard', { user: req.session.user }) } if (code.data == "403") { console.log('Invalid Creds!') } if (code.data == "404") { console.log('User not found') }
Step 3: Create an Auth Check Middleware
This middleware will block access to protected routes if the user isn't logged in. Add this function anywhere in your main file (before routes):
function checkAuth(req, res, next) { // Check if user exists in session if (req.session.user) { return next(); // User is logged in, proceed to the route } // User isn't logged in: redirect to login page (or send 403 error) res.redirect('/login'); // Replace with your actual login route // If this was an API endpoint, you could do: res.status(403).send('Unauthorized'); }
Step 4: Protect Your Routes
Add the checkAuth middleware to any routes you want to restrict (like /new and even /dashboard to prevent direct access):
// Protect /dashboard app.get('/dashboard', checkAuth, (req, res) => { res.render('dashboard', { user: req.session.user }); }); // Protect /new and pass user data to the template app.get('/new', checkAuth, (req, res) => { // Session data is available here, so pass it to your EJS template res.render('new', { user: req.session.user }); });
Step 5: Access Data in EJS Templates
In your /new EJS file, you can now access the user data just like you did in /dashboard:
<!-- Example in new.ejs --> <h1>Welcome <%= user.name %>!</h1> <p>Your UID is: <%= user.uid %></p>
Step 6: Add Logout Functionality (Optional but Recommended)
Let users invalidate their session when logging out:
app.get('/logout', (req, res) => { req.session.destroy(err => { if (err) { console.error('Logout error:', err); } res.redirect('/login'); }); });
Notes for Production
- Secret Key: Use a long, random string for
secret(never hardcode it in production—use environment variables likeprocess.env.SESSION_SECRET). - Session Persistence: The default session store is in-memory, which means sessions are lost when the server restarts. For production, use a persistent store like
connect-mongo(to store sessions in MongoDB) orconnect-redis. - HTTPS: If your site uses HTTPS, set
cookie.secure: trueto ensure cookies are only sent over secure connections.
This solution doesn't require modifying your core login logic (just adding one line to save the session) and avoids the complexity of Passport. It should work seamlessly with your existing Node.js/EJS setup.
内容的提问来源于stack exchange,提问作者pTools

