♻️ Single table to store auth preferences

This commit is contained in:
2024-10-13 12:36:51 +08:00
parent 9287e6c5cc
commit 39c3799d82
8 changed files with 69 additions and 33 deletions

View File

@ -26,8 +26,8 @@ func MapAPIs(app *fiber.App, baseURL string) {
preferences := api.Group("/preferences").Name("Preferences API")
{
preferences.Get("/auth", getAuthConfig)
preferences.Put("/auth", updateAuthConfig)
preferences.Get("/auth", getAuthPreference)
preferences.Put("/auth", updateAuthPreference)
preferences.Get("/notifications", getNotificationPreference)
preferences.Put("/notifications", updateNotificationPreference)
}

View File

@ -1,24 +1,27 @@
package api
import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/server/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"github.com/gofiber/fiber/v2"
"gorm.io/datatypes"
)
func getAuthConfig(c *fiber.Ctx) error {
func getAuthPreference(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
return c.JSON(user.AuthConfig)
cfg, err := services.GetAuthPreference(user)
if err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
return c.JSON(cfg.Config)
}
func updateAuthConfig(c *fiber.Ctx) error {
func updateAuthPreference(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
@ -29,15 +32,12 @@ func updateAuthConfig(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
user.AuthConfig = datatypes.NewJSONType(data)
if err := database.C.Save(&user).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
services.InvalidAuthCacheWithUser(user.ID)
cfg, err := services.UpdateAuthPreference(user, data)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
return c.JSON(user.AuthConfig)
return c.JSON(cfg.Config)
}
func getNotificationPreference(c *fiber.Ctx) error {