feat: scaffold Django multi-tenant project with 5 of 9 apps
Phase 1 scaffolding: config/, core/, base models, AES-256-GCM phone encryption, enums mirror apps.tenant: Tenant + Domain (django-tenants) apps.org: 11 models (OrgUnit hierarchy, Staff, audit logs) apps.account: 4 models (UserAccount as AUTH_USER_MODEL, login/password tracking) apps.permission: 7 models (RBAC + overrides + datascope + append-only changelog) apps.region: 5 models (District, BusinessArea, MetroLine, MetroStation, School) All migrations generated, manage.py check passes
This commit is contained in:
0
apps/account/__init__.py
Normal file
0
apps/account/__init__.py
Normal file
7
apps/account/apps.py
Normal file
7
apps/account/apps.py
Normal file
@@ -0,0 +1,7 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class AccountConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "apps.account"
|
||||
label = "account"
|
||||
81
apps/account/migrations/0001_initial.py
Normal file
81
apps/account/migrations/0001_initial.py
Normal file
@@ -0,0 +1,81 @@
|
||||
# Generated by Django 4.2.16 on 2026-04-29 08:42
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UserAccount',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('password', models.CharField(max_length=128, verbose_name='password')),
|
||||
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
|
||||
('username', models.CharField(max_length=30)),
|
||||
('email', models.EmailField(blank=True, max_length=254, null=True)),
|
||||
('phone_enc', models.TextField(blank=True, help_text='AES-256-GCM ciphertext of phone (core.encryption.PhoneEncryption).', null=True)),
|
||||
('phone_hash', models.CharField(blank=True, max_length=64, null=True)),
|
||||
('is_tenant_admin', models.BooleanField(default=False)),
|
||||
('status', models.CharField(choices=[('active', '启用'), ('disabled', '停用'), ('locked', '锁定')], default='active', max_length=10)),
|
||||
('is_initial_password', models.BooleanField(default=True)),
|
||||
('locked_until', models.DateTimeField(blank=True, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='created_accounts', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'user_accounts',
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='PasswordResetToken',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('token', models.CharField(max_length=86, unique=True)),
|
||||
('expires_at', models.DateTimeField()),
|
||||
('is_used', models.BooleanField(default=False)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reset_tokens', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'password_reset_tokens',
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='PasswordHistory',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('password_hash', models.CharField(max_length=128)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='password_histories', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'password_histories',
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='LoginAttempt',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('username', models.CharField(max_length=30)),
|
||||
('ip_address', models.GenericIPAddressField()),
|
||||
('user_agent', models.TextField(blank=True, null=True)),
|
||||
('success', models.BooleanField()),
|
||||
('failure_reason', models.CharField(blank=True, choices=[('wrong_password', '用户名或密码错误'), ('wrong_captcha', '验证码错误'), ('account_locked', '账号锁定'), ('account_disabled', '账号停用'), ('tenant_not_found', '租户不存在')], max_length=30, null=True)),
|
||||
('attempted_at', models.DateTimeField(auto_now_add=True)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'login_attempts',
|
||||
'indexes': [models.Index(fields=['username'], name='idx_login_attempts_username'), models.Index(fields=['ip_address'], name='idx_login_attempts_ip'), models.Index(fields=['-attempted_at'], name='idx_login_attempts_time'), models.Index(fields=['username', 'success', '-attempted_at'], name='idx_login_attempts_fail_check')],
|
||||
},
|
||||
),
|
||||
]
|
||||
50
apps/account/migrations/0002_initial.py
Normal file
50
apps/account/migrations/0002_initial.py
Normal file
@@ -0,0 +1,50 @@
|
||||
# Generated by Django 4.2.16 on 2026-04-29 08:42
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('account', '0001_initial'),
|
||||
('org', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='useraccount',
|
||||
name='staff',
|
||||
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='account', to='org.staff'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='passwordresettoken',
|
||||
index=models.Index(fields=['user'], name='idx_pw_reset_tokens_user'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='passwordhistory',
|
||||
index=models.Index(fields=['user', '-created_at'], name='idx_pw_histories_user'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='useraccount',
|
||||
index=models.Index(fields=['status'], name='idx_user_accounts_status'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='useraccount',
|
||||
index=models.Index(fields=['staff'], name='idx_user_accounts_staff'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='useraccount',
|
||||
constraint=models.UniqueConstraint(fields=('username',), name='uq_user_accounts_username'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='useraccount',
|
||||
constraint=models.UniqueConstraint(condition=models.Q(('email__isnull', False)), fields=('email',), name='uq_user_accounts_email'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='useraccount',
|
||||
constraint=models.UniqueConstraint(condition=models.Q(('phone_hash__isnull', False)), fields=('phone_hash',), name='uq_user_accounts_phone'),
|
||||
),
|
||||
]
|
||||
0
apps/account/migrations/__init__.py
Normal file
0
apps/account/migrations/__init__.py
Normal file
15
apps/account/models/__init__.py
Normal file
15
apps/account/models/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from apps.account.models.account import (
|
||||
LoginAttempt,
|
||||
PasswordHistory,
|
||||
PasswordResetToken,
|
||||
UserAccount,
|
||||
UserAccountManager,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"LoginAttempt",
|
||||
"PasswordHistory",
|
||||
"PasswordResetToken",
|
||||
"UserAccount",
|
||||
"UserAccountManager",
|
||||
]
|
||||
151
apps/account/models/account.py
Normal file
151
apps/account/models/account.py
Normal file
@@ -0,0 +1,151 @@
|
||||
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
|
||||
from django.db import models
|
||||
from django.utils import timezone
|
||||
|
||||
from core.enums import LoginFailureReason, UserAccountStatus
|
||||
|
||||
|
||||
class UserAccountManager(BaseUserManager):
|
||||
def create_user(self, username, password=None, **extra_fields):
|
||||
if not username:
|
||||
raise ValueError("username 不能为空")
|
||||
user = self.model(username=username, **extra_fields)
|
||||
if password:
|
||||
user.set_password(password)
|
||||
user.save(using=self._db)
|
||||
return user
|
||||
|
||||
|
||||
class UserAccount(AbstractBaseUser):
|
||||
username = models.CharField(max_length=30)
|
||||
email = models.EmailField(null=True, blank=True)
|
||||
phone_enc = models.TextField(
|
||||
null=True,
|
||||
blank=True,
|
||||
help_text="AES-256-GCM ciphertext of phone (core.encryption.PhoneEncryption).",
|
||||
)
|
||||
phone_hash = models.CharField(max_length=64, null=True, blank=True)
|
||||
staff = models.OneToOneField(
|
||||
"org.Staff",
|
||||
null=True,
|
||||
blank=True,
|
||||
on_delete=models.SET_NULL,
|
||||
related_name="account",
|
||||
)
|
||||
is_tenant_admin = models.BooleanField(default=False)
|
||||
status = models.CharField(
|
||||
max_length=10,
|
||||
choices=UserAccountStatus.choices,
|
||||
default=UserAccountStatus.ACTIVE,
|
||||
)
|
||||
is_initial_password = models.BooleanField(default=True)
|
||||
locked_until = models.DateTimeField(null=True, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
created_by = models.ForeignKey(
|
||||
"self",
|
||||
null=True,
|
||||
blank=True,
|
||||
on_delete=models.SET_NULL,
|
||||
related_name="created_accounts",
|
||||
)
|
||||
|
||||
USERNAME_FIELD = "username"
|
||||
REQUIRED_FIELDS: list = []
|
||||
|
||||
objects = UserAccountManager()
|
||||
|
||||
class Meta:
|
||||
db_table = "user_accounts"
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["username"], name="uq_user_accounts_username"),
|
||||
models.UniqueConstraint(
|
||||
fields=["email"],
|
||||
name="uq_user_accounts_email",
|
||||
condition=models.Q(email__isnull=False),
|
||||
),
|
||||
models.UniqueConstraint(
|
||||
fields=["phone_hash"],
|
||||
name="uq_user_accounts_phone",
|
||||
condition=models.Q(phone_hash__isnull=False),
|
||||
),
|
||||
]
|
||||
indexes = [
|
||||
models.Index(fields=["status"], name="idx_user_accounts_status"),
|
||||
models.Index(fields=["staff"], name="idx_user_accounts_staff"),
|
||||
]
|
||||
|
||||
def __str__(self) -> str:
|
||||
kind = "admin" if self.is_tenant_admin else "staff"
|
||||
return f"{self.username} ({kind})"
|
||||
|
||||
def is_locked(self) -> bool:
|
||||
if self.status != UserAccountStatus.LOCKED:
|
||||
return False
|
||||
if self.locked_until and timezone.now() >= self.locked_until:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class LoginAttempt(models.Model):
|
||||
username = models.CharField(max_length=30)
|
||||
ip_address = models.GenericIPAddressField()
|
||||
user_agent = models.TextField(null=True, blank=True)
|
||||
success = models.BooleanField()
|
||||
failure_reason = models.CharField(
|
||||
max_length=30,
|
||||
null=True,
|
||||
blank=True,
|
||||
choices=LoginFailureReason.choices,
|
||||
)
|
||||
attempted_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "login_attempts"
|
||||
indexes = [
|
||||
models.Index(fields=["username"], name="idx_login_attempts_username"),
|
||||
models.Index(fields=["ip_address"], name="idx_login_attempts_ip"),
|
||||
models.Index(fields=["-attempted_at"], name="idx_login_attempts_time"),
|
||||
models.Index(
|
||||
fields=["username", "success", "-attempted_at"],
|
||||
name="idx_login_attempts_fail_check",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
class PasswordResetToken(models.Model):
|
||||
user = models.ForeignKey(
|
||||
"account.UserAccount",
|
||||
on_delete=models.CASCADE,
|
||||
related_name="reset_tokens",
|
||||
)
|
||||
token = models.CharField(max_length=86, unique=True)
|
||||
expires_at = models.DateTimeField()
|
||||
is_used = models.BooleanField(default=False)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "password_reset_tokens"
|
||||
indexes = [
|
||||
models.Index(fields=["user"], name="idx_pw_reset_tokens_user"),
|
||||
]
|
||||
|
||||
def is_valid(self) -> bool:
|
||||
return not self.is_used and timezone.now() < self.expires_at
|
||||
|
||||
|
||||
class PasswordHistory(models.Model):
|
||||
user = models.ForeignKey(
|
||||
"account.UserAccount",
|
||||
on_delete=models.CASCADE,
|
||||
related_name="password_histories",
|
||||
)
|
||||
password_hash = models.CharField(max_length=128)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "password_histories"
|
||||
ordering = ["-created_at"]
|
||||
indexes = [
|
||||
models.Index(fields=["user", "-created_at"], name="idx_pw_histories_user"),
|
||||
]
|
||||
0
apps/account/serializers.py
Normal file
0
apps/account/serializers.py
Normal file
0
apps/account/services/__init__.py
Normal file
0
apps/account/services/__init__.py
Normal file
0
apps/account/tasks.py
Normal file
0
apps/account/tasks.py
Normal file
0
apps/account/templates/account/.gitkeep
Normal file
0
apps/account/templates/account/.gitkeep
Normal file
0
apps/account/tests/__init__.py
Normal file
0
apps/account/tests/__init__.py
Normal file
5
apps/account/urls.py
Normal file
5
apps/account/urls.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from django.urls import path
|
||||
|
||||
app_name = "account"
|
||||
|
||||
urlpatterns: list = []
|
||||
0
apps/account/views.py
Normal file
0
apps/account/views.py
Normal file
Reference in New Issue
Block a user