/*
* Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
*
* This file is licensed under AGPL-3.0-or-later, see NOTICE and LICENSE for
* more information.
*/
package handlers
import (
"net/http"
"git.src.quest/~skye/felu-ddns/internal/db"
"github.com/alexedwards/scs/v2"
"github.com/gin-gonic/gin"
)
type postUserPasswordData struct {
CurrentPassword string `form:"current_password"`
NewPassword string `form:"new_password"`
ConfirmNewPassword string `form:"confirm_new_password"`
}
func PostUserPassword() gin.HandlerFunc {
return func(c *gin.Context) {
data := &postUserPasswordData{}
if err := c.Bind(data); err != nil {
c.String(http.StatusBadRequest, "Could not bind password data")
c.Abort()
return
}
if len(data.NewPassword) < 10 {
c.String(http.StatusBadRequest, "Password should be at least 10 chars")
c.Abort()
return
}
if data.NewPassword != data.ConfirmNewPassword {
c.String(http.StatusBadRequest, "New and confirm do not match")
c.Abort()
return
}
userId, exists := c.Get("user_id")
if !exists {
c.String(http.StatusInternalServerError, "This should not be possible, but don't quote me on that")
c.Abort()
return
}
if !db.VerifyUserPassword(userId.(string), data.CurrentPassword) {
c.String(http.StatusBadRequest, "Current password is not correct")
c.Abort()
return
}
err := db.UpdateUserPassword(userId.(string), data.NewPassword)
if err != nil {
// FIXME: Handle better
c.String(http.StatusInternalServerError, "Something went wrong while deleting the user")
c.Abort()
return
}
c.Header("HX-Refresh", "true")
}
}
type postUserEmailData struct {
Email string `form:"email"`
}
func PostUserEmail() gin.HandlerFunc {
return func(c *gin.Context) {
data := &postUserEmailData{}
if err := c.Bind(data); err != nil {
c.String(http.StatusBadRequest, "Could not bind email data")
c.Abort()
return
}
if data.Email == "" {
c.String(http.StatusBadRequest, "Email can't be empty")
c.Abort()
return
}
userId, exists := c.Get("user_id")
if !exists {
c.String(http.StatusInternalServerError, "This should not be possible, but don't quote me on that")
c.Abort()
return
}
err := db.UpdateUserEmail(userId.(string), data.Email)
if err != nil {
// FIXME: Handle better
c.String(http.StatusInternalServerError, "Something went wrong while deleting the user")
c.Abort()
return
}
c.Header("HX-Refresh", "true")
}
}
func DeleteUser(sm *scs.SessionManager) gin.HandlerFunc {
return func(c *gin.Context) {
userId, exists := c.Get("user_id")
if !exists {
c.String(http.StatusInternalServerError, "This should not be possible, but don't quote me on that")
c.Abort()
return
}
err := db.DeleteUser(userId.(string))
if err != nil {
// FIXME: Handle better
c.String(http.StatusInternalServerError, "Something went wrong while deleting the user")
c.Abort()
return
}
sm.Destroy(c.Request.Context())
c.Header("HX-Refresh", "true")
}
}