♻️ Move models.Account to sec.UserInfo

This commit is contained in:
2024-10-30 23:26:13 +08:00
parent 14baee03fe
commit 8fbb79607b
38 changed files with 346 additions and 272 deletions

View File

@ -2,18 +2,21 @@ package gap
import (
"fmt"
"strings"
"git.solsynth.dev/hypernet/nexus/pkg/nex"
"git.solsynth.dev/hypernet/nexus/pkg/proto"
"git.solsynth.dev/hypernet/pusher/pkg/pushkit/pushcon"
"github.com/rs/zerolog/log"
"github.com/samber/lo"
"strings"
"github.com/spf13/viper"
)
var Nx *nex.Conn
var Px *pushcon.Conn
var (
Nx *nex.Conn
Px *pushcon.Conn
)
func InitializeToNexus() error {
grpcBind := strings.SplitN(viper.GetString("grpc_bind"), ":", 2)
@ -30,7 +33,7 @@ func InitializeToNexus() error {
Type: nex.ServiceTypeAuth,
Label: "Passport",
GrpcAddr: grpcOutbound,
HttpAddr: lo.ToPtr("http://" + httpOutbound),
HttpAddr: lo.ToPtr("http://" + httpOutbound + "/api"),
})
if err == nil {
go func() {

View File

@ -45,7 +45,7 @@ func (v *App) ListAvailableRealm(ctx context.Context, request *proto.LookupUserR
if err != nil {
return nil, fmt.Errorf("unable to find target account: %v", err)
}
realms, err := services.ListAvailableRealm(account)
realms, err := services.ListAvailableRealm(account.ID)
if err != nil {
return nil, err
}
@ -77,7 +77,7 @@ func (v *App) ListOwnedRealm(ctx context.Context, request *proto.LookupUserRealm
if err != nil {
return nil, fmt.Errorf("unable to find target account: %v", err)
}
realms, err := services.ListOwnedRealm(account)
realms, err := services.ListOwnedRealm(account.ID)
if err != nil {
return nil, err
}

View File

@ -5,6 +5,7 @@ import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log"
)
@ -27,13 +28,13 @@ func notifyAllUser(c *fiber.Ctx) error {
if err := exts.EnsureGrantedPerm(c, "AdminNotifyAll", true); err != nil {
return err
}
operator := c.Locals("user").(models.Account)
operator := c.Locals("user").(*sec.UserInfo)
var users []models.Account
if err := database.C.Find(&users).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
services.AddAuditRecord(operator, "notify.all", c.IP(), c.Get(fiber.HeaderUserAgent), map[string]any{
services.AddAuditRecord(operator.ID, "notify.all", c.IP(), c.Get(fiber.HeaderUserAgent), map[string]any{
"payload": data,
})
}
@ -85,13 +86,13 @@ func notifyOneUser(c *fiber.Ctx) error {
if err := exts.EnsureGrantedPerm(c, "AdminNotifyAll", true); err != nil {
return err
}
operator := c.Locals("user").(models.Account)
operator := c.Locals("user").(*sec.UserInfo)
var user models.Account
if err := database.C.Where("id = ?", data.UserID).First(&user).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
services.AddAuditRecord(operator, "notify.one", c.IP(), c.Get(fiber.HeaderUserAgent), map[string]any{
services.AddAuditRecord(operator.ID, "notify.one", c.IP(), c.Get(fiber.HeaderUserAgent), map[string]any{
"user_id": user.ID,
"payload": data,
})

View File

@ -2,6 +2,7 @@ package admin
import (
"fmt"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
@ -16,7 +17,7 @@ func editUserPermission(c *fiber.Ctx) error {
if err := exts.EnsureGrantedPerm(c, "AdminUserPermission", true); err != nil {
return err
}
operator := c.Locals("user").(models.Account)
operator := c.Locals("user").(*sec.UserInfo)
var data struct {
PermNodes map[string]any `json:"perm_nodes" validate:"required"`
@ -39,7 +40,7 @@ func editUserPermission(c *fiber.Ctx) error {
if err := database.C.Save(&user).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
services.AddAuditRecord(operator, "user.permissions.edit", c.IP(), c.Get(fiber.HeaderUserAgent), map[string]any{
services.AddAuditRecord(operator.ID, "user.permissions.edit", c.IP(), c.Get(fiber.HeaderUserAgent), map[string]any{
"user_id": user.ID,
"previous_permissions": prev,
"new_permissions": data.PermNodes,

View File

@ -6,6 +6,7 @@ import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
)
@ -53,7 +54,7 @@ func forceConfirmAccount(c *fiber.Ctx) error {
if err := exts.EnsureGrantedPerm(c, "AdminUserConfirmation", true); err != nil {
return err
}
operator := c.Locals("user").(models.Account)
operator := c.Locals("user").(*sec.UserInfo)
var user models.Account
if err := database.C.Where("id = ?", userId).First(&user).Error; err != nil {
@ -63,7 +64,7 @@ func forceConfirmAccount(c *fiber.Ctx) error {
if err := services.ForceConfirmAccount(user); err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
services.AddAuditRecord(operator, "user.confirm", c.IP(), c.Get(fiber.HeaderUserAgent), map[string]any{
services.AddAuditRecord(operator.ID, "user.confirm", c.IP(), c.Get(fiber.HeaderUserAgent), map[string]any{
"user_id": user.ID,
})
}

View File

@ -2,6 +2,7 @@ package api
import (
"fmt"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"strconv"
"strings"
"time"
@ -48,7 +49,7 @@ func getUserinfo(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data models.Account
if err := database.C.
@ -84,7 +85,7 @@ func getEvents(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
take := c.QueryInt("take", 0)
offset := c.QueryInt("offset", 0)
@ -116,7 +117,7 @@ func editUserinfo(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data struct {
Nick string `json:"nick" validate:"required"`
@ -222,11 +223,16 @@ func requestDeleteAccount(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
if err := services.CheckAbleToDeleteAccount(user); err != nil {
var account models.Account
if err := database.C.Where("id = ?", user.ID).First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("account was not found: %v", err))
}
if err := services.CheckAbleToDeleteAccount(account); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else if err = services.RequestDeleteAccount(user); err != nil {
} else if err = services.RequestDeleteAccount(account); err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}

View File

@ -1,10 +1,12 @@
package api
import (
"fmt"
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
"strconv"
)
@ -13,7 +15,7 @@ func setAvatar(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data struct {
AttachmentID string `json:"attachment" validate:"required"`
@ -23,9 +25,7 @@ func setAvatar(c *fiber.Ctx) error {
return err
}
user.Avatar = &data.AttachmentID
if err := database.C.Save(&user).Error; err != nil {
if err := database.C.Where("id = ?", user.ID).Updates(&models.Account{Avatar: &data.AttachmentID}).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
services.AddEvent(user.ID, "profile.edit.avatar", strconv.Itoa(int(user.ID)), c.IP(), c.Get(fiber.HeaderUserAgent))
@ -39,7 +39,7 @@ func setBanner(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data struct {
AttachmentID string `json:"attachment" validate:"required"`
@ -49,9 +49,7 @@ func setBanner(c *fiber.Ctx) error {
return err
}
user.Banner = &data.AttachmentID
if err := database.C.Save(&user).Error; err != nil {
if err := database.C.Where("id = ?", user.ID).Updates(&models.Account{Banner: &data.AttachmentID}).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
services.AddEvent(user.ID, "profile.edit.banner", strconv.Itoa(int(user.ID)), c.IP(), c.Get(fiber.HeaderUserAgent))
@ -65,9 +63,14 @@ func getAvatar(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
if content := user.GetAvatar(); content == nil {
var account models.Account
if err := database.C.Where("id = ?", user.ID).First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("account was not found: %v", err))
}
if content := account.GetAvatar(); content == nil {
return c.SendStatus(fiber.StatusNotFound)
} else {
return c.Redirect(*content, fiber.StatusFound)
@ -78,9 +81,14 @@ func getBanner(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
if content := user.GetBanner(); content == nil {
var account models.Account
if err := database.C.Where("id = ?", user.ID).First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("account was not found: %v", err))
}
if content := account.GetBanner(); content == nil {
return c.SendStatus(fiber.StatusNotFound)
} else {
return c.Redirect(*content, fiber.StatusFound)

View File

@ -6,6 +6,7 @@ import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)
@ -14,7 +15,7 @@ func listBotKeys(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var tx *gorm.DB
@ -50,7 +51,7 @@ func getBotKey(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
id, _ := c.ParamsInt("id", 0)
@ -69,7 +70,7 @@ func createBotKey(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data struct {
Name string `json:"name" validate:"required"`
@ -82,7 +83,7 @@ func createBotKey(c *fiber.Ctx) error {
return err
}
target := user
var target models.Account
botId, _ := c.ParamsInt("botId", 0)
if botId > 0 {
@ -91,6 +92,12 @@ func createBotKey(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("bot not found: %v", err))
}
target = bot
} else {
var account models.Account
if err := database.C.Where("id = ?", user.ID).First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("account not found: %v", err))
}
target = account
}
key, err := services.NewApiKey(target, models.ApiKey{
@ -109,7 +116,7 @@ func editBotKey(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data struct {
Name string `json:"name" validate:"required"`
@ -156,7 +163,7 @@ func rollBotKey(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
id, _ := c.ParamsInt("id", 0)
@ -189,7 +196,7 @@ func revokeBotKey(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
id, _ := c.ParamsInt("id", 0)

View File

@ -1,10 +1,12 @@
package api
import (
"fmt"
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
"github.com/samber/lo"
"gorm.io/datatypes"
@ -16,7 +18,7 @@ func listBots(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
tx := database.C.Where("automated_id = ?", user.ID)
@ -41,9 +43,9 @@ func createBot(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
cnt, _ := services.GetBotCount(user)
cnt, _ := services.GetBotCount(user.ID)
if err := exts.EnsureGrantedPerm(c, "CreateBots", cnt+1); err != nil {
return err
}
@ -65,7 +67,14 @@ func createBot(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusBadRequest, "invalid bot nick, length requires 4 to 24")
}
bot, err := services.NewBot(user, models.Account{
var account models.Account
if err := database.C.Where(&models.Account{
Name: data.Name,
}).First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("account was not found: %v", err))
}
bot, err := services.NewBot(account, models.Account{
Name: data.Name,
Nick: data.Nick,
Description: data.Description,
@ -84,7 +93,7 @@ func deleteBot(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
id, _ := c.ParamsInt("botId", 0)

View File

@ -18,9 +18,6 @@ func MapAPIs(app *fiber.App, baseURL string) {
notify := api.Group("/notifications").Name("Notifications API")
{
// Deprecated, use /subscription instead, will be removed in the future
notify.Post("/subscribe", addNotifySubscriber)
notify.Get("/", getNotifications)
notify.Get("/subscription", getNotifySubscriber)
notify.Post("/subscription", addNotifySubscriber)

View File

@ -1,10 +1,12 @@
package api
import (
"fmt"
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
"github.com/samber/lo"
"strconv"
@ -18,7 +20,7 @@ func getNotifications(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
tx := database.C.Where(&models.Notification{AccountID: user.ID}).Model(&models.Notification{})
@ -47,7 +49,7 @@ func markNotificationRead(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
id, _ := c.ParamsInt("notificationId", 0)
if err := exts.EnsureAuthenticated(c); err != nil {
@ -76,7 +78,7 @@ func markNotificationReadBatch(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data struct {
MessageIDs []uint `json:"messages"`
@ -100,7 +102,7 @@ func getNotifySubscriber(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var subscribers []models.NotificationSubscriber
if err := database.C.Where(&models.NotificationSubscriber{
@ -116,7 +118,7 @@ func addNotifySubscriber(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data struct {
Provider string `json:"provider" validate:"required"`
@ -137,8 +139,13 @@ func addNotifySubscriber(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK)
}
var account models.Account
if err := database.C.Where("id = ?", user.ID).First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("account was not found: %v", err))
}
subscriber, err := services.AddNotifySubscriber(
user,
account,
data.Provider,
data.DeviceID,
data.DeviceToken,
@ -156,7 +163,7 @@ func removeNotifySubscriber(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
device := c.Params("deviceId")

View File

@ -2,6 +2,7 @@ package api
import (
"fmt"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
@ -13,7 +14,7 @@ func notifyUser(c *fiber.Ctx) error {
if err := exts.EnsureGrantedPerm(c, "DevNotifyUser", true); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data struct {
ClientID string `json:"client_id" validate:"required"`

View File

@ -1,6 +1,8 @@
package api
import (
"fmt"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"strings"
"time"
@ -31,7 +33,7 @@ func tryAuthorizeThirdClient(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var ticket models.AuthTicket
if err := database.C.Where(&models.AuthTicket{
@ -72,18 +74,23 @@ func authorizeThirdClient(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var client models.ThirdClient
if err := database.C.Where(&models.ThirdClient{Alias: id}).First(&client).Error; err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
var account models.Account
if err := database.C.Where("id = ?", user.ID).First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("account was not found: %v", err))
}
switch response {
case "code":
// OAuth Authorization Mode
ticket, err := services.NewOauthTicket(
user,
account,
client,
strings.Split(scope, " "),
[]string{services.InternalTokenAudience, client.Alias},
@ -104,7 +111,7 @@ func authorizeThirdClient(c *fiber.Ctx) error {
case "token":
// OAuth Implicit Mode
ticket, err := services.NewOauthTicket(
user,
account,
client,
strings.Split(scope, " "),
[]string{services.InternalTokenAudience, client.Alias},

View File

@ -4,6 +4,7 @@ import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
)
@ -11,9 +12,9 @@ func getAuthPreference(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
cfg, err := services.GetAuthPreference(user)
cfg, err := services.GetAuthPreference(user.ID)
if err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
@ -25,14 +26,14 @@ func updateAuthPreference(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data models.AuthConfig
if err := exts.BindAndValidate(c, &data); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
cfg, err := services.UpdateAuthPreference(user, data)
cfg, err := services.UpdateAuthPreference(user.ID, data)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
@ -46,8 +47,8 @@ func getNotificationPreference(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
notification, err := services.GetNotificationPreference(user)
user := c.Locals("user").(*sec.UserInfo)
notification, err := services.GetNotificationPreference(user.ID)
if err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
@ -59,7 +60,7 @@ func updateNotificationPreference(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data struct {
Config map[string]bool `json:"config"`
@ -69,7 +70,7 @@ func updateNotificationPreference(c *fiber.Ctx) error {
return err
}
notification, err := services.UpdateNotificationPreference(user, data.Config)
notification, err := services.UpdateNotificationPreference(user.ID, data.Config)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {

View File

@ -5,6 +5,7 @@ import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
)
@ -25,7 +26,7 @@ func getMyRealmMember(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
if realm, err := services.GetRealmWithAlias(alias); err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
@ -40,7 +41,7 @@ func addRealmMember(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
alias := c.Params("realm")
var data struct {
@ -63,7 +64,7 @@ func addRealmMember(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
if err := services.AddRealmMember(user, account, realm); err != nil {
if err := services.AddRealmMember(user.ID, account, realm); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
return c.SendStatus(fiber.StatusOK)
@ -74,7 +75,7 @@ func removeRealmMember(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
alias := c.Params("realm")
var data struct {
@ -97,7 +98,7 @@ func removeRealmMember(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
if err := services.RemoveRealmMember(user, account, realm); err != nil {
if err := services.RemoveRealmMember(user.ID, account, realm); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
return c.SendStatus(fiber.StatusOK)
@ -108,7 +109,7 @@ func leaveRealm(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
alias := c.Params("realm")
realm, err := services.GetRealmWithAlias(alias)
@ -125,7 +126,7 @@ func leaveRealm(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
if err := services.RemoveRealmMember(user, account, realm); err != nil {
if err := services.RemoveRealmMember(user.ID, account, realm); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
return c.SendStatus(fiber.StatusOK)

View File

@ -5,6 +5,7 @@ import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
"strconv"
)
@ -31,8 +32,8 @@ func listOwnedRealm(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
if realms, err := services.ListOwnedRealm(user); err != nil {
user := c.Locals("user").(*sec.UserInfo)
if realms, err := services.ListOwnedRealm(user.ID); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
return c.JSON(realms)
@ -43,8 +44,8 @@ func listAvailableRealm(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
if realms, err := services.ListAvailableRealm(user); err != nil {
user := c.Locals("user").(*sec.UserInfo)
if realms, err := services.ListAvailableRealm(user.ID); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
return c.JSON(realms)
@ -55,7 +56,7 @@ func createRealm(c *fiber.Ctx) error {
if err := exts.EnsureGrantedPerm(c, "CreateRealms", true); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data struct {
Alias string `json:"alias" validate:"required,lowercase,min=4,max=32"`
@ -82,7 +83,7 @@ func createRealm(c *fiber.Ctx) error {
IsPublic: data.IsPublic,
IsCommunity: data.IsCommunity,
AccountID: user.ID,
}, user)
}, user.ID)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
@ -97,7 +98,7 @@ func editRealm(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
id, _ := c.ParamsInt("realmId", 0)
var data struct {
@ -146,7 +147,7 @@ func deleteRealm(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
id, _ := c.ParamsInt("realmId", 0)
var realm models.Realm

View File

@ -1,9 +1,11 @@
package api
import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
"strconv"
)
@ -12,17 +14,17 @@ func listRelationship(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
status := c.QueryInt("status", -1)
var err error
var friends []models.AccountRelationship
if status < 0 {
if friends, err = services.ListAllRelationship(user); err != nil {
if friends, err = services.ListAllRelationship(user.ID); err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
} else {
if friends, err = services.ListRelationshipWithFilter(user, models.RelationshipStatus(status)); err != nil {
if friends, err = services.ListRelationshipWithFilter(user.ID, models.RelationshipStatus(status)); err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
}
@ -34,7 +36,7 @@ func getRelationship(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
relatedId, _ := c.ParamsInt("relatedId", 0)
related, err := services.GetAccount(uint(relatedId))
@ -53,7 +55,7 @@ func editRelationship(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
relatedId, _ := c.ParamsInt("relatedId", 0)
var data struct {
@ -85,7 +87,7 @@ func deleteRelationship(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
relatedId, _ := c.ParamsInt("relatedId", 0)
related, err := services.GetAccount(uint(relatedId))
@ -111,7 +113,7 @@ func makeFriendship(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
relatedName := c.Query("related")
relatedId, _ := c.ParamsInt("relatedId", 0)
@ -131,7 +133,14 @@ func makeFriendship(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusBadRequest, "must one of username or user id")
}
friend, err := services.NewFriend(user, related)
var account models.Account
if err := database.C.Where(&models.Account{
BaseModel: models.BaseModel{ID: user.ID},
}).First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
friend, err := services.NewFriend(account, related)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
@ -144,7 +153,7 @@ func makeBlockship(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
relatedName := c.Query("related")
relatedId, _ := c.ParamsInt("relatedId", 0)
@ -164,7 +173,14 @@ func makeBlockship(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusBadRequest, "must one of username or user id")
}
friend, err := services.NewBlockship(user, related)
var account models.Account
if err := database.C.Where(&models.Account{
BaseModel: models.BaseModel{ID: user.ID},
}).First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
friend, err := services.NewBlockship(account, related)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
@ -177,15 +193,22 @@ func acceptFriend(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
relatedId, _ := c.ParamsInt("relatedId", 0)
var account models.Account
if err := database.C.Where(&models.Account{
BaseModel: models.BaseModel{ID: user.ID},
}).First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
related, err := services.GetAccount(uint(relatedId))
if err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
if err := services.HandleFriend(user, related, true); err != nil {
if err := services.HandleFriend(account, related, true); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
services.AddEvent(user.ID, "relationships.friends.accept", strconv.Itoa(relatedId), c.IP(), c.Get(fiber.HeaderUserAgent))
@ -197,7 +220,7 @@ func declineFriend(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
relatedId, _ := c.ParamsInt("relatedId", 0)
related, err := services.GetAccount(uint(relatedId))
@ -205,7 +228,14 @@ func declineFriend(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
if err := services.HandleFriend(user, related, false); err != nil {
var account models.Account
if err := database.C.Where(&models.Account{
BaseModel: models.BaseModel{ID: user.ID},
}).First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
if err := services.HandleFriend(account, related, false); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
services.AddEvent(user.ID, "relationships.friends.decline", strconv.Itoa(relatedId), c.IP(), c.Get(fiber.HeaderUserAgent))

View File

@ -2,8 +2,8 @@ package api
import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
)
@ -11,9 +11,9 @@ func listAbuseReports(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
reports, err := services.ListAbuseReport(user)
reports, err := services.ListAbuseReport(user.ID)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}
@ -58,7 +58,7 @@ func createAbuseReport(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var data struct {
Resource string `json:"resource" validate:"required"`
@ -69,7 +69,7 @@ func createAbuseReport(c *fiber.Ctx) error {
return err
}
report, err := services.NewAbuseReport(data.Resource, data.Reason, user)
report, err := services.NewAbuseReport(data.Resource, data.Reason, user.ID)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
}

View File

@ -4,6 +4,7 @@ import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
)
@ -11,7 +12,7 @@ func getTickets(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
take := c.QueryInt("take", 0)
offset := c.QueryInt("offset", 0)
@ -43,7 +44,7 @@ func killTicket(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
id, _ := c.ParamsInt("ticketId", 0)
if err := database.C.Delete(&models.AuthTicket{}, &models.AuthTicket{

View File

@ -5,6 +5,7 @@ import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/http/exts"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
"strconv"
)
@ -16,7 +17,7 @@ func listDailySignRecord(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var count int64
if err := database.C.
@ -81,9 +82,9 @@ func getTodayDailySign(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
if record, err := services.GetTodayDailySign(user); err != nil {
if record, err := services.GetTodayDailySign(user.ID); err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
} else {
return c.JSON(record)
@ -94,9 +95,9 @@ func doDailySign(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
if record, err := services.DailySign(user); err != nil {
if record, err := services.DailySign(user.ID); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
services.AddEvent(user.ID, "dailySign", strconv.Itoa(int(record.ID)), c.IP(), c.Get(fiber.HeaderUserAgent))

View File

@ -2,6 +2,7 @@ package api
import (
"fmt"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"strconv"
"time"
@ -39,15 +40,22 @@ func getMyselfStatus(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
status, err := services.GetStatus(user.ID)
disturbable := services.GetStatusDisturbable(user.ID) == nil
online := services.GetStatusOnline(user.ID) == nil
var account models.Account
if err := database.C.Where(&models.Account{
BaseModel: models.BaseModel{ID: user.ID},
}).Preload("Profile").First(&account).Error; err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error())
}
return c.JSON(fiber.Map{
"status": lo.Ternary(err == nil, &status, nil),
"last_seen_at": user.Profile.LastSeenAt,
"last_seen_at": account.Profile.LastSeenAt,
"is_disturbable": disturbable,
"is_online": online,
})
@ -57,7 +65,7 @@ func setStatus(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var req struct {
Type string `json:"type" validate:"required"`
@ -88,7 +96,7 @@ func setStatus(c *fiber.Ctx) error {
AccountID: user.ID,
}
if status, err := services.NewStatus(user, status); err != nil {
if status, err := services.NewStatus(user.ID, status); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
services.AddEvent(user.ID, "statuses.set", strconv.Itoa(int(status.ID)), c.IP(), c.Get(fiber.HeaderUserAgent))
@ -100,7 +108,7 @@ func editStatus(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
var req struct {
Type string `json:"type" validate:"required"`
@ -127,7 +135,7 @@ func editStatus(c *fiber.Ctx) error {
status.IsInvisible = req.IsInvisible
status.ClearAt = req.ClearAt
if status, err := services.EditStatus(user, status); err != nil {
if status, err := services.EditStatus(user.ID, status); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else {
services.AddEvent(user.ID, "statuses.edit", strconv.Itoa(int(status.ID)), c.IP(), c.Get(fiber.HeaderUserAgent))
@ -139,9 +147,9 @@ func clearStatus(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil {
return err
}
user := c.Locals("user").(models.Account)
user := c.Locals("user").(*sec.UserInfo)
if err := services.ClearStatus(user); err != nil {
if err := services.ClearStatus(user.ID); err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
services.AddEvent(user.ID, "statuses.clear", strconv.Itoa(int(user.ID)), c.IP(), c.Get(fiber.HeaderUserAgent))

View File

@ -2,13 +2,13 @@ package exts
import (
"fmt"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2"
)
func EnsureAuthenticated(c *fiber.Ctx) error {
if _, ok := c.Locals("user").(models.Account); !ok {
if _, ok := c.Locals("user").(*sec.UserInfo); !ok {
return fiber.NewError(fiber.StatusUnauthorized)
}

View File

@ -56,6 +56,12 @@ func NewServer() *App {
}))
app.Use(sec.ContextMiddleware(IReader))
app.Use(func(c *fiber.Ctx) error {
if user, ok := c.Locals("nex_user").(*sec.UserInfo); ok {
c.Locals("user", user)
}
return c.Next()
})
admin.MapAdminAPIs(app, "/api/admin")
api.MapAPIs(app, "/api")

View File

@ -5,9 +5,9 @@ import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
)
func GetBotCount(user models.Account) (int64, error) {
func GetBotCount(user uint) (int64, error) {
var count int64
if err := database.C.Where("automated_id = ?", user.ID).Count(&count).Error; err != nil {
if err := database.C.Where("automated_id = ?", user).Count(&count).Error; err != nil {
return 0, err
}
return count, nil

View File

@ -21,13 +21,13 @@ func AddEvent(user uint, event, target, ip, ua string) {
}
// AddAuditRecord to keep logs to make administrators' operations clear to query
func AddAuditRecord(operator models.Account, act, ip, ua string, metadata map[string]any) {
func AddAuditRecord(operator uint, act, ip, ua string, metadata map[string]any) {
writeAuditQueue = append(writeAuditQueue, models.AuditRecord{
Action: act,
Metadata: metadata,
IpAddress: ip,
UserAgent: ua,
AccountID: operator.ID,
AccountID: operator,
})
}

View File

@ -1,7 +1,7 @@
package services
import (
"fmt"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"time"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
@ -9,6 +9,9 @@ import (
"github.com/spf13/viper"
)
var EReader *sec.JwtReader
var EWriter *sec.JwtWriter
type PayloadClaims struct {
jwt.RegisteredClaims
@ -66,26 +69,5 @@ func EncodeJwt(id string, typ, sub, sed string, nonce *string, aud []string, exp
claims.Nonce = *nonce
}
tk := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
return tk.SignedString([]byte(viper.GetString("secret")))
}
func DecodeJwt(str string) (PayloadClaims, error) {
var claims PayloadClaims
tk, err := jwt.ParseWithClaims(str, &claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(viper.GetString("secret")), nil
})
if err != nil {
return claims, err
}
if data, ok := tk.Claims.(*PayloadClaims); ok {
return *data, nil
} else {
return claims, fmt.Errorf("unexpected token payload: not payload claims type")
}
return sec.WriteJwt(EWriter, claims)
}

View File

@ -15,21 +15,21 @@ import (
"gorm.io/datatypes"
)
func GetAuthPreference(account models.Account) (models.PreferenceAuth, error) {
func GetAuthPreference(account uint) (models.PreferenceAuth, error) {
var auth models.PreferenceAuth
if err := database.C.Where("account_id = ?", account.ID).First(&auth).Error; err != nil {
if err := database.C.Where("account_id = ?", account).First(&auth).Error; err != nil {
return auth, err
}
return auth, nil
}
func UpdateAuthPreference(account models.Account, config models.AuthConfig) (models.PreferenceAuth, error) {
func UpdateAuthPreference(account uint, config models.AuthConfig) (models.PreferenceAuth, error) {
var auth models.PreferenceAuth
var err error
if auth, err = GetAuthPreference(account); err != nil {
auth = models.PreferenceAuth{
AccountID: account.ID,
AccountID: account,
Config: datatypes.NewJSONType(config),
}
} else {
@ -44,16 +44,16 @@ func GetNotificationPreferenceCacheKey(accountId uint) string {
return fmt.Sprintf("notification-preference#%d", accountId)
}
func GetNotificationPreference(account models.Account) (models.PreferenceNotification, error) {
func GetNotificationPreference(account uint) (models.PreferenceNotification, error) {
var notification models.PreferenceNotification
cacheManager := cache.New[any](localCache.S)
marshal := marshaler.New(cacheManager)
contx := context.Background()
if val, err := marshal.Get(contx, GetNotificationPreferenceCacheKey(account.ID), new(models.PreferenceNotification)); err == nil {
if val, err := marshal.Get(contx, GetNotificationPreferenceCacheKey(account), new(models.PreferenceNotification)); err == nil {
notification = val.(models.PreferenceNotification)
} else {
if err := database.C.Where("account_id = ?", account.ID).First(&notification).Error; err != nil {
if err := database.C.Where("account_id = ?", account).First(&notification).Error; err != nil {
return notification, err
}
CacheNotificationPreference(notification)
@ -76,12 +76,12 @@ func CacheNotificationPreference(prefs models.PreferenceNotification) {
)
}
func UpdateNotificationPreference(account models.Account, config map[string]bool) (models.PreferenceNotification, error) {
func UpdateNotificationPreference(account uint, config map[string]bool) (models.PreferenceNotification, error) {
var notification models.PreferenceNotification
var err error
if notification, err = GetNotificationPreference(account); err != nil {
notification = models.PreferenceNotification{
AccountID: account.ID,
AccountID: account,
Config: lo.MapValues(config, func(v bool, k string) any { return v }),
}
} else {

View File

@ -18,20 +18,20 @@ func ListCommunityRealm() ([]models.Realm, error) {
return realms, nil
}
func ListOwnedRealm(user models.Account) ([]models.Realm, error) {
func ListOwnedRealm(user uint) ([]models.Realm, error) {
var realms []models.Realm
if err := database.C.Where(&models.Realm{AccountID: user.ID}).Find(&realms).Error; err != nil {
if err := database.C.Where(&models.Realm{AccountID: user}).Find(&realms).Error; err != nil {
return realms, err
}
return realms, nil
}
func ListAvailableRealm(user models.Account) ([]models.Realm, error) {
func ListAvailableRealm(user uint) ([]models.Realm, error) {
var realms []models.Realm
var members []models.RealmMember
if err := database.C.Where(&models.RealmMember{
AccountID: user.ID,
AccountID: user,
}).Find(&members).Error; err != nil {
return realms, err
}
@ -57,9 +57,9 @@ func GetRealmWithAlias(alias string) (models.Realm, error) {
return realm, nil
}
func NewRealm(realm models.Realm, user models.Account) (models.Realm, error) {
func NewRealm(realm models.Realm, user uint) (models.Realm, error) {
realm.Members = []models.RealmMember{
{AccountID: user.ID, PowerLevel: 100},
{AccountID: user, PowerLevel: 100},
}
err := database.C.Save(&realm).Error
@ -90,14 +90,14 @@ func GetRealmMember(userId uint, realmId uint) (models.RealmMember, error) {
return member, nil
}
func AddRealmMember(user models.Account, affected models.Account, target models.Realm) error {
func AddRealmMember(user uint, affected models.Account, target models.Realm) error {
if !target.IsPublic && !target.IsCommunity {
if member, err := GetRealmMember(user.ID, target.ID); err != nil {
if member, err := GetRealmMember(user, target.ID); err != nil {
return fmt.Errorf("only realm member can add people: %v", err)
} else if member.PowerLevel < 50 {
return fmt.Errorf("only realm moderator can add people")
}
rel, err := GetRelationWithTwoNode(affected.ID, user.ID)
rel, err := GetRelationWithTwoNode(affected.ID, user)
if err != nil || HasPermNodeWithDefault(
rel.PermNodes,
"RealmAdd",
@ -116,9 +116,9 @@ func AddRealmMember(user models.Account, affected models.Account, target models.
return err
}
func RemoveRealmMember(user models.Account, affected models.Account, target models.Realm) error {
if user.ID != affected.ID {
if member, err := GetRealmMember(user.ID, target.ID); err != nil {
func RemoveRealmMember(user uint, affected models.Account, target models.Realm) error {
if user != affected.ID {
if member, err := GetRealmMember(user, target.ID); err != nil {
return fmt.Errorf("only realm member can remove other member: %v", err)
} else if member.PowerLevel < 50 {
return fmt.Errorf("only realm moderator can invite people")

View File

@ -9,10 +9,10 @@ import (
"gorm.io/gorm"
)
func ListAllRelationship(user models.Account) ([]models.AccountRelationship, error) {
func ListAllRelationship(user uint) ([]models.AccountRelationship, error) {
var relationships []models.AccountRelationship
if err := database.C.
Where("account_id = ?", user.ID).
Where("account_id = ?", user).
Preload("Account").
Preload("Related").
Find(&relationships).Error; err != nil {
@ -22,10 +22,10 @@ func ListAllRelationship(user models.Account) ([]models.AccountRelationship, err
return relationships, nil
}
func ListRelationshipWithFilter(user models.Account, status models.RelationshipStatus) ([]models.AccountRelationship, error) {
func ListRelationshipWithFilter(user uint, status models.RelationshipStatus) ([]models.AccountRelationship, error) {
var relationships []models.AccountRelationship
if err := database.C.
Where("account_id = ? AND status = ?", user.ID, status).
Where("account_id = ? AND status = ?", user, status).
Preload("Account").
Preload("Related").
Find(&relationships).Error; err != nil {

View File

@ -7,10 +7,10 @@ import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
)
func ListAbuseReport(account models.Account) ([]models.AbuseReport, error) {
func ListAbuseReport(account uint) ([]models.AbuseReport, error) {
var reports []models.AbuseReport
err := database.C.
Where("account_id = ?", account.ID).
Where("account_id = ?", account).
Find(&reports).Error
return reports, err
}
@ -53,13 +53,13 @@ func UpdateAbuseReportStatus(id uint, status, message string) error {
return nil
}
func NewAbuseReport(resource string, reason string, account models.Account) (models.AbuseReport, error) {
func NewAbuseReport(resource string, reason string, account uint) (models.AbuseReport, error) {
var report models.AbuseReport
if err := database.C.
Where(
"resource = ? AND account_id = ? AND status IN ?",
resource,
account.ID,
account,
[]string{models.ReportStatusPending, models.ReportStatusReviewing},
).First(&report).Error; err == nil {
return report, fmt.Errorf("you already reported this resource and it still in process")
@ -68,7 +68,7 @@ func NewAbuseReport(resource string, reason string, account models.Account) (mod
report = models.AbuseReport{
Resource: resource,
Reason: reason,
AccountID: account.ID,
AccountID: account,
}
err := database.C.Create(&report).Error

View File

@ -11,11 +11,11 @@ import (
"time"
)
func CheckDailyCanSign(user models.Account) error {
func CheckDailyCanSign(user uint) error {
probe := time.Now().Format("2006-01-02")
var record models.SignRecord
if err := database.C.Where("account_id = ? AND created_at::date = ?", user.ID, probe).First(&record).Error; err != nil {
if err := database.C.Where("account_id = ? AND created_at::date = ?", user, probe).First(&record).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil
}
@ -24,22 +24,22 @@ func CheckDailyCanSign(user models.Account) error {
return fmt.Errorf("daliy sign record exists")
}
func GetTodayDailySign(user models.Account) (models.SignRecord, error) {
func GetTodayDailySign(user uint) (models.SignRecord, error) {
probe := time.Now().Format("2006-01-02")
var record models.SignRecord
if err := database.C.Where("account_id = ? AND created_at::date = ?", user.ID, probe).First(&record).Error; err != nil {
if err := database.C.Where("account_id = ? AND created_at::date = ?", user, probe).First(&record).Error; err != nil {
return record, fmt.Errorf("unable get daliy sign record: %v", err)
}
return record, nil
}
func DailySign(user models.Account) (models.SignRecord, error) {
func DailySign(user uint) (models.SignRecord, error) {
tier := rand.Intn(5)
record := models.SignRecord{
ResultTier: tier,
ResultExperience: rand.Intn(int(math.Max(float64(tier), 1)*100)+1-100) + 100,
AccountID: user.ID,
AccountID: user,
}
if err := CheckDailyCanSign(user); err != nil {
@ -47,7 +47,7 @@ func DailySign(user models.Account) (models.SignRecord, error) {
}
var profile models.AccountProfile
if err := database.C.Where("account_id = ?", user.ID).First(&profile).Error; err != nil {
if err := database.C.Where("account_id = ?", user).First(&profile).Error; err != nil {
return record, fmt.Errorf("unable get account profile: %v", err)
} else {
profile.Experience += uint64(record.ResultExperience)

View File

@ -98,27 +98,27 @@ func GetStatusOnline(uid uint) error {
}
}
func NewStatus(user models.Account, status models.Status) (models.Status, error) {
func NewStatus(user uint, status models.Status) (models.Status, error) {
if err := database.C.Save(&status).Error; err != nil {
return status, err
} else {
CacheUserStatus(user.ID, status)
CacheUserStatus(user, status)
}
return status, nil
}
func EditStatus(user models.Account, status models.Status) (models.Status, error) {
func EditStatus(user uint, status models.Status) (models.Status, error) {
if err := database.C.Save(&status).Error; err != nil {
return status, err
} else {
CacheUserStatus(user.ID, status)
CacheUserStatus(user, status)
}
return status, nil
}
func ClearStatus(user models.Account) error {
func ClearStatus(user uint) error {
if err := database.C.
Where("account_id = ?", user.ID).
Where("account_id = ?", user).
Where("clear_at > ?", time.Now()).
Updates(models.Status{ClearAt: lo.ToPtr(time.Now())}).Error; err != nil {
return err
@ -127,7 +127,7 @@ func ClearStatus(user models.Account) error {
marshal := marshaler.New(cacheManager)
contx := context.Background()
marshal.Delete(contx, GetStatusCacheKey(user.ID))
marshal.Delete(contx, GetStatusCacheKey(user))
}
return nil

View File

@ -57,7 +57,7 @@ func NewTicket(user models.Account, ip, ua string) (models.AuthTicket, error) {
} else {
steps = min(steps, int(count))
cfg, err := GetAuthPreference(user)
cfg, err := GetAuthPreference(user.ID)
if err == nil && cfg.Config.Data().MaximumAuthSteps >= 1 {
steps = min(steps, cfg.Config.Data().MaximumAuthSteps)
}

View File

@ -2,6 +2,7 @@ package services
import (
"fmt"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"strconv"
"time"
@ -102,7 +103,7 @@ func RefreshToken(token string) (atk, rtk string, err error) {
var ticket models.AuthTicket
var claims PayloadClaims
if claims, err = DecodeJwt(token); err != nil {
if claims, err = sec.ReadJwt[PayloadClaims](EReader, token); err != nil {
return
} else if claims.Type != JwtRefreshType {
err = fmt.Errorf("invalid token type, expected refresh token")

View File

@ -58,6 +58,18 @@ func main() {
http.IReader = reader
log.Info().Msg("Internal jwt public key loaded.")
}
if reader, err := sec.NewJwtReader(viper.GetString("security.public_key")); err != nil {
log.Error().Err(err).Msg("An error occurred when reading public key for jwt. Signing token may not work.")
} else {
services.EReader = reader
log.Info().Msg("Jwt public key loaded.")
}
if writer, err := sec.NewJwtWriter(viper.GetString("security.private_key")); err != nil {
log.Error().Err(err).Msg("An error occurred when reading private key for jwt. Signing token may not work.")
} else {
services.EWriter = writer
log.Info().Msg("Jwt private key loaded.")
}
// Connect to database
if err := database.NewGorm(); err != nil {