Help us shape the future of Go! Take the 2026 Go Developer Survey

verifycode

package
v1.75.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package verifycode 提供独立的验证码插件。

这是从 admin 插件中拆分出的独立验证码插件,可单独注册使用, 也可与 admin 插件一起使用(admin 插件会自动识别并使用本插件)。

功能:

  • 生成验证码(绑定角色/权限)
  • 验证码验证(支持一次性和多次使用)
  • 有效期控制
  • 验证码吊销

使用示例:

pm.Register(verifycode.New())
vcSvc := ctx.Service[*verifycode.Plugin]("verifycode")
code, _ := vc.Generate(verifycode.Config{Role: "vip", TTL: 24*time.Hour, MaxUses: 1})
role, err := vc.Verify(userID, codeStr)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(onVerify OnVerifyHook, opts ...Option) *plugin.Descriptor

New 创建验证码插件描述符

Types

type CodeConfig

type CodeConfig struct {
	// Role 验证成功后授予的角色
	Role string
	// TTL 有效期(0 表示永不过期)
	TTL time.Duration
	// MaxUses 最大使用次数(0=一次性,<0=无限次)
	MaxUses int
}

CodeConfig 验证码配置

type CodeEntry

type CodeEntry struct {
	Code      string     `json:"code"`
	Role      string     `json:"role"`
	CreatedAt time.Time  `json:"created_at"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	MaxUses   int        `json:"max_uses"`
	UsedCount int        `json:"used_count"`
	UsedBy    []string   `json:"used_by,omitempty"`
}

CodeEntry 验证码记录

func (*CodeEntry) IsExhausted

func (e *CodeEntry) IsExhausted() bool

IsExhausted 检查验证码是否已达使用上限

func (*CodeEntry) IsExpired

func (e *CodeEntry) IsExpired() bool

IsExpired 检查验证码是否已过期

func (*CodeEntry) IsValid

func (e *CodeEntry) IsValid() bool

IsValid 检查验证码是否可用

type OnVerifyHook

type OnVerifyHook func(userID, role string) error

OnVerifyHook 验证成功后的回调(用于授予角色/权限)

type Option

type Option func(*Plugin)

Option 配置选项

func WithStore added in v1.4.0

func WithStore(path string) Option

WithStore 设置 LevelDB 持久化路径。空字符串表示纯内存模式。

type Plugin

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

Plugin 验证码插件

func NewPlugin

func NewPlugin(onVerify OnVerifyHook, opts ...Option) *Plugin

NewPlugin 创建 Plugin 实例

func (*Plugin) Descriptor

func (p *Plugin) Descriptor() *plugin.Descriptor

Descriptor 从已有 Plugin 创建描述符

func (*Plugin) GC

func (p *Plugin) GC() int

GC 清理过期验证码,返回清理数量

func (*Plugin) Generate

func (p *Plugin) Generate(cfg CodeConfig) (string, error)

Generate 生成验证码,返回验证码字符串

func (*Plugin) ListValid

func (p *Plugin) ListValid() []*CodeEntry

ListValid 返回所有有效(未过期未耗尽)的验证码

func (*Plugin) Revoke

func (p *Plugin) Revoke(code string) bool

Revoke 吊销验证码

func (*Plugin) Verify

func (p *Plugin) Verify(userID, code string) (string, error)

Verify 验证验证码,成功则调用 OnVerifyHook 并返回角色名

Jump to

Keyboard shortcuts

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