Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rust Auth Demo (Axum + MySQL)

这是一个最小但完整可运行的认证与登录 Demo,实现三类用户体系彼此独立、同自然人可拥有多种身份、同一设备可同时存在多个登录态、并支持多设备登录并存。

技术栈

  • 后端:Rust axum
  • 数据库:MySQL(sqlx 异步驱动)
  • 密码哈希:argon2(Argon2id)
  • 会话:DB session(auth_sessions 表落库),通过 Cookie 指向 sid
  • 前端:React + TypeScript + Vite

架构说明(关键约束如何满足)

三类身份登录/资料彼此独立

后端为每类身份提供独立的:

  • 认证(密码)表:member_auth / community_staff_auth / platform_staff_auth
  • 资料(profile)表:member_profile / community_staff_profile / platform_staff_profile
  • me 接口:/api/member/me/api/community-staff/me/api/platform-staff/me

每个 me 只会校验对应 cookie(对应 session 的 auth_type),不会互相影响。

同一设备可同时存在多个登录态

不同身份在同一浏览器/设备中使用不同 cookie 名:

  • member_sid
  • community_staff_sid
  • platform_staff_sid

因此同一设备同时登录三类身份不会互相“覆盖”。

同一个自然人可以拥有多种身份

注册时使用同一个 email:三类身份都会写入同一个共享自然人表 person,从而复用同一个 person_id

同一 email 分别注册 Member/Community Staff/Platform Staff 后,/me 返回的 person.email 相同,但 profile 字段来自各自独立表。

多设备登录需被正确支持

每次登录都会生成一个新的不可预测 sid,写入 auth_sessions 表,并把该 sid 放入对应 cookie。

不同设备会携带不同的 sid,彼此不冲突;退出(logout)只会撤销当前 cookie 对应的那一条 session(仅当前身份类型)。

数据库表(MySQL)

后端启动时会执行 CREATE TABLE IF NOT EXISTS

  • person:共享自然人(email 唯一)
  • *_auth:三类身份独立密码体系(person_id 主键外键)
  • *_profile:三类身份独立资料体系
  • auth_sessions:DB session,包含 sidauth_typeperson_idexpires_atrevoked_at

运行方式(一键启动)

1. 准备 MySQL

确保本机已安装并运行 MySQL,并创建一个数据库(示例:rust_auth_demo)。

Demo 不使用 Docker;后端会直接连接你提供的 DATABASE_URL,并在该数据库内建表。

2. 设置环境变量

在项目根目录执行:

export DATABASE_URL='mysql://USER:PASSWORD@localhost:3306/rust_auth_demo'

可选:

export BACKEND_PORT=3001
export FRONTEND_PORT=5173

3. 一键启动

./start.sh

前端会把请求 /api/* 通过 Vite proxy 转发到后端,因此无需额外配置 CORS。

API(最小集合)

  • 注册
    • POST /api/member/register
    • POST /api/community-staff/register
    • POST /api/platform-staff/register
  • 登录(创建 session + 设置 cookie)
    • POST /api/member/login
    • POST /api/community-staff/login
    • POST /api/platform-staff/login
  • 退出(撤销当前 cookie 对应 session)
    • POST /api/member/logout
    • POST /api/community-staff/logout
    • POST /api/platform-staff/logout
  • 查询当前登录资料
    • GET /api/member/me
    • GET /api/community-staff/me
    • GET /api/platform-staff/me

关键设计取舍

  • Demo 为了最小可运行,使用 DB session(落库 sid)而非 JWT:减少 token 刷新/撤销复杂度。
  • cookie 名按身份类型分离:确保同一浏览器可同时存在多个登录态。

About

rustTest

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages