905086
2026-11-07 7fd2270570811c0d29f0d5d87d11bfc4612e0743
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
package handlers
 
import (
    "math/rand"
    "net/http"
    "time"
 
    "gamebox-server/config"
    "gamebox-server/models"
 
    "github.com/gin-gonic/gin"
    "golang.org/x/crypto/bcrypt"
)
 
// ListResetRequests 密码重置申请列表(管理后台)
func ListResetRequests(c *gin.Context) {
    var list []models.PasswordResetRequest
    config.DB.Order("id DESC").Find(&list)
    c.JSON(http.StatusOK, gin.H{"code": 0, "data": list})
}
 
// ApproveResetRequest 同意找回密码申请:为该用户设置新密码并标记已处理
// body 可传 new_password(至少6位),不传则自动生成
func ApproveResetRequest(c *gin.Context) {
    id := c.Param("id")
    var req struct {
        NewPassword string `json:"new_password"`
    }
    _ = c.ShouldBindJSON(&req)
 
    var apply models.PasswordResetRequest
    if err := config.DB.First(&apply, id).Error; err != nil {
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "申请不存在"})
        return
    }
    if apply.Status != 0 {
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该申请已处理过"})
        return
    }
    var user models.User
    if err := config.DB.Where("phone = ?", apply.Phone).First(&user).Error; err != nil {
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "用户不存在"})
        return
    }
    // 新密码优先级:管理员指定 > 用户申请时填写的期望密码 > 随机生成
    newPwd := req.NewPassword
    if len(newPwd) < 6 {
        newPwd = apply.ProposedPwd
    }
    if len(newPwd) < 6 {
        newPwd = randomPassword()
    }
    hash, _ := bcrypt.GenerateFromPassword([]byte(newPwd), bcrypt.DefaultCost)
    if err := config.DB.Model(&user).Update("password", string(hash)).Error; err != nil {
        c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "重置失败"})
        return
    }
    now := time.Now()
    config.DB.Model(&apply).Updates(map[string]interface{}{
        "status":     1,
        "new_pwd":    newPwd,
        "handled_at": &now,
    })
    c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已同意并重置密码",
        "data": gin.H{"phone": apply.Phone, "new_password": newPwd}})
}
 
// DeleteResetRequest 删除申请
func DeleteResetRequest(c *gin.Context) {
    config.DB.Delete(&models.PasswordResetRequest{}, c.Param("id"))
    c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "已删除"})
}
 
// randomPassword 生成8位随机密码(字母+数字)
func randomPassword() string {
    const charset = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789"
    b := make([]byte, 8)
    for i := range b {
        b[i] = charset[rand.Intn(len(charset))]
    }
    return string(b)
}