feat(singleuser): add setpwd api

This commit is contained in:
hexxa 2020-12-05 22:12:49 +08:00
parent 4d6e7ff938
commit 57124451ad
4 changed files with 38 additions and 43 deletions

View file

@ -18,6 +18,7 @@ var (
ErrInvalidConfig = errors.New("invalid user config")
UserParam = "user"
PwdParam = "pwd"
NewPwdParam = "newpwd"
RoleParam = "role"
ExpireParam = "expire"
TokenCookie = "tk"
@ -88,3 +89,38 @@ func (h *SimpleUserHandlers) Logout(c *gin.Context) {
c.SetCookie(TokenCookie, "", 0, "/", "nohost", false, true)
c.JSON(q.Resp(200))
}
func (h *SimpleUserHandlers) SetPwd(c *gin.Context) {
user, ok1 := c.GetPostForm(UserParam)
pwd1, ok2 := c.GetPostForm(PwdParam)
pwd2, ok3 := c.GetPostForm(NewPwdParam)
if !ok1 || !ok2 || !ok3 {
c.JSON(q.ErrResp(c, 401, ErrInvalidUser))
return
}
expectedHash, ok := h.deps.KV().GetStringIn(UsersNamespace, user)
if !ok {
c.JSON(q.ErrResp(c, 500, ErrInvalidConfig))
return
}
err := bcrypt.CompareHashAndPassword([]byte(expectedHash), []byte(pwd1))
if err != nil {
c.JSON(q.ErrResp(c, 401, ErrInvalidUser))
return
}
newHash, err := bcrypt.GenerateFromPassword([]byte(pwd2), 10)
if err != nil {
c.JSON(q.ErrResp(c, 500, errors.New("fail to set password")))
return
}
err = h.deps.KV().SetStringIn(UsersNamespace, user, string(newHash))
if err != nil {
c.JSON(q.ErrResp(c, 500, ErrInvalidConfig))
return
}
c.JSON(q.Resp(200))
}

Binary file not shown.