users

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 24, 2026 License: GPL-3.0 Imports: 24 Imported by: 0

Documentation

Overview

Package users 用户管理模块

Index

Constants

View Source
const (
	RoleAdmin = "admin"
	RoleUser  = "user"
	RoleGuest = "guest"
)

UserRole 用户角色常量

View Source
const (
	StatusActive   = "active"
	StatusDisabled = "disabled"
)

UserStatus 用户状态常量

View Source
const (
	ModuleID      = "users"
	ModuleName    = "用户管理"
	ModuleVersion = "1.0.0"
)
View Source
const (
	TrustedDeviceDuration = 30 * 24 * time.Hour // 30 天
)

Variables

View Source
var (
	ErrUserNotFound      = errors.New("user not found")
	ErrUserExists        = errors.New("user already exists")
	ErrInvalidPassword   = errors.New("invalid password")
	ErrGroupNotFound     = errors.New("group not found")
	ErrGroupExists       = errors.New("group already exists")
	ErrCannotDeleteAdmin = errors.New("cannot delete admin user")
)

Functions

This section is empty.

Types

type ChangePasswordRequest

type ChangePasswordRequest struct {
	OldPassword string `json:"old_password" binding:"required"`
	NewPassword string `json:"new_password" binding:"required,min=6"`
}

ChangePasswordRequest 修改密码请求

type CreateGroupRequest

type CreateGroupRequest struct {
	Name        string `json:"name" binding:"required,min=2,max=64"`
	Description string `json:"description,omitempty"`
	Permissions string `json:"permissions,omitempty"`
}

CreateGroupRequest 创建用户组请求

type CreateUserRequest

type CreateUserRequest struct {
	Username string `json:"username" binding:"required,min=3,max=64"`
	Password string `json:"password" binding:"required,min=6"`
	Email    string `json:"email,omitempty" binding:"omitempty,email"`
	Nickname string `json:"nickname,omitempty"`
	Role     string `json:"role,omitempty"`
	GroupID  string `json:"group_id,omitempty"`
}

CreateUserRequest 创建用户请求

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler HTTP 处理器

func NewHandler

func NewHandler(service *Service, tokenManager *auth.TokenManager, logger *zap.Logger) *Handler

NewHandler 创建处理器

func (*Handler) ChangePassword

func (h *Handler) ChangePassword(c *gin.Context)

ChangePassword 修改密码

func (*Handler) CreateGroup

func (h *Handler) CreateGroup(c *gin.Context)

CreateGroup 创建用户组

func (*Handler) CreateUser

func (h *Handler) CreateUser(c *gin.Context)

CreateUser 创建用户

func (*Handler) DeleteGroup

func (h *Handler) DeleteGroup(c *gin.Context)

DeleteGroup 删除用户组

func (*Handler) DeleteUser

func (h *Handler) DeleteUser(c *gin.Context)

DeleteUser 删除用户

func (*Handler) Disable2FA

func (h *Handler) Disable2FA(c *gin.Context)

Disable2FA 关闭 2FA(需要已登录)

func (*Handler) Enable2FA

func (h *Handler) Enable2FA(c *gin.Context)

Enable2FA 验证并启用 2FA(需要已登录)

func (*Handler) Get2FAStatus

func (h *Handler) Get2FAStatus(c *gin.Context)

Get2FAStatus 获取 2FA 状态(需要已登录)

func (*Handler) GetCurrentUser

func (h *Handler) GetCurrentUser(c *gin.Context)

GetCurrentUser 获取当前用户

func (*Handler) GetUser

func (h *Handler) GetUser(c *gin.Context)

GetUser 获取单个用户

func (*Handler) ListGroups

func (h *Handler) ListGroups(c *gin.Context)

ListGroups 获取用户组列表

func (*Handler) ListUsers

func (h *Handler) ListUsers(c *gin.Context)

ListUsers 获取用户列表

func (*Handler) Login

func (h *Handler) Login(c *gin.Context)

Login 用户登录

func (*Handler) RefreshToken

func (h *Handler) RefreshToken(c *gin.Context)

RefreshToken 刷新访问令牌

func (*Handler) Register

func (h *Handler) Register(c *gin.Context)

Register 用户注册(已关闭,仅支持已登录用户通过 CreateUser 创建新用户)

func (*Handler) ResetPassword

func (h *Handler) ResetPassword(c *gin.Context)

ResetPassword 管理员重置密码(无需旧密码)

func (*Handler) Setup2FA

func (h *Handler) Setup2FA(c *gin.Context)

Setup2FA 开始设置 2FA(需要已登录)

func (*Handler) UpdateGroup

func (h *Handler) UpdateGroup(c *gin.Context)

UpdateGroup 更新用户组

func (*Handler) UpdateUser

func (h *Handler) UpdateUser(c *gin.Context)

UpdateUser 更新用户

func (*Handler) UploadAvatar

func (h *Handler) UploadAvatar(c *gin.Context)

UploadAvatar 上传用户头像

func (*Handler) Verify2FA

func (h *Handler) Verify2FA(c *gin.Context)

Verify2FA 验证 2FA 码完成登录(公开路由,通过 temp_token 鉴权)

type LoginRequest

type LoginRequest struct {
	Username    string `json:"username" binding:"required"`
	Password    string `json:"password" binding:"required"`
	DeviceToken string `json:"device_token,omitempty"` // 受信任设备令牌(可跳过 2FA)
}

LoginRequest 登录请求 LoginRequest 登录请求

type LoginResponse

type LoginResponse struct {
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expires_at"`
	User      *User     `json:"user"`
}

LoginResponse 登录响应

type Module

type Module struct {
	// contains filtered or unexported fields
}

Module 用户管理模块

func New

func New() *Module

New 创建用户模块

func NewModule

func NewModule() *Module

NewModule 创建用户模块(别名)

func (*Module) CreateAdminUser

func (m *Module) CreateAdminUser(username, password string) error

CreateAdminUser 创建管理员用户(用于安装初始化)

func (*Module) Dependencies

func (m *Module) Dependencies() []string

Dependencies 返回依赖的模块

func (*Module) GetService

func (m *Module) GetService() *Service

GetService 获取服务实例(供其他模块调用)

func (*Module) ID

func (m *Module) ID() string

ID 返回模块 ID

func (*Module) Init

func (m *Module) Init(ctx *module.Context) error

Init 初始化模块

func (*Module) Name

func (m *Module) Name() string

Name 返回模块名称

func (*Module) RegisterRoutes

func (m *Module) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes 注册路由

func (*Module) Start

func (m *Module) Start() error

Start 启动模块

func (*Module) Stop

func (m *Module) Stop() error

Stop 停止模块

func (*Module) Version

func (m *Module) Version() string

Version 返回模块版本

type ResetPasswordRequest

type ResetPasswordRequest struct {
	NewPassword string `json:"new_password" binding:"required,min=6"`
}

ResetPasswordRequest 管理员重置密码请求(无需旧密码)

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service 用户服务

func NewService

func NewService(db *gorm.DB, logger *zap.Logger) *Service

NewService 创建用户服务

func (*Service) AddTrustedDevice

func (s *Service) AddTrustedDevice(userID, userAgent, ip string) (string, error)

AddTrustedDevice 添加受信任设备

func (*Service) ChangePassword

func (s *Service) ChangePassword(id, oldPassword, newPassword string) error

ChangePassword 修改密码

func (*Service) CreateGroup

func (s *Service) CreateGroup(req *CreateGroupRequest) (*UserGroup, error)

CreateGroup 创建用户组

func (*Service) CreateUser

func (s *Service) CreateUser(req *CreateUserRequest) error

CreateUser 创建用户

func (*Service) DeleteGroup

func (s *Service) DeleteGroup(id string) error

DeleteGroup 删除用户组

func (*Service) DeleteUser

func (s *Service) DeleteUser(id string) error

DeleteUser 删除用户

func (*Service) Disable2FA

func (s *Service) Disable2FA(userID string) error

Disable2FA 关闭 2FA

func (*Service) Enable2FA

func (s *Service) Enable2FA(userID, code string) error

Enable2FA 验证 TOTP 码并启用 2FA

func (*Service) EnsureAdminExists

func (s *Service) EnsureAdminExists() error

EnsureAdminExists 检查是否存在管理员账户 注意:不再自动创建默认 admin 账户,管理员应通过 Setup 流程创建

func (*Service) GetByID

func (s *Service) GetByID(id string) (*User, error)

GetByID 根据 ID 获取用户(GetUserByID 的别名)

func (*Service) GetGroupByID

func (s *Service) GetGroupByID(id string) (*UserGroup, error)

GetGroupByID 根据 ID 获取用户组

func (*Service) GetUserByID

func (s *Service) GetUserByID(id string) (*User, error)

GetUserByID 根据 ID 获取用户

func (*Service) GetUserByUsername

func (s *Service) GetUserByUsername(username string) (*User, error)

GetUserByUsername 根据用户名获取用户

func (*Service) IsOnline

func (s *Service) IsOnline(userID string) bool

IsOnline 检查用户是否在线(5 分钟内有活动)

func (*Service) IsTotpEnabled

func (s *Service) IsTotpEnabled(userID string) bool

IsTotpEnabled 检查用户是否启用了 2FA

func (*Service) IsTrustedDevice

func (s *Service) IsTrustedDevice(userID, deviceToken string) bool

IsTrustedDevice 检查是否为受信任设备

func (*Service) ListGroups

func (s *Service) ListGroups() ([]UserGroup, error)

ListGroups 获取用户组列表

func (*Service) ListTrustedDevices

func (s *Service) ListTrustedDevices(userID string) ([]TrustedDevice, error)

ListTrustedDevices 列出用户的受信任设备

func (*Service) ListUsers

func (s *Service) ListUsers(page, pageSize int) ([]User, int64, error)

ListUsers 获取用户列表

func (*Service) RecordActivity

func (s *Service) RecordActivity(userID string)

RecordActivity 记录用户活跃(由 auth 中间件调用)

func (*Service) RemoveTrustedDevice

func (s *Service) RemoveTrustedDevice(userID, deviceID string) error

RemoveTrustedDevice 移除受信任设备

func (*Service) ResetPassword

func (s *Service) ResetPassword(id, newPassword string) error

ResetPassword 管理员重置密码(无需旧密码)

func (*Service) SaveAvatar

func (s *Service) SaveAvatar(userID string, file *multipart.FileHeader, c *gin.Context) (string, error)

SaveAvatar 保存用户头像文件并更新数据库

func (*Service) SetAvatarsDir

func (s *Service) SetAvatarsDir(dir string)

SetAvatarsDir 设置头像存储目录

func (*Service) SetEventBus

func (s *Service) SetEventBus(eventBus module.EventBus)

SetEventBus 设置事件总线

func (*Service) Setup2FA

func (s *Service) Setup2FA(userID string) (*TwoFactorSetupResponse, error)

Setup2FA 设置 2FA(生成密钥和恢复码,尚未启用)

func (*Service) UpdateGroup

func (s *Service) UpdateGroup(id string, req *UpdateGroupRequest) error

UpdateGroup 更新用户组

func (*Service) UpdateLastLogin

func (s *Service) UpdateLastLogin(userID string) error

UpdateLastLogin 更新用户最后登录时间

func (*Service) UpdateUser

func (s *Service) UpdateUser(id string, req *UpdateUserRequest) error

UpdateUser 更新用户

func (*Service) Validate2FA

func (s *Service) Validate2FA(userID, code string) (bool, error)

Validate2FA 验证 TOTP 码或备用恢复码

func (*Service) ValidatePassword

func (s *Service) ValidatePassword(username, password string) (*User, error)

ValidatePassword 验证密码

type TrustedDevice

type TrustedDevice struct {
	ID        string    `json:"id"`         // 设备唯一标识(随机生成)
	Token     string    `json:"token"`      // 设备信任令牌
	UserAgent string    `json:"user_agent"` // 浏览器 UA
	IP        string    `json:"ip"`         // 登录 IP
	CreatedAt time.Time `json:"created_at"` // 创建时间
	ExpiresAt time.Time `json:"expires_at"` // 过期时间
}

TrustedDevice 受信任设备

type TwoFactorSettings

type TwoFactorSettings struct {
	TotpSecret     string          `json:"totp_secret"`
	TotpEnabled    bool            `json:"totp_enabled"`
	BackupCodes    []string        `json:"backup_codes"`
	TrustedDevices []TrustedDevice `json:"trusted_devices,omitempty"`
}

TwoFactorSettings 2FA 设置(存储在 User.Settings JSON 中)

type TwoFactorSetupResponse

type TwoFactorSetupResponse struct {
	Secret      string   `json:"secret"`
	QRCodeURL   string   `json:"qr_code_url"`
	BackupCodes []string `json:"backup_codes"`
}

TwoFactorSetupResponse 2FA 设置响应

type UpdateGroupRequest

type UpdateGroupRequest struct {
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
	Permissions string `json:"permissions,omitempty"`
}

UpdateGroupRequest 更新用户组请求

type UpdateUserRequest

type UpdateUserRequest struct {
	Email    string `json:"email,omitempty" binding:"omitempty,email"`
	Nickname string `json:"nickname,omitempty"`
	Avatar   string `json:"avatar,omitempty"`
	Role     string `json:"role,omitempty"`
	Status   string `json:"status,omitempty"`
	GroupID  string `json:"group_id,omitempty"`
	Settings string `json:"settings,omitempty"`
}

UpdateUserRequest 更新用户请求

type User

type User struct {
	ID        string         `json:"id" gorm:"primaryKey;size:36"`
	Username  string         `json:"username" gorm:"uniqueIndex;size:64;not null"`
	Email     string         `json:"email,omitempty" gorm:"size:128"`
	Password  string         `json:"-" gorm:"size:128;not null"` // 不返回给前端
	Nickname  string         `json:"nickname" gorm:"size:64"`
	Avatar    string         `json:"avatar,omitempty" gorm:"size:255"`
	Role      string         `json:"role" gorm:"size:32;default:'user'"`     // admin, user, guest
	Status    string         `json:"status" gorm:"size:32;default:'active'"` // active, disabled
	GroupID   string         `json:"group_id,omitempty" gorm:"size:36;index"`
	Settings  string         `json:"settings,omitempty" gorm:"type:text"` // JSON 存储用户设置
	LastLogin *time.Time     `json:"last_login,omitempty"`
	CreatedAt time.Time      `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt time.Time      `json:"updated_at" gorm:"autoUpdateTime"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	Group *UserGroup `json:"group,omitempty" gorm:"foreignKey:GroupID"`
}

User 用户模型

func (User) TableName

func (User) TableName() string

TableName 指定表名

type UserGroup

type UserGroup struct {
	ID          string         `json:"id" gorm:"primaryKey;size:36"`
	Name        string         `json:"name" gorm:"uniqueIndex;size:64;not null"`
	Description string         `json:"description,omitempty" gorm:"size:255"`
	Permissions string         `json:"permissions,omitempty" gorm:"type:text"` // JSON 存储权限列表
	CreatedAt   time.Time      `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt   time.Time      `json:"updated_at" gorm:"autoUpdateTime"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	Users []User `json:"users,omitempty" gorm:"foreignKey:GroupID"`
}

UserGroup 用户组模型

func (UserGroup) TableName

func (UserGroup) TableName() string

TableName 指定表名

type Verify2FARequest

type Verify2FARequest struct {
	Code           string `json:"code" binding:"required"`
	TempToken      string `json:"temp_token,omitempty"`      // 登录时使用
	RememberDevice bool   `json:"remember_device,omitempty"` // 记住此设备
}

Verify2FARequest 验证 2FA 请求

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL