Просмотр исходного кода

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

lejianwen месяцев назад: 11
Родитель
Сommit
7410b539a0
13 измененных файлов с 213 добавлено и 198 удалено
  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
 	global.Jwt = jwt.NewJwt(global.Config.Jwt.Key, global.Config.Jwt.ExpireDuration)
164
 	global.Jwt = jwt.NewJwt(global.Config.Jwt.Key, global.Config.Jwt.ExpireDuration)
165
 	//locker
165
 	//locker
166
 	global.Lock = lock.NewLocal()
166
 	global.Lock = lock.NewLocal()
167
+
168
+	//service
169
+	service.New(&global.Config, global.DB, global.Logger, global.Jwt, global.Lock)
167
 }
170
 }
168
 func DatabaseAutoUpdate() {
171
 func DatabaseAutoUpdate() {
169
 	version := 262
172
 	version := 262

+ 31 - 32
service/addressBook.go

@@ -3,7 +3,6 @@ package service
3
 import (
3
 import (
4
 	"encoding/json"
4
 	"encoding/json"
5
 	"github.com/google/uuid"
5
 	"github.com/google/uuid"
6
-	"github.com/lejianwen/rustdesk-api/v2/global"
7
 	"github.com/lejianwen/rustdesk-api/v2/model"
6
 	"github.com/lejianwen/rustdesk-api/v2/model"
8
 	"gorm.io/gorm"
7
 	"gorm.io/gorm"
9
 	"strings"
8
 	"strings"
@@ -14,24 +13,24 @@ type AddressBookService struct {
14
 
13
 
15
 func (s *AddressBookService) Info(id string) *model.AddressBook {
14
 func (s *AddressBookService) Info(id string) *model.AddressBook {
16
 	p := &model.AddressBook{}
15
 	p := &model.AddressBook{}
17
-	global.DB.Where("id = ?", id).First(p)
16
+	DB.Where("id = ?", id).First(p)
18
 	return p
17
 	return p
19
 }
18
 }
20
 
19
 
21
 func (s *AddressBookService) InfoByUserIdAndId(userid uint, id string) *model.AddressBook {
20
 func (s *AddressBookService) InfoByUserIdAndId(userid uint, id string) *model.AddressBook {
22
 	p := &model.AddressBook{}
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
 	return p
23
 	return p
25
 }
24
 }
26
 
25
 
27
 func (s *AddressBookService) InfoByUserIdAndIdAndCid(userid uint, id string, cid uint) *model.AddressBook {
26
 func (s *AddressBookService) InfoByUserIdAndIdAndCid(userid uint, id string, cid uint) *model.AddressBook {
28
 	p := &model.AddressBook{}
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
 	return p
29
 	return p
31
 }
30
 }
32
 func (s *AddressBookService) InfoByRowId(id uint) *model.AddressBook {
31
 func (s *AddressBookService) InfoByRowId(id uint) *model.AddressBook {
33
 	p := &model.AddressBook{}
32
 	p := &model.AddressBook{}
34
-	global.DB.Where("row_id = ?", id).First(p)
33
+	DB.Where("row_id = ?", id).First(p)
35
 	return p
34
 	return p
36
 }
35
 }
37
 func (s *AddressBookService) ListByUserId(userId, page, pageSize uint) (res *model.AddressBookList) {
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
 // AddAddressBook
49
 // AddAddressBook
51
 func (s *AddressBookService) AddAddressBook(ab *model.AddressBook) error {
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
 // UpdateAddressBook
54
 // UpdateAddressBook
56
 func (s *AddressBookService) UpdateAddressBook(abs []*model.AddressBook, userId uint) error {
55
 func (s *AddressBookService) UpdateAddressBook(abs []*model.AddressBook, userId uint) error {
57
 	//比较peers和数据库中的数据,如果peers中的数据在数据库中不存在,则添加,如果存在则更新,如果数据库中的数据在peers中不存在,则删除
56
 	//比较peers和数据库中的数据,如果peers中的数据在数据库中不存在,则添加,如果存在则更新,如果数据库中的数据在peers中不存在,则删除
58
 	// 开始事务
57
 	// 开始事务
59
-	tx := global.DB.Begin()
58
+	tx := DB.Begin()
60
 	//1. 获取数据库中的数据
59
 	//1. 获取数据库中的数据
61
 	var dbABs []*model.AddressBook
60
 	var dbABs []*model.AddressBook
62
 	tx.Where("user_id = ?", userId).Find(&dbABs)
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
 	res = &model.AddressBookList{}
106
 	res = &model.AddressBookList{}
108
 	res.Page = int64(page)
107
 	res.Page = int64(page)
109
 	res.PageSize = int64(pageSize)
108
 	res.PageSize = int64(pageSize)
110
-	tx := global.DB.Model(&model.AddressBook{})
109
+	tx := DB.Model(&model.AddressBook{})
111
 	if where != nil {
110
 	if where != nil {
112
 		where(tx)
111
 		where(tx)
113
 	}
112
 	}
@@ -129,38 +128,38 @@ func (s *AddressBookService) FromPeer(peer *model.Peer) (a *model.AddressBook) {
129
 
128
 
130
 // Create 创建
129
 // Create 创建
131
 func (s *AddressBookService) Create(u *model.AddressBook) error {
130
 func (s *AddressBookService) Create(u *model.AddressBook) error {
132
-	res := global.DB.Create(u).Error
131
+	res := DB.Create(u).Error
133
 	return res
132
 	return res
134
 }
133
 }
135
 func (s *AddressBookService) Delete(u *model.AddressBook) error {
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
 // Update 更新
138
 // Update 更新
140
 func (s *AddressBookService) Update(u *model.AddressBook) error {
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
 // UpdateByMap 更新
143
 // UpdateByMap 更新
145
 func (s *AddressBookService) UpdateByMap(u *model.AddressBook, data map[string]interface{}) error {
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
 // UpdateAll 更新
148
 // UpdateAll 更新
150
 func (s *AddressBookService) UpdateAll(u *model.AddressBook) error {
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
 // ShareByWebClient 分享
153
 // ShareByWebClient 分享
155
 func (s *AddressBookService) ShareByWebClient(m *model.ShareRecord) error {
154
 func (s *AddressBookService) ShareByWebClient(m *model.ShareRecord) error {
156
 	m.ShareToken = uuid.New().String()
155
 	m.ShareToken = uuid.New().String()
157
-	return global.DB.Create(m).Error
156
+	return DB.Create(m).Error
158
 }
157
 }
159
 
158
 
160
 // SharedPeer
159
 // SharedPeer
161
 func (s *AddressBookService) SharedPeer(shareToken string) *model.ShareRecord {
160
 func (s *AddressBookService) SharedPeer(shareToken string) *model.ShareRecord {
162
 	m := &model.ShareRecord{}
161
 	m := &model.ShareRecord{}
163
-	global.DB.Where("share_token = ?", shareToken).First(m)
162
+	DB.Where("share_token = ?", shareToken).First(m)
164
 	return m
163
 	return m
165
 }
164
 }
166
 
165
 
@@ -190,7 +189,7 @@ func (s *AddressBookService) ListCollection(page, pageSize uint, where func(tx *
190
 	res = &model.AddressBookCollectionList{}
189
 	res = &model.AddressBookCollectionList{}
191
 	res.Page = int64(page)
190
 	res.Page = int64(page)
192
 	res.PageSize = int64(pageSize)
191
 	res.PageSize = int64(pageSize)
193
-	tx := global.DB.Model(&model.AddressBookCollection{})
192
+	tx := DB.Model(&model.AddressBookCollection{})
194
 	if where != nil {
193
 	if where != nil {
195
 		where(tx)
194
 		where(tx)
196
 	}
195
 	}
@@ -200,7 +199,7 @@ func (s *AddressBookService) ListCollection(page, pageSize uint, where func(tx *
200
 	return
199
 	return
201
 }
200
 }
202
 func (s *AddressBookService) ListCollectionByIds(ids []uint) (res []*model.AddressBookCollection) {
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
 	return res
203
 	return res
205
 }
204
 }
206
 
205
 
@@ -212,20 +211,20 @@ func (s *AddressBookService) ListCollectionByUserId(userId uint) (res *model.Add
212
 }
211
 }
213
 func (s *AddressBookService) CollectionInfoById(id uint) *model.AddressBookCollection {
212
 func (s *AddressBookService) CollectionInfoById(id uint) *model.AddressBookCollection {
214
 	p := &model.AddressBookCollection{}
213
 	p := &model.AddressBookCollection{}
215
-	global.DB.Where("id = ?", id).First(p)
214
+	DB.Where("id = ?", id).First(p)
216
 	return p
215
 	return p
217
 }
216
 }
218
 
217
 
219
 func (s *AddressBookService) CollectionReadRules(user *model.User) (res []*model.AddressBookCollectionRule) {
218
 func (s *AddressBookService) CollectionReadRules(user *model.User) (res []*model.AddressBookCollectionRule) {
220
 	// personalRules
219
 	// personalRules
221
 	var personalRules []*model.AddressBookCollectionRule
220
 	var personalRules []*model.AddressBookCollectionRule
222
-	tx2 := global.DB.Model(&model.AddressBookCollectionRule{})
221
+	tx2 := DB.Model(&model.AddressBookCollectionRule{})
223
 	tx2.Where("type = ? and to_id = ? and rule > 0", model.ShareAddressBookRuleTypePersonal, user.Id).Find(&personalRules)
222
 	tx2.Where("type = ? and to_id = ? and rule > 0", model.ShareAddressBookRuleTypePersonal, user.Id).Find(&personalRules)
224
 	res = append(res, personalRules...)
223
 	res = append(res, personalRules...)
225
 
224
 
226
 	//group
225
 	//group
227
 	var groupRules []*model.AddressBookCollectionRule
226
 	var groupRules []*model.AddressBookCollectionRule
228
-	tx3 := global.DB.Model(&model.AddressBookCollectionRule{})
227
+	tx3 := DB.Model(&model.AddressBookCollectionRule{})
229
 	tx3.Where("type = ? and to_id = ? and rule > 0", model.ShareAddressBookRuleTypeGroup, user.GroupId).Find(&groupRules)
228
 	tx3.Where("type = ? and to_id = ? and rule > 0", model.ShareAddressBookRuleTypeGroup, user.GroupId).Find(&groupRules)
230
 	res = append(res, groupRules...)
229
 	res = append(res, groupRules...)
231
 	return
230
 	return
@@ -238,7 +237,7 @@ func (s *AddressBookService) UserMaxRule(user *model.User, uid, cid uint) int {
238
 	}
237
 	}
239
 	max := 0
238
 	max := 0
240
 	personalRules := &model.AddressBookCollectionRule{}
239
 	personalRules := &model.AddressBookCollectionRule{}
241
-	tx := global.DB.Model(personalRules)
240
+	tx := DB.Model(personalRules)
242
 	tx.Where("type = ? and collection_id = ? and to_id = ?", model.ShareAddressBookRuleTypePersonal, cid, user.Id).First(&personalRules)
241
 	tx.Where("type = ? and collection_id = ? and to_id = ?", model.ShareAddressBookRuleTypePersonal, cid, user.Id).First(&personalRules)
243
 	if personalRules.Id != 0 {
242
 	if personalRules.Id != 0 {
244
 		max = personalRules.Rule
243
 		max = personalRules.Rule
@@ -248,7 +247,7 @@ func (s *AddressBookService) UserMaxRule(user *model.User, uid, cid uint) int {
248
 	}
247
 	}
249
 
248
 
250
 	groupRules := &model.AddressBookCollectionRule{}
249
 	groupRules := &model.AddressBookCollectionRule{}
251
-	tx2 := global.DB.Model(groupRules)
250
+	tx2 := DB.Model(groupRules)
252
 	tx2.Where("type = ? and collection_id = ? and to_id = ?", model.ShareAddressBookRuleTypeGroup, cid, user.GroupId).First(&groupRules)
251
 	tx2.Where("type = ? and collection_id = ? and to_id = ?", model.ShareAddressBookRuleTypeGroup, cid, user.GroupId).First(&groupRules)
253
 	if groupRules.Id != 0 {
252
 	if groupRules.Id != 0 {
254
 		if groupRules.Rule > max {
253
 		if groupRules.Rule > max {
@@ -272,16 +271,16 @@ func (s *AddressBookService) CheckUserFullControlPrivilege(user *model.User, uid
272
 }
271
 }
273
 
272
 
274
 func (s *AddressBookService) CreateCollection(t *model.AddressBookCollection) error {
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
 func (s *AddressBookService) UpdateCollection(t *model.AddressBookCollection) error {
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
 func (s *AddressBookService) DeleteCollection(t *model.AddressBookCollection) error {
281
 func (s *AddressBookService) DeleteCollection(t *model.AddressBookCollection) error {
283
 	//删除集合下的所有规则、地址簿,再删除集合
282
 	//删除集合下的所有规则、地址簿,再删除集合
284
-	tx := global.DB.Begin()
283
+	tx := DB.Begin()
285
 	tx.Where("collection_id = ?", t.Id).Delete(&model.AddressBookCollectionRule{})
284
 	tx.Where("collection_id = ?", t.Id).Delete(&model.AddressBookCollectionRule{})
286
 	tx.Where("collection_id = ?", t.Id).Delete(&model.AddressBook{})
285
 	tx.Where("collection_id = ?", t.Id).Delete(&model.AddressBook{})
287
 	tx.Delete(t)
286
 	tx.Delete(t)
@@ -290,23 +289,23 @@ func (s *AddressBookService) DeleteCollection(t *model.AddressBookCollection) er
290
 
289
 
291
 func (s *AddressBookService) RuleInfoById(u uint) *model.AddressBookCollectionRule {
290
 func (s *AddressBookService) RuleInfoById(u uint) *model.AddressBookCollectionRule {
292
 	p := &model.AddressBookCollectionRule{}
291
 	p := &model.AddressBookCollectionRule{}
293
-	global.DB.Where("id = ?", u).First(p)
292
+	DB.Where("id = ?", u).First(p)
294
 	return p
293
 	return p
295
 }
294
 }
296
 func (s *AddressBookService) RulePersonalInfoByToIdAndCid(toid, cid uint) *model.AddressBookCollectionRule {
295
 func (s *AddressBookService) RulePersonalInfoByToIdAndCid(toid, cid uint) *model.AddressBookCollectionRule {
297
 	p := &model.AddressBookCollectionRule{}
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
 	return p
298
 	return p
300
 }
299
 }
301
 func (s *AddressBookService) CreateRule(t *model.AddressBookCollectionRule) error {
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
 func (s *AddressBookService) ListRules(page uint, size uint, f func(tx *gorm.DB)) *model.AddressBookCollectionRuleList {
304
 func (s *AddressBookService) ListRules(page uint, size uint, f func(tx *gorm.DB)) *model.AddressBookCollectionRuleList {
306
 	res := &model.AddressBookCollectionRuleList{}
305
 	res := &model.AddressBookCollectionRuleList{}
307
 	res.Page = int64(page)
306
 	res.Page = int64(page)
308
 	res.PageSize = int64(size)
307
 	res.PageSize = int64(size)
309
-	tx := global.DB.Model(&model.AddressBookCollectionRule{})
308
+	tx := DB.Model(&model.AddressBookCollectionRule{})
310
 	if f != nil {
309
 	if f != nil {
311
 		f(tx)
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
 func (s *AddressBookService) UpdateRule(t *model.AddressBookCollectionRule) error {
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
 func (s *AddressBookService) DeleteRule(t *model.AddressBookCollectionRule) error {
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
 // CheckCollectionOwner 检查Collection的所有者
326
 // CheckCollectionOwner 检查Collection的所有者
@@ -336,5 +335,5 @@ func (s *AddressBookService) BatchUpdateTags(abs []*model.AddressBook, tags []st
336
 		ids = append(ids, ab.RowId)
335
 		ids = append(ids, ab.RowId)
337
 	}
336
 	}
338
 	tagsv, _ := json.Marshal(tags)
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
 package service
1
 package service
2
 
2
 
3
 import (
3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5
 	"github.com/lejianwen/rustdesk-api/v2/model"
4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6
 	"gorm.io/gorm"
5
 	"gorm.io/gorm"
7
 )
6
 )
@@ -13,7 +12,7 @@ func (as *AuditService) AuditConnList(page, pageSize uint, where func(tx *gorm.D
13
 	res = &model.AuditConnList{}
12
 	res = &model.AuditConnList{}
14
 	res.Page = int64(page)
13
 	res.Page = int64(page)
15
 	res.PageSize = int64(pageSize)
14
 	res.PageSize = int64(pageSize)
16
-	tx := global.DB.Model(&model.AuditConn{})
15
+	tx := DB.Model(&model.AuditConn{})
17
 	if where != nil {
16
 	if where != nil {
18
 		where(tx)
17
 		where(tx)
19
 	}
18
 	}
@@ -25,36 +24,36 @@ func (as *AuditService) AuditConnList(page, pageSize uint, where func(tx *gorm.D
25
 
24
 
26
 // Create 创建
25
 // Create 创建
27
 func (as *AuditService) CreateAuditConn(u *model.AuditConn) error {
26
 func (as *AuditService) CreateAuditConn(u *model.AuditConn) error {
28
-	res := global.DB.Create(u).Error
27
+	res := DB.Create(u).Error
29
 	return res
28
 	return res
30
 }
29
 }
31
 func (as *AuditService) DeleteAuditConn(u *model.AuditConn) error {
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
 // Update 更新
34
 // Update 更新
36
 func (as *AuditService) UpdateAuditConn(u *model.AuditConn) error {
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
 // InfoByPeerIdAndConnId
39
 // InfoByPeerIdAndConnId
41
 func (as *AuditService) InfoByPeerIdAndConnId(peerId string, connId int64) (res *model.AuditConn) {
40
 func (as *AuditService) InfoByPeerIdAndConnId(peerId string, connId int64) (res *model.AuditConn) {
42
 	res = &model.AuditConn{}
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
 	return
43
 	return
45
 }
44
 }
46
 
45
 
47
 // ConnInfoById
46
 // ConnInfoById
48
 func (as *AuditService) ConnInfoById(id uint) (res *model.AuditConn) {
47
 func (as *AuditService) ConnInfoById(id uint) (res *model.AuditConn) {
49
 	res = &model.AuditConn{}
48
 	res = &model.AuditConn{}
50
-	global.DB.Where("id = ?", id).First(res)
49
+	DB.Where("id = ?", id).First(res)
51
 	return
50
 	return
52
 }
51
 }
53
 
52
 
54
 // FileInfoById
53
 // FileInfoById
55
 func (as *AuditService) FileInfoById(id uint) (res *model.AuditFile) {
54
 func (as *AuditService) FileInfoById(id uint) (res *model.AuditFile) {
56
 	res = &model.AuditFile{}
55
 	res = &model.AuditFile{}
57
-	global.DB.Where("id = ?", id).First(res)
56
+	DB.Where("id = ?", id).First(res)
58
 	return
57
 	return
59
 }
58
 }
60
 
59
 
@@ -62,7 +61,7 @@ func (as *AuditService) AuditFileList(page, pageSize uint, where func(tx *gorm.D
62
 	res = &model.AuditFileList{}
61
 	res = &model.AuditFileList{}
63
 	res.Page = int64(page)
62
 	res.Page = int64(page)
64
 	res.PageSize = int64(pageSize)
63
 	res.PageSize = int64(pageSize)
65
-	tx := global.DB.Model(&model.AuditFile{})
64
+	tx := DB.Model(&model.AuditFile{})
66
 	if where != nil {
65
 	if where != nil {
67
 		where(tx)
66
 		where(tx)
68
 	}
67
 	}
@@ -74,22 +73,22 @@ func (as *AuditService) AuditFileList(page, pageSize uint, where func(tx *gorm.D
74
 
73
 
75
 // CreateAuditFile
74
 // CreateAuditFile
76
 func (as *AuditService) CreateAuditFile(u *model.AuditFile) error {
75
 func (as *AuditService) CreateAuditFile(u *model.AuditFile) error {
77
-	res := global.DB.Create(u).Error
76
+	res := DB.Create(u).Error
78
 	return res
77
 	return res
79
 }
78
 }
80
 func (as *AuditService) DeleteAuditFile(u *model.AuditFile) error {
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
 // Update 更新
83
 // Update 更新
85
 func (as *AuditService) UpdateAuditFile(u *model.AuditFile) error {
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
 func (as *AuditService) BatchDeleteAuditConn(ids []uint) error {
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
 func (as *AuditService) BatchDeleteAuditFile(ids []uint) error {
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
 package service
1
 package service
2
 
2
 
3
 import (
3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5
 	"github.com/lejianwen/rustdesk-api/v2/model"
4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6
 	"gorm.io/gorm"
5
 	"gorm.io/gorm"
7
 )
6
 )
@@ -12,7 +11,7 @@ type GroupService struct {
12
 // InfoById 根据用户id取用户信息
11
 // InfoById 根据用户id取用户信息
13
 func (us *GroupService) InfoById(id uint) *model.Group {
12
 func (us *GroupService) InfoById(id uint) *model.Group {
14
 	u := &model.Group{}
13
 	u := &model.Group{}
15
-	global.DB.Where("id = ?", id).First(u)
14
+	DB.Where("id = ?", id).First(u)
16
 	return u
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
 	res = &model.GroupList{}
19
 	res = &model.GroupList{}
21
 	res.Page = int64(page)
20
 	res.Page = int64(page)
22
 	res.PageSize = int64(pageSize)
21
 	res.PageSize = int64(pageSize)
23
-	tx := global.DB.Model(&model.Group{})
22
+	tx := DB.Model(&model.Group{})
24
 	if where != nil {
23
 	if where != nil {
25
 		where(tx)
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
 // Create 创建
32
 // Create 创建
34
 func (us *GroupService) Create(u *model.Group) error {
33
 func (us *GroupService) Create(u *model.Group) error {
35
-	res := global.DB.Create(u).Error
34
+	res := DB.Create(u).Error
36
 	return res
35
 	return res
37
 }
36
 }
38
 func (us *GroupService) Delete(u *model.Group) error {
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
 // Update 更新
41
 // Update 更新
43
 func (us *GroupService) Update(u *model.Group) error {
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
 // DeviceGroupInfoById 根据用户id取用户信息
46
 // DeviceGroupInfoById 根据用户id取用户信息
48
 func (us *GroupService) DeviceGroupInfoById(id uint) *model.DeviceGroup {
47
 func (us *GroupService) DeviceGroupInfoById(id uint) *model.DeviceGroup {
49
 	u := &model.DeviceGroup{}
48
 	u := &model.DeviceGroup{}
50
-	global.DB.Where("id = ?", id).First(u)
49
+	DB.Where("id = ?", id).First(u)
51
 	return u
50
 	return u
52
 }
51
 }
53
 
52
 
@@ -55,7 +54,7 @@ func (us *GroupService) DeviceGroupList(page, pageSize uint, where func(tx *gorm
55
 	res = &model.DeviceGroupList{}
54
 	res = &model.DeviceGroupList{}
56
 	res.Page = int64(page)
55
 	res.Page = int64(page)
57
 	res.PageSize = int64(pageSize)
56
 	res.PageSize = int64(pageSize)
58
-	tx := global.DB.Model(&model.DeviceGroup{})
57
+	tx := DB.Model(&model.DeviceGroup{})
59
 	if where != nil {
58
 	if where != nil {
60
 		where(tx)
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
 func (us *GroupService) DeviceGroupCreate(u *model.DeviceGroup) error {
67
 func (us *GroupService) DeviceGroupCreate(u *model.DeviceGroup) error {
69
-	res := global.DB.Create(u).Error
68
+	res := DB.Create(u).Error
70
 	return res
69
 	return res
71
 }
70
 }
72
 func (us *GroupService) DeviceGroupDelete(u *model.DeviceGroup) error {
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
 func (us *GroupService) DeviceGroupUpdate(u *model.DeviceGroup) error {
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
 	"github.com/go-ldap/ldap/v3"
10
 	"github.com/go-ldap/ldap/v3"
11
 
11
 
12
 	"github.com/lejianwen/rustdesk-api/v2/config"
12
 	"github.com/lejianwen/rustdesk-api/v2/config"
13
-	"github.com/lejianwen/rustdesk-api/v2/global"
14
 	"github.com/lejianwen/rustdesk-api/v2/model"
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
 	if !ldapUser.Enabled {
113
 	if !ldapUser.Enabled {
115
 		return nil, ErrLdapUserDisabled
114
 		return nil, ErrLdapUserDisabled
116
 	}
115
 	}
117
-	cfg := &global.Config.Ldap
116
+	cfg := &Config.Ldap
118
 	user, err := ls.mapToLocalUser(cfg, ldapUser)
117
 	user, err := ls.mapToLocalUser(cfg, ldapUser)
119
 	if err != nil {
118
 	if err != nil {
120
 		return nil, errors.Join(ErrLdapToLocalUserFailed, err)
119
 		return nil, errors.Join(ErrLdapToLocalUserFailed, err)
@@ -135,7 +134,7 @@ func (ls *LdapService) mapToLocalUser(cfg *config.Ldap, lu *LdapUser) (*model.Us
135
 		// If needed, you can set a random password here.
134
 		// If needed, you can set a random password here.
136
 		newUser.IsAdmin = &isAdmin
135
 		newUser.IsAdmin = &isAdmin
137
 		newUser.GroupId = 1
136
 		newUser.GroupId = 1
138
-		if err := global.DB.Create(newUser).Error; err != nil {
137
+		if err := DB.Create(newUser).Error; err != nil {
139
 			return nil, errors.Join(ErrLdapCreateUserFailed, err)
138
 			return nil, errors.Join(ErrLdapCreateUserFailed, err)
140
 		}
139
 		}
141
 		return userService.InfoByUsername(lu.Username), nil
140
 		return userService.InfoByUsername(lu.Username), nil
@@ -164,7 +163,7 @@ func (ls *LdapService) mapToLocalUser(cfg *config.Ldap, lu *LdapUser) (*model.Us
164
 // IsUsernameExists checks if a username exists in LDAP (can be useful for local registration checks).
163
 // IsUsernameExists checks if a username exists in LDAP (can be useful for local registration checks).
165
 func (ls *LdapService) IsUsernameExists(username string) bool {
164
 func (ls *LdapService) IsUsernameExists(username string) bool {
166
 
165
 
167
-	cfg := &global.Config.Ldap
166
+	cfg := &Config.Ldap
168
 	if !cfg.Enable {
167
 	if !cfg.Enable {
169
 		return false
168
 		return false
170
 	}
169
 	}
@@ -177,7 +176,7 @@ func (ls *LdapService) IsUsernameExists(username string) bool {
177
 
176
 
178
 // IsEmailExists checks if an email exists in LDAP (can be useful for local registration checks).
177
 // IsEmailExists checks if an email exists in LDAP (can be useful for local registration checks).
179
 func (ls *LdapService) IsEmailExists(email string) bool {
178
 func (ls *LdapService) IsEmailExists(email string) bool {
180
-	cfg := &global.Config.Ldap
179
+	cfg := &Config.Ldap
181
 	if !cfg.Enable {
180
 	if !cfg.Enable {
182
 		return false
181
 		return false
183
 	}
182
 	}
@@ -190,7 +189,7 @@ func (ls *LdapService) IsEmailExists(email string) bool {
190
 
189
 
191
 // GetUserInfoByUsernameLdap returns the user info from LDAP for the given username.
190
 // GetUserInfoByUsernameLdap returns the user info from LDAP for the given username.
192
 func (ls *LdapService) GetUserInfoByUsernameLdap(username string) (*LdapUser, error) {
191
 func (ls *LdapService) GetUserInfoByUsernameLdap(username string) (*LdapUser, error) {
193
-	cfg := &global.Config.Ldap
192
+	cfg := &Config.Ldap
194
 	if !cfg.Enable {
193
 	if !cfg.Enable {
195
 		return nil, ErrLdapNotEnabled
194
 		return nil, ErrLdapNotEnabled
196
 	}
195
 	}
@@ -210,12 +209,12 @@ func (ls *LdapService) GetUserInfoByUsernameLocal(username string) (*model.User,
210
 	if err != nil {
209
 	if err != nil {
211
 		return &model.User{}, err
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
 // GetUserInfoByEmailLdap returns the user info from LDAP for the given email.
215
 // GetUserInfoByEmailLdap returns the user info from LDAP for the given email.
217
 func (ls *LdapService) GetUserInfoByEmailLdap(email string) (*LdapUser, error) {
216
 func (ls *LdapService) GetUserInfoByEmailLdap(email string) (*LdapUser, error) {
218
-	cfg := &global.Config.Ldap
217
+	cfg := &Config.Ldap
219
 	if !cfg.Enable {
218
 	if !cfg.Enable {
220
 		return nil, ErrLdapNotEnabled
219
 		return nil, ErrLdapNotEnabled
221
 	}
220
 	}
@@ -235,7 +234,7 @@ func (ls *LdapService) GetUserInfoByEmailLocal(email string) (*model.User, error
235
 	if err != nil {
234
 	if err != nil {
236
 		return &model.User{}, err
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
 // usernameSearchResult returns the search result for the given username.
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
 		// Account is disabled if the ACCOUNTDISABLE flag (0x2) is set
453
 		// Account is disabled if the ACCOUNTDISABLE flag (0x2) is set
455
 		const ACCOUNTDISABLE = 0x2
454
 		const ACCOUNTDISABLE = 0x2
456
-		ldapUser.Enabled = (userAccountControl&ACCOUNTDISABLE == 0)
455
+		ldapUser.Enabled = userAccountControl&ACCOUNTDISABLE == 0
457
 		return ldapUser.Enabled
456
 		return ldapUser.Enabled
458
 	}
457
 	}
459
 
458
 
460
 	// For other attributes, perform a direct comparison with the expected value
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
 	return ldapUser.Enabled
461
 	return ldapUser.Enabled
463
 }
462
 }
464
 
463
 

+ 7 - 8
service/loginLog.go

@@ -1,7 +1,6 @@
1
 package service
1
 package service
2
 
2
 
3
 import (
3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5
 	"github.com/lejianwen/rustdesk-api/v2/model"
4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6
 	"gorm.io/gorm"
5
 	"gorm.io/gorm"
7
 )
6
 )
@@ -12,7 +11,7 @@ type LoginLogService struct {
12
 // InfoById 根据用户id取用户信息
11
 // InfoById 根据用户id取用户信息
13
 func (us *LoginLogService) InfoById(id uint) *model.LoginLog {
12
 func (us *LoginLogService) InfoById(id uint) *model.LoginLog {
14
 	u := &model.LoginLog{}
13
 	u := &model.LoginLog{}
15
-	global.DB.Where("id = ?", id).First(u)
14
+	DB.Where("id = ?", id).First(u)
16
 	return u
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
 	res = &model.LoginLogList{}
19
 	res = &model.LoginLogList{}
21
 	res.Page = int64(page)
20
 	res.Page = int64(page)
22
 	res.PageSize = int64(pageSize)
21
 	res.PageSize = int64(pageSize)
23
-	tx := global.DB.Model(&model.LoginLog{})
22
+	tx := DB.Model(&model.LoginLog{})
24
 	if where != nil {
23
 	if where != nil {
25
 		where(tx)
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
 // Create 创建
32
 // Create 创建
34
 func (us *LoginLogService) Create(u *model.LoginLog) error {
33
 func (us *LoginLogService) Create(u *model.LoginLog) error {
35
-	res := global.DB.Create(u).Error
34
+	res := DB.Create(u).Error
36
 	return res
35
 	return res
37
 }
36
 }
38
 func (us *LoginLogService) Delete(u *model.LoginLog) error {
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
 // Update 更新
41
 // Update 更新
43
 func (us *LoginLogService) Update(u *model.LoginLog) error {
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
 func (us *LoginLogService) BatchDelete(ids []uint) error {
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
 func (us *LoginLogService) SoftDelete(l *model.LoginLog) error {
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
 func (us *LoginLogService) BatchSoftDelete(uid uint, ids []uint) error {
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
 	"encoding/json"
5
 	"encoding/json"
6
 	"errors"
6
 	"errors"
7
 	"github.com/coreos/go-oidc/v3/oidc"
7
 	"github.com/coreos/go-oidc/v3/oidc"
8
-	"github.com/lejianwen/rustdesk-api/v2/global"
9
 	"github.com/lejianwen/rustdesk-api/v2/model"
8
 	"github.com/lejianwen/rustdesk-api/v2/model"
10
 	"github.com/lejianwen/rustdesk-api/v2/utils"
9
 	"github.com/lejianwen/rustdesk-api/v2/utils"
11
 	"golang.org/x/oauth2"
10
 	"golang.org/x/oauth2"
@@ -99,7 +98,7 @@ func (os *OauthService) BeginAuth(op string) (error error, state, verifier, nonc
99
 	verifier = ""
98
 	verifier = ""
100
 	nonce = ""
99
 	nonce = ""
101
 	if op == model.OauthTypeWebauth {
100
 	if op == model.OauthTypeWebauth {
102
-		url = global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + state
101
+		url = Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + state
103
 		//url = "http://localhost:8888/_admin/#/oauth/" + code
102
 		//url = "http://localhost:8888/_admin/#/oauth/" + code
104
 		return nil, state, verifier, nonce, url
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
 	// If the redirect URL is empty, use the default redirect URL
164
 	// If the redirect URL is empty, use the default redirect URL
166
 	if oauthInfo.RedirectUrl == "" {
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
 	oauthConfig = &oauth2.Config{
168
 	oauthConfig = &oauth2.Config{
170
 		ClientID:     oauthInfo.ClientId,
169
 		ClientID:     oauthInfo.ClientId,
@@ -202,14 +201,14 @@ func (os *OauthService) GetOauthConfig(op string) (err error, oauthInfo *model.O
202
 func getHTTPClientWithProxy() *http.Client {
201
 func getHTTPClientWithProxy() *http.Client {
203
 	//add timeout 30s
202
 	//add timeout 30s
204
 	timeout := time.Duration(60) * time.Second
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
 			return http.DefaultClient
207
 			return http.DefaultClient
209
 		}
208
 		}
210
-		proxyURL, err := url.Parse(global.Config.Proxy.Host)
209
+		proxyURL, err := url.Parse(Config.Proxy.Host)
211
 		if err != nil {
210
 		if err != nil {
212
-			global.Logger.Warn("Invalid proxy URL: ", err)
211
+			Logger.Warn("Invalid proxy URL: ", err)
213
 			return http.DefaultClient
212
 			return http.DefaultClient
214
 		}
213
 		}
215
 		transport := &http.Transport{
214
 		transport := &http.Transport{
@@ -233,7 +232,7 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
233
 	token, err := oauthConfig.Exchange(ctx, code, exchangeOpts...)
232
 	token, err := oauthConfig.Exchange(ctx, code, exchangeOpts...)
234
 
233
 
235
 	if err != nil {
234
 	if err != nil {
236
-		global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
235
+		Logger.Warn("oauthConfig.Exchange() failed: ", err)
237
 		return errors.New("GetOauthTokenError"), nil
236
 		return errors.New("GetOauthTokenError"), nil
238
 	}
237
 	}
239
 
238
 
@@ -244,7 +243,7 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
244
 		v := provider.Verifier(&oidc.Config{ClientID: oauthConfig.ClientID})
243
 		v := provider.Verifier(&oidc.Config{ClientID: oauthConfig.ClientID})
245
 		idToken, err2 := v.Verify(ctx, rawIDToken)
244
 		idToken, err2 := v.Verify(ctx, rawIDToken)
246
 		if err2 != nil {
245
 		if err2 != nil {
247
-			global.Logger.Warn("IdTokenVerifyError: ", err2)
246
+			Logger.Warn("IdTokenVerifyError: ", err2)
248
 			return errors.New("IdTokenVerifyError"), nil
247
 			return errors.New("IdTokenVerifyError"), nil
249
 		}
248
 		}
250
 		if nonce != "" {
249
 		if nonce != "" {
@@ -253,12 +252,12 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
253
 				Nonce string `json:"nonce"`
252
 				Nonce string `json:"nonce"`
254
 			}
253
 			}
255
 			if err2 = idToken.Claims(&claims); err2 != nil {
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
 				return errors.New("IDTokenClaimsError"), nil
256
 				return errors.New("IDTokenClaimsError"), nil
258
 			}
257
 			}
259
 
258
 
260
 			if claims.Nonce != nonce {
259
 			if claims.Nonce != nonce {
261
-				global.Logger.Warn("Nonce does not match")
260
+				Logger.Warn("Nonce does not match")
262
 				return errors.New("NonceDoesNotMatch"), nil
261
 				return errors.New("NonceDoesNotMatch"), nil
263
 			}
262
 			}
264
 		}
263
 		}
@@ -268,18 +267,18 @@ func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.
268
 	client = oauthConfig.Client(ctx, token)
267
 	client = oauthConfig.Client(ctx, token)
269
 	resp, err := client.Get(provider.UserInfoEndpoint())
268
 	resp, err := client.Get(provider.UserInfoEndpoint())
270
 	if err != nil {
269
 	if err != nil {
271
-		global.Logger.Warn("failed getting user info: ", err)
270
+		Logger.Warn("failed getting user info: ", err)
272
 		return errors.New("GetOauthUserInfoError"), nil
271
 		return errors.New("GetOauthUserInfoError"), nil
273
 	}
272
 	}
274
 	defer func() {
273
 	defer func() {
275
 		if closeErr := resp.Body.Close(); closeErr != nil {
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
 	if err = json.NewDecoder(resp.Body).Decode(userData); err != nil {
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
 		return errors.New("DecodeOauthUserInfoError"), nil
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
 func (os *OauthService) UserThirdInfo(op string, openId string) *model.UserThird {
330
 func (os *OauthService) UserThirdInfo(op string, openId string) *model.UserThird {
332
 	ut := &model.UserThird{}
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
 	return ut
333
 	return ut
335
 }
334
 }
336
 
335
 
@@ -342,7 +341,7 @@ func (os *OauthService) BindOauthUser(userId uint, oauthUser *model.OauthUser, o
342
 		return err
341
 		return err
343
 	}
342
 	}
344
 	utr.FromOauthUser(userId, oauthUser, oauthType, op)
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
 // UnBindOauthUser: Unbind third party account
347
 // UnBindOauthUser: Unbind third party account
@@ -352,25 +351,25 @@ func (os *OauthService) UnBindOauthUser(userId uint, op string) error {
352
 
351
 
353
 // UnBindThird: Unbind third party account
352
 // UnBindThird: Unbind third party account
354
 func (os *OauthService) UnBindThird(op string, userId uint) error {
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
 // DeleteUserByUserId: When user is deleted, delete all third party bindings
357
 // DeleteUserByUserId: When user is deleted, delete all third party bindings
359
 func (os *OauthService) DeleteUserByUserId(userId uint) error {
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
 // InfoById 根据id获取Oauth信息
362
 // InfoById 根据id获取Oauth信息
364
 func (os *OauthService) InfoById(id uint) *model.Oauth {
363
 func (os *OauthService) InfoById(id uint) *model.Oauth {
365
 	oauthInfo := &model.Oauth{}
364
 	oauthInfo := &model.Oauth{}
366
-	global.DB.Where("id = ?", id).First(oauthInfo)
365
+	DB.Where("id = ?", id).First(oauthInfo)
367
 	return oauthInfo
366
 	return oauthInfo
368
 }
367
 }
369
 
368
 
370
 // InfoByOp 根据op获取Oauth信息
369
 // InfoByOp 根据op获取Oauth信息
371
 func (os *OauthService) InfoByOp(op string) *model.Oauth {
370
 func (os *OauthService) InfoByOp(op string) *model.Oauth {
372
 	oauthInfo := &model.Oauth{}
371
 	oauthInfo := &model.Oauth{}
373
-	global.DB.Where("op = ?", op).First(oauthInfo)
372
+	DB.Where("op = ?", op).First(oauthInfo)
374
 	return oauthInfo
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
 	res = &model.OauthList{}
392
 	res = &model.OauthList{}
394
 	res.Page = int64(page)
393
 	res.Page = int64(page)
395
 	res.PageSize = int64(pageSize)
394
 	res.PageSize = int64(pageSize)
396
-	tx := global.DB.Model(&model.Oauth{})
395
+	tx := DB.Model(&model.Oauth{})
397
 	if where != nil {
396
 	if where != nil {
398
 		where(tx)
397
 		where(tx)
399
 	}
398
 	}
@@ -406,7 +405,7 @@ func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res
406
 // GetTypeByOp 根据op获取OauthType
405
 // GetTypeByOp 根据op获取OauthType
407
 func (os *OauthService) GetTypeByOp(op string) (error, string) {
406
 func (os *OauthService) GetTypeByOp(op string) (error, string) {
408
 	oauthInfo := &model.Oauth{}
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
 		return fmt.Errorf("OAuth provider with op '%s' not found", op), ""
409
 		return fmt.Errorf("OAuth provider with op '%s' not found", op), ""
411
 	}
410
 	}
412
 	return nil, oauthInfo.OauthType
411
 	return nil, oauthInfo.OauthType
@@ -424,7 +423,7 @@ func (os *OauthService) ValidateOauthProvider(op string) error {
424
 func (os *OauthService) IsOauthProviderExist(op string) bool {
423
 func (os *OauthService) IsOauthProviderExist(op string) bool {
425
 	oauthInfo := &model.Oauth{}
424
 	oauthInfo := &model.Oauth{}
426
 	// 使用 Gorm 的 Take 方法查找符合条件的记录
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
 		return false
427
 		return false
429
 	}
428
 	}
430
 	return true
429
 	return true
@@ -436,11 +435,11 @@ func (os *OauthService) Create(oauthInfo *model.Oauth) error {
436
 	if err != nil {
435
 	if err != nil {
437
 		return err
436
 		return err
438
 	}
437
 	}
439
-	res := global.DB.Create(oauthInfo).Error
438
+	res := DB.Create(oauthInfo).Error
440
 	return res
439
 	return res
441
 }
440
 }
442
 func (os *OauthService) Delete(oauthInfo *model.Oauth) error {
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
 // Update 更新
445
 // Update 更新
@@ -449,13 +448,13 @@ func (os *OauthService) Update(oauthInfo *model.Oauth) error {
449
 	if err != nil {
448
 	if err != nil {
450
 		return err
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
 // GetOauthProviders 获取所有的provider
454
 // GetOauthProviders 获取所有的provider
456
 func (os *OauthService) GetOauthProviders() []string {
455
 func (os *OauthService) GetOauthProviders() []string {
457
 	var res []string
456
 	var res []string
458
-	global.DB.Model(&model.Oauth{}).Pluck("op", &res)
457
+	DB.Model(&model.Oauth{}).Pluck("op", &res)
459
 	return res
458
 	return res
460
 }
459
 }
461
 
460
 

+ 14 - 15
service/peer.go

@@ -1,7 +1,6 @@
1
 package service
1
 package service
2
 
2
 
3
 import (
3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5
 	"github.com/lejianwen/rustdesk-api/v2/model"
4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6
 	"gorm.io/gorm"
5
 	"gorm.io/gorm"
7
 )
6
 )
@@ -12,24 +11,24 @@ type PeerService struct {
12
 // FindById 根据id查找
11
 // FindById 根据id查找
13
 func (ps *PeerService) FindById(id string) *model.Peer {
12
 func (ps *PeerService) FindById(id string) *model.Peer {
14
 	p := &model.Peer{}
13
 	p := &model.Peer{}
15
-	global.DB.Where("id = ?", id).First(p)
14
+	DB.Where("id = ?", id).First(p)
16
 	return p
15
 	return p
17
 }
16
 }
18
 func (ps *PeerService) FindByUuid(uuid string) *model.Peer {
17
 func (ps *PeerService) FindByUuid(uuid string) *model.Peer {
19
 	p := &model.Peer{}
18
 	p := &model.Peer{}
20
-	global.DB.Where("uuid = ?", uuid).First(p)
19
+	DB.Where("uuid = ?", uuid).First(p)
21
 	return p
20
 	return p
22
 }
21
 }
23
 func (ps *PeerService) InfoByRowId(id uint) *model.Peer {
22
 func (ps *PeerService) InfoByRowId(id uint) *model.Peer {
24
 	p := &model.Peer{}
23
 	p := &model.Peer{}
25
-	global.DB.Where("row_id = ?", id).First(p)
24
+	DB.Where("row_id = ?", id).First(p)
26
 	return p
25
 	return p
27
 }
26
 }
28
 
27
 
29
 // FindByUserIdAndUuid 根据用户id和uuid查找peer
28
 // FindByUserIdAndUuid 根据用户id和uuid查找peer
30
 func (ps *PeerService) FindByUserIdAndUuid(uuid string, userId uint) *model.Peer {
29
 func (ps *PeerService) FindByUserIdAndUuid(uuid string, userId uint) *model.Peer {
31
 	p := &model.Peer{}
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
 	return p
32
 	return p
34
 }
33
 }
35
 
34
 
@@ -43,7 +42,7 @@ func (ps *PeerService) UuidBindUserId(deviceId string, uuid string, userId uint)
43
 	} else {
42
 	} else {
44
 		// 不存在则创建
43
 		// 不存在则创建
45
 		/*if deviceId != "" {
44
 		/*if deviceId != "" {
46
-			global.DB.Create(&model.Peer{
45
+			DB.Create(&model.Peer{
47
 				Id:     deviceId,
46
 				Id:     deviceId,
48
 				Uuid:   uuid,
47
 				Uuid:   uuid,
49
 				UserId: userId,
48
 				UserId: userId,
@@ -56,13 +55,13 @@ func (ps *PeerService) UuidBindUserId(deviceId string, uuid string, userId uint)
56
 func (ps *PeerService) UuidUnbindUserId(uuid string, userId uint) {
55
 func (ps *PeerService) UuidUnbindUserId(uuid string, userId uint) {
57
 	peer := ps.FindByUserIdAndUuid(uuid, userId)
56
 	peer := ps.FindByUserIdAndUuid(uuid, userId)
58
 	if peer.RowId > 0 {
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
 // EraseUserId 清除用户id, 用于用户删除
62
 // EraseUserId 清除用户id, 用于用户删除
64
 func (ps *PeerService) EraseUserId(userId uint) error {
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
 // ListByUserIds 根据用户id取列表
67
 // ListByUserIds 根据用户id取列表
@@ -70,7 +69,7 @@ func (ps *PeerService) ListByUserIds(userIds []uint, page, pageSize uint) (res *
70
 	res = &model.PeerList{}
69
 	res = &model.PeerList{}
71
 	res.Page = int64(page)
70
 	res.Page = int64(page)
72
 	res.PageSize = int64(pageSize)
71
 	res.PageSize = int64(pageSize)
73
-	tx := global.DB.Model(&model.Peer{})
72
+	tx := DB.Model(&model.Peer{})
74
 	tx.Where("user_id in (?)", userIds)
73
 	tx.Where("user_id in (?)", userIds)
75
 	tx.Count(&res.Total)
74
 	tx.Count(&res.Total)
76
 	tx.Scopes(Paginate(page, pageSize))
75
 	tx.Scopes(Paginate(page, pageSize))
@@ -82,7 +81,7 @@ func (ps *PeerService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *
82
 	res = &model.PeerList{}
81
 	res = &model.PeerList{}
83
 	res.Page = int64(page)
82
 	res.Page = int64(page)
84
 	res.PageSize = int64(pageSize)
83
 	res.PageSize = int64(pageSize)
85
-	tx := global.DB.Model(&model.Peer{})
84
+	tx := DB.Model(&model.Peer{})
86
 	if where != nil {
85
 	if where != nil {
87
 		where(tx)
86
 		where(tx)
88
 	}
87
 	}
@@ -106,14 +105,14 @@ func (ps *PeerService) ListFilterByUserId(page, pageSize uint, where func(tx *go
106
 
105
 
107
 // Create 创建
106
 // Create 创建
108
 func (ps *PeerService) Create(u *model.Peer) error {
107
 func (ps *PeerService) Create(u *model.Peer) error {
109
-	res := global.DB.Create(u).Error
108
+	res := DB.Create(u).Error
110
 	return res
109
 	return res
111
 }
110
 }
112
 
111
 
113
 // Delete 删除, 同时也应该删除token
112
 // Delete 删除, 同时也应该删除token
114
 func (ps *PeerService) Delete(u *model.Peer) error {
113
 func (ps *PeerService) Delete(u *model.Peer) error {
115
 	uuid := u.Uuid
114
 	uuid := u.Uuid
116
-	err := global.DB.Delete(u).Error
115
+	err := DB.Delete(u).Error
117
 	if err != nil {
116
 	if err != nil {
118
 		return err
117
 		return err
119
 	}
118
 	}
@@ -124,7 +123,7 @@ func (ps *PeerService) Delete(u *model.Peer) error {
124
 // GetUuidListByIDs 根据ids获取uuid列表
123
 // GetUuidListByIDs 根据ids获取uuid列表
125
 func (ps *PeerService) GetUuidListByIDs(ids []uint) ([]string, error) {
124
 func (ps *PeerService) GetUuidListByIDs(ids []uint) ([]string, error) {
126
 	var uuids []string
125
 	var uuids []string
127
-	err := global.DB.Model(&model.Peer{}).
126
+	err := DB.Model(&model.Peer{}).
128
 		Where("row_id in (?)", ids).
127
 		Where("row_id in (?)", ids).
129
 		Pluck("uuid", &uuids).Error
128
 		Pluck("uuid", &uuids).Error
130
 	return uuids, err
129
 	return uuids, err
@@ -133,7 +132,7 @@ func (ps *PeerService) GetUuidListByIDs(ids []uint) ([]string, error) {
133
 // BatchDelete 批量删除, 同时也应该删除token
132
 // BatchDelete 批量删除, 同时也应该删除token
134
 func (ps *PeerService) BatchDelete(ids []uint) error {
133
 func (ps *PeerService) BatchDelete(ids []uint) error {
135
 	uuids, err := ps.GetUuidListByIDs(ids)
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
 	if err != nil {
136
 	if err != nil {
138
 		return err
137
 		return err
139
 	}
138
 	}
@@ -143,5 +142,5 @@ func (ps *PeerService) BatchDelete(ids []uint) error {
143
 
142
 
144
 // Update 更新
143
 // Update 更新
145
 func (ps *PeerService) Update(u *model.Peer) error {
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
 import (
3
 import (
4
 	"fmt"
4
 	"fmt"
5
-	"github.com/lejianwen/rustdesk-api/v2/global"
6
 	"github.com/lejianwen/rustdesk-api/v2/model"
5
 	"github.com/lejianwen/rustdesk-api/v2/model"
7
 	"net"
6
 	"net"
8
 	"time"
7
 	"time"
@@ -15,7 +14,7 @@ func (is *ServerCmdService) List(page, pageSize uint) (res *model.ServerCmdList)
15
 	res = &model.ServerCmdList{}
14
 	res = &model.ServerCmdList{}
16
 	res.Page = int64(page)
15
 	res.Page = int64(page)
17
 	res.PageSize = int64(pageSize)
16
 	res.PageSize = int64(pageSize)
18
-	tx := global.DB.Model(&model.ServerCmd{})
17
+	tx := DB.Model(&model.ServerCmd{})
19
 	tx.Count(&res.Total)
18
 	tx.Count(&res.Total)
20
 	tx.Scopes(Paginate(page, pageSize))
19
 	tx.Scopes(Paginate(page, pageSize))
21
 	tx.Find(&res.ServerCmds)
20
 	tx.Find(&res.ServerCmds)
@@ -25,18 +24,18 @@ func (is *ServerCmdService) List(page, pageSize uint) (res *model.ServerCmdList)
25
 // Info
24
 // Info
26
 func (is *ServerCmdService) Info(id uint) *model.ServerCmd {
25
 func (is *ServerCmdService) Info(id uint) *model.ServerCmd {
27
 	u := &model.ServerCmd{}
26
 	u := &model.ServerCmd{}
28
-	global.DB.Where("id = ?", id).First(u)
27
+	DB.Where("id = ?", id).First(u)
29
 	return u
28
 	return u
30
 }
29
 }
31
 
30
 
32
 // Delete
31
 // Delete
33
 func (is *ServerCmdService) Delete(u *model.ServerCmd) error {
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
 // Create
36
 // Create
38
 func (is *ServerCmdService) Create(u *model.ServerCmd) error {
37
 func (is *ServerCmdService) Create(u *model.ServerCmd) error {
39
-	res := global.DB.Create(u).Error
38
+	res := DB.Create(u).Error
40
 	return res
39
 	return res
41
 }
40
 }
42
 
41
 
@@ -45,9 +44,9 @@ func (is *ServerCmdService) SendCmd(target string, cmd string, arg string) (stri
45
 	port := 0
44
 	port := 0
46
 	switch target {
45
 	switch target {
47
 	case model.ServerCmdTargetIdServer:
46
 	case model.ServerCmdTargetIdServer:
48
-		port = global.Config.Rustdesk.IdServerPort - 1
47
+		port = Config.Rustdesk.IdServerPort - 1
49
 	case model.ServerCmdTargetRelayServer:
48
 	case model.ServerCmdTargetRelayServer:
50
-		port = global.Config.Rustdesk.RelayServerPort
49
+		port = Config.Rustdesk.RelayServerPort
51
 	}
50
 	}
52
 	//组装命令
51
 	//组装命令
53
 	cmd = cmd + " " + arg
52
 	cmd = cmd + " " + arg
@@ -73,14 +72,14 @@ func (is *ServerCmdService) SendSocketCmd(ty string, port int, cmd string) (stri
73
 	}
72
 	}
74
 	conn, err := net.Dial(tcp, fmt.Sprintf("%s:%v", addr, port))
73
 	conn, err := net.Dial(tcp, fmt.Sprintf("%s:%v", addr, port))
75
 	if err != nil {
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
 		return "", err
76
 		return "", err
78
 	}
77
 	}
79
 	defer conn.Close()
78
 	defer conn.Close()
80
 	//发送命令
79
 	//发送命令
81
 	_, err = conn.Write([]byte(cmd))
80
 	_, err = conn.Write([]byte(cmd))
82
 	if err != nil {
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
 		return "", err
83
 		return "", err
85
 	}
84
 	}
86
 	time.Sleep(100 * time.Millisecond)
85
 	time.Sleep(100 * time.Millisecond)
@@ -88,12 +87,12 @@ func (is *ServerCmdService) SendSocketCmd(ty string, port int, cmd string) (stri
88
 	buf := make([]byte, 1024)
87
 	buf := make([]byte, 1024)
89
 	n, err := conn.Read(buf)
88
 	n, err := conn.Read(buf)
90
 	if err != nil && err.Error() != "EOF" {
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
 		return "", err
91
 		return "", err
93
 	}
92
 	}
94
 	return string(buf[:n]), nil
93
 	return string(buf[:n]), nil
95
 }
94
 }
96
 
95
 
97
 func (is *ServerCmdService) Update(f *model.ServerCmd) error {
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
 package service
1
 package service
2
 
2
 
3
 import (
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
 	"github.com/lejianwen/rustdesk-api/v2/model"
7
 	"github.com/lejianwen/rustdesk-api/v2/model"
8
+	log "github.com/sirupsen/logrus"
5
 	"gorm.io/gorm"
9
 	"gorm.io/gorm"
6
 )
10
 )
7
 
11
 
@@ -21,12 +25,31 @@ type Service struct {
21
 	*LdapService
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
 func Paginate(page, pageSize uint) func(db *gorm.DB) *gorm.DB {
54
 func Paginate(page, pageSize uint) func(db *gorm.DB) *gorm.DB {
32
 	return func(db *gorm.DB) *gorm.DB {
55
 	return func(db *gorm.DB) *gorm.DB {

+ 6 - 7
service/shareRecord.go

@@ -1,7 +1,6 @@
1
 package service
1
 package service
2
 
2
 
3
 import (
3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5
 	"github.com/lejianwen/rustdesk-api/v2/model"
4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6
 	"gorm.io/gorm"
5
 	"gorm.io/gorm"
7
 )
6
 )
@@ -12,7 +11,7 @@ type ShareRecordService struct {
12
 // InfoById 根据用户id取用户信息
11
 // InfoById 根据用户id取用户信息
13
 func (srs *ShareRecordService) InfoById(id uint) *model.ShareRecord {
12
 func (srs *ShareRecordService) InfoById(id uint) *model.ShareRecord {
14
 	u := &model.ShareRecord{}
13
 	u := &model.ShareRecord{}
15
-	global.DB.Where("id = ?", id).First(u)
14
+	DB.Where("id = ?", id).First(u)
16
 	return u
15
 	return u
17
 }
16
 }
18
 
17
 
@@ -20,7 +19,7 @@ func (srs *ShareRecordService) List(page, pageSize uint, where func(tx *gorm.DB)
20
 	res = &model.ShareRecordList{}
19
 	res = &model.ShareRecordList{}
21
 	res.Page = int64(page)
20
 	res.Page = int64(page)
22
 	res.PageSize = int64(pageSize)
21
 	res.PageSize = int64(pageSize)
23
-	tx := global.DB.Model(&model.ShareRecord{})
22
+	tx := DB.Model(&model.ShareRecord{})
24
 	if where != nil {
23
 	if where != nil {
25
 		where(tx)
24
 		where(tx)
26
 	}
25
 	}
@@ -32,18 +31,18 @@ func (srs *ShareRecordService) List(page, pageSize uint, where func(tx *gorm.DB)
32
 
31
 
33
 // Create 创建
32
 // Create 创建
34
 func (srs *ShareRecordService) Create(u *model.ShareRecord) error {
33
 func (srs *ShareRecordService) Create(u *model.ShareRecord) error {
35
-	res := global.DB.Create(u).Error
34
+	res := DB.Create(u).Error
36
 	return res
35
 	return res
37
 }
36
 }
38
 func (srs *ShareRecordService) Delete(u *model.ShareRecord) error {
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
 // Update 更新
41
 // Update 更新
43
 func (srs *ShareRecordService) Update(u *model.ShareRecord) error {
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
 func (srs *ShareRecordService) BatchDelete(ids []uint) error {
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
 package service
1
 package service
2
 
2
 
3
 import (
3
 import (
4
-	"github.com/lejianwen/rustdesk-api/v2/global"
5
 	"github.com/lejianwen/rustdesk-api/v2/model"
4
 	"github.com/lejianwen/rustdesk-api/v2/model"
6
 	"gorm.io/gorm"
5
 	"gorm.io/gorm"
7
 )
6
 )
@@ -11,12 +10,12 @@ type TagService struct {
11
 
10
 
12
 func (s *TagService) Info(id uint) *model.Tag {
11
 func (s *TagService) Info(id uint) *model.Tag {
13
 	p := &model.Tag{}
12
 	p := &model.Tag{}
14
-	global.DB.Where("id = ?", id).First(p)
13
+	DB.Where("id = ?", id).First(p)
15
 	return p
14
 	return p
16
 }
15
 }
17
 func (s *TagService) InfoByUserIdAndNameAndCollectionId(userid uint, name string, cid uint) *model.Tag {
16
 func (s *TagService) InfoByUserIdAndNameAndCollectionId(userid uint, name string, cid uint) *model.Tag {
18
 	p := &model.Tag{}
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
 	return p
19
 	return p
21
 }
20
 }
22
 
21
 
@@ -34,7 +33,7 @@ func (s *TagService) ListByUserIdAndCollectionId(userId, cid uint) (res *model.T
34
 	return
33
 	return
35
 }
34
 }
36
 func (s *TagService) UpdateTags(userId uint, tags map[string]uint) {
35
 func (s *TagService) UpdateTags(userId uint, tags map[string]uint) {
37
-	tx := global.DB.Begin()
36
+	tx := DB.Begin()
38
 	//先查询所有tag
37
 	//先查询所有tag
39
 	var allTags []*model.Tag
38
 	var allTags []*model.Tag
40
 	tx.Where("user_id = ?", userId).Find(&allTags)
39
 	tx.Where("user_id = ?", userId).Find(&allTags)
@@ -66,7 +65,7 @@ func (s *TagService) UpdateTags(userId uint, tags map[string]uint) {
66
 // InfoById 根据用户id取用户信息
65
 // InfoById 根据用户id取用户信息
67
 func (s *TagService) InfoById(id uint) *model.Tag {
66
 func (s *TagService) InfoById(id uint) *model.Tag {
68
 	u := &model.Tag{}
67
 	u := &model.Tag{}
69
-	global.DB.Where("id = ?", id).First(u)
68
+	DB.Where("id = ?", id).First(u)
70
 	return u
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
 	res = &model.TagList{}
73
 	res = &model.TagList{}
75
 	res.Page = int64(page)
74
 	res.Page = int64(page)
76
 	res.PageSize = int64(pageSize)
75
 	res.PageSize = int64(pageSize)
77
-	tx := global.DB.Model(&model.Tag{})
76
+	tx := DB.Model(&model.Tag{})
78
 	if where != nil {
77
 	if where != nil {
79
 		where(tx)
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
 // Create 创建
86
 // Create 创建
88
 func (s *TagService) Create(u *model.Tag) error {
87
 func (s *TagService) Create(u *model.Tag) error {
89
-	res := global.DB.Create(u).Error
88
+	res := DB.Create(u).Error
90
 	return res
89
 	return res
91
 }
90
 }
92
 func (s *TagService) Delete(u *model.Tag) error {
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
 // Update 更新
95
 // Update 更新
97
 func (s *TagService) Update(u *model.Tag) error {
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
 import (
3
 import (
4
 	"errors"
4
 	"errors"
5
-	"github.com/lejianwen/rustdesk-api/v2/global"
6
 	"github.com/lejianwen/rustdesk-api/v2/model"
5
 	"github.com/lejianwen/rustdesk-api/v2/model"
7
 	"github.com/lejianwen/rustdesk-api/v2/utils"
6
 	"github.com/lejianwen/rustdesk-api/v2/utils"
8
 	"math/rand"
7
 	"math/rand"
@@ -20,43 +19,43 @@ type UserService struct {
20
 // InfoById 根据用户id取用户信息
19
 // InfoById 根据用户id取用户信息
21
 func (us *UserService) InfoById(id uint) *model.User {
20
 func (us *UserService) InfoById(id uint) *model.User {
22
 	u := &model.User{}
21
 	u := &model.User{}
23
-	global.DB.Where("id = ?", id).First(u)
22
+	DB.Where("id = ?", id).First(u)
24
 	return u
23
 	return u
25
 }
24
 }
26
 
25
 
27
 // InfoByUsername 根据用户名取用户信息
26
 // InfoByUsername 根据用户名取用户信息
28
 func (us *UserService) InfoByUsername(un string) *model.User {
27
 func (us *UserService) InfoByUsername(un string) *model.User {
29
 	u := &model.User{}
28
 	u := &model.User{}
30
-	global.DB.Where("username = ?", un).First(u)
29
+	DB.Where("username = ?", un).First(u)
31
 	return u
30
 	return u
32
 }
31
 }
33
 
32
 
34
 // InfoByEmail 根据邮箱取用户信息
33
 // InfoByEmail 根据邮箱取用户信息
35
 func (us *UserService) InfoByEmail(email string) *model.User {
34
 func (us *UserService) InfoByEmail(email string) *model.User {
36
 	u := &model.User{}
35
 	u := &model.User{}
37
-	global.DB.Where("email = ?", email).First(u)
36
+	DB.Where("email = ?", email).First(u)
38
 	return u
37
 	return u
39
 }
38
 }
40
 
39
 
41
 // InfoByOpenid 根据openid取用户信息
40
 // InfoByOpenid 根据openid取用户信息
42
 func (us *UserService) InfoByOpenid(openid string) *model.User {
41
 func (us *UserService) InfoByOpenid(openid string) *model.User {
43
 	u := &model.User{}
42
 	u := &model.User{}
44
-	global.DB.Where("openid = ?", openid).First(u)
43
+	DB.Where("openid = ?", openid).First(u)
45
 	return u
44
 	return u
46
 }
45
 }
47
 
46
 
48
 // InfoByUsernamePassword 根据用户名密码取用户信息
47
 // InfoByUsernamePassword 根据用户名密码取用户信息
49
 func (us *UserService) InfoByUsernamePassword(username, password string) *model.User {
48
 func (us *UserService) InfoByUsernamePassword(username, password string) *model.User {
50
-	if global.Config.Ldap.Enable {
49
+	if Config.Ldap.Enable {
51
 		u, err := AllService.LdapService.Authenticate(username, password)
50
 		u, err := AllService.LdapService.Authenticate(username, password)
52
 		if err == nil {
51
 		if err == nil {
53
 			return u
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
 	u := &model.User{}
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
 	return u
59
 	return u
61
 }
60
 }
62
 
61
 
@@ -64,21 +63,21 @@ func (us *UserService) InfoByUsernamePassword(username, password string) *model.
64
 func (us *UserService) InfoByAccessToken(token string) (*model.User, *model.UserToken) {
63
 func (us *UserService) InfoByAccessToken(token string) (*model.User, *model.UserToken) {
65
 	u := &model.User{}
64
 	u := &model.User{}
66
 	ut := &model.UserToken{}
65
 	ut := &model.UserToken{}
67
-	global.DB.Where("token = ?", token).First(ut)
66
+	DB.Where("token = ?", token).First(ut)
68
 	if ut.Id == 0 {
67
 	if ut.Id == 0 {
69
 		return u, ut
68
 		return u, ut
70
 	}
69
 	}
71
 	if ut.ExpiredAt < time.Now().Unix() {
70
 	if ut.ExpiredAt < time.Now().Unix() {
72
 		return u, ut
71
 		return u, ut
73
 	}
72
 	}
74
-	global.DB.Where("id = ?", ut.UserId).First(u)
73
+	DB.Where("id = ?", ut.UserId).First(u)
75
 	return u, ut
74
 	return u, ut
76
 }
75
 }
77
 
76
 
78
 // GenerateToken 生成token
77
 // GenerateToken 生成token
79
 func (us *UserService) GenerateToken(u *model.User) string {
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
 	return utils.Md5(u.Username + time.Now().String())
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
 		DeviceId:   llog.DeviceId,
92
 		DeviceId:   llog.DeviceId,
94
 		ExpiredAt:  us.UserTokenExpireTimestamp(),
93
 		ExpiredAt:  us.UserTokenExpireTimestamp(),
95
 	}
94
 	}
96
-	global.DB.Create(ut)
95
+	DB.Create(ut)
97
 	llog.UserTokenId = ut.UserId
96
 	llog.UserTokenId = ut.UserId
98
-	global.DB.Create(llog)
97
+	DB.Create(llog)
99
 	if llog.Uuid != "" {
98
 	if llog.Uuid != "" {
100
 		AllService.PeerService.UuidBindUserId(llog.DeviceId, llog.Uuid, u.Id)
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
 	res = &model.UserList{}
115
 	res = &model.UserList{}
117
 	res.Page = int64(page)
116
 	res.Page = int64(page)
118
 	res.PageSize = int64(pageSize)
117
 	res.PageSize = int64(pageSize)
119
-	tx := global.DB.Model(&model.User{})
118
+	tx := DB.Model(&model.User{})
120
 	if where != nil {
119
 	if where != nil {
121
 		where(tx)
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
 func (us *UserService) ListByIds(ids []uint) (res []*model.User) {
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
 	return res
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
 // ListIdsByGroupId 根据组id取用户id列表
141
 // ListIdsByGroupId 根据组id取用户id列表
143
 func (us *UserService) ListIdsByGroupId(groupId uint) (ids []uint) {
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
 	return ids
144
 	return ids
146
 
145
 
147
 }
146
 }
148
 
147
 
149
 // ListIdAndNameByGroupId 根据组id取用户id和用户名列表
148
 // ListIdAndNameByGroupId 根据组id取用户id和用户名列表
150
 func (us *UserService) ListIdAndNameByGroupId(groupId uint) (res []*model.User) {
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
 	return res
151
 	return res
153
 }
152
 }
154
 
153
 
@@ -170,14 +169,14 @@ func (us *UserService) Create(u *model.User) error {
170
 	}
169
 	}
171
 	u.Username = us.formatUsername(u.Username)
170
 	u.Username = us.formatUsername(u.Username)
172
 	u.Password = us.EncryptPassword(u.Password)
171
 	u.Password = us.EncryptPassword(u.Password)
173
-	res := global.DB.Create(u).Error
172
+	res := DB.Create(u).Error
174
 	return res
173
 	return res
175
 }
174
 }
176
 
175
 
177
 // GetUuidByToken 根据token和user取uuid
176
 // GetUuidByToken 根据token和user取uuid
178
 func (us *UserService) GetUuidByToken(u *model.User, token string) string {
177
 func (us *UserService) GetUuidByToken(u *model.User, token string) string {
179
 	ut := &model.UserToken{}
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
 	if err != nil {
180
 	if err != nil {
182
 		return ""
181
 		return ""
183
 	}
182
 	}
@@ -187,7 +186,7 @@ func (us *UserService) GetUuidByToken(u *model.User, token string) string {
187
 // Logout 退出登录 -> 删除token, 解绑uuid
186
 // Logout 退出登录 -> 删除token, 解绑uuid
188
 func (us *UserService) Logout(u *model.User, token string) error {
187
 func (us *UserService) Logout(u *model.User, token string) error {
189
 	uuid := us.GetUuidByToken(u, token)
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
 	if err != nil {
190
 	if err != nil {
192
 		return err
191
 		return err
193
 	}
192
 	}
@@ -203,7 +202,7 @@ func (us *UserService) Delete(u *model.User) error {
203
 	if userCount <= 1 && us.IsAdmin(u) {
202
 	if userCount <= 1 && us.IsAdmin(u) {
204
 		return errors.New("The last admin user cannot be deleted")
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
 	if err := tx.Delete(u).Error; err != nil {
207
 	if err := tx.Delete(u).Error; err != nil {
209
 		tx.Rollback()
208
 		tx.Rollback()
@@ -232,7 +231,7 @@ func (us *UserService) Delete(u *model.User) error {
232
 	tx.Commit()
231
 	tx.Commit()
233
 	// 删除关联的peer
232
 	// 删除关联的peer
234
 	if err := AllService.PeerService.EraseUserId(u.Id); err != nil {
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
 		return nil
235
 		return nil
237
 	}
236
 	}
238
 	return nil
237
 	return nil
@@ -249,28 +248,28 @@ func (us *UserService) Update(u *model.User) error {
249
 			return errors.New("The last admin user cannot be disabled or demoted")
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
 // FlushToken 清空token
254
 // FlushToken 清空token
256
 func (us *UserService) FlushToken(u *model.User) error {
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
 // FlushTokenByUuid 清空token
259
 // FlushTokenByUuid 清空token
261
 func (us *UserService) FlushTokenByUuid(uuid string) error {
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
 // FlushTokenByUuids 清空token
264
 // FlushTokenByUuids 清空token
266
 func (us *UserService) FlushTokenByUuids(uuids []string) error {
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
 // UpdatePassword 更新密码
269
 // UpdatePassword 更新密码
271
 func (us *UserService) UpdatePassword(u *model.User, password string) error {
270
 func (us *UserService) UpdatePassword(u *model.User, password string) error {
272
 	u.Password = us.EncryptPassword(password)
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
 	if err != nil {
273
 	if err != nil {
275
 		return err
274
 		return err
276
 	}
275
 	}
@@ -306,8 +305,8 @@ func (us *UserService) InfoByOauthId(op string, openId string) *model.User {
306
 
305
 
307
 // RegisterByOauth 注册
306
 // RegisterByOauth 注册
308
 func (us *UserService) RegisterByOauth(oauthUser *model.OauthUser, op string) (error, *model.User) {
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
 	ut := AllService.OauthService.UserThirdInfo(op, oauthUser.OpenId)
310
 	ut := AllService.OauthService.UserThirdInfo(op, oauthUser.OpenId)
312
 	if ut.Id != 0 {
311
 	if ut.Id != 0 {
313
 		return nil, us.InfoById(ut.UserId)
312
 		return nil, us.InfoById(ut.UserId)
@@ -335,12 +334,12 @@ func (us *UserService) RegisterByOauth(oauthUser *model.OauthUser, op string) (e
335
 		}
334
 		}
336
 		if user.Id != 0 {
335
 		if user.Id != 0 {
337
 			ut.FromOauthUser(user.Id, oauthUser, oauthType, op)
336
 			ut.FromOauthUser(user.Id, oauthUser, oauthType, op)
338
-			global.DB.Create(ut)
337
+			DB.Create(ut)
339
 			return nil, user
338
 			return nil, user
340
 		}
339
 		}
341
 	}
340
 	}
342
 
341
 
343
-	tx := global.DB.Begin()
342
+	tx := DB.Begin()
344
 	ut = &model.UserThird{}
343
 	ut = &model.UserThird{}
345
 	ut.FromOauthUser(0, oauthUser, oauthType, op)
344
 	ut.FromOauthUser(0, oauthUser, oauthType, op)
346
 	// The initial username should be formatted
345
 	// The initial username should be formatted
@@ -372,27 +371,27 @@ func (us *UserService) GenerateUsernameByOauth(name string) string {
372
 
371
 
373
 // UserThirdsByUserId
372
 // UserThirdsByUserId
374
 func (us *UserService) UserThirdsByUserId(userId uint) (res []*model.UserThird) {
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
 	return res
375
 	return res
377
 }
376
 }
378
 
377
 
379
 func (us *UserService) UserThirdInfo(userId uint, op string) *model.UserThird {
378
 func (us *UserService) UserThirdInfo(userId uint, op string) *model.UserThird {
380
 	ut := &model.UserThird{}
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
 	return ut
381
 	return ut
383
 }
382
 }
384
 
383
 
385
 // FindLatestUserIdFromLoginLogByUuid 根据uuid查找最后登录的用户id
384
 // FindLatestUserIdFromLoginLogByUuid 根据uuid查找最后登录的用户id
386
 func (us *UserService) FindLatestUserIdFromLoginLogByUuid(uuid string) uint {
385
 func (us *UserService) FindLatestUserIdFromLoginLogByUuid(uuid string) uint {
387
 	llog := &model.LoginLog{}
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
 	return llog.UserId
388
 	return llog.UserId
390
 }
389
 }
391
 
390
 
392
 // IsPasswordEmptyById 根据用户id判断密码是否为空,主要用于第三方登录的自动注册
391
 // IsPasswordEmptyById 根据用户id判断密码是否为空,主要用于第三方登录的自动注册
393
 func (us *UserService) IsPasswordEmptyById(id uint) bool {
392
 func (us *UserService) IsPasswordEmptyById(id uint) bool {
394
 	u := &model.User{}
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
 		return false
395
 		return false
397
 	}
396
 	}
398
 	return u.Password == ""
397
 	return u.Password == ""
@@ -401,7 +400,7 @@ func (us *UserService) IsPasswordEmptyById(id uint) bool {
401
 // IsPasswordEmptyByUsername 根据用户id判断密码是否为空,主要用于第三方登录的自动注册
400
 // IsPasswordEmptyByUsername 根据用户id判断密码是否为空,主要用于第三方登录的自动注册
402
 func (us *UserService) IsPasswordEmptyByUsername(username string) bool {
401
 func (us *UserService) IsPasswordEmptyByUsername(username string) bool {
403
 	u := &model.User{}
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
 		return false
404
 		return false
406
 	}
405
 	}
407
 	return u.Password == ""
406
 	return u.Password == ""
@@ -431,7 +430,7 @@ func (us *UserService) TokenList(page uint, size uint, f func(tx *gorm.DB)) *mod
431
 	res := &model.UserTokenList{}
430
 	res := &model.UserTokenList{}
432
 	res.Page = int64(page)
431
 	res.Page = int64(page)
433
 	res.PageSize = int64(size)
432
 	res.PageSize = int64(size)
434
-	tx := global.DB.Model(&model.UserToken{})
433
+	tx := DB.Model(&model.UserToken{})
435
 	if f != nil {
434
 	if f != nil {
436
 		f(tx)
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
 func (us *UserService) TokenInfoById(id uint) *model.UserToken {
443
 func (us *UserService) TokenInfoById(id uint) *model.UserToken {
445
 	ut := &model.UserToken{}
444
 	ut := &model.UserToken{}
446
-	global.DB.Where("id = ?", id).First(ut)
445
+	DB.Where("id = ?", id).First(ut)
447
 	return ut
446
 	return ut
448
 }
447
 }
449
 
448
 
450
 func (us *UserService) DeleteToken(l *model.UserToken) error {
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
 // Helper functions, used for formatting username
453
 // Helper functions, used for formatting username
@@ -461,20 +460,20 @@ func (us *UserService) formatUsername(username string) string {
461
 // Helper functions, getUserCount
460
 // Helper functions, getUserCount
462
 func (us *UserService) getUserCount() int64 {
461
 func (us *UserService) getUserCount() int64 {
463
 	var count int64
462
 	var count int64
464
-	global.DB.Model(&model.User{}).Count(&count)
463
+	DB.Model(&model.User{}).Count(&count)
465
 	return count
464
 	return count
466
 }
465
 }
467
 
466
 
468
 // helper functions, getAdminUserCount
467
 // helper functions, getAdminUserCount
469
 func (us *UserService) getAdminUserCount() int64 {
468
 func (us *UserService) getAdminUserCount() int64 {
470
 	var count int64
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
 	return count
471
 	return count
473
 }
472
 }
474
 
473
 
475
 // UserTokenExpireTimestamp 生成用户token过期时间
474
 // UserTokenExpireTimestamp 生成用户token过期时间
476
 func (us *UserService) UserTokenExpireTimestamp() int64 {
475
 func (us *UserService) UserTokenExpireTimestamp() int64 {
477
-	exp := global.Config.App.TokenExpire
476
+	exp := Config.App.TokenExpire
478
 	if exp == 0 {
477
 	if exp == 0 {
479
 		//默认七天
478
 		//默认七天
480
 		exp = 604800
479
 		exp = 604800
@@ -484,7 +483,7 @@ func (us *UserService) UserTokenExpireTimestamp() int64 {
484
 
483
 
485
 func (us *UserService) RefreshAccessToken(ut *model.UserToken) {
484
 func (us *UserService) RefreshAccessToken(ut *model.UserToken) {
486
 	ut.ExpiredAt = us.UserTokenExpireTimestamp()
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
 func (us *UserService) AutoRefreshAccessToken(ut *model.UserToken) {
488
 func (us *UserService) AutoRefreshAccessToken(ut *model.UserToken) {
490
 	if ut.ExpiredAt-time.Now().Unix() < 86400 {
489
 	if ut.ExpiredAt-time.Now().Unix() < 86400 {
@@ -493,11 +492,11 @@ func (us *UserService) AutoRefreshAccessToken(ut *model.UserToken) {
493
 }
492
 }
494
 
493
 
495
 func (us *UserService) BatchDeleteUserToken(ids []uint) error {
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
 func (us *UserService) VerifyJWT(token string) (uint, error) {
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
 // IsUsernameExists 判断用户名是否存在, it will check the internal database and LDAP(if enabled)
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
 func (us *UserService) IsUsernameExistsLocal(username string) bool {
507
 func (us *UserService) IsUsernameExistsLocal(username string) bool {
509
 	u := &model.User{}
508
 	u := &model.User{}
510
-	global.DB.Where("username = ?", username).First(u)
509
+	DB.Where("username = ?", username).First(u)
511
 	return u.Id != 0
510
 	return u.Id != 0
512
 }
511
 }
513
 
512