加固后台管理安全
This commit is contained in:
@@ -106,8 +106,13 @@ func (h *Handler) AssignRoles(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *Handler) ChangePassword(c *gin.Context) {
|
||||
id, ok := parseID(c)
|
||||
h.ChangeOwnPassword(c)
|
||||
}
|
||||
|
||||
func (h *Handler) ChangeOwnPassword(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
var req ChangePasswordRequest
|
||||
@@ -115,13 +120,39 @@ func (h *Handler) ChangePassword(c *gin.Context) {
|
||||
response.BadRequest(c, "密码不能为空")
|
||||
return
|
||||
}
|
||||
if err := h.service.ChangePassword(c.Request.Context(), id, req); err != nil {
|
||||
if err := h.service.ChangeOwnPassword(c.Request.Context(), adminID, req); err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"updated": true})
|
||||
}
|
||||
|
||||
func (h *Handler) ResetPassword(c *gin.Context) {
|
||||
id, ok := parseID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req ResetPasswordRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "密码不能为空")
|
||||
return
|
||||
}
|
||||
if err := h.service.ResetPassword(c.Request.Context(), id, req); err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"updated": true})
|
||||
}
|
||||
|
||||
func currentAdminID(c *gin.Context) (uint64, bool) {
|
||||
value, ok := c.Get(middleware.ContextAdminID)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
adminID, ok := value.(uint64)
|
||||
return adminID, ok
|
||||
}
|
||||
|
||||
func parseID(c *gin.Context) (uint64, bool) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
@@ -141,6 +172,8 @@ func writeError(c *gin.Context, err error) {
|
||||
response.BadRequest(c, "不能删除最后一个超级管理员")
|
||||
case errors.Is(err, ErrWrongPassword):
|
||||
response.BadRequest(c, "原密码错误")
|
||||
case errors.Is(err, ErrWeakPassword):
|
||||
response.BadRequest(c, "密码至少 8 位且需包含字母和数字")
|
||||
case IsNotFound(err):
|
||||
response.Error(c, http.StatusNotFound, "not_found", "管理员不存在")
|
||||
default:
|
||||
|
||||
Reference in New Issue
Block a user