70 lines
1.9 KiB
Go
70 lines
1.9 KiB
Go
package endpoints
|
|
|
|
// this endpoint server at "/user/settings" will show the settings page
|
|
// depeding on which action is taken the user will be logged out or
|
|
// the password will be changed
|
|
|
|
import (
|
|
"arbeitszeitmessung/helper"
|
|
"arbeitszeitmessung/models"
|
|
"arbeitszeitmessung/templates"
|
|
"context"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
func UserSettingsHandler(w http.ResponseWriter, r *http.Request) {
|
|
helper.RequiresLogin(Session, w, r)
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
showUserPage(w, r, 0)
|
|
case http.MethodPost:
|
|
switch r.FormValue("action") {
|
|
case "change-pass":
|
|
changePassword(w, r)
|
|
case "logout-user":
|
|
logoutUser(w, r)
|
|
}
|
|
default:
|
|
http.Error(w, "Method not allowed!", http.StatusMethodNotAllowed)
|
|
}
|
|
}
|
|
|
|
// change user password and store salted hash in db
|
|
func changePassword(w http.ResponseWriter, r *http.Request) {
|
|
err := r.ParseForm()
|
|
if err != nil {
|
|
log.Println("Error parsing form!", err)
|
|
http.Error(w, "Error parsing form error", http.StatusBadRequest)
|
|
return
|
|
}
|
|
password := r.FormValue("password")
|
|
newPassword := r.FormValue("new_password")
|
|
if password == "" || newPassword == "" || newPassword != r.FormValue("new_password_repeat") {
|
|
showUserPage(w, r, http.StatusBadRequest)
|
|
return
|
|
}
|
|
user, err := models.GetUserByPersonalNr(Session.GetInt(r.Context(), "user"))
|
|
if err != nil {
|
|
log.Println("Error getting user!", err)
|
|
showUserPage(w, r, http.StatusBadRequest)
|
|
}
|
|
auth, err := user.ChangePass(password, newPassword)
|
|
if err != nil {
|
|
log.Println("Error when changing password!", err)
|
|
}
|
|
if auth {
|
|
showUserPage(w, r, http.StatusAccepted)
|
|
return
|
|
}
|
|
showUserPage(w, r, http.StatusUnauthorized)
|
|
}
|
|
|
|
func showUserPage(w http.ResponseWriter, r *http.Request, status int) {
|
|
var ctx context.Context
|
|
if user, err := models.GetUserFromSession(Session, r.Context()); err == nil {
|
|
ctx = context.WithValue(r.Context(), "user", user)
|
|
}
|
|
templates.SettingsPage(status).Render(ctx, w)
|
|
}
|