-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrouteAdmin.go
990 lines (916 loc) · 31.2 KB
/
routeAdmin.go
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
// Copyright (c) 2023 gpress Authors.
//
// This file is part of gpress.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"context"
"encoding/hex"
"fmt"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
//"github.com/bytedance/go-tagexpr/v2/binding"
"gitee.com/chunanyong/zorm"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol"
"github.com/cloudwego/hertz/pkg/route/param"
"golang.org/x/crypto/sha3"
)
// alphaNumericReg 传入的列名只能是字母数字或下划线,长度不超过20
var alphaNumericReg = regexp.MustCompile("^[a-zA-Z0-9_]{1,20}$")
// init 初始化函数
func init() {
// adminGroup 初始化管理员路由组
var adminGroup = h.Group("/admin")
//设置权限
adminGroup.Use(permissionHandler())
//设置json处理函数
//binding.ResetJSONUnmarshaler(json.Unmarshal)
/*
binding.Default().ResetJSONUnmarshaler(func(data []byte, v interface{}) error {
dec := json.NewDecoder(bytes.NewBuffer(data))
dec.UseNumber()
return dec.Decode(v)
})
*/
// 异常页面
h.GET("/admin/error", func(ctx context.Context, c *app.RequestContext) {
cHtmlAdmin(c, http.StatusOK, "admin/error.html", nil)
})
// 安装
h.GET("/admin/install", funcAdminInstallPre)
h.POST("/admin/install", funcAdminInstall)
// 生成30位随机数,钱包签名随机校验.如果32位metamask会解析成16进制字符串,可能是metamask的bug
h.POST("/admin/random", func(ctx context.Context, c *app.RequestContext) {
generateChainRandStr()
c.JSON(http.StatusOK, ResponseData{StatusCode: 1, Data: chainRandStr})
})
// 后台管理员登录
h.GET("/admin/login", funcAdminLoginPre)
h.POST("/admin/login", funcAdminLogin)
// 后台管理员使用区块链账号登录
h.GET("/admin/chainlogin", funcAdminChainloginPre)
h.POST("/admin/chainlogin", funcAdminChainlogin)
// 后台管理员首页
adminGroup.GET("/index", func(ctx context.Context, c *app.RequestContext) {
cHtmlAdmin(c, http.StatusOK, "admin/index.html", nil)
})
// 刷新站点,重新加载资源包含模板和对应的静态文件
adminGroup.GET("/reload", funcAdminReload)
//上传文件
adminGroup.POST("/upload", funcUploadFile)
//上传主题文件
adminGroup.POST("/themeTemplate/uploadTheme", funcUploadTheme)
// 通用list列表
adminGroup.GET("/:urlPathParam/list", funcList)
// 查询主题模板
adminGroup.GET("/themeTemplate/list", funcListThemeTemplate)
// 查询Content列表,根据CategoryId like
adminGroup.GET("/content/list", funcContentList)
// 通用查看
adminGroup.GET("/:urlPathParam/look", funcLook)
// 内容预览
adminGroup.GET("/content/look", funcContentPreview)
// 导航菜单预览
adminGroup.GET("/category/look", funcCategoryPreview)
//跳转到修改页面
adminGroup.GET("/:urlPathParam/update", funcUpdatePre)
// 修改Config
adminGroup.POST("/config/update", funcUpdateConfig)
// 修改Site
adminGroup.POST("/site/update", funcUpdateSite)
// 修改User
adminGroup.POST("/user/update", funcUpdateUser)
// 修改Category
adminGroup.POST("/category/update", funcUpdateCategory)
// 修改Content
adminGroup.POST("/content/update", funcUpdateContent)
// 修改ThemeTemplate
adminGroup.POST("/themeTemplate/update", funcUpdateThemeTemplate)
//跳转到保存页面
adminGroup.GET("/:urlPathParam/save", funcSavePre)
//保存Category
adminGroup.POST("/category/save", funcSaveCategory)
//保存Content
adminGroup.POST("/content/save", funcSaveContent)
//ajax POST删除数据
adminGroup.POST("/:urlPathParam/delete", funcDelete)
//ajax POST执行更新语句
adminGroup.POST("/updatesql", funcUpdateSQL)
}
// funcAdminInstallPre 跳转到安装界面
func funcAdminInstallPre(ctx context.Context, c *app.RequestContext) {
if installed { // 如果已经安装过了,跳转到登录
c.Redirect(http.StatusOK, cRedirecURI("admin/login"))
c.Abort() // 终止后续调用
return
}
cHtmlAdmin(c, http.StatusOK, "admin/install.html", nil)
}
// funcAdminInstall 后台安装
func funcAdminInstall(ctx context.Context, c *app.RequestContext) {
if installed { // 如果已经安装过了,跳转到登录
c.Redirect(http.StatusOK, cRedirecURI("admin/login"))
c.Abort() // 终止后续调用
return
}
// 使用后端管理界面配置,jwtSecret也有后端随机产生
user := User{}
user.Account = c.PostForm("account")
user.UserName = c.PostForm("account")
user.Password = c.PostForm("password")
user.ChainType = c.PostForm("chainType")
user.ChainAddress = c.PostForm("chainAddress")
// 重新hash密码,避免拖库后撞库
sha3Bytes := sha3.Sum512([]byte(user.Password))
user.Password = hex.EncodeToString(sha3Bytes[:])
loginHtml := "admin/login?message=" + funcT("Congratulations, you have successfully installed GPRESS. Please log in now")
if user.ChainAddress != "" && user.ChainType != "" { //如果使用了address作为登录方式
user.Account = ""
user.UserName = ""
loginHtml = "admin/chainlogin"
}
err := insertUser(ctx, user)
if err != nil {
c.Redirect(http.StatusOK, cRedirecURI("admin/error"))
c.Abort() // 终止后续调用
return
}
// 安装成功,更新安装状态
updateInstall(ctx)
c.Redirect(http.StatusOK, cRedirecURI(loginHtml))
}
// funcAdminLoginPre 跳转到登录界面
func funcAdminLoginPre(ctx context.Context, c *app.RequestContext) {
if !installed { // 如果没有安装,跳转到安装
c.Redirect(http.StatusOK, cRedirecURI("admin/install"))
c.Abort() // 终止后续调用
return
}
responseData := make(map[string]string, 0)
message, ok := c.GetQuery("message")
if ok {
responseData["message"] = message
}
if errorLoginCount.Load() >= errCount { //连续错误3次显示验证码
responseData["showCaptcha"] = "1"
generateCaptcha()
responseData["captchaBase64"] = captchaBase64
}
c.SetCookie(config.JwttokenKey, "", config.Timeout, "/", "", protocol.CookieSameSiteStrictMode, false, true)
cHtmlAdmin(c, http.StatusOK, "admin/login.html", responseData)
}
// funcAdminLogin 后台登录
func funcAdminLogin(ctx context.Context, c *app.RequestContext) {
if !installed { // 如果没有安装,跳转到安装
c.Redirect(http.StatusOK, cRedirecURI("admin/install"))
c.Abort() // 终止后续调用
return
}
if errorLoginCount.Load() >= errCount { //连续错误3次显示验证码
answer := c.PostForm("answer")
if answer != captchaAnswer { //答案不对
c.Redirect(http.StatusOK, cRedirecURI("admin/login?message="+funcT("Incorrect verification code")))
c.Abort() // 终止后续调用
return
}
}
account := strings.TrimSpace(c.PostForm("account"))
password := strings.TrimSpace(c.PostForm("password"))
if account == "" || password == "" { // 用户不存在或者异常
c.Redirect(http.StatusOK, cRedirecURI("admin/login?message="+funcT("Account or password cannot be empty")))
c.Abort() // 终止后续调用
return
}
// 重新hash密码,避免拖库后撞库
sha3Bytes := sha3.Sum512([]byte(password))
password = hex.EncodeToString(sha3Bytes[:])
userId, err := findUserId(ctx, account, password)
if userId == "" || err != nil { // 用户不存在或者异常
errorLoginCount.Add(1)
c.Redirect(http.StatusOK, cRedirecURI("admin/login?message="+funcT("Account or password is incorrect")))
c.Abort() // 终止后续调用
return
}
jwttoken, _ := newJWTToken(userId)
// c.HTML(http.StatusOK, "admin/index.html", nil)
c.SetCookie(config.JwttokenKey, jwttoken, config.Timeout, "/", "", protocol.CookieSameSiteStrictMode, false, true)
errorLoginCount.Store(0)
c.Redirect(http.StatusOK, cRedirecURI("admin/index"))
}
// funcAdminChainloginPre 跳转到区块链登录页面
func funcAdminChainloginPre(ctx context.Context, c *app.RequestContext) {
if !installed { // 如果没有安装,跳转到安装
c.Redirect(http.StatusOK, cRedirecURI("admin/install"))
c.Abort() // 终止后续调用
return
}
var responseData map[string]string = nil
message, ok := c.GetQuery("message")
if ok {
responseData = make(map[string]string, 0)
responseData["message"] = message
}
c.SetCookie(config.JwttokenKey, "", config.Timeout, "/", "", protocol.CookieSameSiteStrictMode, false, true)
cHtmlAdmin(c, http.StatusOK, "admin/chainlogin.html", responseData)
}
// funcAdminChainlogin 区块链登录
func funcAdminChainlogin(ctx context.Context, c *app.RequestContext) {
if !installed { // 如果没有安装,跳转到安装
c.Redirect(http.StatusOK, cRedirecURI("admin/install"))
c.Abort() // 终止后续调用
return
}
//获取签名
signature := c.PostForm("signature")
userId, chainType, chainAddress, err := findUserAddress(ctx)
if userId == "" || chainType == "" || chainAddress == "" || err != nil {
c.Redirect(http.StatusOK, cRedirecURI("admin/chainlogin?message="+funcT("Address anomaly")))
c.Abort() // 终止后续调用
return
}
verify := false
switch chainType {
case "ETH":
verify, err = verifySecp256k1Signature(chainAddress, chainRandStr, signature)
case "XUPER":
verify, err = verifyXuperChainSignature(chainAddress, chainRandStr, signature)
default:
c.Redirect(http.StatusOK, cRedirecURI("admin/chainlogin?message="+funcT("We currently do not support this type of blockchain account")))
c.Abort() // 终止后续调用
return
}
if !verify || err != nil {
c.Redirect(http.StatusOK, cRedirecURI("admin/chainlogin?message="+funcT("Signature verification failed")))
c.Abort() // 终止后续调用
return
}
jwttoken, _ := newJWTToken(userId)
c.SetCookie(config.JwttokenKey, jwttoken, config.Timeout, "/", "", protocol.CookieSameSiteStrictMode, false, true)
c.Redirect(http.StatusOK, cRedirecURI("admin/content/list"))
}
// funcAdminReload 刷新站点,会重新加载模板文件,生成静态文件
func funcAdminReload(ctx context.Context, c *app.RequestContext) {
err := loadTemplate()
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, ERR: err})
c.Abort() // 终止后续调用
return
}
//重新生成静态文件
go genStaticFile()
c.JSON(http.StatusOK, ResponseData{StatusCode: 1})
}
// funcUploadFile 上传文件
func funcUploadFile(ctx context.Context, c *app.RequestContext) {
fileHeader, err := c.FormFile("file")
// 相对于上传的目录路径,只能是目录路径
dirPath := string(c.FormValue("dirPath"))
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, ERR: err})
c.Abort() // 终止后续调用
return
}
dirPath = filepath.ToSlash(dirPath)
dirPath = funcTrimSlash(dirPath)
if dirPath == "/" {
dirPath = ""
}
fileName := FuncGenerateStringID() + filepath.Ext(fileHeader.Filename)
if dirPath != "" {
dirPath = dirPath + "/"
fileName = fileHeader.Filename
}
//服务器的目录,并创建目录
serverDirPath := datadir + "public/upload/" + dirPath
err = os.MkdirAll(serverDirPath, 0755) //目录需要是755权限,才能正常读取,上传的文件默认是644
if err != nil && !os.IsExist(err) {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, ERR: err})
c.Abort() // 终止后续调用
return
}
path := "public/upload/" + dirPath + fileName
newFilePath := datadir + path
err = c.SaveUploadedFile(fileHeader, newFilePath)
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, ERR: err})
c.Abort() // 终止后续调用
return
}
c.JSON(http.StatusOK, ResponseData{StatusCode: 1, Data: path})
}
// funcUploadTheme 上传主题
func funcUploadTheme(ctx context.Context, c *app.RequestContext) {
fileHeader, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, ERR: err})
c.Abort() // 终止后续调用
return
}
ext := filepath.Ext(fileHeader.Filename)
if ext != ".zip" { //不是zip
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, ERR: err})
c.Abort() // 终止后续调用
return
}
path := themeDir + fileHeader.Filename
err = c.SaveUploadedFile(fileHeader, path)
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, ERR: err})
c.Abort() // 终止后续调用
return
}
defer func() {
_ = os.Remove(path)
}()
//解压压缩包
err = unzip(path, themeDir)
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, ERR: err})
c.Abort() // 终止后续调用
return
}
c.JSON(http.StatusOK, ResponseData{StatusCode: 1, Data: path})
}
// funcList 通用list列表
func funcList(ctx context.Context, c *app.RequestContext) {
urlPathParam := c.Param("urlPathParam")
//获取页码
pageNoStr := c.DefaultQuery("pageNo", "1")
pageNo, _ := strconv.Atoi(pageNoStr)
q := strings.TrimSpace(c.Query("q"))
mapParams := make(map[string]interface{}, 0)
//获取所有的参数
c.Bind(&mapParams)
//删除掉固定的两个
delete(mapParams, "pageNo")
delete(mapParams, "q")
where := " WHERE 1=1 "
var values []interface{} = make([]interface{}, 0)
for k := range mapParams {
if !alphaNumericReg.MatchString(k) {
continue
}
value := c.Query(k)
if strings.TrimSpace(value) == "" {
continue
}
where = where + " and " + k + "=? "
values = append(values, value)
}
sql := "* from " + urlPathParam + where + " order by sortNo desc "
var responseData ResponseData
var err error
if len(values) == 0 {
responseData, err = funcSelectList(urlPathParam, q, pageNo, defaultPageSize, sql)
} else {
responseData, err = funcSelectList(urlPathParam, q, pageNo, defaultPageSize, sql, values)
}
responseData.UrlPathParam = urlPathParam
if err != nil {
c.Redirect(http.StatusOK, cRedirecURI("admin/error"))
c.Abort() // 终止后续调用
return
}
listFile := "admin/" + urlPathParam + "/list.html"
cHtmlAdmin(c, http.StatusOK, listFile, responseData)
}
// funcLook 通用查看,根据id查看
func funcLook(ctx context.Context, c *app.RequestContext) {
funcLookById(ctx, c, "look.html")
}
// funcContentPreview 内容预览
func funcContentPreview(ctx context.Context, c *app.RequestContext) {
id := c.Query("id")
if id == "" {
c.Redirect(http.StatusOK, cRedirecURI("admin/error"))
c.Abort() // 终止后续调用
return
}
params := make([]param.Param, 0, 1)
params = append(params, param.Param{
Key: "urlPathParam",
Value: id,
})
c.Params = params
funcOneContent(ctx, c)
}
// funcCategoryPreview 导航菜单预览
func funcCategoryPreview(ctx context.Context, c *app.RequestContext) {
id := c.Query("id")
if id == "" {
c.Redirect(http.StatusOK, cRedirecURI("admin/error"))
c.Abort() // 终止后续调用
return
}
params := make([]param.Param, 0, 1)
params = append(params, param.Param{
Key: "urlPathParam",
Value: id,
})
c.Params = params
funcListCategory(ctx, c)
}
// funcContentList 查询Content列表,根据CategoryId like
func funcContentList(ctx context.Context, c *app.RequestContext) {
urlPathParam := "content"
//获取页码
pageNoStr := c.DefaultQuery("pageNo", "1")
q := strings.TrimSpace(c.Query("q"))
pageNo, _ := strconv.Atoi(pageNoStr)
id := strings.TrimSpace(c.Query("id"))
values := make([]interface{}, 0)
sql := ""
if id != "" {
sql = " * from content where id like ? order by sortNo desc "
values = append(values, id+"%")
} else {
sql = " * from content order by sortNo desc "
}
var responseData ResponseData
var err error
if len(values) == 0 {
responseData, err = funcSelectList(urlPathParam, q, pageNo, defaultPageSize, sql)
} else {
responseData, err = funcSelectList(urlPathParam, q, pageNo, defaultPageSize, sql, values)
}
responseData.UrlPathParam = urlPathParam
if err != nil {
c.Redirect(http.StatusOK, cRedirecURI("admin/error"))
c.Abort() // 终止后续调用
return
}
listFile := "admin/" + urlPathParam + "/list.html"
cHtmlAdmin(c, http.StatusOK, listFile, responseData)
}
// funcListThemeTemplate 所有的主题文件列表
func funcListThemeTemplate(ctx context.Context, c *app.RequestContext) {
urlPathParam := "themeTemplate"
var responseData ResponseData
extMap := make(map[string]interface{})
extMap["file"] = ""
responseData.ExtMap = extMap
list := make([]ThemeTemplate, 0)
//遍历当前使用的模板文件夹
err := filepath.Walk(themeDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// 分隔符统一为 / 斜杠
path = filepath.ToSlash(path)
path = path[strings.Index(path, themeDir)+len(themeDir):]
if path == "" {
return err
}
//获取文件后缀
ext := filepath.Ext(path)
ext = strings.ToLower(ext)
// 跳过压缩的 gz文件
if ext == ".gz" {
return nil
}
pid := filepath.ToSlash(filepath.Dir(path))
if pid == "." {
pid = ""
}
themeTemplate := ThemeTemplate{}
themeTemplate.FilePath = path
themeTemplate.Pid = pid
themeTemplate.Id = path
themeTemplate.FileSuffix = ext
themeTemplate.Name = info.Name()
if info.IsDir() {
themeTemplate.FileType = "dir"
} else {
themeTemplate.FileType = "file"
}
list = append(list, themeTemplate)
return nil
})
responseData.UrlPathParam = urlPathParam
responseData.Data = list
responseData.ERR = err
listFile := "admin/" + urlPathParam + "/list.html"
filePath := c.Query("file")
if filePath == "" || strings.Contains(filePath, "..") {
//c.HTML(http.StatusOK, listFile, responseData)
cHtmlAdmin(c, http.StatusOK, listFile, responseData)
return
}
filePath = filepath.ToSlash(filePath)
fileContent, err := os.ReadFile(themeDir + filePath)
if err != nil {
responseData.ERR = err
cHtmlAdmin(c, http.StatusOK, listFile, responseData)
return
}
responseData.ExtMap["file"] = string(fileContent)
cHtmlAdmin(c, http.StatusOK, listFile, responseData)
}
// funcUpdateThemeTemplate 更新主题模板
func funcUpdateThemeTemplate(ctx context.Context, c *app.RequestContext) {
themeTemplate := ThemeTemplate{}
c.Bind(&themeTemplate)
filePath := filepath.ToSlash(themeTemplate.FilePath)
if filePath == "" || strings.Contains(filePath, "..") {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0})
c.Abort() // 终止后续调用
return
}
if !pathExist(themeDir + filePath) {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0})
c.Abort() // 终止后续调用
return
}
//打开文件
file, err := os.OpenFile(themeDir+filePath, os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0})
c.Abort() // 终止后续调用
return
}
defer file.Close() // 确保在函数结束时关闭文件
// 写入内容
_, err = file.WriteString(themeTemplate.FileContent)
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0})
c.Abort() // 终止后续调用
return
}
c.JSON(http.StatusOK, ResponseData{StatusCode: 1})
}
// funcUpdatePre 跳转到修改页面
func funcUpdatePre(ctx context.Context, c *app.RequestContext) {
funcLookById(ctx, c, "update.html")
}
// funcUpdateConfig 更新配置
func funcUpdateConfig(ctx context.Context, c *app.RequestContext) {
now := time.Now().Format("2006-01-02 15:04:05")
entity := &Config{}
ok := funcUpdateInit(ctx, c, entity)
if !ok {
return
}
if !strings.HasPrefix(entity.BasePath, "/") {
entity.BasePath = "/" + entity.BasePath
}
if !strings.HasSuffix(entity.BasePath, "/") {
entity.BasePath = entity.BasePath + "/"
}
entity.UpdateTime = now
funcUpdate(ctx, c, entity, entity.Id)
}
// funcUpdateSite 更新站点
func funcUpdateSite(ctx context.Context, c *app.RequestContext) {
now := time.Now().Format("2006-01-02 15:04:05")
entity := &Site{}
ok := funcUpdateInit(ctx, c, entity)
if !ok {
return
}
entity.UpdateTime = now
funcUpdate(ctx, c, entity, entity.Id)
}
// funcUpdateUser 更新用户信息
func funcUpdateUser(ctx context.Context, c *app.RequestContext) {
now := time.Now().Format("2006-01-02 15:04:05")
entity := &User{}
ok := funcUpdateInit(ctx, c, entity)
if !ok {
return
}
if entity.Password != "" {
// 重新hash密码,避免拖库后撞库
sha3Bytes := sha3.Sum512([]byte(entity.Password))
entity.Password = hex.EncodeToString(sha3Bytes[:])
} else {
f1 := zorm.NewSelectFinder(tableUserName, "password").Append("WHERE id=?", entity.Id)
password := ""
zorm.QueryRow(ctx, f1, &password)
entity.Password = password
}
entity.UpdateTime = now
funcUpdate(ctx, c, entity, entity.Id)
}
// funcUpdateCategory 更新导航菜单
func funcUpdateCategory(ctx context.Context, c *app.RequestContext) {
entity := &Category{}
ok := funcUpdateInit(ctx, c, entity)
if !ok {
return
}
funcUpdate(ctx, c, entity, entity.Id)
}
// funcUpdateContent 更新内容
func funcUpdateContent(ctx context.Context, c *app.RequestContext) {
now := time.Now().Format("2006-01-02 15:04:05")
entity := &Content{}
ok := funcUpdateInit(ctx, c, entity)
if !ok {
return
}
if entity.Markdown != "" {
content, toc, err := renderMarkdownHtml(entity.Markdown)
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("Markdown to HTML conversion error")})
c.Abort() // 终止后续调用
FuncLogError(ctx, err)
return
}
entity.Content = content
entity.Toc = toc
}
newId := ""
if entity.CategoryID != "" {
f := zorm.NewSelectFinder(tableCategoryName, "name as categoryName").Append(" where id =?", entity.CategoryID)
zorm.QueryRow(ctx, f, entity)
urls := strings.Split(entity.Id, "/")
newId = entity.CategoryID + urls[len(urls)-1]
}
entity.UpdateTime = now
zorm.Transaction(ctx, func(ctx context.Context) (interface{}, error) {
funcUpdate(ctx, c, entity, entity.Id)
if newId != "" {
finder := zorm.NewUpdateFinder(tableContentName).Append("id=? WHERE id=?", newId, entity.Id)
return zorm.UpdateFinder(ctx, finder)
}
return nil, nil
})
}
// funcUpdateInit 初始化更新的对象参数,先从数据库查询,再更新数据
func funcUpdateInit(ctx context.Context, c *app.RequestContext, entity zorm.IEntityStruct) bool {
jsontmp := make(map[string]interface{}, 0)
c.Bind(&jsontmp)
id := jsontmp["id"]
finder := zorm.NewSelectFinder(entity.GetTableName()).Append("WHERE id=?", id)
has, err := zorm.QueryRow(ctx, finder, entity)
if !has || err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("ID does not exist")})
c.Abort() // 终止后续调用
FuncLogError(ctx, err)
return false
}
err = c.Bind(entity)
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("JSON data conversion error")})
c.Abort() // 终止后续调用
FuncLogError(ctx, err)
return false
}
return true
}
// funcUpdate 更新表数据
func funcUpdate(ctx context.Context, c *app.RequestContext, entity zorm.IEntityStruct, id string) {
if id == "" { //没有id,终止调用
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("ID cannot be empty")})
c.Abort() // 终止后续调用
return
}
_, err := zorm.Transaction(ctx, func(ctx context.Context) (interface{}, error) {
_, err := zorm.Update(ctx, entity)
return nil, err
})
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("Failed to update data")})
c.Abort() // 终止后续调用
FuncLogError(ctx, err)
return
}
c.JSON(http.StatusOK, ResponseData{StatusCode: 1})
}
// funcSavePre 跳转到保存页面
func funcSavePre(ctx context.Context, c *app.RequestContext) {
urlPathParam := c.Param("urlPathParam")
templateFile := "admin/" + urlPathParam + "/save.html"
responseData := ResponseData{UrlPathParam: urlPathParam}
responseData.QueryStringMap = wrapQueryStringMap(c)
cHtmlAdmin(c, http.StatusOK, templateFile, responseData)
}
// funcSaveCategory 保存导航菜单
func funcSaveCategory(ctx context.Context, c *app.RequestContext) {
entity := &Category{}
err := c.Bind(entity)
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("JSON data conversion error")})
c.Abort() // 终止后续调用
FuncLogError(ctx, err)
return
}
now := time.Now().Format("2006-01-02 15:04:05")
if entity.CreateTime == "" {
entity.CreateTime = now
}
if entity.UpdateTime == "" {
entity.UpdateTime = now
}
if entity.Pid != "" {
entity.Id = entity.Pid + entity.Id + "/"
} else {
entity.Id = "/" + entity.Id + "/"
}
has := validateIDExists(ctx, entity.Id)
if has {
c.JSON(http.StatusConflict, ResponseData{StatusCode: 0, Message: funcT("URL path is duplicated, please modify the path identifier")})
c.Abort() // 终止后续调用
return
}
count, err := zorm.Transaction(ctx, func(ctx context.Context) (interface{}, error) {
return zorm.Insert(ctx, entity)
})
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("Failed to save data")})
c.Abort() // 终止后续调用
FuncLogError(ctx, err)
return
}
//增加路由映射
addCategoryRoute(entity.Id)
// 增加自定义路由映射
//routeCategoryMap[funcTrimSuffixSlash(entity.Id)] = entity.Id
c.JSON(http.StatusOK, ResponseData{StatusCode: count.(int), Message: funcT("Saved successfully!")})
}
// funcSaveContent 保存内容
func funcSaveContent(ctx context.Context, c *app.RequestContext) {
entity := &Content{}
err := c.Bind(entity)
if err != nil || entity.Id == "" || entity.CategoryID == "" {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("JSON data conversion error")})
c.Abort() // 终止后续调用
FuncLogError(ctx, err)
return
}
now := time.Now().Format("2006-01-02 15:04:05")
// 构建ID
entity.Id = entity.CategoryID + entity.Id
has := validateIDExists(ctx, entity.Id)
if has {
c.JSON(http.StatusConflict, ResponseData{StatusCode: 0, Message: funcT("URL path is duplicated, please modify the path identifier")})
c.Abort() // 终止后续调用
return
}
if entity.CreateTime == "" {
entity.CreateTime = now
}
if entity.UpdateTime == "" {
entity.UpdateTime = now
}
if entity.Markdown != "" {
content, toc, err := renderMarkdownHtml(entity.Markdown)
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("Markdown to HTML conversion error")})
c.Abort() // 终止后续调用
FuncLogError(ctx, err)
return
}
entity.Content = content
entity.Toc = toc
}
f := zorm.NewSelectFinder(tableCategoryName, "name as categoryName").Append(" where id =?", entity.CategoryID)
zorm.QueryRow(ctx, f, entity)
count, err := zorm.Transaction(ctx, func(ctx context.Context) (interface{}, error) {
return zorm.Insert(ctx, entity)
})
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("Failed to save data")})
c.Abort() // 终止后续调用
FuncLogError(ctx, err)
return
}
c.JSON(http.StatusOK, ResponseData{StatusCode: count.(int), Message: funcT("Saved successfully!")})
}
// funcDelete 删除数据
func funcDelete(ctx context.Context, c *app.RequestContext) {
id := c.PostForm("id")
//id := c.Query("id")
if id == "" { //没有id,终止调用
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("ID cannot be empty")})
c.Abort() // 终止后续调用
return
}
urlPathParam := c.Param("urlPathParam")
if urlPathParam == "category" {
finder := zorm.NewSelectFinder(tableCategoryName, "*").Append(" where pid =?", id)
page := zorm.NewPage()
pageNo, _ := strconv.Atoi("1")
page.PageNo = pageNo
data := make([]Category, 0)
zorm.Query(context.Background(), finder, &data, page)
if len(data) != 0 {
c.JSON(http.StatusOK, ResponseData{StatusCode: 0, Message: funcT("Cannot delete a navigation item with child elements!")})
} else {
err := deleteById(ctx, urlPathParam, id)
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("Failed to delete data")})
c.Abort() // 终止后续调用
}
c.JSON(http.StatusOK, ResponseData{StatusCode: 1, Message: funcT("Data deleted successfully")})
}
} else {
err := deleteById(ctx, urlPathParam, id)
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: funcT("Failed to delete data")})
c.Abort() // 终止后续调用
}
c.JSON(http.StatusOK, ResponseData{StatusCode: 1, Message: funcT("Data deleted successfully")})
}
}
func funcUpdateSQL(ctx context.Context, c *app.RequestContext) {
ajaxMap := make(map[string]string, 0)
c.Bind(&ajaxMap)
updateSQL := ajaxMap["updateSQL"]
finder := zorm.NewFinder().Append(updateSQL)
finder.InjectionCheck = false
count, err := zorm.Transaction(ctx, func(ctx context.Context) (interface{}, error) {
return zorm.UpdateFinder(ctx, finder)
})
if err != nil {
c.JSON(http.StatusInternalServerError, ResponseData{StatusCode: 0, Message: err.Error()})
c.Abort() // 终止后续调用
FuncLogError(ctx, err)
return
}
c.JSON(http.StatusOK, ResponseData{StatusCode: 1, Message: fmt.Sprintf(funcT("Updated %d records"), count)})
}
// permissionHandler 权限拦截器
func permissionHandler() app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
jwttoken := string(c.Cookie(config.JwttokenKey))
//fmt.Println(config.JwtSecret)
userId, err := userIdByToken(jwttoken)
if err != nil || userId == "" {
c.Redirect(http.StatusOK, cRedirecURI("admin/login"))
c.Abort() // 终止后续调用
return
}
c.SetCookie(config.JwttokenKey, jwttoken, config.Timeout, "/", "", protocol.CookieSameSiteStrictMode, false, true)
// 传递从jwttoken获取的userId
c.Set(tokenUserId, userId)
// 设置用户类型是 管理员
c.Set(userTypeKey, 1)
}
}
// funcLookById 根据Id,跳转到查看页面
func funcLookById(ctx context.Context, c *app.RequestContext, templateFile string) {
id := c.Query("id")
if id == "" {
c.Redirect(http.StatusOK, cRedirecURI("admin/error"))
c.Abort() // 终止后续调用
return
}
urlPathParam := c.Param("urlPathParam")
if !alphaNumericReg.MatchString(urlPathParam) {
c.Redirect(http.StatusOK, cRedirecURI("admin/error"))
c.Abort() // 终止后续调用
return
}
responseData := ResponseData{StatusCode: 0}
data, err := funcSelectOne(urlPathParam, "* FROM "+urlPathParam+" WHERE id=? ", id)
responseData.Data = data
responseData.UrlPathParam = urlPathParam
if err != nil {
c.Redirect(http.StatusOK, cRedirecURI("admin/error"))
c.Abort() // 终止后续调用
return
}
lookFile := "admin/" + urlPathParam + "/" + templateFile
responseData.StatusCode = 1
responseData.QueryStringMap = wrapQueryStringMap(c)
cHtmlAdmin(c, http.StatusOK, lookFile, responseData)
}
// renderMarkdownHtml 渲染markdown内容,返回html,toc和error
func renderMarkdownHtml(mkstring string) (string, string, error) {
if mkstring != "" {
_, tocHtml, html, err := conver2Html([]byte(mkstring))
if err != nil {
return "", "", err
}
return *html, *tocHtml, nil
}
return "", "", nil
}
// wrapQueryStringMap 包装查询参数Map
func wrapQueryStringMap(c *app.RequestContext) map[string]string {
queryStringMap := make(map[string]string, 0)
c.BindQuery(&queryStringMap)
for k := range queryStringMap {
queryStringMap[k] = c.Query(k)
}
return queryStringMap
}