From 5d3d26b907775e3cd56109c128cfa669fa9dee46 Mon Sep 17 00:00:00 2001
From: sysnix <535420543@qq.com>
Date: Mon, 25 Sep 2023 10:54:40 +0800
Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=96=87=E4=BB=B6=E6=B5=81?=
 =?UTF-8?q?=E8=BF=94=E5=9B=9E=E5=89=8D=E7=9A=84=E5=88=A4=E6=96=AD=EF=BC=8C?=
 =?UTF-8?q?=E6=97=A5=E8=AE=B0=E6=96=87=E6=9C=AC=E7=8A=B6=E6=80=81bug?=
 =?UTF-8?q?=EF=BC=8C=E7=99=BB=E5=BD=95=E6=8F=90=E7=A4=BA=E4=BF=9D=E5=AD=98?=
 =?UTF-8?q?=E5=AF=86=E7=A0=81(=E5=B0=BD=E5=8A=9B=E4=BA=86Vuetify=E5=AE=98?=
 =?UTF-8?q?=E6=96=B9=E9=83=BD=E6=97=A0=E8=83=BD=E4=B8=BA=E5=8A=9B)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
 internal/controller/FileController.go        |  8 +-
 internal/controller/admin/DiaryController.go |  7 +-
 internal/controller/admin/LoginController.go | 29 ++++++--
 internal/service/ArticleService.go           |  2 +-
 template/admin/diary/index.html              |  2 +-
 template/admin/login.html                    | 78 +++++++++++++-------
 template/index.html                          |  2 +-
 7 files changed, 86 insertions(+), 42 deletions(-)
diff --git a/internal/controller/FileController.go b/internal/controller/FileController.go
index e88fc1f..9368b0f 100644
--- a/internal/controller/FileController.go
+++ b/internal/controller/FileController.go
@@ -1,6 +1,7 @@
 package controller
 
 import (
+	"blog/internal/model/AjaxResult"
 	"blog/internal/service"
 	"net/http"
 	"net/url"
@@ -19,11 +20,14 @@ type FileController struct {
 func (ctrl *FileController) ViewFile() {
 	id := ctrl.Ctx.Params().Get("id")
 	file, err := service.FileService.GetFile(id)
-	if err != nil {
+	if err != nil || file.Id == "" {
+		ctrl.Ctx.JSON(AjaxResult.Error("文件不存在"))
 		return
 	}
 	ctrl.Ctx.Header("Content-Disposition", "attachment;filename="+url.QueryEscape(file.FileName))
-	ctrl.Ctx.Header("Content-Length", strconv.FormatInt(file.FileSize, 10))
+	if file.FileSize != 0 {
+		ctrl.Ctx.Header("Content-Length", strconv.FormatInt(file.FileSize, 10))
+	}
 	ctrl.Ctx.Write(file.Data)
 }
 
diff --git a/internal/controller/admin/DiaryController.go b/internal/controller/admin/DiaryController.go
index 98833d6..0cd9b9d 100644
--- a/internal/controller/admin/DiaryController.go
+++ b/internal/controller/admin/DiaryController.go
@@ -43,7 +43,7 @@ func (ctrl *DiaryController) PostSubmit() {
 	database.WGorm().Transaction(func(tx *gorm.DB) error {
 		now := time.Now().UnixMilli()
 		diary := admin.AdminDiary{Id: diaryId, PublishTime: now, Del: 0, CreateTime: now, CreateBy: userId}
-		ctn := vo.CommonContent{Id: uuid.NewString(), RelId: diaryId, Content: content}
+		ctn := vo.CommonContent{Id: uuid.NewString(), RelId: diaryId, Content: content, State: consts.CONTENT_STATE_PUBLISH}
 		err = tx.Table("common_contents").Create(ctn).Error
 		if err != nil {
 			return err
@@ -57,7 +57,8 @@ func (ctrl *DiaryController) PostSubmit() {
 		for i, file := range files {
 			defer file.Close()
 			header := headers[i]
-			var bytes []byte = make([]byte, header.Size)
+			fileSize := header.Size
+			var bytes []byte = make([]byte, fileSize)
 			_, err = file.Read(bytes)
 			if err != nil {
 				return err
@@ -65,7 +66,7 @@ func (ctrl *DiaryController) PostSubmit() {
 			fileName := header.Filename
 			fileId := uuid.NewString()
 			fileIds = append(fileIds, fileId)
-			sysFile := admin.SysFile{Id: fileId, FileName: fileName, Data: bytes, Sort: i, Del: 0, CreateBy: userId, CreateTime: now}
+			sysFile := admin.SysFile{Id: fileId, FileName: fileName, FileSize: fileSize, Data: bytes, Sort: i, Del: 0, CreateBy: userId, CreateTime: now}
 			err = tx.Table("common_files").Create(&sysFile).Error
 			if err != nil {
 				return err
diff --git a/internal/controller/admin/LoginController.go b/internal/controller/admin/LoginController.go
index 5e236ec..ca4d8c0 100644
--- a/internal/controller/admin/LoginController.go
+++ b/internal/controller/admin/LoginController.go
@@ -60,16 +60,20 @@ func (ctrl *LoginController) GetRefreshcaptcha() {
 func (ctrl *LoginController) Post() {
 	var loginUser admin.SysUserLogin
 	if err := ctrl.Ctx.ReadBody(&loginUser); err != nil {
-		result := AjaxResult.Error("参数错误")
-		ctrl.Ctx.JSON(result)
+		// result := AjaxResult.Error("参数错误")
+		// ctrl.Ctx.JSON(result)
+		ctrl.Ctx.Redirect("/admin")
 		return
 	}
 	session := sessions.Get(ctrl.Ctx)
 	captcha := loginUser.Captcha
 	sessionCaptcha := session.GetString("captcha")
 	if !strings.EqualFold(captcha, sessionCaptcha) {
-		result := AjaxResult.Error("验证码错误")
-		ctrl.Ctx.JSON(result)
+		// result := AjaxResult.Error("验证码错误")
+		// ctrl.Ctx.JSON(result)
+		ctrl.Ctx.ViewData("user", loginUser)
+		ctrl.Ctx.ViewData("errorMsg", "验证码错误")
+		ctrl.Ctx.View("/admin/login")
 		return
 	}
 
@@ -77,12 +81,22 @@ func (ctrl *LoginController) Post() {
 	result := database.GormTemplate.Where("username = ?", loginUser.Username).First(&user)
 	rowsAffected := result.RowsAffected
 	if rowsAffected > 1 {
-		ctrl.Ctx.JSON(AjaxResult.Error("数据异常,后台错误!"))
+		// ctrl.Ctx.JSON(AjaxResult.Error("数据异常,后台错误!"))
+		ctrl.Ctx.Redirect("/admin")
+		return
+	}
+	if rowsAffected == 0 {
+		ctrl.Ctx.ViewData("user", loginUser)
+		ctrl.Ctx.ViewData("errorMsg", "账号不存在")
+		ctrl.Ctx.View("/admin/login")
 		return
 	}
 	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(loginUser.Password))
 	if err != nil {
-		ctrl.Ctx.JSON(AjaxResult.Error("密码错误!"))
+		// ctrl.Ctx.JSON(AjaxResult.Error("密码错误!"))
+		ctrl.Ctx.ViewData("user", loginUser)
+		ctrl.Ctx.ViewData("errorMsg", "密码错误")
+		ctrl.Ctx.View("/admin/login")
 		return
 	}
 
@@ -95,5 +109,6 @@ func (ctrl *LoginController) Post() {
 
 	xFrowardedFor := ctrl.Ctx.GetHeader("X-Forwarded-For")
 	log.Println("用户:", user.Username, "登录,IP为:", xFrowardedFor)
-	ctrl.Ctx.JSON(AjaxResult.Ok("login"))
+	// ctrl.Ctx.JSON(AjaxResult.Ok("login"))
+	ctrl.Ctx.Redirect("/admin")
 }
diff --git a/internal/service/ArticleService.go b/internal/service/ArticleService.go
index 84a6ebc..05c1219 100644
--- a/internal/service/ArticleService.go
+++ b/internal/service/ArticleService.go
@@ -99,7 +99,7 @@ func (*articleService) CreateArticle(articel *admin.AdminArticle) (string, error
 	err := database.WGorm().Transaction(func(tx *gorm.DB) error {
 		contentId := uuid.NewString()
 		content := articel.Content
-		commonContent := vo.CommonContent{Id: contentId, RelId: articleId, Content: content, State: "down"}
+		commonContent := vo.CommonContent{Id: contentId, RelId: articleId, Content: content, State: consts.CONTENT_STATE_DOWN}
 		err := tx.Table("common_contents").Create(commonContent).Error
 		if err != nil {
 			return err
diff --git a/template/admin/diary/index.html b/template/admin/diary/index.html
index dcab60a..bbdb1d8 100644
--- a/template/admin/diary/index.html
+++ b/template/admin/diary/index.html
@@ -102,8 +102,8 @@
                 axios.post('/admin/diary/submit', formData, {headers: {"Content-Type": "multipart/form-data"}}).then(res => {
                     let data = res.data
                     console.log(data)
-                    location.href = '/diary'
                     this.sending = false
+                    location.href = '/diary'
                 }).catch(err => {
                     ths.error = err
                     console.error(err)
diff --git a/template/admin/login.html b/template/admin/login.html
index 37e6bd3..9839c6d 100644
--- a/template/admin/login.html
+++ b/template/admin/login.html
@@ -46,13 +46,16 @@
                 
                     {{errorMsg}}
                 
-                
+                
                     
                     
+                        autocomplete="iris-password"
+                        id="iris-password">
+                    
                     
+                        id="iris-captcha">
+                    
                     
                     
                     登录
@@ -85,7 +93,7 @@
         template: '#app-template',
         data: {
             captchaBase64: '#{.captchaBase64 }',
-            errorMsg: null,
+            errorMsg: "#{.errorMsg}",
             valid: true,
             requiredRules: [
                 v => !!v || '不能为空',
@@ -97,6 +105,7 @@
         },
         methods: {
             refreshCaptcha() {
+                console.log("获取验证码");
                 axios.get('/admin/login/refreshcaptcha')
                     .then((response) => {
                         console.log(response);
@@ -110,32 +119,47 @@
             login() {
                 let validate = this.$refs.form.validate()
                 if (validate) {
-                    axios.post('/admin/login', {
-                        username: this.username,
-                        password: this.password,
-                        captcha: this.captcha,
-                    })
-                        .then((response) => {
-                            // console.log(response);
-                            let data = response.data
-                            return data
-                        }).
-                        then((data) => {
-                            console.log(data)
-                            if (data.code !== 200) {
-                                this.errorMsg = data.msg
-                                this.refreshCaptcha()
-                                return
-                            }
-                            this.errorMsg = null
-                            location.href = "/admin"
+                    // console.log(this.$refs.form);
+                    localStorage.setItem("username", this.username)
+                    localStorage.setItem("password", this.password)
+                    this.$refs.form.$el.submit()
+                    // axios.post('/admin/login', {
+                    //     username: this.username,
+                    //     password: this.password,
+                    //     captcha: this.captcha,
+                    // })
+                    //     .then((response) => {
+                    //         // console.log(response);
+                    //         let data = response.data
+                    //         return data
+                    //     }).
+                    //     then((data) => {
+                    //         console.log(data)
+                    //         if (data.code !== 200) {
+                    //             this.errorMsg = data.msg
+                    //             this.refreshCaptcha()
+                    //             return
+                    //         }
+                    //         this.errorMsg = null
+                    //         location.href = "/admin"
 
-                        })
-                        .catch(function (error) {
-                            console.log(error);
-                        });
+                    //     })
+                    //     .catch(function (error) {
+                    //         console.log(error);
+                    //     });
                 }
             },
+        },
+        mounted() {
+            // console.log(this.captchaBase64);
+            if (!this.captchaBase64) {
+                this.refreshCaptcha()
+            }
+
+            if (!this.username) {
+                this.username = localStorage.getItem("username")
+                this.password = localStorage.getItem("password")
+            }
 
         },
         vuetify: new Vuetify(),
diff --git a/template/index.html b/template/index.html
index 5779d8e..71d78b6 100644
--- a/template/index.html
+++ b/template/index.html
@@ -86,7 +86,7 @@
                                                     
                                                         
                                                             
+                                                                   class="d-flex child-flex" cols="12">