style(service): refactor global dependencies to use local variables

This commit is contained in:
lejianwen
2025-02-26 19:15:38 +08:00
parent 0403d71502
commit 7410b539a0
13 changed files with 213 additions and 198 deletions
+27 -28
View File
@@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/lejianwen/rustdesk-api/v2/global"
"github.com/lejianwen/rustdesk-api/v2/model"
"github.com/lejianwen/rustdesk-api/v2/utils"
"golang.org/x/oauth2"
@@ -99,7 +98,7 @@ func (os *OauthService) BeginAuth(op string) (error error, state, verifier, nonc
verifier = ""
nonce = ""
if op == model.OauthTypeWebauth {
url = global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + state
url = Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + state
//url = "http://localhost:8888/_admin/#/oauth/" + code
return nil, state, verifier, nonce, url
}
@@ -164,7 +163,7 @@ func (os *OauthService) GetOauthConfig(op string) (err error, oauthInfo *model.O
}
// If the redirect URL is empty, use the default redirect URL
if oauthInfo.RedirectUrl == "" {
oauthInfo.RedirectUrl = global.Config.Rustdesk.ApiServer + "/api/oidc/callback"
oauthInfo.RedirectUrl = Config.Rustdesk.ApiServer + "/api/oidc/callback"
}
oauthConfig = &oauth2.Config{
ClientID: oauthInfo.ClientId,
@@ -202,14 +201,14 @@ func (os *OauthService) GetOauthConfig(op string) (err error, oauthInfo *model.O
func getHTTPClientWithProxy() *http.Client {
//add timeout 30s
timeout := time.Duration(60) * time.Second
if global.Config.Proxy.Enable {
if global.Config.Proxy.Host == "" {
global.Logger.Warn("Proxy is enabled but proxy host is empty.")
if Config.Proxy.Enable {
if Config.Proxy.Host == "" {
Logger.Warn("Proxy is enabled but proxy host is empty.")
return http.DefaultClient
}
proxyURL, err := url.Parse(global.Config.Proxy.Host)
proxyURL, err := url.Parse(Config.Proxy.Host)
if err != nil {
global.Logger.Warn("Invalid proxy URL: ", err)
Logger.Warn("Invalid proxy URL: ", err)
return http.DefaultClient
}
transport := &http.Transport{
@@ -233,7 +232,7 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
token, err := oauthConfig.Exchange(ctx, code, exchangeOpts...)
if err != nil {
global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
Logger.Warn("oauthConfig.Exchange() failed: ", err)
return errors.New("GetOauthTokenError"), nil
}
@@ -244,7 +243,7 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
v := provider.Verifier(&oidc.Config{ClientID: oauthConfig.ClientID})
idToken, err2 := v.Verify(ctx, rawIDToken)
if err2 != nil {
global.Logger.Warn("IdTokenVerifyError: ", err2)
Logger.Warn("IdTokenVerifyError: ", err2)
return errors.New("IdTokenVerifyError"), nil
}
if nonce != "" {
@@ -253,12 +252,12 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
Nonce string `json:"nonce"`
}
if err2 = idToken.Claims(&claims); err2 != nil {
global.Logger.Warn("Failed to parse ID Token claims: ", err)
Logger.Warn("Failed to parse ID Token claims: ", err)
return errors.New("IDTokenClaimsError"), nil
}
if claims.Nonce != nonce {
global.Logger.Warn("Nonce does not match")
Logger.Warn("Nonce does not match")
return errors.New("NonceDoesNotMatch"), nil
}
}
@@ -268,18 +267,18 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
client = oauthConfig.Client(ctx, token)
resp, err := client.Get(provider.UserInfoEndpoint())
if err != nil {
global.Logger.Warn("failed getting user info: ", err)
Logger.Warn("failed getting user info: ", err)
return errors.New("GetOauthUserInfoError"), nil
}
defer func() {
if closeErr := resp.Body.Close(); closeErr != nil {
global.Logger.Warn("failed closing response body: ", closeErr)
Logger.Warn("failed closing response body: ", closeErr)
}
}()
// 解析用户信息
if err = json.NewDecoder(resp.Body).Decode(userData); err != nil {
global.Logger.Warn("failed decoding user info: ", err)
Logger.Warn("failed decoding user info: ", err)
return errors.New("DecodeOauthUserInfoError"), nil
}
@@ -330,7 +329,7 @@ func (os *OauthService) Callback(code, verifier, op, nonce string) (err error, o
func (os *OauthService) UserThirdInfo(op string, openId string) *model.UserThird {
ut := &model.UserThird{}
global.DB.Where("open_id = ? and op = ?", openId, op).First(ut)
DB.Where("open_id = ? and op = ?", openId, op).First(ut)
return ut
}
@@ -342,7 +341,7 @@ func (os *OauthService) BindOauthUser(userId uint, oauthUser *model.OauthUser, o
return err
}
utr.FromOauthUser(userId, oauthUser, oauthType, op)
return global.DB.Create(utr).Error
return DB.Create(utr).Error
}
// UnBindOauthUser: Unbind third party account
@@ -352,25 +351,25 @@ func (os *OauthService) UnBindOauthUser(userId uint, op string) error {
// UnBindThird: Unbind third party account
func (os *OauthService) UnBindThird(op string, userId uint) error {
return global.DB.Where("user_id = ? and op = ?", userId, op).Delete(&model.UserThird{}).Error
return DB.Where("user_id = ? and op = ?", userId, op).Delete(&model.UserThird{}).Error
}
// DeleteUserByUserId: When user is deleted, delete all third party bindings
func (os *OauthService) DeleteUserByUserId(userId uint) error {
return global.DB.Where("user_id = ?", userId).Delete(&model.UserThird{}).Error
return DB.Where("user_id = ?", userId).Delete(&model.UserThird{}).Error
}
// InfoById 根据id获取Oauth信息
func (os *OauthService) InfoById(id uint) *model.Oauth {
oauthInfo := &model.Oauth{}
global.DB.Where("id = ?", id).First(oauthInfo)
DB.Where("id = ?", id).First(oauthInfo)
return oauthInfo
}
// InfoByOp 根据op获取Oauth信息
func (os *OauthService) InfoByOp(op string) *model.Oauth {
oauthInfo := &model.Oauth{}
global.DB.Where("op = ?", op).First(oauthInfo)
DB.Where("op = ?", op).First(oauthInfo)
return oauthInfo
}
@@ -393,7 +392,7 @@ func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res
res = &model.OauthList{}
res.Page = int64(page)
res.PageSize = int64(pageSize)
tx := global.DB.Model(&model.Oauth{})
tx := DB.Model(&model.Oauth{})
if where != nil {
where(tx)
}
@@ -406,7 +405,7 @@ func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res
// GetTypeByOp 根据op获取OauthType
func (os *OauthService) GetTypeByOp(op string) (error, string) {
oauthInfo := &model.Oauth{}
if global.DB.Where("op = ?", op).First(oauthInfo).Error != nil {
if DB.Where("op = ?", op).First(oauthInfo).Error != nil {
return fmt.Errorf("OAuth provider with op '%s' not found", op), ""
}
return nil, oauthInfo.OauthType
@@ -424,7 +423,7 @@ func (os *OauthService) ValidateOauthProvider(op string) error {
func (os *OauthService) IsOauthProviderExist(op string) bool {
oauthInfo := &model.Oauth{}
// 使用 Gorm 的 Take 方法查找符合条件的记录
if err := global.DB.Where("op = ?", op).Take(oauthInfo).Error; err != nil {
if err := DB.Where("op = ?", op).Take(oauthInfo).Error; err != nil {
return false
}
return true
@@ -436,11 +435,11 @@ func (os *OauthService) Create(oauthInfo *model.Oauth) error {
if err != nil {
return err
}
res := global.DB.Create(oauthInfo).Error
res := DB.Create(oauthInfo).Error
return res
}
func (os *OauthService) Delete(oauthInfo *model.Oauth) error {
return global.DB.Delete(oauthInfo).Error
return DB.Delete(oauthInfo).Error
}
// Update 更新
@@ -449,13 +448,13 @@ func (os *OauthService) Update(oauthInfo *model.Oauth) error {
if err != nil {
return err
}
return global.DB.Model(oauthInfo).Updates(oauthInfo).Error
return DB.Model(oauthInfo).Updates(oauthInfo).Error
}
// GetOauthProviders 获取所有的provider
func (os *OauthService) GetOauthProviders() []string {
var res []string
global.DB.Model(&model.Oauth{}).Pluck("op", &res)
DB.Model(&model.Oauth{}).Pluck("op", &res)
return res
}