🔮

会员模块

模块注册

package internal import ( "github.com/zlsgo/app_core/service" "github.com/zlsgo/app_module/database" "github.com/zlsgo/app_module/member" ) func RegModule() []service.Module { dbMod := database.New() // TODO: 请自行随机生成一个新的密钥,注意密钥需要妥善保管,不要泄露 key := "Kj9#mP2$nL5@qR8*vX4&hC7!wY3^bN6" memberMod := member.New(key, func(o *member.Options) { // 开启手动注册功能 o.EnableRegister = true }) return []service.Module{ memberMod, dbMod, } }
 

路由中间件

h.DI.InvokeWithErrorOnly(func(memberModule *member.Module) { // 获取鉴权中间件 memberMiddleware := memberModule.Instance().GetMiddleware() // 给当前路由组配置中间件 r.Use(memberMiddleware) })
 

路由注入用户信息

// 注册路由的时候可以使用 *member.User 动态注入用户信息 r.Any("info", func(c *znet.Context, user *member.User) (any, error) { return user, nil })
 

第三方授权

自定义授权示例

授权接口
package common import ( "errors" "strings" "github.com/sohaha/zlsgo/znet" "github.com/sohaha/zlsgo/zstring" "github.com/zlsgo/app_module/account/auth" ) type AuthDemo struct{} func (a *AuthDemo) Callback(c *znet.Context) (auth.Provider, error) { id := c.DefaultQuery("id", "") if id == "" { return auth.Provider{}, errors.New("id is empty") } return auth.Provider{ Provider: "demo", ProviderID: id, ProviderUsername: id, }, nil } func (a *AuthDemo) Init(r *znet.Engine) error { return nil } func (a *AuthDemo) Login(c *znet.Context) error { paths := strings.Split(c.Request.URL.Path, "/") paths = paths[:len(paths)-1] paths = append(paths, "callback") url := strings.Join(paths, "/") url = url + "?id=" + zstring.UniqueID(8) // 跳转到授权页面 c.Redirect(url) return nil } func (a *AuthDemo) Name() string { return "demo" } var _ auth.AuthProvider = (*AuthDemo)(nil)
注册接口
package internal import ( "app/internal/common" "github.com/zlsgo/app_core/service" "github.com/zlsgo/app_module/account/auth" "github.com/zlsgo/app_module/database" "github.com/zlsgo/app_module/member" ) func RegModule() []service.Module { dbMod := database.New() key := "Kj9#mP2$nL5@qR8*vX4&hC7!wY3^bN6" memberMod := member.New(key, func(o *member.Options) { // 注册自定义provider o.Providers = []auth.AuthProvider{&common.AuthDemo{}} o.EnabledProviders = []string{"demo"} }) return []service.Module{ memberMod, dbMod, } }
使用方式
# 直接访问授权链接: curl -L http://127.0.0.1:8181/member/auth/demo/login