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)
|
}
|