-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcore.go
More file actions
1998 lines (1899 loc) · 47.9 KB
/
Copy pathcore.go
File metadata and controls
1998 lines (1899 loc) · 47.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"CoolPush/wework"
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/julienschmidt/httprouter"
"github.com/google/uuid"
"github.com/wxpusher/wxpusher-sdk-go"
wxModel "github.com/wxpusher/wxpusher-sdk-go/model"
"gopkg.in/gomail.v2"
)
// Write 输出返回结果
func Write(w http.ResponseWriter, response []byte) {
//公共的响应头设置
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
w.Header().Set("Content-Type", "application/json;charset=utf-8")
w.Header().Set("Content-Length", strconv.Itoa(len(string(response))))
_, _ = w.Write(response)
return
}
// Ping 联通性检测
func Ping(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
response, _ := json.Marshal(struct {
Ping string `json:"ping"`
}{
Ping: "PONG",
})
Write(w, response)
}
// ResetSkey 重置Skey
func ResetSkey(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
//先检验token
tokenString := r.Header.Get("token")
if _, err := CheckToken(tokenString); err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: err.Error(),
})
Write(w, ret)
return
}
//获取记录id
var _id = r.URL.Query().Get("id")
if _id == "" {
body, _ := json.Marshal(&Response{
Code: StatusClientError,
Message: "缺少id参数",
})
Write(w, body)
return
}
//_id的string转为int64
if id, err := strconv.ParseInt(_id, 10, 64); err != nil {
body, _ := json.Marshal(&Response{
Code: StatusClientError,
Message: "id参数格式错误",
Data: err,
})
Write(w, body)
} else {
h := sha256.New()
h.Write([]byte(uuid.Must(uuid.NewRandom()).String()))
key := hex.EncodeToString(h.Sum(nil))[:32]
var u = &User{
Id: id,
Skey: key,
}
if _, err = engine.ID(id).Cols("skey").Update(u); err != nil {
body, _ := json.Marshal(&Response{
Code: StatusServerGeneralError,
Message: "重置失败",
Data: err,
})
Write(w, body)
return
}
body, _ := json.Marshal(&Response{
Code: StatusOk,
Message: "重置成功",
})
Write(w, body)
return
}
}
// AuthToken 验证token路由
func AuthToken(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
tokenString := r.Header.Get("token")
id, err := CheckToken(tokenString)
//检测故障
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: err.Error(),
})
Write(w, ret)
return
}
u, exist, _ := SearchByID(id)
if !exist {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "token已失效",
})
Write(w, ret)
return
}
ret, _ := json.Marshal(&Response{
Code: StatusOk,
Message: "ok",
Data: u,
})
Write(w, ret)
}
// GetPort 获得服务QQ对应服务端口 需要手动维护 config.yaml 文件
func GetPort(from string) string {
if v, ok := conf.Robots[from]; ok {
return v
}
return ":5700"
}
// Send 发起推送
func Send(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
var message string
//优先GET 其次获取POST 再次获取POST-body
if r.URL.Query().Get("c") != "" {
message = r.URL.Query().Get("c")
} else if r.Method == "POST" {
message = r.PostFormValue("c")
}
//都为空? 尝试获取raw
if message == "" {
buf := make([]byte, RecvBuff)
n, _ := r.Body.Read(buf)
message = string(buf[:n])
}
//检测长度
rawContent := []rune(message)
if len(rawContent) > SendLength || len(rawContent) == 0 {
body, _ := json.Marshal(&Response{
Code: StatusClientError,
Message: "文本超限或不能为空 推送失败",
})
Write(w, body)
return
}
u, _, err := SearchByKey(p.ByName("skey"))
if err != nil {
//失败 返回错误
body, _ := json.Marshal(&Response{
Code: StatusServerGeneralError,
Message: err.Error(),
})
Write(w, body)
return
}
//检测是否绑定
if u.SendFrom == "" || u.SendTo == "" {
body, _ := json.Marshal(&Response{
Code: StatusClientError,
Message: "用户未绑定推送QQ或用户未指定被推送QQ地址",
})
Write(w, body)
return
}
//检测发送次数是否达到上限 是则不允许再次发送
if u.Count > SendLimit {
body, _ := json.Marshal(&Response{
Code: StatusServerForbid,
Message: "当日推送数据已达到上限",
})
Write(w, body)
return
}
//内容 --> 敏感词检验
validate, _ := filter.Validate(message)
if !validate {
//文本不正常
u.Fouls++
}
//内容 --> 敏感词过滤
message = filter.Replace(message, '*')
//CQ码转换
//message = convImg(message)
//
message = convAt(message)
//
message = convFace(message)
//
//message = convMusic(message)
//
//message = convXml(message)
//
//message = convJson(message)
//内容 --> 字符编码
message = url.QueryEscape(message)
//更新count
zeroPoint, _ := time.ParseInLocation("2006-01-02",
time.Now().Format("2006-01-02"), time.Local) //zeroPoint是当日零点
if u != nil && zeroPoint.Unix() < u.LastSend {
//未到第二日 执行count++
_, _ = engine.ID(u.Id).Update(&User{
Count: u.Count + 1,
Fouls: u.Fouls,
LastSend: time.Now().Unix(),
})
} else if u != nil && zeroPoint.Unix() >= u.LastSend {
//到了第二日 重置count
_, _ = engine.ID(u.Id).Update(&User{
Count: 1,
Fouls: u.Fouls,
LastSend: time.Now().Unix(),
})
}
//发送地址
var port = GetPort(u.SendFrom)
var sendURL = conf.CQHttp + port + "/send_private_msg"
//发起推送
var pushRet = &struct {
RetCode int64 `json:"retcode"`
Status string `json:"status"`
}{}
resp, err := http.Post(sendURL, "application/x-www-form-urlencoded", strings.NewReader("user_id="+u.SendTo+"&message="+message))
if err != nil {
body, _ := json.Marshal(&Response{
Code: StatusServerNetworkError,
Message: "服务端网络异常,请稍后再试",
})
Write(w, body)
return
}
defer resp.Body.Close()
content, _ := ioutil.ReadAll(resp.Body)
_ = json.Unmarshal(content, pushRet)
var ret = new(Response)
if pushRet.RetCode == 0 {
ret = &Response{
Code: StatusOk,
Message: "ok",
Data: nil,
}
} else if pushRet.RetCode == 100 {
ret = &Response{
Code: StatusClientError,
Message: pushRet.Status,
Data: "推送异常,请从QQ列表删除机器人并重新添加好友关系",
}
} else {
ret = &Response{
Code: StatusClientError,
Message: pushRet.Status,
Data: "推送异常",
}
}
_t, _ := json.Marshal(ret)
Write(w, _t)
}
// GroupSend 发起推送
func GroupSend(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
var message string
//优先GET 其次获取POST 再次获取POST-body
if r.URL.Query().Get("c") != "" {
message = r.URL.Query().Get("c")
} else if r.Method == "POST" {
message = r.PostFormValue("c")
}
//都为空? 尝试获取raw
if message == "" {
buf := make([]byte, RecvBuff)
n, _ := r.Body.Read(buf)
message = string(buf[:n])
}
//检测长度
rawContent := []rune(message)
if len(rawContent) > SendLength || len(rawContent) == 0 {
body, _ := json.Marshal(&Response{
Code: StatusClientError,
Message: "文本超限或不能为空 推送失败",
})
Write(w, body)
return
}
u, _, err := SearchByKey(p.ByName("skey"))
if err != nil {
//失败 返回错误
body, _ := json.Marshal(&Response{
Code: StatusServerGeneralError,
Message: err.Error(),
})
Write(w, body)
return
}
//检测是否绑定
if u.GroupFrom == "" || u.GroupTo == "" {
body, _ := json.Marshal(&Response{
Code: StatusClientError,
Message: "用户未绑定推送QQ或用户未指定推送目标群号码",
})
Write(w, body)
return
}
//内容 --> 敏感词检验
validate, _ := filter.Validate(message)
if !validate {
//文本不正常
u.Fouls++
}
//内容 --> 敏感词过滤
message = filter.Replace(message, '*')
//CQ码转换
//message = convImg(message)
//
message = convAt(message)
//
message = convFace(message)
//
//message = convMusic(message)
//
//message = convXml(message)
//
//message = convJson(message)
//内容 --> 字符编码
message = url.QueryEscape(message)
//检测发送次数是否达到上限 是则不允许再次发送
if u.Count > SendLimit {
body, _ := json.Marshal(&Response{
Code: StatusServerForbid,
Message: "当日推送数据已达到上限",
})
Write(w, body)
return
}
//更新count
zeroPoint, _ := time.ParseInLocation("2006-01-02",
time.Now().Format("2006-01-02"), time.Local) //zeroPoint是当日零点
if u != nil && zeroPoint.Unix() < u.LastSend {
//未到第二日 执行count++
_, _ = engine.ID(u.Id).Update(&User{
Count: u.Count + 1,
Fouls: u.Fouls,
LastSend: time.Now().Unix(),
})
} else if u != nil && zeroPoint.Unix() >= u.LastSend {
//到了第二日 重置count
_, _ = engine.ID(u.Id).Update(&User{
Count: 1,
Fouls: u.Fouls,
LastSend: time.Now().Unix(),
})
}
//发送地址
var port = GetPort(u.GroupFrom)
var sendURL = conf.CQHttp + port + "/send_group_msg"
//发起推送
var pushRet = &struct {
RetCode int64 `json:"retcode"`
Status string `json:"status"`
}{}
resp, err := http.Post(sendURL, "application/x-www-form-urlencoded", strings.NewReader("group_id="+u.GroupTo+"&message="+message))
if err != nil {
body, _ := json.Marshal(&Response{
Code: StatusServerNetworkError,
Message: "服务端网络异常,请稍后再试",
})
Write(w, body)
return
}
defer resp.Body.Close()
content, _ := ioutil.ReadAll(resp.Body)
_ = json.Unmarshal(content, pushRet)
var ret = new(Response)
if pushRet.RetCode == 0 {
ret = &Response{
Code: StatusOk,
Message: "ok",
Data: nil,
}
} else if pushRet.RetCode == 100 {
ret = &Response{
Code: StatusClientError,
Message: pushRet.Status,
Data: "推送内容格式异常",
}
} else {
ret = &Response{
Code: StatusClientError,
Message: pushRet.Status,
Data: "推送异常",
}
}
_t, _ := json.Marshal(ret)
Write(w, _t)
}
// MessageFilterAll 检测消息的所有敏感词 有则返回词汇数组 否则返回真
func MessageFilterAll(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var message string
//优先GET
if r.URL.Query().Get("c") != "" {
message = r.URL.Query().Get("c")
} else if r.Method == "POST" {
message = r.PostFormValue("c")
}
//检测长度
if len(message) > 1500 || len(message) == 0 {
body, _ := json.Marshal(&Response{
Code: StatusClientError,
Message: "文本超限或不能为空 推送失败",
})
Write(w, body)
return
}
//开始检测
list := filter.FindAll(message)
if len(list) == 0 {
body, _ := json.Marshal(&Response{
Code: StatusOk,
Message: "文本没有敏感词",
})
Write(w, body)
return
}
body, _ := json.Marshal(&Response{
Code: StatusClientError,
Message: "服务存在敏感词",
Data: list,
})
Write(w, body)
}
// AuthGithub 授权github登录
func AuthGithub(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var code = r.URL.Query().Get("code")
var target = fmt.Sprintf("https://qtqq-login.now.sh/api?code=%s", code)
resp, err := http.Get(target)
if err != nil {
body, _ := json.Marshal(&Response{
Code: StatusServerNetworkError,
Message: "服务端网络异常,请稍后再试",
})
Write(w, body)
return
}
defer resp.Body.Close()
_c, _ := ioutil.ReadAll(resp.Body)
//结果解析
var response = new(Response)
decoder := json.NewDecoder(bytes.NewReader(_c))
decoder.UseNumber()
_ = decoder.Decode(response)
if response.Code != 200 {
//不成功 直接返回错误信息
Write(w, _c)
return
} else {
//登录成功 拿到gu信息
idRaw := response.Data.(map[string]interface{})["id"].(json.Number)
id, _ := idRaw.Int64()
//判断 是否存在 pid 存在则不变 不存在则创建用户
u, exist, err := SearchByPID(id, "github")
if !exist {
//没找到 注册用户
err = NewUserByPid(id, "github")
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerGeneralError,
Message: "新用户初始化故障",
Data: err.Error(),
})
Write(w, ret)
return
}
u, _, _ = SearchByPID(id, "github")
}
if u == nil {
body, _ := json.Marshal(&Response{
Code: StatusServerGeneralError,
Message: "操作被禁止,请重新操作",
})
Write(w, body)
return
}
if !u.Status || u.Fouls >= FoulsNumber {
//用户禁用
ret, _ := json.Marshal(&Response{
Code: StatusServerForbid,
Message: "用户被禁用:由于多次推送违规内容,您的账号目前已被系统锁定,请联系管理员处理",
Data: nil,
})
Write(w, ret)
return
}
//找到了 下发jwt token
token, err := DistributeToken(u.Skey)
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "下发token失败:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
ret, _ := json.Marshal(&Response{
Code: StatusOk,
Message: token,
Data: u,
})
Write(w, ret)
return
}
}
// AuthGitee 授权gitee登陆
func AuthGitee(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var code = r.URL.Query().Get("code")
var target = fmt.Sprintf("https://gitee.com/oauth/token?grant_type=authorization_code&code=%s&client_id=%s&redirect_uri=%s&client_secret=%s", code, conf.Oauth.Gitee.ClientID, conf.Oauth.Gitee.Callback, conf.Oauth.Gitee.ClientSecret)
resp, err := http.Post(target, "application/json; charset=utf-8", nil)
//请求结果
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerNetworkError,
Message: "服务端网络故障:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
defer resp.Body.Close()
//结果解析
_c, _ := ioutil.ReadAll(resp.Body)
var token = &struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
CreatedAt int `json:"created_at"`
}{}
_ = json.Unmarshal(_c, token)
//将AccessToken 请求用户信息
var userInfo = fmt.Sprintf("https://gitee.com/api/v5/user?access_token=%s", token.AccessToken)
_u, err := http.Get(userInfo)
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerNetworkError,
Message: "服务端网络故障:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
defer _u.Body.Close()
ub, _ := ioutil.ReadAll(_u.Body)
var user = new(PlatformUser)
_ = json.Unmarshal(ub, user)
//解析出来的 user.ID 为 0 肯定是有问题的
if user.PID == 0 {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "授权认证出错",
Data: "授权认证出错",
})
Write(w, ret)
return
}
//登录成功 拿到用户信息 下一步操作
{
//判断 是否存在 pid 存在则不变 不存在则创建用户
u, exist, err := SearchByPID(user.PID, "gitee")
if !exist {
//没找到 注册用户
err = NewUserByPid(user.PID, "gitee")
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerGeneralError,
Message: "新用户初始化故障",
Data: err.Error(),
})
Write(w, ret)
return
}
u, _, _ = SearchByPID(user.PID, "gitee")
}
if u == nil {
body, _ := json.Marshal(&Response{
Code: StatusServerGeneralError,
Message: "操作被禁止,请重新操作",
})
Write(w, body)
return
}
if !u.Status || u.Fouls >= FoulsNumber {
//用户禁用
ret, _ := json.Marshal(&Response{
Code: StatusServerForbid,
Message: "用户被禁用:由于多次推送违规内容,您的账号目前已被系统锁定,请联系管理员处理",
Data: nil,
})
Write(w, ret)
return
}
//找到了 下发jwt token
token, err := DistributeToken(u.Skey)
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "下发token失败:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
ret, _ := json.Marshal(&Response{
Code: StatusOk,
Message: token,
Data: u,
})
Write(w, ret)
return
}
}
// AuthOSC 授权开源中国登陆
func AuthOSC(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var code = r.URL.Query().Get("code")
var client = &http.Client{}
var target = fmt.Sprintf("https://www.oschina.net/action/openapi/token?client_id=%s&client_secret=%s&grant_type=authorization_code&redirect_uri=%s&code=%s", conf.Oauth.Osc.ClientID, conf.Oauth.Osc.ClientSecret, conf.Oauth.Osc.Callback, code)
tokenReq, _ := http.NewRequest("GET", target, nil)
tokenReq.Header.Add("Content-Type", "application/json")
tokenReq.Header.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36")
tokenResp, err := client.Do(tokenReq)
//请求结果
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerNetworkError,
Message: "服务端网络故障:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
defer tokenResp.Body.Close()
//结果解析
_c, _ := ioutil.ReadAll(tokenResp.Body)
var token = &struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
UID int `json:"uid"`
}{}
if err = json.Unmarshal(_c, token); err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerNetworkError,
Message: "服务端故障:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
//将AccessToken 请求用户信息
var userInfo = fmt.Sprintf("https://www.oschina.net/action/openapi/user?access_token=%s&dataType=json", token.AccessToken)
userReq, _ := http.NewRequest("GET", userInfo, nil)
userReq.Header.Add("Content-Type", "application/json")
userReq.Header.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36")
userResq, err := client.Do(userReq)
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerNetworkError,
Message: "服务端网络故障:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
defer userResq.Body.Close()
ub, _ := ioutil.ReadAll(userResq.Body)
var user = new(PlatformUser)
if err = json.Unmarshal(ub, user); err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerNetworkError,
Message: "服务端故障:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
//解析出来的 user.ID 为 0 肯定是有问题的
if user.PID == 0 {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "授权认证出错",
Data: "授权认证出错",
})
Write(w, ret)
return
}
//登录成功 拿到用户信息 下一步操作
{
//判断 是否存在 Pid 存在则不变 不存在则创建用户
u, exist, err := SearchByPID(user.PID, "osc")
if !exist {
//没找到 注册用户
err = NewUserByPid(user.PID, "osc")
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerGeneralError,
Message: "新用户初始化故障",
Data: err.Error(),
})
Write(w, ret)
return
}
u, _, _ = SearchByPID(user.PID, "osc")
}
if u == nil {
body, _ := json.Marshal(&Response{
Code: StatusServerGeneralError,
Message: "操作被禁止,请重新操作",
})
Write(w, body)
return
}
if !u.Status || u.Fouls >= FoulsNumber {
//用户禁用
ret, _ := json.Marshal(&Response{
Code: StatusServerForbid,
Message: "用户被禁用:由于多次推送违规内容,您的账号目前已被系统锁定,请联系管理员处理",
Data: nil,
})
Write(w, ret)
return
}
//找到了 下发jwt token
token, err := DistributeToken(u.Skey)
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "下发token失败:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
ret, _ := json.Marshal(&Response{
Code: StatusOk,
Message: token,
Data: u,
})
Write(w, ret)
return
}
}
// AuthQQ 授权QQ登陆
func AuthQQ(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var code = r.URL.Query().Get("code")
var target = fmt.Sprintf("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&code=%s&client_id=%s&redirect_uri=%s&client_secret=%s&fmt=json", code, conf.Oauth.QQ.ClientID, conf.Oauth.QQ.Callback, conf.Oauth.QQ.ClientSecret)
resp, err := http.Get(target)
//请求结果
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerNetworkError,
Message: "服务端网络故障:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
defer resp.Body.Close()
//结果解析
_c, _ := ioutil.ReadAll(resp.Body)
var token = &struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
}{}
_ = json.Unmarshal(_c, token)
//将AccessToken 请求用户信息
var userInfo = fmt.Sprintf("https://graph.qq.com/oauth2.0/me?access_token=%s&fmt=json", token.AccessToken)
_u, err := http.Get(userInfo)
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerNetworkError,
Message: "服务端网络故障:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
defer _u.Body.Close()
ub, _ := ioutil.ReadAll(_u.Body)
var user = &struct {
ClientID string
OpenID string
}{}
_ = json.Unmarshal(ub, user)
//解析出来的 user.ID 为 0 肯定是有问题的
if user.OpenID == "" || user.ClientID == "" {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "授权认证出错",
Data: "授权认证出错",
})
Write(w, ret)
return
}
//登录成功 拿到用户信息 下一步操作
{
//判断 是否存在 pid 存在则不变 不存在则创建用户
u, exist, err := SearchByOID(user.OpenID, "qq")
if !exist {
//没找到 注册用户
err = NewUserByOid(user.OpenID, "qq")
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerGeneralError,
Message: "新用户初始化故障",
Data: err.Error(),
})
Write(w, ret)
return
}
u, _, _ = SearchByOID(user.OpenID, "qq")
}
if u == nil {
body, _ := json.Marshal(&Response{
Code: StatusServerGeneralError,
Message: "操作被禁止,请重新操作",
})
Write(w, body)
return
}
if !u.Status || u.Fouls >= FoulsNumber {
//用户禁用
ret, _ := json.Marshal(&Response{
Code: StatusServerForbid,
Message: "用户被禁用:由于多次推送违规内容,您的账号目前已被系统锁定,请联系管理员处理",
Data: nil,
})
Write(w, ret)
return
}
//找到了 下发jwt token
token, err := DistributeToken(u.Skey)
if err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "下发token失败:" + err.Error(),
Data: err,
})
Write(w, ret)
return
}
ret, _ := json.Marshal(&Response{
Code: StatusOk,
Message: token,
Data: u,
})
Write(w, ret)
return
}
}
// Bind 用户绑定QQ
func Bind(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
//先检验token
tokenString := r.Header.Get("token")
if _, err := CheckToken(tokenString); err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: err.Error(),
})
Write(w, ret)
return
}
//绑定qq
idString := r.URL.Query().Get("id")
id, err := strconv.ParseInt(idString, 10, 64)
if err != nil {
//转换失败 说明id有问题
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "用户身份无法确定",
})
Write(w, ret)
return
}
to := r.URL.Query().Get("sendTo")
from := r.URL.Query().Get("sendFrom")
var user = &User{
Id: id,
SendTo: to,
SendFrom: from,
}
//检测用户是否存在
if _, exist, _ := SearchByID(id); !exist {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "用户不存在,非法操作",
})
Write(w, ret)
return
} else {
_, err = engine.Where("id = ?", id).Update(user)
if err != nil {
//转换失败 说明id有问题
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "绑定失败",
})
Write(w, ret)
return
}
}
ret, _ := json.Marshal(&Response{
Code: StatusOk,
Message: "绑定成功",
})
Write(w, ret)
return
}
// GroupBind 用户群绑定QQ
func GroupBind(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
//先检验token
tokenString := r.Header.Get("token")
if _, err := CheckToken(tokenString); err != nil {
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: err.Error(),
})
Write(w, ret)
return
}
//绑定qq群
idString := r.URL.Query().Get("id")
id, err := strconv.ParseInt(idString, 10, 64)
if err != nil {
//转换失败 说明id有问题
ret, _ := json.Marshal(&Response{
Code: StatusServerAuthError,
Message: "用户身份无法确定",
})
Write(w, ret)
return
}
to := r.URL.Query().Get("groupTo")
from := r.URL.Query().Get("groupFrom")
var user = &User{
Id: id,
GroupTo: to,
GroupFrom: from,
}
//检测用户是否存在