You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2.3 KiB
2.3 KiB
Casdoor 客户端封装
代码
package casdoorx
import (
"context"
"fmt"
"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
)
type Client struct {
client *casdoorsdk.Client
}
func NewClient(endpoint, clientId, clientSecret, certificate, organization, application string) *Client {
client := casdoorsdk.NewClient(
endpoint,
clientId,
clientSecret,
certificate,
organization,
application,
)
return &Client{client: client}
}
// GetSignInUrl 获取登录链接
func (c *Client) GetSignInUrl(state string) string {
return c.client.GetSignInUrl(state)
}
// ExchangeToken 用 code 换取 access token
func (c *Client) ExchangeToken(code string) (*casdoorsdk.AuthConfig, error) {
token, err := c.client.GetOAuthToken(code, state)
if err != nil {
return nil, fmt.Errorf("exchange token failed: %w", err)
}
claims, err := c.client.ParseJwtToken(token.AccessToken)
if err != nil {
return nil, fmt.Errorf("parse token failed: %w", err)
}
return &casdoorsdk.AuthConfig{
AccessToken: token.AccessToken,
Claims: claims,
}, nil
}
// ParseToken 解析 JWT Token
func (c *Client) ParseToken(token string) (*casdoorsdk.Claims, error) {
return c.client.ParseJwtToken(token)
}
ServiceContext 集成
package svc
import (
"backend/internal/casdoorx"
"backend/internal/config"
"backend/internal/jwtx"
"backend/model"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type ServiceContext struct {
Config config.Config
DB *gorm.DB
Casdoor *casdoorx.Client
JWT *jwtx.JWTManager
}
func NewServiceContext(c config.Config) *ServiceContext {
// 数据库连接
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=true",
c.MySQL.Username, c.MySQL.Password, c.MySQL.Host, c.MySQL.Port, c.MySQL.Database)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
// 自动迁移
db.AutoMigrate(&model.User{})
// Casdoor 客户端
casdoorClient := casdoorx.NewClient(
c.Casdoor.Endpoint,
c.Casdoor.ClientId,
c.Casdoor.ClientSecret,
c.Casdoor.JwtPublicKey,
c.Casdoor.Organization,
c.Casdoor.Application,
)
// JWT 管理器
jwtManager := jwtx.NewJWTManager(c.JWT.Secret, c.JWT.Expire)
return &ServiceContext{
Config: c,
DB: db,
Casdoor: casdoorClient,
JWT: jwtManager,
}
}