1
0
mirror of https://github.com/osmarks/mycorrhiza.git synced 2024-10-30 03:36:16 +00:00
mycorrhiza/settings/settings.go
Jackson 5f592acc55 implement user facing password change page
similar to the admin password change, but with a few changes:
- require current password verification

the following still included:
- empty password check
- confirm password check
2023-11-27 22:33:12 +03:00

63 lines
1.5 KiB
Go

package settings
import (
"fmt"
"mime"
"net/http"
"reflect"
"github.com/bouncepaw/mycorrhiza/viewutil"
"github.com/bouncepaw/mycorrhiza/user"
"github.com/bouncepaw/mycorrhiza/util"
)
func handlerUserChangePassword(w http.ResponseWriter, rq *http.Request) {
u := user.FromRequest(rq)
// TODO: is there a better way?
if reflect.DeepEqual(u, user.EmptyUser()) || u == nil {
util.HTTP404Page(w, "404 page not found")
return
}
f := util.FormDataFromRequest(rq, []string{"current_password", "password", "password_confirm"})
currentPassword := f.Get("current_password")
if user.CredentialsOK(u.Name, currentPassword) {
password := f.Get("password")
passwordConfirm := f.Get("password_confirm")
// server side validation
if password == "" {
err := fmt.Errorf("passwords should not be empty")
f = f.WithError(err)
}
if password == passwordConfirm {
previousPassword := u.Password // for rollback
if err := u.ChangePassword(password); err != nil {
f = f.WithError(err)
} else {
if err := user.SaveUserDatabase(); err != nil {
u.Password = previousPassword
f = f.WithError(err)
} else {
http.Redirect(w, rq, "/", http.StatusSeeOther)
return
}
}
} else {
err := fmt.Errorf("passwords do not match")
f = f.WithError(err)
}
} else {
err := fmt.Errorf("incorrect password")
f = f.WithError(err)
}
if f.HasError() {
w.WriteHeader(http.StatusBadRequest)
}
w.Header().Set("Content-Type", mime.TypeByExtension(".html"))
changePasswordPage(viewutil.MetaFrom(w, rq), f, u)
}