Documentation
¶
Index ¶
- Constants
- func AccountLockoutMiddleware() mist.HandleFunc
- func CheckLoginMiddleware(paths ...string) mist.Middleware
- func CleanupSecurity()
- func ClearToken(ctx *mist.Context) error
- func Middleware() mist.HandleFunc
- func RecordFailedLoginAttempt(ctx *mist.Context) bool
- func RenewAccessToken(ctx *mist.Context) error
- func ResetLockout(ctx *mist.Context)
- func SessionWithSecurityMiddleware(manager *session.Manager) mist.HandleFunc
- func SetDefaultProvider(sp Provider)
- func SetSecurityConfig(config SecurityConfig)
- func SetSecurityLevel(level SecurityLevel)
- func UpdateClaims(ctx *mist.Context, claims Claims) error
- type AccountLockoutConfig
- type AuthConfig
- type Builder
- type CSRFConfig
- type Claims
- type HeadersConfig
- type MiddlewareBuilder
- type PasswordConfig
- type Provider
- type RateLimitConfig
- type SecurityConfig
- type SecurityLevel
- type Session
- type SessionConfig
Constants ¶
const CtxSessionKey = "_session"
CtxSessionKey is a constant string used as a key for storing session data in the context.
Variables ¶
This section is empty.
Functions ¶
func AccountLockoutMiddleware ¶ added in v0.1.26
func AccountLockoutMiddleware() mist.HandleFunc
AccountLockoutMiddleware 创建账户锁定中间件
func CheckLoginMiddleware ¶
func CheckLoginMiddleware(paths ...string) mist.Middleware
CheckLoginMiddleware creates a middleware that checks if the user is logged in for specified paths. Parameters: - paths: A variadic list of URL paths to be checked (string). Returns: - mist.Middleware: The constructed middleware.
func ClearToken ¶ added in v0.1.12
ClearToken is a function that serves as a wrapper to invoke the ClearToken method of the defaultProvider. It clears the access and refresh tokens for a session by leveraging the default session provider.
Parameters:
- ctx: The mist.Context object representing the current HTTP request and response.
Returns:
- An error object if the underlying ClearToken method in defaultProvider fails, otherwise it returns nil.
func RecordFailedLoginAttempt ¶ added in v0.1.26
RecordFailedLoginAttempt 记录失败的登录尝试
func RenewAccessToken ¶
RenewAccessToken renews the access token for the session associated with the given context. Parameters: - ctx: The request context (*mist.Context). Returns: - error: An error if the token renewal fails.
func SessionWithSecurityMiddleware ¶ added in v0.1.26
func SessionWithSecurityMiddleware(manager *session.Manager) mist.HandleFunc
SessionWithSecurityMiddleware 创建增强的安全会话中间件
func SetDefaultProvider ¶
func SetDefaultProvider(sp Provider)
SetDefaultProvider sets the default session provider. Parameters: - sp: The session provider to be set as the default (Provider).
func SetSecurityConfig ¶ added in v0.1.20
func SetSecurityConfig(config SecurityConfig)
SetSecurityConfig 设置全局安全配置
func SetSecurityLevel ¶ added in v0.1.20
func SetSecurityLevel(level SecurityLevel)
SetSecurityLevel 设置全局安全级别
func UpdateClaims ¶
UpdateClaims updates the claims for the session associated with the given context. Parameters: - ctx: The request context (*mist.Context). - claims: The claims to be updated (Claims). Returns: - error: An error if the claims update fails.
Types ¶
type AccountLockoutConfig ¶ added in v0.1.26
type AccountLockoutConfig struct {
// Enabled 是否启用账户锁定
Enabled bool
// MaxAttempts 允许的最大失败尝试次数
MaxAttempts int
// LockoutDuration 锁定持续时间
LockoutDuration time.Duration
// ResetDuration 失败尝试记录重置时间
ResetDuration time.Duration
// IncludeIPInKey 是否在锁定键中包含IP地址
IncludeIPInKey bool
// CleanupInterval 清理过期锁定记录的间隔
CleanupInterval time.Duration
}
AccountLockoutConfig 账户锁定配置
type AuthConfig ¶ added in v0.1.20
type AuthConfig struct {
// JWTSecret JWT密钥
JWTSecret string
// EnableRefreshToken 是否启用刷新令牌
EnableRefreshToken bool
// MaxLoginAttempts 最大登录尝试次数
MaxLoginAttempts int
// LockoutDuration 锁定时长
LockoutDuration time.Duration
// AccountLockout 账户锁定策略
AccountLockout AccountLockoutConfig
}
AuthConfig 身份验证配置
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder is a structure that helps in building a session configuration step by step. It contains the context, user ID, JWT data, session data, and a session provider.
func InitSessionBuilder ¶ added in v0.1.11
InitSessionBuilder initializes and returns a new instance of Builder with the given context and user ID. The default session provider is set during initialization. Parameters: - ctx: The request context (*mist.Context). - uid: The user ID for the session (int64). Returns: - *Builder: A pointer to a newly created Builder instance.
func (*Builder) Build ¶
Build constructs the session using the provided or default session provider, context, user ID, JWT data, and session data. Returns: - Session: The newly created session. - error: An error if the session creation fails.
func (*Builder) SetJwtData ¶
SetJwtData sets the JWT data for the Builder. Parameters: - data: The JWT-related data (map[string]any). Returns: - *Builder: The Builder instance with the updated JWT data.
func (*Builder) SetProvider ¶
SetProvider sets a custom session provider for the Builder. Parameters: - p: The custom session provider (Provider). Returns: - *Builder: The Builder instance with the updated provider.
type CSRFConfig ¶ added in v0.1.20
type CSRFConfig struct {
// Enabled 是否启用CSRF保护
Enabled bool
// TokenLength CSRF令牌长度
TokenLength int
// CookieName CSRF Cookie名称
CookieName string
// HeaderName CSRF HTTP头名称
HeaderName string
// FormField CSRF表单字段名称
FormField string
// IgnoreMethods 忽略的HTTP方法
IgnoreMethods []string
}
CSRFConfig CSRF配置
type Claims ¶
type Claims struct {
UserID int64 // User ID
SessionID string // Session ID
Data map[string]any // Additional data related to the claims
}
Claims structure holds the data associated with the session's JWT claims.
type HeadersConfig ¶ added in v0.1.20
type HeadersConfig struct {
// EnableXSSProtection 是否启用XSS防护
EnableXSSProtection bool
// EnableContentTypeNosniff 是否启用内容类型嗅探保护
EnableContentTypeNosniff bool
// EnableXFrameOptions 是否启用X-Frame-Options
EnableXFrameOptions bool
// XFrameOptionsValue X-Frame-Options的值
XFrameOptionsValue string
// EnableHSTS 是否启用HSTS
EnableHSTS bool
// HSTSMaxAge HSTS最大存活时间
HSTSMaxAge time.Duration
// HSTSIncludeSubdomains 是否包含子域名
HSTSIncludeSubdomains bool
// HSTSPreload 是否启用预加载
HSTSPreload bool
// ContentSecurityPolicy 内容安全策略
ContentSecurityPolicy string
// EnablePermissionsPolicy 是否启用权限策略
EnablePermissionsPolicy bool
// PermissionsPolicy 权限策略内容
PermissionsPolicy string
// EnableCrossOriginPolicies 是否启用跨域策略
EnableCrossOriginPolicies bool
// CrossOriginEmbedderPolicy 跨域嵌入者策略
CrossOriginEmbedderPolicy string
// CrossOriginOpenerPolicy 跨域打开者策略
CrossOriginOpenerPolicy string
// CrossOriginResourcePolicy 跨域资源策略
CrossOriginResourcePolicy string
// EnableCacheControl 是否启用缓存控制
EnableCacheControl bool
// CacheControl 缓存控制内容
CacheControl string
// EnableReferrerPolicy 是否启用引用策略
EnableReferrerPolicy bool
// ReferrerPolicy 引用策略内容
ReferrerPolicy string
}
HeadersConfig 安全HTTP头配置
type MiddlewareBuilder ¶
type MiddlewareBuilder struct {
// contains filtered or unexported fields
}
MiddlewareBuilder 是用于构建登录检查中间件的构建器
func InitMiddlewareBuilder ¶ added in v0.1.11
func InitMiddlewareBuilder(provider Provider, paths ...string) *MiddlewareBuilder
InitMiddlewareBuilder 初始化一个新的中间件构建器 Parameters: - provider: 会话提供者接口 - paths: 需要检查登录状态的路径 Returns: - *MiddlewareBuilder: 初始化后的中间件构建器
func (*MiddlewareBuilder) Build ¶
func (m *MiddlewareBuilder) Build() mist.Middleware
Build 构建中间件 Returns: - mist.Middleware: 构建的中间件函数
type PasswordConfig ¶ added in v0.1.20
type PasswordConfig struct {
// MinLength 最小长度
MinLength int
// RequireUppercase 是否要求大写字母
RequireUppercase bool
// RequireLowercase 是否要求小写字母
RequireLowercase bool
// RequireDigits 是否要求数字
RequireDigits bool
// RequireSpecialChars 是否要求特殊字符
RequireSpecialChars bool
// MaxAge 密码最长使用时间
MaxAge time.Duration
// PreventReuseCount 禁止重复使用最近密码的数量
PreventReuseCount int
}
PasswordConfig 密码配置
type Provider ¶
type Provider interface {
// InitSession initializes a new session with the specified user ID, JWT data, and session data.
// Parameters:
// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('mist.Context')
// - uid: user ID for which the session is being created ('int64')
// - jwtData: JWT token data (usually claims) to store with the session ('map[string]any')
// - sessData: additional session-specific data to associate with the session ('map[string]any')
// Returns:
// - Session: the initialized session
// - error: error, if any occurred while initializing the session
InitSession(ctx *mist.Context, uid int64, jwtData map[string]any, sessData map[string]any) (Session, error)
// Get retrieves the current session associated with the context.
// Parameters:
// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('mist.Context')
// Returns:
// - Session: the current session
// - error: error, if any occurred while retrieving the session
Get(ctx *mist.Context) (Session, error)
// UpdateClaims updates the claims associated with the current session.
// Parameters:
// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('mist.Context')
// - claims: a new set of claims to associate with the session ('Claims')
// Returns:
// - error: error, if any occurred while updating the claims
UpdateClaims(ctx *mist.Context, claims Claims) error
// RenewAccessToken renews the access token associated with the session.
// Parameters:
// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('mist.Context')
// Returns:
// - error: error, if any occurred while renewing the access token
RenewAccessToken(ctx *mist.Context) error
// The ClearToken function is designed to remove or invalidate a security or session token associated with the given context.
//
// Parameters:
// ctx: A pointer to a mist.Context object, which holds contextual information for the function to operate within.
// The mist.Context might include various details like user information, request scope, or environmental settings.
//
// Return:
// error: This function returns an error type. If the token clearing process fails for any reason (e.g., token doesn't exist,
// network issues, permission issues), the function will return a non-nil error indicating what went wrong.
// If the token clearing process is successful, it returns nil.
ClearToken(ctx *mist.Context) error
}
Provider interface defines methods for session lifecycle management and JWT claim updates.
func DefaultProvider ¶
func DefaultProvider() Provider
DefaultProvider returns the current default session provider. Returns: - Provider: The current default session provider.
type RateLimitConfig ¶ added in v0.1.20
type RateLimitConfig struct {
// Enabled 是否启用限流
Enabled bool
// Rate 每秒请求限制
Rate float64
// Burst 突发请求限制
Burst int
// EnableIPRateLimit 是否启用IP限流
EnableIPRateLimit bool
// UseRedisBackend 是否使用Redis后端
UseRedisBackend bool
}
RateLimitConfig 限流配置
type SecurityConfig ¶ added in v0.1.20
type SecurityConfig struct {
// Level 安全级别
Level SecurityLevel
// Session 会话配置
Session SessionConfig
// CSRF 防跨站请求伪造配置
CSRF CSRFConfig
// RateLimit 请求限流配置
RateLimit RateLimitConfig
// Headers HTTP安全头配置
Headers HeadersConfig
// Auth 身份验证配置
Auth AuthConfig
// Password 密码策略配置
Password PasswordConfig
}
SecurityConfig 是安全模块的主配置结构
func DefaultSecurityConfig ¶ added in v0.1.20
func DefaultSecurityConfig(level SecurityLevel) SecurityConfig
DefaultSecurityConfig 返回基于指定安全级别的默认配置
func GetSecurityConfig ¶ added in v0.1.20
func GetSecurityConfig() SecurityConfig
GetSecurityConfig 获取当前全局安全配置
type SecurityLevel ¶ added in v0.1.20
type SecurityLevel int
SecurityLevel 表示应用程序的安全级别
const ( // LevelBasic 基本安全级别,适用于开发或不太敏感的应用 LevelBasic SecurityLevel = iota // LevelIntermediate 中级安全级别,适用于一般Web应用 LevelIntermediate // LevelStrict 严格安全级别,适用于处理敏感数据的应用 LevelStrict // LevelCustom 自定义安全级别,使用用户指定的设置 LevelCustom )
func GetSecurityLevel ¶ added in v0.1.20
func GetSecurityLevel() SecurityLevel
GetSecurityLevel 获取当前安全级别
type Session ¶
type Session interface {
// Set assigns a value to a session key. The context is typically used for request-scoped values.
// Parameters:
// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('context.Context')
// - key: the key under which the value is stored ('string')
// - val: the value to store, which can be of any type ('any')
// Returns:
// - error: error, if any occurred while setting the value
Set(ctx context.Context, key string, val any) error
// Get retrieves the value associated with the key from the session.
// Parameters:
// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('context.Context')
// - key: the key for the value to be retrieved ('string')
// Returns:
// - mist.AnyValue: a wrapper containing the retrieved value or an error if the key wasn't found
Get(ctx context.Context, key string) mist.AnyValue
// Del deletes the key-value pair associated with the key from the session.
// Parameters:
// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('context.Context')
// - key: the key for the value to be deleted ('string')
// Returns:
// - error: error, if any occurred while deleting the value
Del(ctx context.Context, key string) error
// Destroy invalidates the session entirely, clearing all data within the session.
// Parameters:
// - ctx: context for managing deadlines, cancel operation signals, and other request-scoped values ('context.Context')
// Returns:
// - error: error, if any occurred while destroying the session
Destroy(ctx context.Context) error
// Claims retrieves the claims associated with the session. Claims usually contain user-related data, often in a JWT context.
// Returns:
// - Claims: a set of claims related to the session
Claims() Claims
}
Session interface defines multiple methods for session management.
func Get ¶
Get retrieves the session associated with the given context using the default provider. Parameters: - ctx: The request context (*mist.Context). Returns: - Session: The session associated with the context. - error: An error if the session retrieval fails.
func InitSession ¶ added in v0.1.11
func InitSession(ctx *mist.Context, uid int64, jwtData map[string]any, sessData map[string]any) (Session, error)
InitSession initializes a new session using the default provider. Parameters: - ctx: The request context (*mist.Context). - uid: User ID for the session (int64). - jwtData: JWT-related data to be included in the session (map[string]any). - sessData: Additional session data (map[string]any). Returns: - Session: The newly created session. - error: An error if the session creation fails.
type SessionConfig ¶ added in v0.1.20
type SessionConfig struct {
// Enabled 是否启用会话管理
Enabled bool
// Domain Cookie域名
Domain string
// Path Cookie路径
Path string
// MaxAge 会话最大存活时间
MaxAge time.Duration
// Secure 是否仅通过HTTPS发送Cookie
Secure bool
// HttpOnly 是否禁止JavaScript访问Cookie
HttpOnly bool
// SameSite Cookie的SameSite属性
SameSite http.SameSite
// AccessTokenExpiry 访问令牌过期时间
AccessTokenExpiry time.Duration
// RefreshTokenExpiry 刷新令牌过期时间
RefreshTokenExpiry time.Duration
// TokenHeader 令牌的HTTP头
TokenHeader string
// AccessTokenHeader 访问令牌的HTTP头
AccessTokenHeader string
// RefreshTokenHeader 刷新令牌的HTTP头
RefreshTokenHeader string
// IdleTimeout 会话闲置超时时间
IdleTimeout time.Duration
// AbsoluteTimeout 会话绝对过期时间(无论活动与否)
AbsoluteTimeout time.Duration
// EnableFingerprinting 启用会话指纹绑定
EnableFingerprinting bool
// RotateTokenOnValidation 每次认证成功后轮换会话令牌
RotateTokenOnValidation bool
// RequireReauthForSensitive 敏感操作需要重新验证
RequireReauthForSensitive bool
// ReauthTimeout 重新验证超时时间
ReauthTimeout time.Duration
}
SessionConfig 会话配置