定义修改密码的结构体
type PasswordReset struct {
CurrentPassword string `json:"currentPassword"`
Password string `json:"password"`
}
密码校验部分
func PasswordVerify(encryptedPassword, password string) error {
if err := bcrypt.CompareHashAndPassword([]byte(encryptedPassword), []byte(password)); err != nil {
return fmt.Errorf("incorrect password")
}
return nil
}
func (u *globaluserOperator) PasswordVerify(username string, password string) error {
obj, err := u.globalUserGetter.Get("", username)
if err != nil {
klog.Error(err)
return err
}
user := obj.(*authv1alpha2.GlobalUser)
err = PasswordVerify(user.Spec.EncryptedPassword, password)
if err != nil {
return fmt.Errorf("incorrect CurrentPassword")
}
return nil
}
func (u *globaluserOperator) fetch(username string) (*authv1alpha2.GlobalUser, error) {
obj, err := u.globalUserGetter.Get("", username)
if err != nil {
klog.Error(err)
return nil, err
}
user := obj.(*authv1alpha2.GlobalUser).DeepCopy()
return user, nil
}
修改密码
func (u *globaluserOperator) ModifyPassword(username string, password string) (*authenticationv1alpha2.GlobalUser, error) {
user, err := u.fetch(username)
if err != nil {
klog.Error(err)
return nil, err
}
newpassword, err := encrypt(password)
user.Spec.EncryptedPassword = newpassword
globaluser, err := u.kubesspaas.AuthenticationV1alpha2().GlobalUsers().Update(context.Background(), user, metav1.UpdateOptions{})
if err != nil {
klog.Error(err)
return nil, err
}
return globaluser, nil
}
Handler层
type PasswordReset struct {
CurrentPassword string `json:"currentPassword"`
Password string `json:"password"`
}
func (a *authenticationHandler) ModifyPassword(request *restful.Request, response *restful.Response) {
username := request.PathParameter("globaluser")
var passwordReset PasswordReset
err := request.ReadEntity(&passwordReset)
if err != nil {
api.HandleBadRequest(request, response, err)
return
}
if passwordReset.CurrentPassword != "" &&passwordReset.Password != ""{
if err = a.authMode.GlobalUser().PasswordVerify(username, passwordReset.CurrentPassword); err !=nil {
if err != nil {
api.HandleError(request, response, err)
return
}
}
result,err := a.authMode.GlobalUser().ModifyPassword(username, passwordReset.Password)
if err != nil {
api.HandleError(request, response, err)
return
}
response.WriteEntity(result)
}else {
err = errors.New("CurrentPassword or NewPassword is null")
api.HandleError(request, response, err)
return
}
}