Browse Source

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

lejianwen 11 months ago
parent
commit
403d9c2233
13 changed files with 213 additions and 198 deletions
  1. 3 0
      cmd/apimain.go
  2. 31 32
      service/addressBook.go
  3. 13 14
      service/audit.go
  4. 10 11
      service/group.go
  5. 10 11
      service/ldap.go
  6. 7 8
      service/loginLog.go
  7. 27 28
      service/oauth.go
  8. 14 15
      service/peer.go
  9. 10 11
      service/serverCmd.go
  10. 27 4
      service/service.go
  11. 6 7
      service/shareRecord.go
  12. 8 9
      service/tag.go
  13. 47 48
      service/user.go

+ 3 - 0
cmd/apimain.go

@@ -164,6 +164,9 @@ func InitGlobal() {
164 164
 	global.Jwt = jwt.NewJwt(global.Config.Jwt.Key, global.Config.Jwt.ExpireDuration)
165 165
 	//locker
166 166
 	global.Lock = lock.NewLocal()
167
+
168
+	//service
169
+	service.New(&global.Config, global.DB, global.Logger, global.Jwt, global.Lock)
167 170
 }
168 171
 func DatabaseAutoUpdate() {
169 172
 	version := 262

+ 31 - 32
service/addressBook.go

@@ -3,7 +3,6 @@ package service
3 3
 import (
4 4
 	"encoding/json"
5 5
 	"github.com/google/uuid"
6
-	"github.com/lejianwen/rustdesk-api/v2/global"
7 6
 	"github.com/lejianwen/rustdesk-api/v2/model"
8 7
 	"gorm.io/gorm"
9 8
 	"strings"
@@ -14,24 +13,24 @@ type AddressBookService struct {
14 13
 
15 14
 func (s *AddressBookService) Info(id string) *model.AddressBook {
16 15
 	p := &model.AddressBook{}
17
-	global.DB.Where("id = ?", id).First(p)
16
+	DB.Where("id = ?", id).First(p)
18 17
 	return p
19 18
 }
20 19
 
21 20
 func (s *AddressBookService) InfoByUserIdAndId(userid uint, id string) *model.AddressBook {
22 21
 	p := &model.AddressBook{}
23
-	global.DB.Where("user_id = ? and id = ?", userid, id).First(p)
22
+	DB.Where("user_id = ? and id = ?", userid, id).First(p)
24 23
 	return p
25 24
 }
26 25
 
27 26
 func (s *AddressBookService) InfoByUserIdAndIdAndCid(userid uint, id string, cid uint) *model.AddressBook {
28 27
 	p := &model.AddressBook{}
29
-	global.DB.Where("user_id = ? and id = ? and collection_id = ?", userid, id, cid).First(p)
28
+	DB.Where("user_id = ? and id = ? and collection_id = ?", userid, id, cid).First(p)
30 29
 	return p
31 30
 }
32 31
 func (s *AddressBookService) InfoByRowId(id uint) *model.AddressBook {
33 32
 	p := &model.AddressBook{}
34
-	global.DB.Where("row_id = ?", id).First(p)
33
+	DB.Where("row_id = ?", id).First(p)
35 34
 	return p
36 35
 }
37 36
 func (s *AddressBookService) ListByUserId(userId, page, pageSize uint) (res *model.AddressBookList) {
@@ -49,14 +48,14 @@ func (s *AddressBookService) ListByUserIds(userIds []uint, page, pageSize uint)
49 48
 
50 49
 // AddAddressBook
51 50
 func (s *AddressBookService) AddAddressBook(ab *model.AddressBook) error {
52
-	return global.DB.Create(ab).Error
51
+	return DB.Create(ab).Error
53 52
 }
54 53
 
55 54
 // UpdateAddressBook
56 55
 func (s *AddressBookService) UpdateAddressBook(abs []*model.AddressBook, userId uint) error {
57 56
 	//比较peers和数据库中的数据,如果peers中的数据在数据库中不存在,则添加,如果存在则更新,如果数据库中的数据在peers中不存在,则删除
58 57
 	// 开始事务
59
-	tx := global.DB.Begin()
58
+	tx := DB.Begin()
60 59
 	//1. 获取数据库中的数据
61 60
 	var dbABs []*model.AddressBook
62 61
 	tx.Where("user_id = ?", userId).Find(&dbABs)
@@ -107,7 +106,7 @@ func (s *AddressBookService) List(page, pageSize uint, where func(tx *gorm.DB))
107 106
 	res = &model.AddressBookList{}
108 107
 	res.Page = int64(page)
109 108
 	res.PageSize = int64(pageSize)
110
-	tx := global.DB.Model(&model.AddressBook{})
109
+	tx := DB.Model(&model.AddressBook{})
111 110
 	if where != nil {
112 111
 		where(tx)
113 112
 	}
@@ -129,38 +128,38 @@ func (s *AddressBookService) FromPeer(peer *model.Peer) (a *model.AddressBook) {
129 128
 
130 129
 // Create 创建
131 130
 func (s *AddressBookService) Create(u *model.AddressBook) error {
132
-	res := global.DB.Create(u).Error
131
+	res := DB.Create(u).Error
133 132
 	return res
134 133
 }
135 134
 func (s *AddressBookService) Delete(u *model.AddressBook) error {
136
-	return global.DB.Delete(u).Error
135
+	return DB.Delete(u).Error
137 136
 }
138 137
 
139 138
 // Update 更新
140 139
 func (s *AddressBookService) Update(u *model.AddressBook) error {
141
-	return global.DB.Model(u).Updates(u).Error
140
+	return DB.Model(u).Updates(u).Error
142 141
 }
143 142
 
144 143
 // UpdateByMap 更新
145 144
 func (s *AddressBookService) UpdateByMap(u *model.AddressBook, data map[string]interface{}) error {
146
-	return global.DB.Model(u).Updates(data).Error
145
+	return DB.Model(u).Updates(data).Error
147 146
 }
148 147
 
149 148
 // UpdateAll 更新
150 149
 func (s *AddressBookService) UpdateAll(u *model.AddressBook) error {
151
-	return global.DB.Model(u).Select("*").Omit("created_at").Updates(u).Error
150
+	return DB.Model(u).Select("*").Omit("created_at").Updates(u).Error
152 151
 }
153 152
 
154 153
 // ShareByWebClient 分享
155 154
 func (s *AddressBookService) ShareByWebClient(m *model.ShareRecord) error {
156 155
 	m.ShareToken = uuid.New().String()
157
-	return global.DB.Create(m).Error
156
+	return DB.Create(m).Error
158 157
 }
159 158
 
160 159
 // SharedPeer
161 160
 func (s *AddressBookService) SharedPeer(shareToken string) *model.ShareRecord {
162 161
 	m := &model.ShareRecord{}
163
-	global.DB.Where("share_token = ?", shareToken).First(m)
162
+	DB.Where("share_token = ?", shareToken).First(m)
164 163
 	return m
165 164
 }
166 165
 
@@ -190,7 +189,7 @@ func (s *AddressBookService) ListCollection(page, pageSize uint, where func(tx *
190 189
 	res = &model.AddressBookCollectionList{}
191 190
 	res.Page = int64(page)
192 191
 	res.PageSize = int64(pageSize)
193
-	tx := global.DB.Model(&model.AddressBookCollection{})
192
+	tx := DB.Model(&model.AddressBookCollection{})
194 193
 	if where != nil {
195 194
 		where(tx)
196 195
 	}
@@ -200,7 +199,7 @@ func (s *AddressBookService) ListCollection(page, pageSize uint, where func(tx *
200 199
 	return
201 200
 }
202 201
 func (s *AddressBookService) ListCollectionByIds(ids []uint) (res []*model.AddressBookCollection) {
203
-	global.DB.Where("id in ?", ids).Find(&res)
202
+	DB.Where("id in ?", ids).Find(&res)
204 203
 	return res
205 204
 }
206 205
 
@@ -212,20 +211,20 @@ func (s *AddressBookService) ListCollectionByUserId(userId uint) (res *model.Add
212 211
 }
213 212
 func (s *AddressBookService) CollectionInfoById(id uint) *model.AddressBookCollection {
214 213
 	p := &model.AddressBookCollection{}
215
-	global.DB.Where("id = ?", id).First(p)
214
+	DB.Where("id = ?", id).First(p)
216 215
 	return p
217 216
 }
218 217
 
219 218
 func (s *AddressBookService) CollectionReadRules(user *model.User) (res []*model.AddressBookCollectionRule) {
220 219
 	// personalRules
221 220
 	var personalRules []*model.AddressBookCollectionRule
222
-	tx2 := global.DB.Model(&model.AddressBookCollectionRule{})
221
+	tx2 := DB.Model(&model.AddressBookCollectionRule{})
223 222
 	tx2.Where("type = ? and to_id = ? and rule > 0", model.ShareAddressBookRuleTypePersonal, user.Id).Find(&personalRules)
224 223
 	res = append(res, personalRules...)
225 224
 
226 225
 	//group
227 226
 	var groupRules []*model.AddressBookCollectionRule
228
-	tx3 := global.DB.Model(&model.AddressBookCollectionRule{})
227
+	tx3 := DB.Model(&model.AddressBookCollectionRule{})
229 228
 	tx3.Where("type = ? and to_id = ? and rule > 0", model.ShareAddressBookRuleTypeGroup, user.GroupId).Find(&groupRules)
230 229
 	res = append(res, groupRules...)
231 230
 	return
@@ -238,7 +237,7 @@ func (s *AddressBookService) UserMaxRule(user *model.User, uid, cid uint) int {
238 237
 	}
239 238
 	max := 0
240 239
 	personalRules := &model.AddressBookCollectionRule{}
241
-	tx := global.DB.Model(personalRules)
240
+	tx := DB.Model(personalRules)
242 241
 	tx.Where("type = ? and collection_id = ? and to_id = ?", model.ShareAddressBookRuleTypePersonal, cid, user.Id).First(&personalRules)
243 242
 	if personalRules.Id != 0 {
244 243
 		max = personalRules.Rule
@@ -248,7 +247,7 @@ func (s *AddressBookService) UserMaxRule(user *model.User, uid, cid uint) int {
248 247
 	}
249 248
 
250 249
 	groupRules := &model.AddressBookCollectionRule{}
251
-	tx2 := global.DB.Model(groupRules)
250
+	tx2 := DB.Model(groupRules)
252 251
 	tx2.Where("type = ? and collection_id = ? and to_id = ?", model.ShareAddressBookRuleTypeGroup, cid, user.GroupId).First(&groupRules)
253 252
 	if groupRules.Id != 0 {
254 253
 		if groupRules.Rule > max {
@@ -272,16 +271,16 @@ func (s *AddressBookService) CheckUserFullControlPrivilege(user *model.User, uid
272 271
 }
273 272
 
274 273
 func (s *AddressBookService) CreateCollection(t *model.AddressBookCollection) error {
275
-	return global.DB.Create(t).Error
274
+	return DB.Create(t).Error
276 275
 }
277 276
 
278 277
 func (s *AddressBookService) UpdateCollection(t *model.AddressBookCollection) error {
279
-	return global.DB.Model(t).Updates(t).Error
278
+	return DB.Model(t).Updates(t).Error
280 279
 }
281 280
 
282 281
 func (s *AddressBookService) DeleteCollection(t *model.AddressBookCollection) error {
283 282
 	//删除集合下的所有规则、地址簿,再删除集合
284
-	tx := global.DB.Begin()
283
+	tx := DB.Begin()
285 284
 	tx.Where("collection_id = ?", t.Id).Delete(&model.AddressBookCollectionRule{})
286 285
 	tx.Where("collection_id = ?", t.Id).Delete(&model.AddressBook{})
287 286
 	tx.Delete(t)
@@ -290,23 +289,23 @@ func (s *AddressBookService) DeleteCollection(t *model.AddressBookCollection) er
290 289
 
291 290
 func (s *AddressBookService) RuleInfoById(u uint) *model.AddressBookCollectionRule {
292 291
 	p := &model.AddressBookCollectionRule{}
293
-	global.DB.Where("id = ?", u).First(p)
292
+	DB.Where("id = ?", u).First(p)
294 293
 	return p
295 294
 }
296 295
 func (s *AddressBookService) RulePersonalInfoByToIdAndCid(toid, cid uint) *model.AddressBookCollectionRule {
297 296
 	p := &model.AddressBookCollectionRule{}
298
-	global.DB.Where("type = ? and to_id = ? and collection_id = ?", model.ShareAddressBookRuleTypePersonal, toid, cid).First(p)
297
+	DB.Where("type = ? and to_id = ? and collection_id = ?", model.ShareAddressBookRuleTypePersonal, toid, cid).First(p)
299 298
 	return p
300 299
 }
301 300
 func (s *AddressBookService) CreateRule(t *model.AddressBookCollectionRule) error {
302
-	return global.DB.Create(t).Error
301
+	return DB.Create(t).Error
303 302
 }
304 303
 
305 304
 func (s *AddressBookService) ListRules(page uint, size uint, f func(tx *gorm.DB)) *model.AddressBookCollectionRuleList {
306 305
 	res := &model.AddressBookCollectionRuleList{}
307 306
 	res.Page = int64(page)
308 307
 	res.PageSize = int64(size)
309
-	tx := global.DB.Model(&model.AddressBookCollectionRule{})
308
+	tx := DB.Model(&model.AddressBookCollectionRule{})
310 309
 	if f != nil {
311 310
 		f(tx)
312 311
 	}
@@ -317,11 +316,11 @@ func (s *AddressBookService) ListRules(page uint, size uint, f func(tx *gorm.DB)
317 316
 }
318 317
 
319 318
 func (s *AddressBookService) UpdateRule(t *model.AddressBookCollectionRule) error {
320
-	return global.DB.Model(t).Updates(t).Error
319
+	return DB.Model(t).Updates(t).Error
321 320
 }
322 321
 
323 322
 func (s *AddressBookService) DeleteRule(t *model.AddressBookCollectionRule) error {
324
-	return global.DB.Delete(t).Error
323
+	return DB.Delete(t).Error
325 324
 }
326 325
 
327 326
 // CheckCollectionOwner 检查Collection的所有者
@@ -336,5 +335,5 @@ func (s *AddressBookService) BatchUpdateTags(abs []*model.AddressBook, tags []st
336 335
 		ids = append(ids, ab.RowId)
337 336
 	}
338 337
 	tagsv, _ := json.Marshal(tags)
339
-	return global.DB.Model(&model.AddressBook{}).Where("row_id in ?", ids).Update("tags", tagsv).Error
338
+	return DB.Model(&model.AddressBook{}).Where("row_id in ?", ids).Update("tags", tagsv).Error
340 339
 }

+ 13 - 14
service/audit.go

@@ -1,7 +1,6 @@
1 1
 package service
2 2
 
3 3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5 4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6 5
 	"gorm.io/gorm"
7 6
 )
@@ -13,7 +12,7 @@ func (as *AuditService) AuditConnList(page, pageSize uint, where func(tx *gorm.D
13 12
 	res = &model.AuditConnList{}
14 13
 	res.Page = int64(page)
15 14
 	res.PageSize = int64(pageSize)
16
-	tx := global.DB.Model(&model.AuditConn{})
15
+	tx := DB.Model(&model.AuditConn{})
17 16
 	if where != nil {
18 17
 		where(tx)
19 18
 	}
@@ -25,36 +24,36 @@ func (as *AuditService) AuditConnList(page, pageSize uint, where func(tx *gorm.D
25 24
 
26 25
 // Create 创建
27 26
 func (as *AuditService) CreateAuditConn(u *model.AuditConn) error {
28
-	res := global.DB.Create(u).Error
27
+	res := DB.Create(u).Error
29 28
 	return res
30 29
 }
31 30
 func (as *AuditService) DeleteAuditConn(u *model.AuditConn) error {
32
-	return global.DB.Delete(u).Error
31
+	return DB.Delete(u).Error
33 32
 }
34 33
 
35 34
 // Update 更新
36 35
 func (as *AuditService) UpdateAuditConn(u *model.AuditConn) error {
37
-	return global.DB.Model(u).Updates(u).Error
36
+	return DB.Model(u).Updates(u).Error
38 37
 }
39 38
 
40 39
 // InfoByPeerIdAndConnId
41 40
 func (as *AuditService) InfoByPeerIdAndConnId(peerId string, connId int64) (res *model.AuditConn) {
42 41
 	res = &model.AuditConn{}
43
-	global.DB.Where("peer_id = ? and conn_id = ?", peerId, connId).First(res)
42
+	DB.Where("peer_id = ? and conn_id = ?", peerId, connId).First(res)
44 43
 	return
45 44
 }
46 45
 
47 46
 // ConnInfoById
48 47
 func (as *AuditService) ConnInfoById(id uint) (res *model.AuditConn) {
49 48
 	res = &model.AuditConn{}
50
-	global.DB.Where("id = ?", id).First(res)
49
+	DB.Where("id = ?", id).First(res)
51 50
 	return
52 51
 }
53 52
 
54 53
 // FileInfoById
55 54
 func (as *AuditService) FileInfoById(id uint) (res *model.AuditFile) {
56 55
 	res = &model.AuditFile{}
57
-	global.DB.Where("id = ?", id).First(res)
56
+	DB.Where("id = ?", id).First(res)
58 57
 	return
59 58
 }
60 59
 
@@ -62,7 +61,7 @@ func (as *AuditService) AuditFileList(page, pageSize uint, where func(tx *gorm.D
62 61
 	res = &model.AuditFileList{}
63 62
 	res.Page = int64(page)
64 63
 	res.PageSize = int64(pageSize)
65
-	tx := global.DB.Model(&model.AuditFile{})
64
+	tx := DB.Model(&model.AuditFile{})
66 65
 	if where != nil {
67 66
 		where(tx)
68 67
 	}
@@ -74,22 +73,22 @@ func (as *AuditService) AuditFileList(page, pageSize uint, where func(tx *gorm.D
74 73
 
75 74
 // CreateAuditFile
76 75
 func (as *AuditService) CreateAuditFile(u *model.AuditFile) error {
77
-	res := global.DB.Create(u).Error
76
+	res := DB.Create(u).Error
78 77
 	return res
79 78
 }
80 79
 func (as *AuditService) DeleteAuditFile(u *model.AuditFile) error {
81
-	return global.DB.Delete(u).Error
80
+	return DB.Delete(u).Error
82 81
 }
83 82
 
84 83
 // Update 更新
85 84
 func (as *AuditService) UpdateAuditFile(u *model.AuditFile) error {
86
-	return global.DB.Model(u).Updates(u).Error
85
+	return DB.Model(u).Updates(u).Error
87 86
 }
88 87
 
89 88
 func (as *AuditService) BatchDeleteAuditConn(ids []uint) error {
90
-	return global.DB.Where("id in (?)", ids).Delete(&model.AuditConn{}).Error
89
+	return DB.Where("id in (?)", ids).Delete(&model.AuditConn{}).Error
91 90
 }
92 91
 
93 92
 func (as *AuditService) BatchDeleteAuditFile(ids []uint) error {
94
-	return global.DB.Where("id in (?)", ids).Delete(&model.AuditFile{}).Error
93
+	return DB.Where("id in (?)", ids).Delete(&model.AuditFile{}).Error
95 94
 }

+ 10 - 11
service/group.go

@@ -1,7 +1,6 @@
1 1
 package service
2 2
 
3 3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5 4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6 5
 	"gorm.io/gorm"
7 6
 )
@@ -12,7 +11,7 @@ type GroupService struct {
12 11
 // InfoById 根据用户id取用户信息
13 12
 func (us *GroupService) InfoById(id uint) *model.Group {
14 13
 	u := &model.Group{}
15
-	global.DB.Where("id = ?", id).First(u)
14
+	DB.Where("id = ?", id).First(u)
16 15
 	return u
17 16
 }
18 17
 
@@ -20,7 +19,7 @@ func (us *GroupService) List(page, pageSize uint, where func(tx *gorm.DB)) (res
20 19
 	res = &model.GroupList{}
21 20
 	res.Page = int64(page)
22 21
 	res.PageSize = int64(pageSize)
23
-	tx := global.DB.Model(&model.Group{})
22
+	tx := DB.Model(&model.Group{})
24 23
 	if where != nil {
25 24
 		where(tx)
26 25
 	}
@@ -32,22 +31,22 @@ func (us *GroupService) List(page, pageSize uint, where func(tx *gorm.DB)) (res
32 31
 
33 32
 // Create 创建
34 33
 func (us *GroupService) Create(u *model.Group) error {
35
-	res := global.DB.Create(u).Error
34
+	res := DB.Create(u).Error
36 35
 	return res
37 36
 }
38 37
 func (us *GroupService) Delete(u *model.Group) error {
39
-	return global.DB.Delete(u).Error
38
+	return DB.Delete(u).Error
40 39
 }
41 40
 
42 41
 // Update 更新
43 42
 func (us *GroupService) Update(u *model.Group) error {
44
-	return global.DB.Model(u).Updates(u).Error
43
+	return DB.Model(u).Updates(u).Error
45 44
 }
46 45
 
47 46
 // DeviceGroupInfoById 根据用户id取用户信息
48 47
 func (us *GroupService) DeviceGroupInfoById(id uint) *model.DeviceGroup {
49 48
 	u := &model.DeviceGroup{}
50
-	global.DB.Where("id = ?", id).First(u)
49
+	DB.Where("id = ?", id).First(u)
51 50
 	return u
52 51
 }
53 52
 
@@ -55,7 +54,7 @@ func (us *GroupService) DeviceGroupList(page, pageSize uint, where func(tx *gorm
55 54
 	res = &model.DeviceGroupList{}
56 55
 	res.Page = int64(page)
57 56
 	res.PageSize = int64(pageSize)
58
-	tx := global.DB.Model(&model.DeviceGroup{})
57
+	tx := DB.Model(&model.DeviceGroup{})
59 58
 	if where != nil {
60 59
 		where(tx)
61 60
 	}
@@ -66,13 +65,13 @@ func (us *GroupService) DeviceGroupList(page, pageSize uint, where func(tx *gorm
66 65
 }
67 66
 
68 67
 func (us *GroupService) DeviceGroupCreate(u *model.DeviceGroup) error {
69
-	res := global.DB.Create(u).Error
68
+	res := DB.Create(u).Error
70 69
 	return res
71 70
 }
72 71
 func (us *GroupService) DeviceGroupDelete(u *model.DeviceGroup) error {
73
-	return global.DB.Delete(u).Error
72
+	return DB.Delete(u).Error
74 73
 }
75 74
 
76 75
 func (us *GroupService) DeviceGroupUpdate(u *model.DeviceGroup) error {
77
-	return global.DB.Model(u).Updates(u).Error
76
+	return DB.Model(u).Updates(u).Error
78 77
 }

+ 10 - 11
service/ldap.go

@@ -10,7 +10,6 @@ import (
10 10
 	"github.com/go-ldap/ldap/v3"
11 11
 
12 12
 	"github.com/lejianwen/rustdesk-api/v2/config"
13
-	"github.com/lejianwen/rustdesk-api/v2/global"
14 13
 	"github.com/lejianwen/rustdesk-api/v2/model"
15 14
 )
16 15
 
@@ -114,7 +113,7 @@ func (ls *LdapService) Authenticate(username, password string) (*model.User, err
114 113
 	if !ldapUser.Enabled {
115 114
 		return nil, ErrLdapUserDisabled
116 115
 	}
117
-	cfg := &global.Config.Ldap
116
+	cfg := &Config.Ldap
118 117
 	user, err := ls.mapToLocalUser(cfg, ldapUser)
119 118
 	if err != nil {
120 119
 		return nil, errors.Join(ErrLdapToLocalUserFailed, err)
@@ -135,7 +134,7 @@ func (ls *LdapService) mapToLocalUser(cfg *config.Ldap, lu *LdapUser) (*model.Us
135 134
 		// If needed, you can set a random password here.
136 135
 		newUser.IsAdmin = &isAdmin
137 136
 		newUser.GroupId = 1
138
-		if err := global.DB.Create(newUser).Error; err != nil {
137
+		if err := DB.Create(newUser).Error; err != nil {
139 138
 			return nil, errors.Join(ErrLdapCreateUserFailed, err)
140 139
 		}
141 140
 		return userService.InfoByUsername(lu.Username), nil
@@ -164,7 +163,7 @@ func (ls *LdapService) mapToLocalUser(cfg *config.Ldap, lu *LdapUser) (*model.Us
164 163
 // IsUsernameExists checks if a username exists in LDAP (can be useful for local registration checks).
165 164
 func (ls *LdapService) IsUsernameExists(username string) bool {
166 165
 
167
-	cfg := &global.Config.Ldap
166
+	cfg := &Config.Ldap
168 167
 	if !cfg.Enable {
169 168
 		return false
170 169
 	}
@@ -177,7 +176,7 @@ func (ls *LdapService) IsUsernameExists(username string) bool {
177 176
 
178 177
 // IsEmailExists checks if an email exists in LDAP (can be useful for local registration checks).
179 178
 func (ls *LdapService) IsEmailExists(email string) bool {
180
-	cfg := &global.Config.Ldap
179
+	cfg := &Config.Ldap
181 180
 	if !cfg.Enable {
182 181
 		return false
183 182
 	}
@@ -190,7 +189,7 @@ func (ls *LdapService) IsEmailExists(email string) bool {
190 189
 
191 190
 // GetUserInfoByUsernameLdap returns the user info from LDAP for the given username.
192 191
 func (ls *LdapService) GetUserInfoByUsernameLdap(username string) (*LdapUser, error) {
193
-	cfg := &global.Config.Ldap
192
+	cfg := &Config.Ldap
194 193
 	if !cfg.Enable {
195 194
 		return nil, ErrLdapNotEnabled
196 195
 	}
@@ -210,12 +209,12 @@ func (ls *LdapService) GetUserInfoByUsernameLocal(username string) (*model.User,
210 209
 	if err != nil {
211 210
 		return &model.User{}, err
212 211
 	}
213
-	return ls.mapToLocalUser(&global.Config.Ldap, ldapUser)
212
+	return ls.mapToLocalUser(&Config.Ldap, ldapUser)
214 213
 }
215 214
 
216 215
 // GetUserInfoByEmailLdap returns the user info from LDAP for the given email.
217 216
 func (ls *LdapService) GetUserInfoByEmailLdap(email string) (*LdapUser, error) {
218
-	cfg := &global.Config.Ldap
217
+	cfg := &Config.Ldap
219 218
 	if !cfg.Enable {
220 219
 		return nil, ErrLdapNotEnabled
221 220
 	}
@@ -235,7 +234,7 @@ func (ls *LdapService) GetUserInfoByEmailLocal(email string) (*model.User, error
235 234
 	if err != nil {
236 235
 		return &model.User{}, err
237 236
 	}
238
-	return ls.mapToLocalUser(&global.Config.Ldap, ldapUser)
237
+	return ls.mapToLocalUser(&Config.Ldap, ldapUser)
239 238
 }
240 239
 
241 240
 // usernameSearchResult returns the search result for the given username.
@@ -453,12 +452,12 @@ func (ls *LdapService) isUserEnabled(cfg *config.Ldap, ldapUser *LdapUser) bool
453 452
 
454 453
 		// Account is disabled if the ACCOUNTDISABLE flag (0x2) is set
455 454
 		const ACCOUNTDISABLE = 0x2
456
-		ldapUser.Enabled = (userAccountControl&ACCOUNTDISABLE == 0)
455
+		ldapUser.Enabled = userAccountControl&ACCOUNTDISABLE == 0
457 456
 		return ldapUser.Enabled
458 457
 	}
459 458
 
460 459
 	// For other attributes, perform a direct comparison with the expected value
461
-	ldapUser.Enabled = (ldapUser.EnableAttrValue == enableAttrValue)
460
+	ldapUser.Enabled = ldapUser.EnableAttrValue == enableAttrValue
462 461
 	return ldapUser.Enabled
463 462
 }
464 463
 

+ 7 - 8
service/loginLog.go

@@ -1,7 +1,6 @@
1 1
 package service
2 2
 
3 3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5 4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6 5
 	"gorm.io/gorm"
7 6
 )
@@ -12,7 +11,7 @@ type LoginLogService struct {
12 11
 // InfoById 根据用户id取用户信息
13 12
 func (us *LoginLogService) InfoById(id uint) *model.LoginLog {
14 13
 	u := &model.LoginLog{}
15
-	global.DB.Where("id = ?", id).First(u)
14
+	DB.Where("id = ?", id).First(u)
16 15
 	return u
17 16
 }
18 17
 
@@ -20,7 +19,7 @@ func (us *LoginLogService) List(page, pageSize uint, where func(tx *gorm.DB)) (r
20 19
 	res = &model.LoginLogList{}
21 20
 	res.Page = int64(page)
22 21
 	res.PageSize = int64(pageSize)
23
-	tx := global.DB.Model(&model.LoginLog{})
22
+	tx := DB.Model(&model.LoginLog{})
24 23
 	if where != nil {
25 24
 		where(tx)
26 25
 	}
@@ -32,20 +31,20 @@ func (us *LoginLogService) List(page, pageSize uint, where func(tx *gorm.DB)) (r
32 31
 
33 32
 // Create 创建
34 33
 func (us *LoginLogService) Create(u *model.LoginLog) error {
35
-	res := global.DB.Create(u).Error
34
+	res := DB.Create(u).Error
36 35
 	return res
37 36
 }
38 37
 func (us *LoginLogService) Delete(u *model.LoginLog) error {
39
-	return global.DB.Delete(u).Error
38
+	return DB.Delete(u).Error
40 39
 }
41 40
 
42 41
 // Update 更新
43 42
 func (us *LoginLogService) Update(u *model.LoginLog) error {
44
-	return global.DB.Model(u).Updates(u).Error
43
+	return DB.Model(u).Updates(u).Error
45 44
 }
46 45
 
47 46
 func (us *LoginLogService) BatchDelete(ids []uint) error {
48
-	return global.DB.Where("id in (?)", ids).Delete(&model.LoginLog{}).Error
47
+	return DB.Where("id in (?)", ids).Delete(&model.LoginLog{}).Error
49 48
 }
50 49
 
51 50
 func (us *LoginLogService) SoftDelete(l *model.LoginLog) error {
@@ -54,5 +53,5 @@ func (us *LoginLogService) SoftDelete(l *model.LoginLog) error {
54 53
 }
55 54
 
56 55
 func (us *LoginLogService) BatchSoftDelete(uid uint, ids []uint) error {
57
-	return global.DB.Model(&model.LoginLog{}).Where("user_id = ? and id in (?)", uid, ids).Update("is_deleted", model.IsDeletedYes).Error
56
+	return DB.Model(&model.LoginLog{}).Where("user_id = ? and id in (?)", uid, ids).Update("is_deleted", model.IsDeletedYes).Error
58 57
 }

+ 27 - 28
service/oauth.go

@@ -5,7 +5,6 @@ import (
5 5
 	"encoding/json"
6 6
 	"errors"
7 7
 	"github.com/coreos/go-oidc/v3/oidc"
8
-	"github.com/lejianwen/rustdesk-api/v2/global"
9 8
 	"github.com/lejianwen/rustdesk-api/v2/model"
10 9
 	"github.com/lejianwen/rustdesk-api/v2/utils"
11 10
 	"golang.org/x/oauth2"
@@ -99,7 +98,7 @@ func (os *OauthService) BeginAuth(op string) (error error, state, verifier, nonc
99 98
 	verifier = ""
100 99
 	nonce = ""
101 100
 	if op == model.OauthTypeWebauth {
102
-		url = global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + state
101
+		url = Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + state
103 102
 		//url = "http://localhost:8888/_admin/#/oauth/" + code
104 103
 		return nil, state, verifier, nonce, url
105 104
 	}
@@ -164,7 +163,7 @@ func (os *OauthService) GetOauthConfig(op string) (err error, oauthInfo *model.O
164 163
 	}
165 164
 	// If the redirect URL is empty, use the default redirect URL
166 165
 	if oauthInfo.RedirectUrl == "" {
167
-		oauthInfo.RedirectUrl = global.Config.Rustdesk.ApiServer + "/api/oidc/callback"
166
+		oauthInfo.RedirectUrl = Config.Rustdesk.ApiServer + "/api/oidc/callback"
168 167
 	}
169 168
 	oauthConfig = &oauth2.Config{
170 169
 		ClientID:     oauthInfo.ClientId,
@@ -202,14 +201,14 @@ func (os *OauthService) GetOauthConfig(op string) (err error, oauthInfo *model.O
202 201
 func getHTTPClientWithProxy() *http.Client {
203 202
 	//add timeout 30s
204 203
 	timeout := time.Duration(60) * time.Second
205
-	if global.Config.Proxy.Enable {
206
-		if global.Config.Proxy.Host == "" {
207
-			global.Logger.Warn("Proxy is enabled but proxy host is empty.")
204
+	if Config.Proxy.Enable {
205
+		if Config.Proxy.Host == "" {
206
+			Logger.Warn("Proxy is enabled but proxy host is empty.")
208 207
 			return http.DefaultClient
209 208
 		}
210
-		proxyURL, err := url.Parse(global.Config.Proxy.Host)
209
+		proxyURL, err := url.Parse(Config.Proxy.Host)
211 210
 		if err != nil {
212
-			global.Logger.Warn("Invalid proxy URL: ", err)
211
+			Logger.Warn("Invalid proxy URL: ", err)
213 212
 			return http.DefaultClient
214 213
 		}
215 214
 		transport := &http.Transport{
@@ -233,7 +232,7 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
233 232
 	token, err := oauthConfig.Exchange(ctx, code, exchangeOpts...)
234 233
 
235 234
 	if err != nil {
236
-		global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
235
+		Logger.Warn("oauthConfig.Exchange() failed: ", err)
237 236
 		return errors.New("GetOauthTokenError"), nil
238 237
 	}
239 238
 
@@ -244,7 +243,7 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
244 243
 		v := provider.Verifier(&oidc.Config{ClientID: oauthConfig.ClientID})
245 244
 		idToken, err2 := v.Verify(ctx, rawIDToken)
246 245
 		if err2 != nil {
247
-			global.Logger.Warn("IdTokenVerifyError: ", err2)
246
+			Logger.Warn("IdTokenVerifyError: ", err2)
248 247
 			return errors.New("IdTokenVerifyError"), nil
249 248
 		}
250 249
 		if nonce != "" {
@@ -253,12 +252,12 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
253 252
 				Nonce string `json:"nonce"`
254 253
 			}
255 254
 			if err2 = idToken.Claims(&claims); err2 != nil {
256
-				global.Logger.Warn("Failed to parse ID Token claims: ", err)
255
+				Logger.Warn("Failed to parse ID Token claims: ", err)
257 256
 				return errors.New("IDTokenClaimsError"), nil
258 257
 			}
259 258
 
260 259
 			if claims.Nonce != nonce {
261
-				global.Logger.Warn("Nonce does not match")
260
+				Logger.Warn("Nonce does not match")
262 261
 				return errors.New("NonceDoesNotMatch"), nil
263 262
 			}
264 263
 		}
@@ -268,18 +267,18 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
268 267
 	client = oauthConfig.Client(ctx, token)
269 268
 	resp, err := client.Get(provider.UserInfoEndpoint())
270 269
 	if err != nil {
271
-		global.Logger.Warn("failed getting user info: ", err)
270
+		Logger.Warn("failed getting user info: ", err)
272 271
 		return errors.New("GetOauthUserInfoError"), nil
273 272
 	}
274 273
 	defer func() {
275 274
 		if closeErr := resp.Body.Close(); closeErr != nil {
276
-			global.Logger.Warn("failed closing response body: ", closeErr)
275
+			Logger.Warn("failed closing response body: ", closeErr)
277 276
 		}
278 277
 	}()
279 278
 
280 279
 	// 解析用户信息
281 280
 	if err = json.NewDecoder(resp.Body).Decode(userData); err != nil {
282
-		global.Logger.Warn("failed decoding user info: ", err)
281
+		Logger.Warn("failed decoding user info: ", err)
283 282
 		return errors.New("DecodeOauthUserInfoError"), nil
284 283
 	}
285 284
 
@@ -330,7 +329,7 @@ func (os *OauthService) Callback(code, verifier, op, nonce string) (err error, o
330 329
 
331 330
 func (os *OauthService) UserThirdInfo(op string, openId string) *model.UserThird {
332 331
 	ut := &model.UserThird{}
333
-	global.DB.Where("open_id = ? and op = ?", openId, op).First(ut)
332
+	DB.Where("open_id = ? and op = ?", openId, op).First(ut)
334 333
 	return ut
335 334
 }
336 335
 
@@ -342,7 +341,7 @@ func (os *OauthService) BindOauthUser(userId uint, oauthUser *model.OauthUser, o
342 341
 		return err
343 342
 	}
344 343
 	utr.FromOauthUser(userId, oauthUser, oauthType, op)
345
-	return global.DB.Create(utr).Error
344
+	return DB.Create(utr).Error
346 345
 }
347 346
 
348 347
 // UnBindOauthUser: Unbind third party account
@@ -352,25 +351,25 @@ func (os *OauthService) UnBindOauthUser(userId uint, op string) error {
352 351
 
353 352
 // UnBindThird: Unbind third party account
354 353
 func (os *OauthService) UnBindThird(op string, userId uint) error {
355
-	return global.DB.Where("user_id = ? and op = ?", userId, op).Delete(&model.UserThird{}).Error
354
+	return DB.Where("user_id = ? and op = ?", userId, op).Delete(&model.UserThird{}).Error
356 355
 }
357 356
 
358 357
 // DeleteUserByUserId: When user is deleted, delete all third party bindings
359 358
 func (os *OauthService) DeleteUserByUserId(userId uint) error {
360
-	return global.DB.Where("user_id = ?", userId).Delete(&model.UserThird{}).Error
359
+	return DB.Where("user_id = ?", userId).Delete(&model.UserThird{}).Error
361 360
 }
362 361
 
363 362
 // InfoById 根据id获取Oauth信息
364 363
 func (os *OauthService) InfoById(id uint) *model.Oauth {
365 364
 	oauthInfo := &model.Oauth{}
366
-	global.DB.Where("id = ?", id).First(oauthInfo)
365
+	DB.Where("id = ?", id).First(oauthInfo)
367 366
 	return oauthInfo
368 367
 }
369 368
 
370 369
 // InfoByOp 根据op获取Oauth信息
371 370
 func (os *OauthService) InfoByOp(op string) *model.Oauth {
372 371
 	oauthInfo := &model.Oauth{}
373
-	global.DB.Where("op = ?", op).First(oauthInfo)
372
+	DB.Where("op = ?", op).First(oauthInfo)
374 373
 	return oauthInfo
375 374
 }
376 375
 
@@ -393,7 +392,7 @@ func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res
393 392
 	res = &model.OauthList{}
394 393
 	res.Page = int64(page)
395 394
 	res.PageSize = int64(pageSize)
396
-	tx := global.DB.Model(&model.Oauth{})
395
+	tx := DB.Model(&model.Oauth{})
397 396
 	if where != nil {
398 397
 		where(tx)
399 398
 	}
@@ -406,7 +405,7 @@ func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res
406 405
 // GetTypeByOp 根据op获取OauthType
407 406
 func (os *OauthService) GetTypeByOp(op string) (error, string) {
408 407
 	oauthInfo := &model.Oauth{}
409
-	if global.DB.Where("op = ?", op).First(oauthInfo).Error != nil {
408
+	if DB.Where("op = ?", op).First(oauthInfo).Error != nil {
410 409
 		return fmt.Errorf("OAuth provider with op '%s' not found", op), ""
411 410
 	}
412 411
 	return nil, oauthInfo.OauthType
@@ -424,7 +423,7 @@ func (os *OauthService) ValidateOauthProvider(op string) error {
424 423
 func (os *OauthService) IsOauthProviderExist(op string) bool {
425 424
 	oauthInfo := &model.Oauth{}
426 425
 	// 使用 Gorm 的 Take 方法查找符合条件的记录
427
-	if err := global.DB.Where("op = ?", op).Take(oauthInfo).Error; err != nil {
426
+	if err := DB.Where("op = ?", op).Take(oauthInfo).Error; err != nil {
428 427
 		return false
429 428
 	}
430 429
 	return true
@@ -436,11 +435,11 @@ func (os *OauthService) Create(oauthInfo *model.Oauth) error {
436 435
 	if err != nil {
437 436
 		return err
438 437
 	}
439
-	res := global.DB.Create(oauthInfo).Error
438
+	res := DB.Create(oauthInfo).Error
440 439
 	return res
441 440
 }
442 441
 func (os *OauthService) Delete(oauthInfo *model.Oauth) error {
443
-	return global.DB.Delete(oauthInfo).Error
442
+	return DB.Delete(oauthInfo).Error
444 443
 }
445 444
 
446 445
 // Update 更新
@@ -449,13 +448,13 @@ func (os *OauthService) Update(oauthInfo *model.Oauth) error {
449 448
 	if err != nil {
450 449
 		return err
451 450
 	}
452
-	return global.DB.Model(oauthInfo).Updates(oauthInfo).Error
451
+	return DB.Model(oauthInfo).Updates(oauthInfo).Error
453 452
 }
454 453
 
455 454
 // GetOauthProviders 获取所有的provider
456 455
 func (os *OauthService) GetOauthProviders() []string {
457 456
 	var res []string
458
-	global.DB.Model(&model.Oauth{}).Pluck("op", &res)
457
+	DB.Model(&model.Oauth{}).Pluck("op", &res)
459 458
 	return res
460 459
 }
461 460
 

+ 14 - 15
service/peer.go

@@ -1,7 +1,6 @@
1 1
 package service
2 2
 
3 3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5 4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6 5
 	"gorm.io/gorm"
7 6
 )
@@ -12,24 +11,24 @@ type PeerService struct {
12 11
 // FindById 根据id查找
13 12
 func (ps *PeerService) FindById(id string) *model.Peer {
14 13
 	p := &model.Peer{}
15
-	global.DB.Where("id = ?", id).First(p)
14
+	DB.Where("id = ?", id).First(p)
16 15
 	return p
17 16
 }
18 17
 func (ps *PeerService) FindByUuid(uuid string) *model.Peer {
19 18
 	p := &model.Peer{}
20
-	global.DB.Where("uuid = ?", uuid).First(p)
19
+	DB.Where("uuid = ?", uuid).First(p)
21 20
 	return p
22 21
 }
23 22
 func (ps *PeerService) InfoByRowId(id uint) *model.Peer {
24 23
 	p := &model.Peer{}
25
-	global.DB.Where("row_id = ?", id).First(p)
24
+	DB.Where("row_id = ?", id).First(p)
26 25
 	return p
27 26
 }
28 27
 
29 28
 // FindByUserIdAndUuid 根据用户id和uuid查找peer
30 29
 func (ps *PeerService) FindByUserIdAndUuid(uuid string, userId uint) *model.Peer {
31 30
 	p := &model.Peer{}
32
-	global.DB.Where("uuid = ? and user_id = ?", uuid, userId).First(p)
31
+	DB.Where("uuid = ? and user_id = ?", uuid, userId).First(p)
33 32
 	return p
34 33
 }
35 34
 
@@ -43,7 +42,7 @@ func (ps *PeerService) UuidBindUserId(deviceId string, uuid string, userId uint)
43 42
 	} else {
44 43
 		// 不存在则创建
45 44
 		/*if deviceId != "" {
46
-			global.DB.Create(&model.Peer{
45
+			DB.Create(&model.Peer{
47 46
 				Id:     deviceId,
48 47
 				Uuid:   uuid,
49 48
 				UserId: userId,
@@ -56,13 +55,13 @@ func (ps *PeerService) UuidBindUserId(deviceId string, uuid string, userId uint)
56 55
 func (ps *PeerService) UuidUnbindUserId(uuid string, userId uint) {
57 56
 	peer := ps.FindByUserIdAndUuid(uuid, userId)
58 57
 	if peer.RowId > 0 {
59
-		global.DB.Model(peer).Update("user_id", 0)
58
+		DB.Model(peer).Update("user_id", 0)
60 59
 	}
61 60
 }
62 61
 
63 62
 // EraseUserId 清除用户id, 用于用户删除
64 63
 func (ps *PeerService) EraseUserId(userId uint) error {
65
-	return global.DB.Model(&model.Peer{}).Where("user_id = ?", userId).Update("user_id", 0).Error
64
+	return DB.Model(&model.Peer{}).Where("user_id = ?", userId).Update("user_id", 0).Error
66 65
 }
67 66
 
68 67
 // ListByUserIds 根据用户id取列表
@@ -70,7 +69,7 @@ func (ps *PeerService) ListByUserIds(userIds []uint, page, pageSize uint) (res *
70 69
 	res = &model.PeerList{}
71 70
 	res.Page = int64(page)
72 71
 	res.PageSize = int64(pageSize)
73
-	tx := global.DB.Model(&model.Peer{})
72
+	tx := DB.Model(&model.Peer{})
74 73
 	tx.Where("user_id in (?)", userIds)
75 74
 	tx.Count(&res.Total)
76 75
 	tx.Scopes(Paginate(page, pageSize))
@@ -82,7 +81,7 @@ func (ps *PeerService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *
82 81
 	res = &model.PeerList{}
83 82
 	res.Page = int64(page)
84 83
 	res.PageSize = int64(pageSize)
85
-	tx := global.DB.Model(&model.Peer{})
84
+	tx := DB.Model(&model.Peer{})
86 85
 	if where != nil {
87 86
 		where(tx)
88 87
 	}
@@ -106,14 +105,14 @@ func (ps *PeerService) ListFilterByUserId(page, pageSize uint, where func(tx *go
106 105
 
107 106
 // Create 创建
108 107
 func (ps *PeerService) Create(u *model.Peer) error {
109
-	res := global.DB.Create(u).Error
108
+	res := DB.Create(u).Error
110 109
 	return res
111 110
 }
112 111
 
113 112
 // Delete 删除, 同时也应该删除token
114 113
 func (ps *PeerService) Delete(u *model.Peer) error {
115 114
 	uuid := u.Uuid
116
-	err := global.DB.Delete(u).Error
115
+	err := DB.Delete(u).Error
117 116
 	if err != nil {
118 117
 		return err
119 118
 	}
@@ -124,7 +123,7 @@ func (ps *PeerService) Delete(u *model.Peer) error {
124 123
 // GetUuidListByIDs 根据ids获取uuid列表
125 124
 func (ps *PeerService) GetUuidListByIDs(ids []uint) ([]string, error) {
126 125
 	var uuids []string
127
-	err := global.DB.Model(&model.Peer{}).
126
+	err := DB.Model(&model.Peer{}).
128 127
 		Where("row_id in (?)", ids).
129 128
 		Pluck("uuid", &uuids).Error
130 129
 	return uuids, err
@@ -133,7 +132,7 @@ func (ps *PeerService) GetUuidListByIDs(ids []uint) ([]string, error) {
133 132
 // BatchDelete 批量删除, 同时也应该删除token
134 133
 func (ps *PeerService) BatchDelete(ids []uint) error {
135 134
 	uuids, err := ps.GetUuidListByIDs(ids)
136
-	err = global.DB.Where("row_id in (?)", ids).Delete(&model.Peer{}).Error
135
+	err = DB.Where("row_id in (?)", ids).Delete(&model.Peer{}).Error
137 136
 	if err != nil {
138 137
 		return err
139 138
 	}
@@ -143,5 +142,5 @@ func (ps *PeerService) BatchDelete(ids []uint) error {
143 142
 
144 143
 // Update 更新
145 144
 func (ps *PeerService) Update(u *model.Peer) error {
146
-	return global.DB.Model(u).Updates(u).Error
145
+	return DB.Model(u).Updates(u).Error
147 146
 }

+ 10 - 11
service/serverCmd.go

@@ -2,7 +2,6 @@ package service
2 2
 
3 3
 import (
4 4
 	"fmt"
5
-	"github.com/lejianwen/rustdesk-api/v2/global"
6 5
 	"github.com/lejianwen/rustdesk-api/v2/model"
7 6
 	"net"
8 7
 	"time"
@@ -15,7 +14,7 @@ func (is *ServerCmdService) List(page, pageSize uint) (res *model.ServerCmdList)
15 14
 	res = &model.ServerCmdList{}
16 15
 	res.Page = int64(page)
17 16
 	res.PageSize = int64(pageSize)
18
-	tx := global.DB.Model(&model.ServerCmd{})
17
+	tx := DB.Model(&model.ServerCmd{})
19 18
 	tx.Count(&res.Total)
20 19
 	tx.Scopes(Paginate(page, pageSize))
21 20
 	tx.Find(&res.ServerCmds)
@@ -25,18 +24,18 @@ func (is *ServerCmdService) List(page, pageSize uint) (res *model.ServerCmdList)
25 24
 // Info
26 25
 func (is *ServerCmdService) Info(id uint) *model.ServerCmd {
27 26
 	u := &model.ServerCmd{}
28
-	global.DB.Where("id = ?", id).First(u)
27
+	DB.Where("id = ?", id).First(u)
29 28
 	return u
30 29
 }
31 30
 
32 31
 // Delete
33 32
 func (is *ServerCmdService) Delete(u *model.ServerCmd) error {
34
-	return global.DB.Delete(u).Error
33
+	return DB.Delete(u).Error
35 34
 }
36 35
 
37 36
 // Create
38 37
 func (is *ServerCmdService) Create(u *model.ServerCmd) error {
39
-	res := global.DB.Create(u).Error
38
+	res := DB.Create(u).Error
40 39
 	return res
41 40
 }
42 41
 
@@ -45,9 +44,9 @@ func (is *ServerCmdService) SendCmd(target string, cmd string, arg string) (stri
45 44
 	port := 0
46 45
 	switch target {
47 46
 	case model.ServerCmdTargetIdServer:
48
-		port = global.Config.Rustdesk.IdServerPort - 1
47
+		port = Config.Rustdesk.IdServerPort - 1
49 48
 	case model.ServerCmdTargetRelayServer:
50
-		port = global.Config.Rustdesk.RelayServerPort
49
+		port = Config.Rustdesk.RelayServerPort
51 50
 	}
52 51
 	//组装命令
53 52
 	cmd = cmd + " " + arg
@@ -73,14 +72,14 @@ func (is *ServerCmdService) SendSocketCmd(ty string, port int, cmd string) (stri
73 72
 	}
74 73
 	conn, err := net.Dial(tcp, fmt.Sprintf("%s:%v", addr, port))
75 74
 	if err != nil {
76
-		global.Logger.Debugf("%s connect to id server failed: %v", ty, err)
75
+		Logger.Debugf("%s connect to id server failed: %v", ty, err)
77 76
 		return "", err
78 77
 	}
79 78
 	defer conn.Close()
80 79
 	//发送命令
81 80
 	_, err = conn.Write([]byte(cmd))
82 81
 	if err != nil {
83
-		global.Logger.Debugf("%s send cmd failed: %v", ty, err)
82
+		Logger.Debugf("%s send cmd failed: %v", ty, err)
84 83
 		return "", err
85 84
 	}
86 85
 	time.Sleep(100 * time.Millisecond)
@@ -88,12 +87,12 @@ func (is *ServerCmdService) SendSocketCmd(ty string, port int, cmd string) (stri
88 87
 	buf := make([]byte, 1024)
89 88
 	n, err := conn.Read(buf)
90 89
 	if err != nil && err.Error() != "EOF" {
91
-		global.Logger.Debugf("%s read response failed: %v", ty, err)
90
+		Logger.Debugf("%s read response failed: %v", ty, err)
92 91
 		return "", err
93 92
 	}
94 93
 	return string(buf[:n]), nil
95 94
 }
96 95
 
97 96
 func (is *ServerCmdService) Update(f *model.ServerCmd) error {
98
-	return global.DB.Model(f).Updates(f).Error
97
+	return DB.Model(f).Updates(f).Error
99 98
 }

+ 27 - 4
service/service.go

@@ -1,7 +1,11 @@
1 1
 package service
2 2
 
3 3
 import (
4
+	"github.com/lejianwen/rustdesk-api/v2/config"
5
+	"github.com/lejianwen/rustdesk-api/v2/lib/jwt"
6
+	"github.com/lejianwen/rustdesk-api/v2/lib/lock"
4 7
 	"github.com/lejianwen/rustdesk-api/v2/model"
8
+	log "github.com/sirupsen/logrus"
5 9
 	"gorm.io/gorm"
6 10
 )
7 11
 
@@ -21,12 +25,31 @@ type Service struct {
21 25
 	*LdapService
22 26
 }
23 27
 
24
-func New() *Service {
25
-	all := new(Service)
26
-	return all
28
+type Dependencies struct {
29
+	Config *config.Config
30
+	DB     *gorm.DB
31
+	Logger *log.Logger
32
+	Jwt    *jwt.Jwt
33
+	Lock   *lock.Locker
27 34
 }
28 35
 
29
-var AllService = New()
36
+var Config *config.Config
37
+var DB *gorm.DB
38
+var Logger *log.Logger
39
+var Jwt *jwt.Jwt
40
+var Lock lock.Locker
41
+
42
+var AllService *Service
43
+
44
+func New(c *config.Config, g *gorm.DB, l *log.Logger, j *jwt.Jwt, lo lock.Locker) *Service {
45
+	Config = c
46
+	DB = g
47
+	Logger = l
48
+	Jwt = j
49
+	Lock = lo
50
+	AllService = new(Service)
51
+	return AllService
52
+}
30 53
 
31 54
 func Paginate(page, pageSize uint) func(db *gorm.DB) *gorm.DB {
32 55
 	return func(db *gorm.DB) *gorm.DB {

+ 6 - 7
service/shareRecord.go

@@ -1,7 +1,6 @@
1 1
 package service
2 2
 
3 3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5 4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6 5
 	"gorm.io/gorm"
7 6
 )
@@ -12,7 +11,7 @@ type ShareRecordService struct {
12 11
 // InfoById 根据用户id取用户信息
13 12
 func (srs *ShareRecordService) InfoById(id uint) *model.ShareRecord {
14 13
 	u := &model.ShareRecord{}
15
-	global.DB.Where("id = ?", id).First(u)
14
+	DB.Where("id = ?", id).First(u)
16 15
 	return u
17 16
 }
18 17
 
@@ -20,7 +19,7 @@ func (srs *ShareRecordService) List(page, pageSize uint, where func(tx *gorm.DB)
20 19
 	res = &model.ShareRecordList{}
21 20
 	res.Page = int64(page)
22 21
 	res.PageSize = int64(pageSize)
23
-	tx := global.DB.Model(&model.ShareRecord{})
22
+	tx := DB.Model(&model.ShareRecord{})
24 23
 	if where != nil {
25 24
 		where(tx)
26 25
 	}
@@ -32,18 +31,18 @@ func (srs *ShareRecordService) List(page, pageSize uint, where func(tx *gorm.DB)
32 31
 
33 32
 // Create 创建
34 33
 func (srs *ShareRecordService) Create(u *model.ShareRecord) error {
35
-	res := global.DB.Create(u).Error
34
+	res := DB.Create(u).Error
36 35
 	return res
37 36
 }
38 37
 func (srs *ShareRecordService) Delete(u *model.ShareRecord) error {
39
-	return global.DB.Delete(u).Error
38
+	return DB.Delete(u).Error
40 39
 }
41 40
 
42 41
 // Update 更新
43 42
 func (srs *ShareRecordService) Update(u *model.ShareRecord) error {
44
-	return global.DB.Model(u).Updates(u).Error
43
+	return DB.Model(u).Updates(u).Error
45 44
 }
46 45
 
47 46
 func (srs *ShareRecordService) BatchDelete(ids []uint) error {
48
-	return global.DB.Where("id in (?)", ids).Delete(&model.ShareRecord{}).Error
47
+	return DB.Where("id in (?)", ids).Delete(&model.ShareRecord{}).Error
49 48
 }

+ 8 - 9
service/tag.go

@@ -1,7 +1,6 @@
1 1
 package service
2 2
 
3 3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5 4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6 5
 	"gorm.io/gorm"
7 6
 )
@@ -11,12 +10,12 @@ type TagService struct {
11 10
 
12 11
 func (s *TagService) Info(id uint) *model.Tag {
13 12
 	p := &model.Tag{}
14
-	global.DB.Where("id = ?", id).First(p)
13
+	DB.Where("id = ?", id).First(p)
15 14
 	return p
16 15
 }
17 16
 func (s *TagService) InfoByUserIdAndNameAndCollectionId(userid uint, name string, cid uint) *model.Tag {
18 17
 	p := &model.Tag{}
19
-	global.DB.Where("user_id = ? and name = ? and collection_id = ?", userid, name, cid).First(p)
18
+	DB.Where("user_id = ? and name = ? and collection_id = ?", userid, name, cid).First(p)
20 19
 	return p
21 20
 }
22 21
 
@@ -34,7 +33,7 @@ func (s *TagService) ListByUserIdAndCollectionId(userId, cid uint) (res *model.T
34 33
 	return
35 34
 }
36 35
 func (s *TagService) UpdateTags(userId uint, tags map[string]uint) {
37
-	tx := global.DB.Begin()
36
+	tx := DB.Begin()
38 37
 	//先查询所有tag
39 38
 	var allTags []*model.Tag
40 39
 	tx.Where("user_id = ?", userId).Find(&allTags)
@@ -66,7 +65,7 @@ func (s *TagService) UpdateTags(userId uint, tags map[string]uint) {
66 65
 // InfoById 根据用户id取用户信息
67 66
 func (s *TagService) InfoById(id uint) *model.Tag {
68 67
 	u := &model.Tag{}
69
-	global.DB.Where("id = ?", id).First(u)
68
+	DB.Where("id = ?", id).First(u)
70 69
 	return u
71 70
 }
72 71
 
@@ -74,7 +73,7 @@ func (s *TagService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *mo
74 73
 	res = &model.TagList{}
75 74
 	res.Page = int64(page)
76 75
 	res.PageSize = int64(pageSize)
77
-	tx := global.DB.Model(&model.Tag{})
76
+	tx := DB.Model(&model.Tag{})
78 77
 	if where != nil {
79 78
 		where(tx)
80 79
 	}
@@ -86,14 +85,14 @@ func (s *TagService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *mo
86 85
 
87 86
 // Create 创建
88 87
 func (s *TagService) Create(u *model.Tag) error {
89
-	res := global.DB.Create(u).Error
88
+	res := DB.Create(u).Error
90 89
 	return res
91 90
 }
92 91
 func (s *TagService) Delete(u *model.Tag) error {
93
-	return global.DB.Delete(u).Error
92
+	return DB.Delete(u).Error
94 93
 }
95 94
 
96 95
 // Update 更新
97 96
 func (s *TagService) Update(u *model.Tag) error {
98
-	return global.DB.Model(u).Select("*").Omit("created_at").Updates(u).Error
97
+	return DB.Model(u).Select("*").Omit("created_at").Updates(u).Error
99 98
 }

+ 47 - 48
service/user.go

@@ -2,7 +2,6 @@ package service
2 2
 
3 3
 import (
4 4
 	"errors"
5
-	"github.com/lejianwen/rustdesk-api/v2/global"
6 5
 	"github.com/lejianwen/rustdesk-api/v2/model"
7 6
 	"github.com/lejianwen/rustdesk-api/v2/utils"
8 7
 	"math/rand"
@@ -20,43 +19,43 @@ type UserService struct {
20 19
 // InfoById 根据用户id取用户信息
21 20
 func (us *UserService) InfoById(id uint) *model.User {
22 21
 	u := &model.User{}
23
-	global.DB.Where("id = ?", id).First(u)
22
+	DB.Where("id = ?", id).First(u)
24 23
 	return u
25 24
 }
26 25
 
27 26
 // InfoByUsername 根据用户名取用户信息
28 27
 func (us *UserService) InfoByUsername(un string) *model.User {
29 28
 	u := &model.User{}
30
-	global.DB.Where("username = ?", un).First(u)
29
+	DB.Where("username = ?", un).First(u)
31 30
 	return u
32 31
 }
33 32
 
34 33
 // InfoByEmail 根据邮箱取用户信息
35 34
 func (us *UserService) InfoByEmail(email string) *model.User {
36 35
 	u := &model.User{}
37
-	global.DB.Where("email = ?", email).First(u)
36
+	DB.Where("email = ?", email).First(u)
38 37
 	return u
39 38
 }
40 39
 
41 40
 // InfoByOpenid 根据openid取用户信息
42 41
 func (us *UserService) InfoByOpenid(openid string) *model.User {
43 42
 	u := &model.User{}
44
-	global.DB.Where("openid = ?", openid).First(u)
43
+	DB.Where("openid = ?", openid).First(u)
45 44
 	return u
46 45
 }
47 46
 
48 47
 // InfoByUsernamePassword 根据用户名密码取用户信息
49 48
 func (us *UserService) InfoByUsernamePassword(username, password string) *model.User {
50
-	if global.Config.Ldap.Enable {
49
+	if Config.Ldap.Enable {
51 50
 		u, err := AllService.LdapService.Authenticate(username, password)
52 51
 		if err == nil {
53 52
 			return u
54 53
 		}
55
-		global.Logger.Errorf("LDAP authentication failed, %v", err)
56
-		global.Logger.Warn("Fallback to local database")
54
+		Logger.Errorf("LDAP authentication failed, %v", err)
55
+		Logger.Warn("Fallback to local database")
57 56
 	}
58 57
 	u := &model.User{}
59
-	global.DB.Where("username = ? and password = ?", username, us.EncryptPassword(password)).First(u)
58
+	DB.Where("username = ? and password = ?", username, us.EncryptPassword(password)).First(u)
60 59
 	return u
61 60
 }
62 61
 
@@ -64,21 +63,21 @@ func (us *UserService) InfoByUsernamePassword(username, password string) *model.
64 63
 func (us *UserService) InfoByAccessToken(token string) (*model.User, *model.UserToken) {
65 64
 	u := &model.User{}
66 65
 	ut := &model.UserToken{}
67
-	global.DB.Where("token = ?", token).First(ut)
66
+	DB.Where("token = ?", token).First(ut)
68 67
 	if ut.Id == 0 {
69 68
 		return u, ut
70 69
 	}
71 70
 	if ut.ExpiredAt < time.Now().Unix() {
72 71
 		return u, ut
73 72
 	}
74
-	global.DB.Where("id = ?", ut.UserId).First(u)
73
+	DB.Where("id = ?", ut.UserId).First(u)
75 74
 	return u, ut
76 75
 }
77 76
 
78 77
 // GenerateToken 生成token
79 78
 func (us *UserService) GenerateToken(u *model.User) string {
80
-	if len(global.Jwt.Key) > 0 {
81
-		return global.Jwt.GenerateToken(u.Id)
79
+	if len(Jwt.Key) > 0 {
80
+		return Jwt.GenerateToken(u.Id)
82 81
 	}
83 82
 	return utils.Md5(u.Username + time.Now().String())
84 83
 }
@@ -93,9 +92,9 @@ func (us *UserService) Login(u *model.User, llog *model.LoginLog) *model.UserTok
93 92
 		DeviceId:   llog.DeviceId,
94 93
 		ExpiredAt:  us.UserTokenExpireTimestamp(),
95 94
 	}
96
-	global.DB.Create(ut)
95
+	DB.Create(ut)
97 96
 	llog.UserTokenId = ut.UserId
98
-	global.DB.Create(llog)
97
+	DB.Create(llog)
99 98
 	if llog.Uuid != "" {
100 99
 		AllService.PeerService.UuidBindUserId(llog.DeviceId, llog.Uuid, u.Id)
101 100
 	}
@@ -116,7 +115,7 @@ func (us *UserService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *
116 115
 	res = &model.UserList{}
117 116
 	res.Page = int64(page)
118 117
 	res.PageSize = int64(pageSize)
119
-	tx := global.DB.Model(&model.User{})
118
+	tx := DB.Model(&model.User{})
120 119
 	if where != nil {
121 120
 		where(tx)
122 121
 	}
@@ -127,7 +126,7 @@ func (us *UserService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *
127 126
 }
128 127
 
129 128
 func (us *UserService) ListByIds(ids []uint) (res []*model.User) {
130
-	global.DB.Where("id in ?", ids).Find(&res)
129
+	DB.Where("id in ?", ids).Find(&res)
131 130
 	return res
132 131
 }
133 132
 
@@ -141,14 +140,14 @@ func (us *UserService) ListByGroupId(groupId, page, pageSize uint) (res *model.U
141 140
 
142 141
 // ListIdsByGroupId 根据组id取用户id列表
143 142
 func (us *UserService) ListIdsByGroupId(groupId uint) (ids []uint) {
144
-	global.DB.Model(&model.User{}).Where("group_id = ?", groupId).Pluck("id", &ids)
143
+	DB.Model(&model.User{}).Where("group_id = ?", groupId).Pluck("id", &ids)
145 144
 	return ids
146 145
 
147 146
 }
148 147
 
149 148
 // ListIdAndNameByGroupId 根据组id取用户id和用户名列表
150 149
 func (us *UserService) ListIdAndNameByGroupId(groupId uint) (res []*model.User) {
151
-	global.DB.Model(&model.User{}).Where("group_id = ?", groupId).Select("id, username").Find(&res)
150
+	DB.Model(&model.User{}).Where("group_id = ?", groupId).Select("id, username").Find(&res)
152 151
 	return res
153 152
 }
154 153
 
@@ -170,14 +169,14 @@ func (us *UserService) Create(u *model.User) error {
170 169
 	}
171 170
 	u.Username = us.formatUsername(u.Username)
172 171
 	u.Password = us.EncryptPassword(u.Password)
173
-	res := global.DB.Create(u).Error
172
+	res := DB.Create(u).Error
174 173
 	return res
175 174
 }
176 175
 
177 176
 // GetUuidByToken 根据token和user取uuid
178 177
 func (us *UserService) GetUuidByToken(u *model.User, token string) string {
179 178
 	ut := &model.UserToken{}
180
-	err := global.DB.Where("user_id = ? and token = ?", u.Id, token).First(ut).Error
179
+	err := DB.Where("user_id = ? and token = ?", u.Id, token).First(ut).Error
181 180
 	if err != nil {
182 181
 		return ""
183 182
 	}
@@ -187,7 +186,7 @@ func (us *UserService) GetUuidByToken(u *model.User, token string) string {
187 186
 // Logout 退出登录 -> 删除token, 解绑uuid
188 187
 func (us *UserService) Logout(u *model.User, token string) error {
189 188
 	uuid := us.GetUuidByToken(u, token)
190
-	err := global.DB.Where("user_id = ? and token = ?", u.Id, token).Delete(&model.UserToken{}).Error
189
+	err := DB.Where("user_id = ? and token = ?", u.Id, token).Delete(&model.UserToken{}).Error
191 190
 	if err != nil {
192 191
 		return err
193 192
 	}
@@ -203,7 +202,7 @@ func (us *UserService) Delete(u *model.User) error {
203 202
 	if userCount <= 1 && us.IsAdmin(u) {
204 203
 		return errors.New("The last admin user cannot be deleted")
205 204
 	}
206
-	tx := global.DB.Begin()
205
+	tx := DB.Begin()
207 206
 	// 删除用户
208 207
 	if err := tx.Delete(u).Error; err != nil {
209 208
 		tx.Rollback()
@@ -232,7 +231,7 @@ func (us *UserService) Delete(u *model.User) error {
232 231
 	tx.Commit()
233 232
 	// 删除关联的peer
234 233
 	if err := AllService.PeerService.EraseUserId(u.Id); err != nil {
235
-		global.Logger.Warn("User deleted successfully, but failed to unlink peer.")
234
+		Logger.Warn("User deleted successfully, but failed to unlink peer.")
236 235
 		return nil
237 236
 	}
238 237
 	return nil
@@ -249,28 +248,28 @@ func (us *UserService) Update(u *model.User) error {
249 248
 			return errors.New("The last admin user cannot be disabled or demoted")
250 249
 		}
251 250
 	}
252
-	return global.DB.Model(u).Updates(u).Error
251
+	return DB.Model(u).Updates(u).Error
253 252
 }
254 253
 
255 254
 // FlushToken 清空token
256 255
 func (us *UserService) FlushToken(u *model.User) error {
257
-	return global.DB.Where("user_id = ?", u.Id).Delete(&model.UserToken{}).Error
256
+	return DB.Where("user_id = ?", u.Id).Delete(&model.UserToken{}).Error
258 257
 }
259 258
 
260 259
 // FlushTokenByUuid 清空token
261 260
 func (us *UserService) FlushTokenByUuid(uuid string) error {
262
-	return global.DB.Where("device_uuid = ?", uuid).Delete(&model.UserToken{}).Error
261
+	return DB.Where("device_uuid = ?", uuid).Delete(&model.UserToken{}).Error
263 262
 }
264 263
 
265 264
 // FlushTokenByUuids 清空token
266 265
 func (us *UserService) FlushTokenByUuids(uuids []string) error {
267
-	return global.DB.Where("device_uuid in (?)", uuids).Delete(&model.UserToken{}).Error
266
+	return DB.Where("device_uuid in (?)", uuids).Delete(&model.UserToken{}).Error
268 267
 }
269 268
 
270 269
 // UpdatePassword 更新密码
271 270
 func (us *UserService) UpdatePassword(u *model.User, password string) error {
272 271
 	u.Password = us.EncryptPassword(password)
273
-	err := global.DB.Model(u).Update("password", u.Password).Error
272
+	err := DB.Model(u).Update("password", u.Password).Error
274 273
 	if err != nil {
275 274
 		return err
276 275
 	}
@@ -306,8 +305,8 @@ func (us *UserService) InfoByOauthId(op string, openId string) *model.User {
306 305
 
307 306
 // RegisterByOauth 注册
308 307
 func (us *UserService) RegisterByOauth(oauthUser *model.OauthUser, op string) (error, *model.User) {
309
-	global.Lock.Lock("registerByOauth")
310
-	defer global.Lock.UnLock("registerByOauth")
308
+	Lock.Lock("registerByOauth")
309
+	defer Lock.UnLock("registerByOauth")
311 310
 	ut := AllService.OauthService.UserThirdInfo(op, oauthUser.OpenId)
312 311
 	if ut.Id != 0 {
313 312
 		return nil, us.InfoById(ut.UserId)
@@ -335,12 +334,12 @@ func (us *UserService) RegisterByOauth(oauthUser *model.OauthUser, op string) (e
335 334
 		}
336 335
 		if user.Id != 0 {
337 336
 			ut.FromOauthUser(user.Id, oauthUser, oauthType, op)
338
-			global.DB.Create(ut)
337
+			DB.Create(ut)
339 338
 			return nil, user
340 339
 		}
341 340
 	}
342 341
 
343
-	tx := global.DB.Begin()
342
+	tx := DB.Begin()
344 343
 	ut = &model.UserThird{}
345 344
 	ut.FromOauthUser(0, oauthUser, oauthType, op)
346 345
 	// The initial username should be formatted
@@ -372,27 +371,27 @@ func (us *UserService) GenerateUsernameByOauth(name string) string {
372 371
 
373 372
 // UserThirdsByUserId
374 373
 func (us *UserService) UserThirdsByUserId(userId uint) (res []*model.UserThird) {
375
-	global.DB.Where("user_id = ?", userId).Find(&res)
374
+	DB.Where("user_id = ?", userId).Find(&res)
376 375
 	return res
377 376
 }
378 377
 
379 378
 func (us *UserService) UserThirdInfo(userId uint, op string) *model.UserThird {
380 379
 	ut := &model.UserThird{}
381
-	global.DB.Where("user_id = ? and op = ?", userId, op).First(ut)
380
+	DB.Where("user_id = ? and op = ?", userId, op).First(ut)
382 381
 	return ut
383 382
 }
384 383
 
385 384
 // FindLatestUserIdFromLoginLogByUuid 根据uuid查找最后登录的用户id
386 385
 func (us *UserService) FindLatestUserIdFromLoginLogByUuid(uuid string) uint {
387 386
 	llog := &model.LoginLog{}
388
-	global.DB.Where("uuid = ?", uuid).Order("id desc").First(llog)
387
+	DB.Where("uuid = ?", uuid).Order("id desc").First(llog)
389 388
 	return llog.UserId
390 389
 }
391 390
 
392 391
 // IsPasswordEmptyById 根据用户id判断密码是否为空,主要用于第三方登录的自动注册
393 392
 func (us *UserService) IsPasswordEmptyById(id uint) bool {
394 393
 	u := &model.User{}
395
-	if global.DB.Where("id = ?", id).First(u).Error != nil {
394
+	if DB.Where("id = ?", id).First(u).Error != nil {
396 395
 		return false
397 396
 	}
398 397
 	return u.Password == ""
@@ -401,7 +400,7 @@ func (us *UserService) IsPasswordEmptyById(id uint) bool {
401 400
 // IsPasswordEmptyByUsername 根据用户id判断密码是否为空,主要用于第三方登录的自动注册
402 401
 func (us *UserService) IsPasswordEmptyByUsername(username string) bool {
403 402
 	u := &model.User{}
404
-	if global.DB.Where("username = ?", username).First(u).Error != nil {
403
+	if DB.Where("username = ?", username).First(u).Error != nil {
405 404
 		return false
406 405
 	}
407 406
 	return u.Password == ""
@@ -431,7 +430,7 @@ func (us *UserService) TokenList(page uint, size uint, f func(tx *gorm.DB)) *mod
431 430
 	res := &model.UserTokenList{}
432 431
 	res.Page = int64(page)
433 432
 	res.PageSize = int64(size)
434
-	tx := global.DB.Model(&model.UserToken{})
433
+	tx := DB.Model(&model.UserToken{})
435 434
 	if f != nil {
436 435
 		f(tx)
437 436
 	}
@@ -443,12 +442,12 @@ func (us *UserService) TokenList(page uint, size uint, f func(tx *gorm.DB)) *mod
443 442
 
444 443
 func (us *UserService) TokenInfoById(id uint) *model.UserToken {
445 444
 	ut := &model.UserToken{}
446
-	global.DB.Where("id = ?", id).First(ut)
445
+	DB.Where("id = ?", id).First(ut)
447 446
 	return ut
448 447
 }
449 448
 
450 449
 func (us *UserService) DeleteToken(l *model.UserToken) error {
451
-	return global.DB.Delete(l).Error
450
+	return DB.Delete(l).Error
452 451
 }
453 452
 
454 453
 // Helper functions, used for formatting username
@@ -461,20 +460,20 @@ func (us *UserService) formatUsername(username string) string {
461 460
 // Helper functions, getUserCount
462 461
 func (us *UserService) getUserCount() int64 {
463 462
 	var count int64
464
-	global.DB.Model(&model.User{}).Count(&count)
463
+	DB.Model(&model.User{}).Count(&count)
465 464
 	return count
466 465
 }
467 466
 
468 467
 // helper functions, getAdminUserCount
469 468
 func (us *UserService) getAdminUserCount() int64 {
470 469
 	var count int64
471
-	global.DB.Model(&model.User{}).Where("is_admin = ?", true).Count(&count)
470
+	DB.Model(&model.User{}).Where("is_admin = ?", true).Count(&count)
472 471
 	return count
473 472
 }
474 473
 
475 474
 // UserTokenExpireTimestamp 生成用户token过期时间
476 475
 func (us *UserService) UserTokenExpireTimestamp() int64 {
477
-	exp := global.Config.App.TokenExpire
476
+	exp := Config.App.TokenExpire
478 477
 	if exp == 0 {
479 478
 		//默认七天
480 479
 		exp = 604800
@@ -484,7 +483,7 @@ func (us *UserService) UserTokenExpireTimestamp() int64 {
484 483
 
485 484
 func (us *UserService) RefreshAccessToken(ut *model.UserToken) {
486 485
 	ut.ExpiredAt = us.UserTokenExpireTimestamp()
487
-	global.DB.Model(ut).Update("expired_at", ut.ExpiredAt)
486
+	DB.Model(ut).Update("expired_at", ut.ExpiredAt)
488 487
 }
489 488
 func (us *UserService) AutoRefreshAccessToken(ut *model.UserToken) {
490 489
 	if ut.ExpiredAt-time.Now().Unix() < 86400 {
@@ -493,11 +492,11 @@ func (us *UserService) AutoRefreshAccessToken(ut *model.UserToken) {
493 492
 }
494 493
 
495 494
 func (us *UserService) BatchDeleteUserToken(ids []uint) error {
496
-	return global.DB.Where("id in ?", ids).Delete(&model.UserToken{}).Error
495
+	return DB.Where("id in ?", ids).Delete(&model.UserToken{}).Error
497 496
 }
498 497
 
499 498
 func (us *UserService) VerifyJWT(token string) (uint, error) {
500
-	return global.Jwt.ParseToken(token)
499
+	return Jwt.ParseToken(token)
501 500
 }
502 501
 
503 502
 // IsUsernameExists 判断用户名是否存在, it will check the internal database and LDAP(if enabled)
@@ -507,7 +506,7 @@ func (us *UserService) IsUsernameExists(username string) bool {
507 506
 
508 507
 func (us *UserService) IsUsernameExistsLocal(username string) bool {
509 508
 	u := &model.User{}
510
-	global.DB.Where("username = ?", username).First(u)
509
+	DB.Where("username = ?", username).First(u)
511 510
 	return u.Id != 0
512 511
 }
513 512