Skip to content

Mô hình miền

Schema nằm trong @nx/core/src/models/schemas/identity/ (và public/configuration/ dùng chung). Cột numeric/text tuân theo quy ước IGNIS.

1. ERD đầy đủ

2. Cột chung

Mỗi entity bổ sung các cột này qua generateCommonColumnDefs():

CộtKiểu
idtext (PK, Snowflake)
createdAt / modifiedAttimestamptz
createdBy / modifiedBytext
deletedAttimestamptz (soft-delete)
metadatajsonb
statustext (khi dùng …WithStatusDefs)

3. Entities

3.1 User

Thuộc tínhGiá trị
BảngUser
Soft-delete
TrườngKiểuBắt buộcMô tả
usernametextUsername hiển thị (cũng được lưu như identifier)
statustextACTIVATED / DEACTIVATED / LOCKED
lastLoginAttimestamptzCập nhật bởi signIn

3.2 UserIdentifier

TrườngKiểuBắt buộcMô tả
userIdtextFK
identifiertextGiá trị đăng nhập (email, phone, username, v.v.)
schemetextUSERNAME / EMAIL / PHONE_NUMBER / USER_NUMBER / NX_AUTH
verifiedbooleanMặc định false; chuyển true sau khi xác nhận OTP

Ràng buộc unique: partial unique trên (scheme, identifier) WHERE deletedAt IS NULL — một giá trị duy nhất trên mỗi scheme.

3.3 UserCredential

TrườngKiểuBắt buộcMô tả
userIdtextFK
schemetextBASIC (mật khẩu) / TWO_FA / OAUTH / OAUTH2
credentialtextĐã hash qua Bun.password (hoặc token ngoài cho OAUTH)

3.4 UserProfile

TrườngKiểuBắt buộcMô tả
userIdtextFK (1:1)
firstName / lastNametext
birthdaytimestamptz
localetexten / vi (quyết định template mail/SMS)

3.5 UserConfiguration

Feature flags / settings theo từng user dưới dạng cặp kv trong jsonb.

3.6 Role

TrườngKiểuBắt buộcMô tả
identifiertextSlug duy nhất (SUPER_ADMIN, v.v.)
namei18n jsonbHiển thị
descriptioni18n jsonb
priorityintKhoảng 101–499 cho custom; system role dùng 500–1000
typetextSYSTEM / CUSTOM / UNKNOWN
statustextACTIVATED / DEACTIVATED

System roles (bất biến, được seed): SUPER_ADMIN(1000), ADMIN(500), OPERATOR(600), OWNER(500), CASHIER(110), EMPLOYEE(100), CUSTOMER(10), GUEST(1).

3.7 Permission

TrườngKiểuBắt buộcMô tả
codetext<Resource>.<action> (ví dụ User.create)
resourcetextĐối tượng phân quyền
actiontextfind / create / updateById / deleteById / domain action
name / descriptioni18n jsonb

3.8 PolicyDefinition (cạnh RBAC)

TrườngKiểuBắt buộcMô tả
varianttextGROUP (subject ↔ subject) / PERMISSION (role ↔ permission)
subjectTypetextUser / Role / Permission
subjectIdtextFK target
targetTypetextRole / Permission / User / Organizer / Merchant
targetIdtextFK target
scopetextSYSTEM / ORGANIZER / MERCHANT (PolicyDomains)

Cạnh thường gặp:

Loại cạnhVariantSubjectTarget
User → RoleGROUPUserRole
User → OrganizerGROUPUserOrganizer
User → MerchantGROUPUserMerchant
Role → PermissionPERMISSIONRolePermission

3.9 Customer

Mở rộng User với các trường ngữ cảnh sales (quản lý ở identity nhưng được sale đọc).

TrườngKiểuBắt buộcMô tả
userIdtextFK tuỳ chọn (một số khách là guest, không có User)
nametextHiển thị
phone / emailtextLiên hệ
merchantIdtextOwner
pointBalancedecimal(15,4)Điểm thưởng (mặc định 0; được sale ghi)

3.10 Employee

TrườngKiểuBắt buộcMô tả
userIdtextFK đến User
merchantIdtextNơi làm việc (hoặc organizerId)
organizerIdtextNơi làm việc thay thế
positiontextChức danh
statustextACTIVATED / DEACTIVATED

3.11 Configuration (dùng chung)

TrườngKiểuBắt buộcMô tả
codetextDuy nhất theo partial (group, principalId, principalType, environment)
grouptextINTEGRATION / MAIL / SMS / OTP / v.v.
principalType / principalIdtextKhi theo từng merchant (ví dụ provider SMS theo merchant)
environmenttextDEVELOPMENT / PRODUCTION
tValuetextGiá trị JSON (mã hoá cho credential)
dataTypetextTEXT / JSON / BOOLEAN
credentialtextĐã mã hoá (AES-256-GCM qua CryptoUtility); ẩn khỏi đọc CRUD

Identity đọc cấu hình mail/SMS/OTP từ bảng này; payment ghi credential provider đã mã hoá.

4. Status Enums

4.1 UserIdentifierSchemes

Giá trịMô tả
USERNAMEUsername hiển thị
EMAILĐịa chỉ email
PHONE_NUMBERSố điện thoại E.164
USER_NUMBERID số nội bộ
NX_AUTHNX-Auth federation

4.2 UserCredentialSchemes

Giá trịDùng để
BASICMật khẩu (Bun.password hash)
TWO_FAToken yếu tố thứ hai (placeholder)
OAUTHOAuth1 federation (đã khai báo, chưa có provider)
OAUTH2OAuth2 federation (đã khai báo, chưa có provider)

4.3 RoleTypes

Giá trị
SYSTEMseed sẵn, bất biến
CUSTOMmerchant tự định nghĩa
UNKNOWNfallback

4.4 PolicyDomains (trường scope)

Giá trịDùng để
SYSTEMcạnh toàn cục
ORGANIZERgiới hạn theo organizer
MERCHANTgiới hạn theo merchant

4.5 OTP namespaces

NamespaceDùng để
verify-emailĐăng ký email
verify-phoneĐăng ký phone
forgot-passwordĐặt lại mật khẩu
phone-authĐăng nhập chỉ-bằng-phone (khi áp dụng)
add-phone / add-emailLiên kết với tài khoản đã xác thực

4.6 OTP defaults

SettingGiá trị
CODE_LENGTH6
EXPIRY5–15 phút tuỳ flow
MAX_ATTEMPTS5
LOCKOUT10–15 phút
RESEND_COOLDOWN60s
MAX_RESENDS_PER_DAY5

5. Invariants liên-entity

InvariantCách đảm bảo
UserIdentifier(scheme, value) duy nhất toàn hệ thống (theo scheme)Partial unique index
UserCredential.scheme=BASIC đã hash (không bao giờ plaintext)AuthenticationService.signUp + changePassword luôn hash
Role.priority duy nhất trong cùng typeValidation service trong RoleService
System role (type=SYSTEM) không thể xoá/sửa trừ qua migrationService guard
Cycle PolicyDefinition (User → Role → User) bị cấmKiểm tra acyclicity ở mức service
Hạn ngạch OTP hàng ngày theo (namespace, identifierValue)Bộ đếm Redis {ns}:daily:{value}
Payload JWT luôn bao gồm userId, roles, organizers, merchantsAuthenticationService.generateToken

6. Hành vi Soft-delete

EntitySoft-deleteGhi chú
Mọi entity của identityCờ deletedAt; mặc định đọc IS NULL
ConfigurationNhưng các bản ghi seed thường được phục hồi khi chạy lại migration

7. Trang liên quan

Proprietary and Confidential. Unauthorized copying, distribution, or use of this software is strictly prohibited.