且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何限制在 Django 中登录到同一帐户的并发用户数

更新时间:2023-12-01 17:20:22

要限制并发用户,请留意现有的 会话.

To limit the concurrent users, keep an eye on the existing sessions.

在您当前的方法中,当用户登录时,会创建一个新会话.该新会话与旧会话共存,因此您同时有 N 个并发会话.

In your current approach, when a user logs in, a new session is created. That new session co-exists with the older sessions, so you have N concurrent sessions at the same time.

您希望允许单个会话.最简单的方法是在发生新登录时使旧会话无效:

You want to allow a single session. The easiest approach would be to invalidate older session when a new login happens:

  • detect/extend the login event (use the "user_logged_in" signal)
  • for each login, remove the other existing sessions from the same user (see "Clearing the session store")

其他(更完整但更复杂)的方法是使用 双因素身份验证、按 IP 阻止、限制登录事件、需要电子邮件确认等...

Other (more complete, but more complex) approaches would be using Two-factor authentication, blocking per IP, throttling the login event, requiring email confirmation, etc...