Wallet/pkg/internal/server/api/wallet_api.go

61 lines
1.5 KiB
Go
Raw Normal View History

2025-01-25 18:33:11 +08:00
package api
import (
"errors"
2025-01-29 01:53:15 +08:00
2025-01-26 19:51:35 +08:00
"git.solsynth.dev/hypernet/wallet/pkg/internal/server/exts"
2025-01-25 18:33:11 +08:00
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"git.solsynth.dev/hypernet/wallet/pkg/internal/database"
"git.solsynth.dev/hypernet/wallet/pkg/internal/models"
"github.com/gofiber/fiber/v2"
"github.com/shopspring/decimal"
"gorm.io/gorm"
2025-01-25 18:33:11 +08:00
)
func createWallet(c *fiber.Ctx) error {
if err := sec.EnsureGrantedPerm(c, "CreateWallet", true); err != nil {
return err
}
2025-01-29 01:53:15 +08:00
user := c.Locals("nex_user").(*sec.UserInfo)
2025-01-26 19:51:35 +08:00
var data struct {
Password string `json:"password" validate:"min=4"`
}
if err := exts.BindAndValidate(c, &data); err != nil {
return err
}
var wallet models.Wallet
if err := database.C.Where("account_id = ?", user.ID).
First(&wallet).Error; err == nil || errors.Is(err, gorm.ErrRecordNotFound) {
return fiber.NewError(fiber.StatusConflict, "wallet already exists")
}
wallet = models.Wallet{
Balance: decimal.NewFromInt(0),
AccountID: user.ID,
}
if err := database.C.Create(&wallet).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
return c.JSON(wallet)
}
2025-01-25 18:33:11 +08:00
func getMyWallet(c *fiber.Ctx) error {
if err := sec.EnsureAuthenticated(c); err != nil {
return err
}
2025-01-29 01:53:15 +08:00
user := c.Locals("nex_user").(*sec.UserInfo)
2025-01-25 18:33:11 +08:00
var wallet models.Wallet
if err := database.C.Where("account_id = ?", user.ID).First(&wallet).Error; err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
return c.JSON(wallet)
}