登陆优化

This commit is contained in:
Azmat@qq.com
2026-09-17 10:28:37 +08:00
parent b487b65575
commit bd4799151c
8 changed files with 222 additions and 95 deletions
+40 -1
View File
@@ -4,7 +4,7 @@ from django.conf import settings
from django.test import TestCase
from rest_framework.test import APIClient
from apps.accounts.models import Invitation, Team, TeamMember, User
from apps.accounts.models import Invitation, LoginSession, Team, TeamMember, User
from apps.billing.models import CreditAccount, CreditLedger
@@ -65,6 +65,45 @@ class AuthApiTests(TestCase):
self.assertEqual(genesis.count(), 0)
class SingleDeviceLoginTests(TestCase):
def setUp(self):
self.user = User.objects.create_user(username="single-device", password="strong-password")
def test_new_login_invalidates_previous_device_and_session(self):
first = APIClient()
first_login = first.post(
"/api/auth/login/",
{"username": self.user.username, "password": "strong-password"},
format="json",
HTTP_USER_AGENT="Device A",
REMOTE_ADDR="10.0.0.1",
)
self.assertEqual(first_login.status_code, 200)
first_token = first_login.data["token"]
second = APIClient()
second_login = second.post(
"/api/auth/login/",
{"username": self.user.username, "password": "strong-password"},
format="json",
HTTP_USER_AGENT="Device B",
REMOTE_ADDR="10.0.0.2",
)
self.assertEqual(second_login.status_code, 200)
second_token = second_login.data["token"]
self.assertNotEqual(second_token, first_token)
first.credentials(HTTP_AUTHORIZATION=f"Token {first_token}")
self.assertEqual(first.get("/api/auth/me/").status_code, 401)
second.credentials(HTTP_AUTHORIZATION=f"Token {second_token}")
self.assertEqual(second.get("/api/auth/me/").status_code, 200)
active = LoginSession.objects.filter(user=self.user, revoked_at__isnull=True)
self.assertEqual(active.count(), 1)
self.assertEqual(active.get().user_agent, "Device B")
class InvitationFlowTests(TestCase):
def _register(self, client, username, **extra):
return client.post(