编写支持邮箱/手机号/用户名三合一的认证后端

解读

国内主流 App(微信、支付宝、抖音)全部允许“邮箱/手机号/用户名 + 密码”任意一种方式登录,面试官想确认候选人能否:

  1. 在不改动现有 User 表结构的前提下扩展认证维度;
  2. 兼顾国内手机号格式(11 位、1 开头、无国家码)与邮箱规范;
  3. 保证唯一性、索引效率、安全(防爆破、防遍历);
  4. 给出可插拔、可单元测试、可灰度发布的实现方案。

一句话:用 Django 的认证钩子写“一个后端”,而不是“三张表”或“重写 User”。

知识点

  • Authentication Backend 接口:继承 ModelBackend,实现 authenticate(request, username=None, password=None) 与 get_user(user_id)
  • Q 对象复合查询:Q(username=xxx)|Q(email=xxx)|Q(profile__mobile=xxx)
  • 正则预校验:re.fullmatch(r'1[3-9]\d{9}', raw_username) 区分手机号与邮箱
  • 唯一性联合约束:User.email 与 User.profile.mobile 必须各自唯一;数据库层加 uniq 索引,防止并发插入脏数据
  • 安全加固:失败次数缓存(cache.incr + TTL)、登录日志(admin.LogEntry 或自建)、防用户名遍历(返回统一“用户名或密码错误”)
  • 可测试性:使用 @override_settings(AUTHENTICATION_BACKENDS) 隔离测试
  • 可灰度:通过 Django App 的 ready() 动态注册 backend,支持 Feature Flag 开关

答案

项目结构 accounts/ ├── init.py ├── apps.py ├── backends.py ├── models.py ├── tests.py ├── validators.py └── migrations/

  1. 扩展用户表(不拆表,仅加一对一 Profile)
# accounts/models.py
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import RegexValidator

phone_validator = RegexValidator(
    regex=r'^1[3-9]\d{9}$',
    message="请输入合法的手机号"
)

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    mobile = models.CharField(
        max_length=11,
        validators=[phone_validator],
        unique=True,
        null=True,
        blank=True,
        db_index=True
    )
  1. 工具函数
# accounts/validators.py
import re
EMAIL_RE = re.compile(r'^[^@]+@[^@]+\.[^@]+$')
PHONE_RE = re.compile(r'^1[3-9]\d{9}$')

def classify_account(account):
    if PHONE_RE.fullmatch(account):
        return 'mobile'
    if EMAIL_RE.fullmatch(account):
        return 'email'
    return 'username'
  1. 认证后端(核心)
# accounts/backends.py
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q
from .validators import classify_account

UserModel = get_user_model()

class TripleAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if not username or not password:
            return None
        key = classify_account(username)
        try:
            if key == 'mobile':
                user = UserModel.objects.get(profile__mobile=username)
            elif key == 'email':
                user = UserModel.objects.get(email=username)
            else:
                user = UserModel.objects.get(username=username)
        except UserModel.DoesNotExist:
            # 跑一遍默认密码哈希,防止时序攻击
            UserModel().set_password(password)
            return None

        if user.check_password(password) and self.user_can_authenticate(user):
            return user
        return None

    def get_user(self, user_id):
        try:
            return UserModel.objects.get(pk=user_id)
        except UserModel.DoesNotExist:
            return None
  1. 注册到 settings.py
AUTHENTICATION_BACKENDS = [
    'accounts.backends.TripleAuthBackend',  # 优先走自定义
    'django.contrib.auth.backends.ModelBackend',  # 兜底
]
  1. 数据层唯一约束(防止并发)
-- migrations/0002_unique_mobile.py
ALTER TABLE accounts_profile ADD CONSTRAINT unique_mobile UNIQUE (mobile);
  1. 登录视图(DRF 或模板均可)
# 伪代码
def login_view(request):
    account = request.POST.get('username')  # 前端统一字段名
    password = request.POST.get('password')
    user = authenticate(request, username=account, password=password)
    if user:
        auth_login(request, user)
        return JsonResponse({'code': 0})
    return JsonResponse({'code': 40001, 'msg': '用户名或密码错误'})
  1. 单元测试
# accounts/tests.py
from django.test import TestCase, override_settings
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from .models import Profile

@override_settings(AUTHENTICATION_BACKENDS=['accounts.backends.TripleAuthBackend'])
class TripleAuthTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username='tester', email='test@example.com', password='123456'
        )
        Profile.objects.create(user=self.user, mobile='13800138000')

    def test_mobile_login(self):
        user = authenticate(username='13800138000', password='123456')
        self.assertEqual(user, self.user)

至此,邮箱/手机号/用户名三合一认证后端完成,零侵入、可测试、可灰度。

拓展思考

  1. 性能优化:手机号与 email 查询量大,可在 Profile.mobile 与 User.email 上建哈希索引;若用户量过亿,考虑分库分表后把登录凭证迁移到独立 Passport 服务。
  2. 安全增强:接入阿里云滑动验证码或极验,失败 3 次触发验证码;登录成功签发 JWT + 刷新机制,替代 Session,方便多端同步。
  3. 第三方融合:国内用户习惯“手机号+短信验证码一键登录”,可再写一个 SMSBackend,与 TripleAuthBackend 并列,优先走短信,再走密码。
  4. 合规要求:手机号属个人信息,需加密落库(AES-256-CBC)并走脱敏接口返回;日志中禁止明文打印。
  5. 老系统迁移:若原系统只有 username,写数据迁移脚本把已有 email 与 mobile 拆入 Profile,同时保证旧密码哈希(PBKDF2)能继续识别,避免强制用户改密。