feat(admin-user): 增加超级管理员实名信息查询

This commit is contained in:
yml
2026-11-22 19:21:24 +08:00
parent 20be2273d5
commit 8c41c258fa
9 changed files with 304 additions and 16 deletions
+12
View File
@@ -38,6 +38,18 @@ type UserDTO struct {
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` UpdatedAt time.Time `json:"updated_at"`
} }
type RealnameIdentityDTO struct {
RealnameID uint64 `json:"realname_id"`
UserID uint64 `json:"user_id"`
TenantID uint64 `json:"tenant_id"`
RealName string `json:"real_name"`
IDNo string `json:"id_no"`
Provider string `json:"provider"`
Status string `json:"status"`
VerifiedAt *time.Time `json:"verified_at,omitempty"`
}
type FreezeRequest struct { type FreezeRequest struct {
Reason string `json:"reason"` Reason string `json:"reason"`
} }
@@ -232,6 +232,31 @@ func (h *Handler) ManualRealname(c *gin.Context) {
response.OK(c, item) response.OK(c, item)
} }
func (h *Handler) RealnameIdentity(c *gin.Context) {
c.Header("Cache-Control", "no-store")
c.Header("Pragma", "no-cache")
adminID, ok := currentAdminID(c)
if !ok {
response.Unauthorized(c, "缺少管理员上下文")
return
}
userID, ok := parseID(c)
if !ok {
return
}
item, err := h.service.ViewRealnameIdentity(
c.Request.Context(),
adminID,
userID,
auditMeta(c),
)
if err != nil {
writeAdminUserError(c, err)
return
}
response.OK(c, item)
}
func (h *Handler) AdjustWallet(c *gin.Context) { func (h *Handler) AdjustWallet(c *gin.Context) {
adminID, ok := currentAdminID(c) adminID, ok := currentAdminID(c)
if !ok { if !ok {
@@ -296,6 +321,8 @@ func writeAdminUserError(c *gin.Context, err error) {
response.Error(c, http.StatusConflict, "realname_id_no_used", "该身份证号已绑定其他实名账号,不能重复认证") response.Error(c, http.StatusConflict, "realname_id_no_used", "该身份证号已绑定其他实名账号,不能重复认证")
case errors.Is(err, ErrRealnameNotRevocable): case errors.Is(err, ErrRealnameNotRevocable):
response.Error(c, http.StatusConflict, "realname_not_revocable", "该用户当前没有可撤销的实名信息") response.Error(c, http.StatusConflict, "realname_not_revocable", "该用户当前没有可撤销的实名信息")
case errors.Is(err, ErrRealnameIdentityUnavailable):
response.Error(c, http.StatusUnprocessableEntity, "realname_identity_unavailable", "实名信息暂时无法查看")
case errors.Is(err, ErrInvalidWalletDirection): case errors.Is(err, ErrInvalidWalletDirection):
response.BadRequest(c, "调账方向不正确,仅支持加款(in)或扣款(out)") response.BadRequest(c, "调账方向不正确,仅支持加款(in)或扣款(out)")
case errors.Is(err, ErrInvalidWalletAmount): case errors.Is(err, ErrInvalidWalletAmount):
@@ -552,6 +552,62 @@ func (r *Repository) ManualRealname(ctx context.Context, adminID uint64, userID
return r.Find(ctx, userID) return r.Find(ctx, userID)
} }
func (r *Repository) ViewRealnameIdentity(
ctx context.Context,
adminID uint64,
userID uint64,
meta AuditMeta,
) (*RealnameIdentityDTO, error) {
var result *RealnameIdentityDTO
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var user model.User
userQuery := applyUserContextScope(ctx, tx.Model(&model.User{}), "")
if err := userQuery.Where("id = ?", userID).First(&user).Error; err != nil {
return err
}
var record model.UserRealname
recordQuery := tx.Where("user_id = ? AND status = ?", userID, "verified")
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
recordQuery = recordQuery.Where("tenant_id = ?", tenantID)
}
if err := recordQuery.First(&record).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrRealnameIdentityUnavailable
}
return err
}
realName, err := r.encryptor.Decrypt(record.EncryptedName)
if err != nil || strings.TrimSpace(realName) == "" {
return fmt.Errorf("%w: decrypt real name: %v", ErrRealnameIdentityUnavailable, err)
}
idNo, err := r.encryptor.Decrypt(record.EncryptedIDNo)
if err != nil || strings.TrimSpace(idNo) == "" {
return fmt.Errorf("%w: decrypt id no: %v", ErrRealnameIdentityUnavailable, err)
}
result = &RealnameIdentityDTO{
RealnameID: record.ID,
UserID: user.ID,
TenantID: user.TenantID,
RealName: realName,
IDNo: idNo,
Provider: record.Provider,
Status: record.Status,
VerifiedAt: record.VerifiedAt,
}
return appendAuditLog(tx, adminID, "admin_user.view_realname", user.ID, meta, map[string]any{
"realname_id": record.ID,
"provider": record.Provider,
})
})
if err != nil {
return nil, err
}
return result, nil
}
func (r *Repository) Find(ctx context.Context, userID uint64) (*UserDTO, error) { func (r *Repository) Find(ctx context.Context, userID uint64) (*UserDTO, error) {
growthConfig, err := rentergrowth.ConfigForTx(r.db.WithContext(ctx)) growthConfig, err := rentergrowth.ConfigForTx(r.db.WithContext(ctx))
if err != nil { if err != nil {
@@ -465,6 +465,91 @@ func TestManualRealnameRejectsIdentityUsedByAnotherUser(t *testing.T) {
} }
} }
func TestViewRealnameIdentityDecryptsAndAudits(t *testing.T) {
db := setupAdminUserTestDB(t)
user := model.User{
Phone: "13900000021",
Nickname: "待查实名",
Status: "active",
RealnameStatus: "verified",
}
if err := db.Create(&user).Error; err != nil {
t.Fatalf("创建用户失败:%v", err)
}
record := model.UserRealname{
UserID: user.ID,
TenantID: user.TenantID,
Provider: "admin_manual",
Status: "verified",
MaskedName: "周**",
EncryptedName: "周奕男",
MaskedIDNo: "1306**********0615",
EncryptedIDNo: "130682200604080615",
}
if err := db.Create(&record).Error; err != nil {
t.Fatalf("创建实名记录失败:%v", err)
}
repo := NewRepository(db)
got, err := repo.ViewRealnameIdentity(t.Context(), 99, user.ID, AuditMeta{
IP: "127.0.0.1",
UserAgent: "realname-view-test",
RequestID: "realname-view-1",
})
if err != nil {
t.Fatalf("ViewRealnameIdentity() error = %v", err)
}
if got.RealName != "周奕男" || got.IDNo != "130682200604080615" {
t.Fatalf("实名信息不正确:%+v", got)
}
var audit model.AuditLog
if err := db.Where("action = ?", "admin_user.view_realname").First(&audit).Error; err != nil {
t.Fatalf("查询查看实名审计失败:%v", err)
}
if audit.ActorID != 99 || audit.BizID == nil || *audit.BizID != user.ID {
t.Fatalf("查看实名审计主体不正确:%+v", audit)
}
if strings.Contains(string(audit.Detail), "130682200604080615") ||
strings.Contains(string(audit.Detail), "周奕男") {
t.Fatalf("查看实名审计不应包含明文:%s", string(audit.Detail))
}
}
func TestViewRealnameIdentityRejectsCrossTenantUser(t *testing.T) {
db := setupAdminUserTestDB(t)
user := model.User{
TenantID: 202,
Phone: "13900000202",
Status: "active",
RealnameStatus: "verified",
}
if err := db.Create(&user).Error; err != nil {
t.Fatalf("创建用户失败:%v", err)
}
if err := db.Create(&model.UserRealname{
UserID: user.ID,
TenantID: user.TenantID,
Provider: "admin_manual",
Status: "verified",
EncryptedName: "钟烜",
EncryptedIDNo: "362428199303087717",
}).Error; err != nil {
t.Fatalf("创建实名记录失败:%v", err)
}
repo := NewRepository(db)
_, err := repo.ViewRealnameIdentity(
adminUserTenantContext(101),
99,
user.ID,
AuditMeta{},
)
if !errors.Is(err, gorm.ErrRecordNotFound) {
t.Fatalf("跨租户查看实名 error = %v, want record not found", err)
}
}
func TestAdjustWalletDebitAndAudit(t *testing.T) { func TestAdjustWalletDebitAndAudit(t *testing.T) {
db := setupAdminUserTestDB(t) db := setupAdminUserTestDB(t)
user := model.User{ user := model.User{
+32 -16
View File
@@ -11,22 +11,23 @@ import (
) )
var ( var (
ErrDependencyUnavailable = errors.New("dependency unavailable") ErrDependencyUnavailable = errors.New("dependency unavailable")
ErrInvalidUser = errors.New("invalid user") ErrInvalidUser = errors.New("invalid user")
ErrInvalidRealnameInput = errors.New("invalid realname input") ErrInvalidRealnameInput = errors.New("invalid realname input")
ErrRealnameAlreadyVerified = errors.New("realname already verified") ErrRealnameAlreadyVerified = errors.New("realname already verified")
ErrRealnameIDNoUsed = realname.ErrIDNoAlreadyUsed ErrRealnameIDNoUsed = realname.ErrIDNoAlreadyUsed
ErrRealnameNotRevocable = errors.New("realname not revocable") ErrRealnameNotRevocable = errors.New("realname not revocable")
ErrInvalidWalletDirection = errors.New("invalid wallet direction") ErrRealnameIdentityUnavailable = errors.New("realname identity unavailable")
ErrInvalidWalletAmount = errors.New("invalid wallet amount") ErrInvalidWalletDirection = errors.New("invalid wallet direction")
ErrInvalidWalletReason = errors.New("invalid wallet reason") ErrInvalidWalletAmount = errors.New("invalid wallet amount")
ErrInsufficientBalance = errors.New("insufficient balance") ErrInvalidWalletReason = errors.New("invalid wallet reason")
ErrInvalidGrowthPoints = errors.New("invalid growth points") ErrInsufficientBalance = errors.New("insufficient balance")
ErrInvalidGrowthReason = errors.New("invalid growth reason") ErrInvalidGrowthPoints = errors.New("invalid growth points")
ErrGrowthPointsUnchanged = errors.New("growth points unchanged") ErrInvalidGrowthReason = errors.New("invalid growth reason")
ErrInvalidGrowthLevel = errors.New("invalid growth level") ErrGrowthPointsUnchanged = errors.New("growth points unchanged")
ErrInvalidGrowthLevelReason = errors.New("invalid growth level reason") ErrInvalidGrowthLevel = errors.New("invalid growth level")
ErrGrowthLevelUnchanged = errors.New("growth level unchanged") ErrInvalidGrowthLevelReason = errors.New("invalid growth level reason")
ErrGrowthLevelUnchanged = errors.New("growth level unchanged")
) )
// 单笔人工调账上限:10 万元,防止误填。 // 单笔人工调账上限:10 万元,防止误填。
@@ -147,6 +148,21 @@ func (s *Service) ManualRealname(ctx context.Context, adminID uint64, userID uin
return s.repo.ManualRealname(ctx, adminID, userID, req, meta) return s.repo.ManualRealname(ctx, adminID, userID, req, meta)
} }
func (s *Service) ViewRealnameIdentity(
ctx context.Context,
adminID uint64,
userID uint64,
meta AuditMeta,
) (*RealnameIdentityDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
if adminID == 0 || userID == 0 {
return nil, ErrInvalidUser
}
return s.repo.ViewRealnameIdentity(ctx, adminID, userID, meta)
}
func (s *Service) AdjustWallet(ctx context.Context, adminID uint64, userID uint64, req WalletAdjustRequest, meta AuditMeta) (*UserDTO, error) { func (s *Service) AdjustWallet(ctx context.Context, adminID uint64, userID uint64, req WalletAdjustRequest, meta AuditMeta) (*UserDTO, error) {
if s.repo == nil { if s.repo == nil {
return nil, ErrDependencyUnavailable return nil, ErrDependencyUnavailable
+1
View File
@@ -909,6 +909,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
adminRoutes.POST("/distribution/settlement-batches/:id/cancel", requirePerm("distribution:settlement_manage"), distributionHandler.CancelSettlementBatch) adminRoutes.POST("/distribution/settlement-batches/:id/cancel", requirePerm("distribution:settlement_manage"), distributionHandler.CancelSettlementBatch)
adminRoutes.GET("/files/object", fileHandler.Object) adminRoutes.GET("/files/object", fileHandler.Object)
adminRoutes.GET("/users", requirePerm("user:view"), adminUserHandler.List) adminRoutes.GET("/users", requirePerm("user:view"), adminUserHandler.List)
adminRoutes.GET("/users/:id/realname", requirePlatformSuperAdmin, adminUserHandler.RealnameIdentity)
adminRoutes.POST("/users/:id/freeze", requirePerm("user:freeze"), adminUserHandler.Freeze) adminRoutes.POST("/users/:id/freeze", requirePerm("user:freeze"), adminUserHandler.Freeze)
adminRoutes.POST("/users/:id/unfreeze", requirePerm("user:unfreeze"), adminUserHandler.Unfreeze) adminRoutes.POST("/users/:id/unfreeze", requirePerm("user:unfreeze"), adminUserHandler.Unfreeze)
adminRoutes.POST("/users/:id/deposit-free-quota", requirePerm("user:deposit_free"), adminUserHandler.SetDepositFreeQuota) adminRoutes.POST("/users/:id/deposit-free-quota", requirePerm("user:deposit_free"), adminUserHandler.SetDepositFreeQuota)
+1
View File
@@ -57,6 +57,7 @@ func TestExtractedAdminRoutesRemainRegisteredWithoutDuplicates(t *testing.T) {
"PUT /api/admin/chat-support-groups/:id/members", "PUT /api/admin/chat-support-groups/:id/members",
"PUT /api/admin/roles/:id/permissions", "PUT /api/admin/roles/:id/permissions",
"PUT /api/admin/admin-users/:id/password", "PUT /api/admin/admin-users/:id/password",
"GET /api/admin/users/:id/realname",
"POST /api/admin/announcements/:id/publish", "POST /api/admin/announcements/:id/publish",
"GET /api/admin/orders/:id/payments", "GET /api/admin/orders/:id/payments",
"GET /api/site/context", "GET /api/site/context",
@@ -47,6 +47,17 @@ export interface AdminWalletAdjustPayload {
reference_no?: string reference_no?: string
} }
export interface AdminRealnameIdentity {
realname_id: number
user_id: number
tenant_id: number
real_name: string
id_no: string
provider: string
status: string
verified_at?: string
}
export interface AdminGrowthPointsAdjustPayload { export interface AdminGrowthPointsAdjustPayload {
target_points: number target_points: number
reason: string reason: string
@@ -151,6 +162,13 @@ export async function manualAdminUserRealname(
return data.data return data.data
} }
export async function fetchAdminUserRealname(id: number) {
const { data } = await apiClient.get<ApiResponse<AdminRealnameIdentity>>(
`/admin/users/${id}/realname`
)
return data.data
}
export async function adjustAdminUserWallet(id: number, payload: AdminWalletAdjustPayload) { export async function adjustAdminUserWallet(id: number, payload: AdminWalletAdjustPayload) {
const { data } = await apiClient.post<ApiResponse<AdminUserItem>>( const { data } = await apiClient.post<ApiResponse<AdminUserItem>>(
`/admin/users/${id}/wallet/adjust`, `/admin/users/${id}/wallet/adjust`,
@@ -8,6 +8,7 @@ import {
adjustAdminUserGrowthLevel, adjustAdminUserGrowthLevel,
adjustAdminUserGrowthPoints, adjustAdminUserGrowthPoints,
adjustAdminUserWallet, adjustAdminUserWallet,
fetchAdminUserRealname,
fetchAdminUsers, fetchAdminUsers,
freezeAdminUser, freezeAdminUser,
manualAdminUserRealname, manualAdminUserRealname,
@@ -17,6 +18,7 @@ import {
unfreezeAdminUser, unfreezeAdminUser,
type AdminUserItem, type AdminUserItem,
type AdminUserQuery, type AdminUserQuery,
type AdminRealnameIdentity,
} from '@/features/admin/api/adminUsers' } from '@/features/admin/api/adminUsers'
import { defaultRenterGrowthConfig } from '@/features/admin/api/renterGrowth' import { defaultRenterGrowthConfig } from '@/features/admin/api/renterGrowth'
import { centToYuan, formatCent, yuanToCent } from '@/shared/utils/money' import { centToYuan, formatCent, yuanToCent } from '@/shared/utils/money'
@@ -34,6 +36,7 @@ const canAdjustWallet = computed(() => adminSession.hasPermission('user:wallet_a
const canAdjustGrowthPoints = computed(() => adminSession.hasPermission('user:growth_points')) const canAdjustGrowthPoints = computed(() => adminSession.hasPermission('user:growth_points'))
const canAdjustGrowthLevel = computed(() => adminSession.hasPermission('user:growth_level')) const canAdjustGrowthLevel = computed(() => adminSession.hasPermission('user:growth_level'))
const canSetQualityOwner = computed(() => adminSession.hasPermission('user:quality_owner')) const canSetQualityOwner = computed(() => adminSession.hasPermission('user:quality_owner'))
const canViewFullRealname = computed(() => adminSession.isSuperAdmin)
const canViewUserDetail = computed( const canViewUserDetail = computed(
() => () =>
adminSession.hasPermission('wallet:view') || adminSession.hasPermission('wallet:view') ||
@@ -46,6 +49,9 @@ const activeUser = ref<AdminUserItem | null>(null)
const detailUser = ref<AdminUserItem | null>(null) const detailUser = ref<AdminUserItem | null>(null)
const quotaUser = ref<AdminUserItem | null>(null) const quotaUser = ref<AdminUserItem | null>(null)
const realnameUser = ref<AdminUserItem | null>(null) const realnameUser = ref<AdminUserItem | null>(null)
const realnameIdentityUser = ref<AdminUserItem | null>(null)
const realnameIdentity = ref<AdminRealnameIdentity | null>(null)
const realnameIdentityLoading = ref(false)
const manualRealnameUser = ref<AdminUserItem | null>(null) const manualRealnameUser = ref<AdminUserItem | null>(null)
const walletUser = ref<AdminUserItem | null>(null) const walletUser = ref<AdminUserItem | null>(null)
const growthUser = ref<AdminUserItem | null>(null) const growthUser = ref<AdminUserItem | null>(null)
@@ -303,6 +309,25 @@ function openRevokeRealname(row: AdminUserItem) {
revokeRealnameReason.value = '' revokeRealnameReason.value = ''
} }
async function openRealnameIdentity(row: AdminUserItem) {
realnameIdentityUser.value = row
realnameIdentity.value = null
realnameIdentityLoading.value = true
try {
realnameIdentity.value = await fetchAdminUserRealname(row.id)
} catch (error) {
realnameIdentityUser.value = null
ElMessage.error(readError(error, '获取实名信息失败'))
} finally {
realnameIdentityLoading.value = false
}
}
function closeRealnameIdentity() {
realnameIdentityUser.value = null
realnameIdentity.value = null
}
function openManualRealname(row: AdminUserItem) { function openManualRealname(row: AdminUserItem) {
manualRealnameUser.value = row manualRealnameUser.value = row
manualRealnameForm.name = '' manualRealnameForm.name = ''
@@ -649,6 +674,16 @@ function moneyCent(value: number | string | undefined) {
> >
明细 明细
</el-button> </el-button>
<el-button
v-if="canViewFullRealname && row.realname_status === 'verified'"
text
type="primary"
size="small"
:loading="realnameIdentityLoading && realnameIdentityUser?.id === row.id"
@click="openRealnameIdentity(row)"
>
查看实名
</el-button>
<el-button <el-button
v-if="canAdjustWallet" v-if="canAdjustWallet"
text text
@@ -844,6 +879,43 @@ function moneyCent(value: number | string | undefined) {
</template> </template>
</el-dialog> </el-dialog>
<el-dialog
:model-value="!!realnameIdentityUser"
title="实名信息"
width="500px"
destroy-on-close
@update:model-value="(visible: boolean) => !visible && closeRealnameIdentity()"
>
<div v-if="realnameIdentityUser" class="dialog-body">
<p>
<strong>{{ realnameIdentityUser.phone }}</strong> · {{ realnameIdentityUser.nickname }} ·
{{ userSiteLabel(realnameIdentityUser) }}
</p>
<el-descriptions v-loading="realnameIdentityLoading" :column="1" border>
<el-descriptions-item label="姓名">
{{ realnameIdentity?.real_name || '-' }}
</el-descriptions-item>
<el-descriptions-item label="身份证号">
<code>{{ realnameIdentity?.id_no || '-' }}</code>
</el-descriptions-item>
<el-descriptions-item label="实名状态">
{{
realnameIdentity?.status === 'verified' ? '已实名' : realnameIdentity?.status || '-'
}}
</el-descriptions-item>
<el-descriptions-item label="认证时间">
{{ formatDateTime(realnameIdentity?.verified_at, '未记录') }}
</el-descriptions-item>
<el-descriptions-item label="认证服务商">
{{ realnameIdentity?.provider || '-' }}
</el-descriptions-item>
</el-descriptions>
</div>
<template #footer>
<el-button @click="closeRealnameIdentity">关闭</el-button>
</template>
</el-dialog>
<el-dialog <el-dialog
:model-value="!!quotaUser" :model-value="!!quotaUser"
title="设置人工免押额度" title="设置人工免押额度"