102 lines
2.4 KiB
Go
102 lines
2.4 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
logtoClient "github.com/logto-io/go/v2/client"
|
|
)
|
|
|
|
// AuthConfig 认证配置
|
|
type AuthConfig struct {
|
|
Type string `json:"type"` // 登录方式
|
|
Password AuthPassword `json:"password"` // 密码登录配置
|
|
Logto AuthLogto `json:"logto"` // Logto登录配置
|
|
}
|
|
|
|
// Validate
|
|
// @description: 验证认证配置
|
|
// @receiver c
|
|
// @return error
|
|
func (c *AuthConfig) Validate() error {
|
|
if c.Type == "" {
|
|
return fmt.Errorf("auth type cannot be empty")
|
|
}
|
|
|
|
switch c.Type {
|
|
case "password":
|
|
if err := c.Password.Validate(); err != nil {
|
|
return err
|
|
}
|
|
case "logto":
|
|
if err := c.Logto.Validate(); err != nil {
|
|
return err
|
|
}
|
|
default:
|
|
return fmt.Errorf("unsupported auth type: %s", c.Type)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// AuthPassword
|
|
// @description: 密码登录
|
|
type AuthPassword struct {
|
|
SecretKey string `mapstructure:"secretKey"` // 用于JWT签名的密钥
|
|
AdminToken string `mapstructure:"adminToken"` // 管理员登录口令
|
|
TokenExpiry int `mapstructure:"tokenExpiry"` // Token过期时间(小时)
|
|
}
|
|
|
|
// Validate 验证认证配置
|
|
func (c *AuthPassword) Validate() error {
|
|
if c.SecretKey == "" {
|
|
return fmt.Errorf("auth secret key cannot be empty")
|
|
}
|
|
|
|
if c.AdminToken == "" {
|
|
return fmt.Errorf("admin token cannot be empty")
|
|
}
|
|
|
|
if c.TokenExpiry <= 0 {
|
|
c.TokenExpiry = 24 // 默认24小时
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// IsValidToken 检查提供的token是否与配置的管理员token匹配
|
|
func (c *AuthPassword) IsValidToken(token string) bool {
|
|
return token == c.AdminToken
|
|
}
|
|
|
|
// AuthLogto
|
|
// @description: Logto登录
|
|
type AuthLogto struct {
|
|
Endpoint string `mapstructure:"endpoint"` // Logto服务地址
|
|
AppId string `mapstructure:"appId"` // Logto应用ID
|
|
AppSecret string `mapstructure:"appSecret"` // Logto应用密钥
|
|
}
|
|
|
|
// Validate 验证Logto配置
|
|
func (c *AuthLogto) Validate() error {
|
|
if c.Endpoint == "" {
|
|
return fmt.Errorf("logto endpoint cannot be empty")
|
|
}
|
|
|
|
if c.AppId == "" {
|
|
return fmt.Errorf("logto app id cannot be empty")
|
|
}
|
|
|
|
if c.AppSecret == "" {
|
|
return fmt.Errorf("logto app secret cannot be empty")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// GetLogtoClient
|
|
// @description: 获取Logto客户端
|
|
// @receiver c
|
|
// @return cli
|
|
func (c *AuthLogto) GetLogtoClient() (cli *logtoClient.LogtoConfig) {
|
|
return &logtoClient.LogtoConfig{Endpoint: c.Endpoint, AppId: c.AppId, AppSecret: c.AppSecret}
|
|
}
|