fix: 完善管理后台密码修改逻辑
This commit is contained in:
+26
-13
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"home-vue-go/internal/config"
|
||||
"home-vue-go/internal/database"
|
||||
"home-vue-go/internal/ent"
|
||||
"home-vue-go/internal/ent/user"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -84,11 +85,11 @@ func ChangePassword(db *database.Database) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var req struct {
|
||||
OldPassword string `json:"oldPassword" binding:"required"`
|
||||
NewPassword string `json:"newPassword" binding:"required,min=8"`
|
||||
NewPassword string `json:"newPassword" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "旧密码和新密码不能为空,且新密码至少8位"})
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "当前密码和新密码不能为空"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -99,19 +100,32 @@ func ChangePassword(db *database.Database) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
usernameStr := username.(string)
|
||||
usernameStr, ok := username.(string)
|
||||
if !ok || strings.TrimSpace(usernameStr) == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "用户信息无效"})
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// 查询用户
|
||||
user, err := db.Client.User.Query().Where(user.UsernameEQ(usernameStr)).First(ctx)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "用户不存在"})
|
||||
if ent.IsNotFound(err) {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "用户不存在"})
|
||||
} else {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "查询用户失败"})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 验证旧密码
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "旧密码错误"})
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "当前密码错误"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := validateNewPassword(usernameStr, req.OldPassword, req.NewPassword); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -123,15 +137,14 @@ func ChangePassword(db *database.Database) gin.HandlerFunc {
|
||||
}
|
||||
|
||||
// 更新密码到数据库
|
||||
updatedUser, err := db.Client.User.UpdateOneID(user.ID).SetPassword(string(hashedPassword)).Save(ctx)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "密码更新失败: " + err.Error()})
|
||||
updatedUser, err := db.Client.User.UpdateOneID(user.ID).SetPassword(string(hashedPassword)).Save(ctx)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "密码更新失败"})
|
||||
return
|
||||
}
|
||||
|
||||
// 验证密码已保存(可选,用于调试)
|
||||
if updatedUser == nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "密码更新失败: 未返回更新后的用户"})
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(updatedUser.Password), []byte(req.NewPassword)); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "密码更新校验失败"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -165,7 +178,7 @@ func JWTAuthMiddleware(secret string) gin.HandlerFunc {
|
||||
location := queryIPLocation(ip)
|
||||
// 记录为失败的登录尝试(token失效)
|
||||
addLoginHistory("", ip, location, userAgent, false)
|
||||
|
||||
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的token"})
|
||||
c.Abort()
|
||||
return
|
||||
@@ -280,7 +293,7 @@ func GetLoginHistory(db *database.Database) gin.HandlerFunc {
|
||||
|
||||
// 从内存获取登录历史
|
||||
histories := getLoginHistoryRecords(limitInt)
|
||||
|
||||
|
||||
result := make([]gin.H, 0, len(histories))
|
||||
for _, h := range histories {
|
||||
result = append(result, gin.H{
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"home-vue-go/internal/config"
|
||||
"home-vue-go/internal/database"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func newAuthTestServer(t *testing.T) (*gin.Engine, *database.Database, *config.Config) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
cfg := config.New(t.TempDir())
|
||||
db, err := database.Init(cfg.DatabasePath, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := gin.New()
|
||||
r.POST("/login", Login(db, cfg))
|
||||
r.PUT("/change-password", JWTAuthMiddleware(cfg.JWTSecret), ChangePassword(db))
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
return r, db, cfg
|
||||
}
|
||||
|
||||
func authJSONRequest(t *testing.T, router http.Handler, method, path string, payload any, token string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(string(body)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, req)
|
||||
return response
|
||||
}
|
||||
|
||||
func tokenFromResponse(t *testing.T, response *httptest.ResponseRecorder) string {
|
||||
t.Helper()
|
||||
var payload struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload.Token == "" {
|
||||
t.Fatalf("login did not return a token: %s", response.Body.String())
|
||||
}
|
||||
return payload.Token
|
||||
}
|
||||
|
||||
func TestChangePasswordPersistsAndAllowsNewLogin(t *testing.T) {
|
||||
router, _, _ := newAuthTestServer(t)
|
||||
login := authJSONRequest(t, router, http.MethodPost, "/login", map[string]string{"username": "admin", "password": "admin123"}, "")
|
||||
if login.Code != http.StatusOK {
|
||||
t.Fatalf("initial login failed: %d %s", login.Code, login.Body.String())
|
||||
}
|
||||
token := tokenFromResponse(t, login)
|
||||
|
||||
change := authJSONRequest(t, router, http.MethodPut, "/change-password", map[string]string{
|
||||
"oldPassword": "admin123",
|
||||
"newPassword": "New-admin-2026!",
|
||||
}, token)
|
||||
if change.Code != http.StatusOK {
|
||||
t.Fatalf("password change failed: %d %s", change.Code, change.Body.String())
|
||||
}
|
||||
|
||||
oldLogin := authJSONRequest(t, router, http.MethodPost, "/login", map[string]string{"username": "admin", "password": "admin123"}, "")
|
||||
if oldLogin.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("old password should be rejected: %d", oldLogin.Code)
|
||||
}
|
||||
newLogin := authJSONRequest(t, router, http.MethodPost, "/login", map[string]string{"username": "admin", "password": "New-admin-2026!"}, "")
|
||||
if newLogin.Code != http.StatusOK {
|
||||
t.Fatalf("new password should work: %d %s", newLogin.Code, newLogin.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangePasswordRejectsInvalidInputWithoutLoggingOut(t *testing.T) {
|
||||
router, _, _ := newAuthTestServer(t)
|
||||
login := authJSONRequest(t, router, http.MethodPost, "/login", map[string]string{"username": "admin", "password": "admin123"}, "")
|
||||
token := tokenFromResponse(t, login)
|
||||
|
||||
weak := authJSONRequest(t, router, http.MethodPut, "/change-password", map[string]string{
|
||||
"oldPassword": "admin123",
|
||||
"newPassword": "12345678",
|
||||
}, token)
|
||||
if weak.Code != http.StatusBadRequest {
|
||||
t.Fatalf("weak password should be rejected: %d", weak.Code)
|
||||
}
|
||||
|
||||
wrongOld := authJSONRequest(t, router, http.MethodPut, "/change-password", map[string]string{
|
||||
"oldPassword": "wrong-password",
|
||||
"newPassword": "New-admin-2026!",
|
||||
}, token)
|
||||
if wrongOld.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("wrong current password should be a validation error: %d", wrongOld.Code)
|
||||
}
|
||||
|
||||
stillValid := authJSONRequest(t, router, http.MethodPut, "/change-password", map[string]string{
|
||||
"oldPassword": "admin123",
|
||||
"newPassword": "New-admin-2026!",
|
||||
}, token)
|
||||
if stillValid.Code != http.StatusOK {
|
||||
t.Fatalf("valid token should remain usable after a rejected attempt: %d %s", stillValid.Code, stillValid.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateNewPassword(t *testing.T) {
|
||||
if err := validateNewPassword("admin", "admin123", "New-admin-2026!"); err != nil {
|
||||
t.Fatalf("expected valid password: %v", err)
|
||||
}
|
||||
for _, password := range []string{"short1!", "admin123", "12345678", "lettersonly", "New-admin-2026! "} {
|
||||
if err := validateNewPassword("admin", "admin123", password); err == nil {
|
||||
t.Errorf("expected password to be rejected: %q", password)
|
||||
}
|
||||
}
|
||||
if err := validateNewPassword("admin", "admin123", strings.Repeat("a1!", 30)); err == nil {
|
||||
t.Fatal("expected bcrypt-overlong password to be rejected")
|
||||
}
|
||||
if err := validateNewPassword("admin", "admin123", "New-管理-2026!"); err != nil {
|
||||
t.Fatalf("expected unicode password to be valid: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
minPasswordRunes = 8
|
||||
maxPasswordBytes = 72 // bcrypt only uses the first 72 bytes.
|
||||
)
|
||||
|
||||
var commonPasswords = map[string]struct{}{
|
||||
"12345678": {},
|
||||
"admin123": {},
|
||||
"password": {},
|
||||
"password123": {},
|
||||
"qwerty123": {},
|
||||
}
|
||||
|
||||
func validateNewPassword(username, oldPassword, newPassword string) error {
|
||||
if !utf8.ValidString(newPassword) {
|
||||
return fmt.Errorf("新密码包含无效字符")
|
||||
}
|
||||
if newPassword == oldPassword {
|
||||
return fmt.Errorf("新密码不能与当前密码相同")
|
||||
}
|
||||
if utf8.RuneCountInString(newPassword) < minPasswordRunes {
|
||||
return fmt.Errorf("新密码至少需要%d个字符", minPasswordRunes)
|
||||
}
|
||||
if len([]byte(newPassword)) > maxPasswordBytes {
|
||||
return fmt.Errorf("新密码不能超过%d字节", maxPasswordBytes)
|
||||
}
|
||||
if strings.TrimSpace(newPassword) != newPassword {
|
||||
return fmt.Errorf("新密码不能以空格开头或结尾")
|
||||
}
|
||||
for _, char := range newPassword {
|
||||
if unicode.IsControl(char) {
|
||||
return fmt.Errorf("新密码不能包含控制字符")
|
||||
}
|
||||
}
|
||||
if _, exists := commonPasswords[strings.ToLower(newPassword)]; exists {
|
||||
return fmt.Errorf("新密码过于常见,请使用更复杂的密码")
|
||||
}
|
||||
if username != "" && strings.EqualFold(newPassword, username) {
|
||||
return fmt.Errorf("新密码不能与用户名相同")
|
||||
}
|
||||
|
||||
categoryCount := 0
|
||||
hasLetter, hasNumber, hasSymbol := false, false, false
|
||||
for _, char := range newPassword {
|
||||
switch {
|
||||
case unicode.IsLetter(char):
|
||||
hasLetter = true
|
||||
case unicode.IsNumber(char):
|
||||
hasNumber = true
|
||||
case unicode.IsPunct(char) || unicode.IsSymbol(char):
|
||||
hasSymbol = true
|
||||
}
|
||||
}
|
||||
for _, present := range []bool{hasLetter, hasNumber, hasSymbol} {
|
||||
if present {
|
||||
categoryCount++
|
||||
}
|
||||
}
|
||||
if categoryCount < 2 {
|
||||
return fmt.Errorf("新密码至少需要包含字母、数字、符号中的两类")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user