You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Node.js+EJS的登录系统:安全重定向、权限验证与页面数据传递问题求助

Solution for Auth Validation & Data Sharing Without Passport

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>

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 like process.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) or connect-redis.
  • HTTPS: If your site uses HTTPS, set cookie.secure: true to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:32:27