Bỏ qua, đến nội dung

Database Schema

Sơ đồ quan hệ (ER Diagram)

Chi tiết từng bảng

authenticators

Lưu trữ các phương thức xác thực đã cấu hình. Model: AuthModel (extends Model, implements Authenticator).

CộtKiểuRàng buộcMô tả
idbigIntPK, autoIncrementKhóa chính
namestringunique, not nullTên định danh (ví dụ: basic, oidc-google)
authTypestringnot nullLoại xác thực, map với registerTypes() (ví dụ: Email/Password)
titlestringnullableTên hiển thị, hỗ trợ translation
descriptionstringnot null, default ''Mô tả
optionsjsonnot null, default {}Cấu hình tùy chỉnh theo authType
enabledbooleandefault falseBật/tắt authenticator
sortbigIntsortableThứ tự hiển thị
createdByIdbigIntFKNgười tạo
updatedByIdbigIntFKNgười cập nhật
createdAtdateThời gian tạo
updatedAtdateThời gian cập nhật

Quan hệ: belongsToMany tới users qua bảng trung gian usersAuthenticators, với sourceKey: 'name', foreignKey: 'authenticator', targetKey: 'id', otherKey: 'userId'. onDelete: CASCADE.

Cấu trúc options (BasicAuth):

json
{
  "public": {
    "allowSignUp": true,
    "enableResetPassword": true,
    "signupForm": [
      { "field": "username", "show": true, "required": true },
      { "field": "email", "show": true, "required": false }
    ]
  },
  "notificationChannel": "email-channel-name",
  "emailSubject": "Reset password for $systemSettings.title",
  "emailContentType": "html",
  "emailContentHTML": "<p>Click <a href='$resetLink'>here</a> to reset</p>",
  "resetTokenExpiresIn": 20
}

usersAuthenticators

Bảng trung gian M2M giữa authenticatorsusers. Lưu thông tin user theo từng phương thức xác thực (SSO uuid, avatar từ provider, metadata).

CộtKiểuRàng buộcMô tả
uuidstringnot nullID duy nhất của user trong auth provider (ví dụ: Google OpenID, số điện thoại)
displaynamestringnot null, default ''Tên hiển thị từ provider
avatarstringnot null, default ''Avatar URL từ provider
metajsondefault {}Metadata bổ sung (tokens, profile data...)
authenticatorstringFK → authenticators.nameTên authenticator
userIdbigIntFK → users.idID user trong hệ thống
createdByIdbigIntFKNgười tạo
updatedByIdbigIntFKNgười cập nhật
createdAtdateThời gian tạo
updatedAtdateThời gian cập nhật

AuthModel sử dụng bảng này qua các phương thức:

  • findUser(uuid) — tìm user qua through.where: { uuid }
  • newUser(uuid, values) — tạo user mới kèm record trong bảng này
  • findOrCreateUser(uuid, values) — tìm hoặc tạo mới

issuedTokens

Theo dõi các JWT đã cấp, dùng cho token renewal và session management.

CộtKiểuRàng buộcMô tả
iduuidPKKhóa chính (giá trị ban đầu = jti)
jtiuuidnot null, indexedJSON Token Identifier hiện tại
signInTimebigIntnot nullTimestamp (ms) khi user đăng nhập (không đổi khi renew)
issuedTimebigIntnot nullTimestamp (ms) lần cấp/renew gần nhất
userIdbigIntnot nullID user
createdAtdateThời gian tạo record
updatedAtdateThời gian cập nhật record

Cách hoạt động:

  • Khi signIn: TokenController.add() tạo record với jti = randomUUID(), signInTime = issuedTime = Date.now()
  • Khi renew: TokenController.renew(oldJti) cập nhật jti thành UUID mới và issuedTime thành Date.now()
  • Session hết hạn: removeSessionExpiredTokens() xóa record có signInTime < now - sessionExpirationTime

tokenBlacklist

Lưu các token bị revoke (signOut, resetPassword đã dùng).

CộtKiểuRàng buộcMô tả
tokenstringindexedNội dung token JWT
expirationdateThời điểm token hết hạn tự nhiên

TokenBlacklistService sử dụng 2 tầng kiểm tra:

  1. Redis Bloom filter (nếu có Redis): kiểm tra nhanh O(1), false positive rate 0.1%, capacity 1 triệu token
  2. Database query: xác nhận chính xác nếu Bloom filter trả true

Khi thêm token vào blacklist (add), service cũng gọi deleteExpiredTokens() để dọn dẹp token đã hết hạn tự nhiên.


tokenControlConfig

Cấu hình token policy cho toàn hệ thống.

CộtKiểuRàng buộcMô tả
keystringPK, not nullKhóa cấu hình, mặc định 'token-policy-config'
configjsonnot null, default {}Object chứa cấu hình policy
createdByIdbigIntFKNgười tạo
updatedByIdbigIntFKNgười cập nhật
createdAtdateThời gian tạo
updatedAtdateThời gian cập nhật

Cấu trúc config:

json
{
  "tokenExpirationTime": "1d",
  "sessionExpirationTime": "7d",
  "expiredTokenRenewLimit": "1d"
}

Giá trị dùng format ms (1d = 86400000ms, 2h = 7200000ms). Khi save, event tokenControlConfig.afterSave tự động gọi tokenController.setConfig() để cập nhật cache.


Migration history

MigrationMô tả
20230506152253-basic-authenticatorTạo bảng authenticatorsusersAuthenticators
20230607174500-update-basicCập nhật cấu hình authenticator basic
20231218132032-fix-allow-signupSửa option allowSignUp
20241229080941-create-token-policy-configTạo bảng tokenControlConfig