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

如何在特定时段自动登出用户?基于passport.js的实现咨询

使用Passport.js实现营业时间内登录限制与自动登出

后端验证与会话销毁

1. 登录时的时间校验

在Passport的登录策略中加入时间检查,非营业时间直接拒绝登录请求:

passport.use(new LocalStrategy(
  function(username, password, done) {
    const now = new Date();
    const hour = now.getHours();
    // 校验是否在7:00-19:00之间
    if (hour < 7 || hour >= 19) {
      return done(null, false, { message: '当前非营业时间,无法登录' });
    }
    // 原有用户账号密码验证逻辑
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false, { message: '用户名错误' }); }
      if (!user.validPassword(password)) { return done(null, false, { message: '密码错误' }); }
      return done(null, user);
    });
  }
));

2. 全局会话校验中间件

创建中间件,对所有已登录用户的请求做时间校验,非营业时间直接销毁会话:

function checkBusinessHours(req, res, next) {
  if (req.isAuthenticated()) {
    const now = new Date();
    const hour = now.getHours();
    if (hour < 7 || hour >= 19) {
      req.logout(function(err) {
        if (err) { return next(err); }
        return res.redirect('/login?message=非营业时间已自动登出');
      });
    } else {
      next();
    }
  } else {
    next();
  }
}

// 将中间件应用到需要登录权限的路由
app.use('/dashboard', checkBusinessHours, (req, res) => {
  // 业务逻辑
});

3. 会话过期辅助配置

结合会话有效期设置,双重保障会话安全,比如设置30分钟自动过期:

app.use(session({
  secret: 'your-custom-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: { 
    maxAge: 30 * 60 * 1000, // 30分钟有效期
    secure: process.env.NODE_ENV === 'production'
  }
}));

前端定时检查与主动登出

1. 定时任务触发时间校验

登录成功后启动定时器,每隔5分钟检查当前时间,非营业时间主动调用登出接口:

let checkInterval;

function startBusinessHourCheck() {
  checkInterval = setInterval(() => {
    const now = new Date();
    const hour = now.getHours();
    if (hour < 7 || hour >= 19) {
      fetch('/logout', { method: 'POST' })
        .then(() => {
          window.location.href = '/login?message=非营业时间已自动登出';
        })
        .catch(err => console.error('登出失败:', err));
      clearInterval(checkInterval);
    }
  }, 5 * 60 * 1000); // 每5分钟检查一次
}

// 页面加载时,若已登录则启动检查
document.addEventListener('DOMContentLoaded', () => {
  // 从后端模板注入登录状态标识
  const isLoggedIn = document.body.dataset.loggedIn === 'true';
  if (isLoggedIn) {
    startBusinessHourCheck();
  }
});

2. 页面可见性监听

避免页面后台运行时定时器暂停,重新激活页面时立即校验时间:

document.addEventListener('visibilitychange', () => {
  if (!document.hidden) {
    const now = new Date();
    const hour = now.getHours();
    if (hour < 7 || hour >= 19) {
      fetch('/logout', { method: 'POST' })
        .then(() => window.location.href = '/login?message=非营业时间已自动登出')
        .catch(err => console.error('登出失败:', err));
    }
  }
});

3. 清理定时器避免内存泄漏

页面卸载时清除定时器:

window.addEventListener('beforeunload', () => {
  if (checkInterval) {
    clearInterval(checkInterval);
  }
});

内容的提问来源于stack exchange,提问作者Kenny Johnson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:35:21