From 8fbb79607b770a3df7a678e77b8036e7c2c1a4d2 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Wed, 30 Oct 2024 23:26:13 +0800 Subject: [PATCH] :recycle: Move models.Account to sec.UserInfo --- .idea/workspace.xml | 127 ++++++++++----------- go.sum | 10 -- pkg/internal/gap/server.go | 11 +- pkg/internal/grpc/realms.go | 4 +- pkg/internal/http/admin/notify_api.go | 9 +- pkg/internal/http/admin/permissions_api.go | 5 +- pkg/internal/http/admin/users_api.go | 5 +- pkg/internal/http/api/accounts_api.go | 18 ++- pkg/internal/http/api/avatar_api.go | 32 ++++-- pkg/internal/http/api/bot_token_api.go | 21 ++-- pkg/internal/http/api/bots_api.go | 19 ++- pkg/internal/http/api/index.go | 3 - pkg/internal/http/api/notifications_api.go | 21 ++-- pkg/internal/http/api/notify_api.go | 3 +- pkg/internal/http/api/oauth_api.go | 15 ++- pkg/internal/http/api/preferences_api.go | 17 +-- pkg/internal/http/api/realm_members_api.go | 15 +-- pkg/internal/http/api/realms_api.go | 17 +-- pkg/internal/http/api/relationships_api.go | 58 +++++++--- pkg/internal/http/api/reports_api.go | 10 +- pkg/internal/http/api/security_api.go | 5 +- pkg/internal/http/api/sign_api.go | 11 +- pkg/internal/http/api/statuses_api.go | 24 ++-- pkg/internal/http/exts/auth.go | 4 +- pkg/internal/http/server.go | 6 + pkg/internal/services/bots.go | 4 +- pkg/internal/services/events.go | 4 +- pkg/internal/services/jwt.go | 28 +---- pkg/internal/services/preferences.go | 18 +-- pkg/internal/services/realms.go | 24 ++-- pkg/internal/services/relationships.go | 8 +- pkg/internal/services/reports.go | 10 +- pkg/internal/services/sign.go | 14 +-- pkg/internal/services/statuses.go | 14 +-- pkg/internal/services/ticket.go | 2 +- pkg/internal/services/ticket_token.go | 3 +- pkg/main.go | 12 ++ settings.toml | 7 +- 38 files changed, 346 insertions(+), 272 deletions(-) diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 27d67c3..6e686be 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -4,51 +4,44 @@ - @@ -221,7 +213,8 @@ - true diff --git a/go.sum b/go.sum index ad80605..4b49961 100644 --- a/go.sum +++ b/go.sum @@ -33,8 +33,6 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9 dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -git.solsynth.dev/hypernet/nexus v0.0.0-20241024155238-421834ae5c4a h1:yl2cnfFvvgOGwr9qoWu4QQHVpVPCI9f1idyaKt2gXxo= -git.solsynth.dev/hypernet/nexus v0.0.0-20241024155238-421834ae5c4a/go.mod h1:68l4+CkuG3sz9aiUhbN5tq3YHrt6KUNK9FIWaGuWCdc= git.solsynth.dev/hypernet/nexus v0.0.0-20241026162044-3d487fa48baf h1:Fil1ASTvxmqFySD3OoptC7uRXEYpWLwLfjlkWZNNwVQ= git.solsynth.dev/hypernet/nexus v0.0.0-20241026162044-3d487fa48baf/go.mod h1:fXQsHXGio+7/0U95IitKF07wS4yTdCMp5ms8wpFBwVI= git.solsynth.dev/hypernet/pusher v0.0.0-20241026153052-cd2c326efa4e h1:DtHhMjgxS/spUt/KEdbRFtaVnepI6Vx8pbHdJaNH1hs= @@ -254,16 +252,10 @@ github.com/hashicorp/serf v0.10.1/go.mod h1:yL2t6BqATOLGc5HF7qbFkTfXoPIY0WZdWHfE github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 h1:L0QtFUgDarD7Fpv9jeVMgy/+Ec0mtnmYuImjTz6dtDA= -github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw= -github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A= github.com/jackc/pgx/v5 v5.7.1 h1:x7SYsPBYDkHDksogeSmZZ5xzThcTgRz++I5E+ePFUcs= github.com/jackc/pgx/v5 v5.7.1/go.mod h1:e7O26IywZZ+naJtWWos6i6fvWK+29etgITqrqHLfoZA= -github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= -github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= @@ -795,8 +787,6 @@ gorm.io/datatypes v1.2.4 h1:uZmGAcK/QZ0uyfCuVg0VQY1ZmV9h1fuG0tMwKByO1z4= gorm.io/datatypes v1.2.4/go.mod h1:f4BsLcFAX67szSv8svwLRjklArSHAvHLeE3pXAS5DZI= gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo= gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= -gorm.io/driver/postgres v1.5.4 h1:Iyrp9Meh3GmbSuyIAGyjkN+n9K+GHX9b9MqsTL4EJCo= -gorm.io/driver/postgres v1.5.4/go.mod h1:Bgo89+h0CRcdA33Y6frlaHHVuTdOf87pmyzwW9C/BH0= gorm.io/driver/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8= gorm.io/driver/postgres v1.5.9/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI= gorm.io/driver/sqlite v1.4.3 h1:HBBcZSDnWi5BW3B3rwvVTc510KGkBkexlOg0QrmLUuU= diff --git a/pkg/internal/gap/server.go b/pkg/internal/gap/server.go index ce830f2..9996e32 100644 --- a/pkg/internal/gap/server.go +++ b/pkg/internal/gap/server.go @@ -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() { diff --git a/pkg/internal/grpc/realms.go b/pkg/internal/grpc/realms.go index fa1ad6e..53eb106 100644 --- a/pkg/internal/grpc/realms.go +++ b/pkg/internal/grpc/realms.go @@ -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 } diff --git a/pkg/internal/http/admin/notify_api.go b/pkg/internal/http/admin/notify_api.go index 12e70f3..6165f8b 100644 --- a/pkg/internal/http/admin/notify_api.go +++ b/pkg/internal/http/admin/notify_api.go @@ -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, }) diff --git a/pkg/internal/http/admin/permissions_api.go b/pkg/internal/http/admin/permissions_api.go index 927edb4..a3e9c06 100644 --- a/pkg/internal/http/admin/permissions_api.go +++ b/pkg/internal/http/admin/permissions_api.go @@ -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, diff --git a/pkg/internal/http/admin/users_api.go b/pkg/internal/http/admin/users_api.go index cdd22bf..7e4811c 100644 --- a/pkg/internal/http/admin/users_api.go +++ b/pkg/internal/http/admin/users_api.go @@ -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, }) } diff --git a/pkg/internal/http/api/accounts_api.go b/pkg/internal/http/api/accounts_api.go index fcae350..6298480 100644 --- a/pkg/internal/http/api/accounts_api.go +++ b/pkg/internal/http/api/accounts_api.go @@ -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()) } diff --git a/pkg/internal/http/api/avatar_api.go b/pkg/internal/http/api/avatar_api.go index 7be6833..b661945 100644 --- a/pkg/internal/http/api/avatar_api.go +++ b/pkg/internal/http/api/avatar_api.go @@ -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) diff --git a/pkg/internal/http/api/bot_token_api.go b/pkg/internal/http/api/bot_token_api.go index b6d6b5c..291720b 100644 --- a/pkg/internal/http/api/bot_token_api.go +++ b/pkg/internal/http/api/bot_token_api.go @@ -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) diff --git a/pkg/internal/http/api/bots_api.go b/pkg/internal/http/api/bots_api.go index ea6be10..80a916e 100644 --- a/pkg/internal/http/api/bots_api.go +++ b/pkg/internal/http/api/bots_api.go @@ -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) diff --git a/pkg/internal/http/api/index.go b/pkg/internal/http/api/index.go index 78b0365..e10e8f5 100644 --- a/pkg/internal/http/api/index.go +++ b/pkg/internal/http/api/index.go @@ -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) diff --git a/pkg/internal/http/api/notifications_api.go b/pkg/internal/http/api/notifications_api.go index b6ddb1c..b0ebd74 100644 --- a/pkg/internal/http/api/notifications_api.go +++ b/pkg/internal/http/api/notifications_api.go @@ -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") diff --git a/pkg/internal/http/api/notify_api.go b/pkg/internal/http/api/notify_api.go index 03b73c9..03012d7 100644 --- a/pkg/internal/http/api/notify_api.go +++ b/pkg/internal/http/api/notify_api.go @@ -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"` diff --git a/pkg/internal/http/api/oauth_api.go b/pkg/internal/http/api/oauth_api.go index 04cd938..9c1e76a 100755 --- a/pkg/internal/http/api/oauth_api.go +++ b/pkg/internal/http/api/oauth_api.go @@ -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}, diff --git a/pkg/internal/http/api/preferences_api.go b/pkg/internal/http/api/preferences_api.go index 34bd73c..3a28b00 100644 --- a/pkg/internal/http/api/preferences_api.go +++ b/pkg/internal/http/api/preferences_api.go @@ -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 { diff --git a/pkg/internal/http/api/realm_members_api.go b/pkg/internal/http/api/realm_members_api.go index f8793c5..2ef8595 100644 --- a/pkg/internal/http/api/realm_members_api.go +++ b/pkg/internal/http/api/realm_members_api.go @@ -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) diff --git a/pkg/internal/http/api/realms_api.go b/pkg/internal/http/api/realms_api.go index ef0d39b..9d514ab 100644 --- a/pkg/internal/http/api/realms_api.go +++ b/pkg/internal/http/api/realms_api.go @@ -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 diff --git a/pkg/internal/http/api/relationships_api.go b/pkg/internal/http/api/relationships_api.go index bc5be5c..69b07dc 100644 --- a/pkg/internal/http/api/relationships_api.go +++ b/pkg/internal/http/api/relationships_api.go @@ -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)) diff --git a/pkg/internal/http/api/reports_api.go b/pkg/internal/http/api/reports_api.go index 1cae138..133ac40 100644 --- a/pkg/internal/http/api/reports_api.go +++ b/pkg/internal/http/api/reports_api.go @@ -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()) } diff --git a/pkg/internal/http/api/security_api.go b/pkg/internal/http/api/security_api.go index fdb624b..9a74a88 100644 --- a/pkg/internal/http/api/security_api.go +++ b/pkg/internal/http/api/security_api.go @@ -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{ diff --git a/pkg/internal/http/api/sign_api.go b/pkg/internal/http/api/sign_api.go index 1747878..708d9e2 100644 --- a/pkg/internal/http/api/sign_api.go +++ b/pkg/internal/http/api/sign_api.go @@ -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)) diff --git a/pkg/internal/http/api/statuses_api.go b/pkg/internal/http/api/statuses_api.go index 2002131..3a0f8ee 100644 --- a/pkg/internal/http/api/statuses_api.go +++ b/pkg/internal/http/api/statuses_api.go @@ -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)) diff --git a/pkg/internal/http/exts/auth.go b/pkg/internal/http/exts/auth.go index a13a134..b4d911f 100644 --- a/pkg/internal/http/exts/auth.go +++ b/pkg/internal/http/exts/auth.go @@ -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) } diff --git a/pkg/internal/http/server.go b/pkg/internal/http/server.go index ea53d08..09bfc72 100644 --- a/pkg/internal/http/server.go +++ b/pkg/internal/http/server.go @@ -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") diff --git a/pkg/internal/services/bots.go b/pkg/internal/services/bots.go index 695a208..5440f08 100644 --- a/pkg/internal/services/bots.go +++ b/pkg/internal/services/bots.go @@ -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 diff --git a/pkg/internal/services/events.go b/pkg/internal/services/events.go index fcfbc4e..b3ba2b7 100644 --- a/pkg/internal/services/events.go +++ b/pkg/internal/services/events.go @@ -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, }) } diff --git a/pkg/internal/services/jwt.go b/pkg/internal/services/jwt.go index 00365e1..04506f6 100644 --- a/pkg/internal/services/jwt.go +++ b/pkg/internal/services/jwt.go @@ -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) } diff --git a/pkg/internal/services/preferences.go b/pkg/internal/services/preferences.go index 639d592..8242c0d 100644 --- a/pkg/internal/services/preferences.go +++ b/pkg/internal/services/preferences.go @@ -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(¬ification).Error; err != nil { + if err := database.C.Where("account_id = ?", account).First(¬ification).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 { diff --git a/pkg/internal/services/realms.go b/pkg/internal/services/realms.go index 5a894e9..8016e1b 100644 --- a/pkg/internal/services/realms.go +++ b/pkg/internal/services/realms.go @@ -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") diff --git a/pkg/internal/services/relationships.go b/pkg/internal/services/relationships.go index 995ba7f..cfd1d13 100644 --- a/pkg/internal/services/relationships.go +++ b/pkg/internal/services/relationships.go @@ -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 { diff --git a/pkg/internal/services/reports.go b/pkg/internal/services/reports.go index dab89c1..32f18ac 100644 --- a/pkg/internal/services/reports.go +++ b/pkg/internal/services/reports.go @@ -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 diff --git a/pkg/internal/services/sign.go b/pkg/internal/services/sign.go index aa0a17d..b0fffac 100644 --- a/pkg/internal/services/sign.go +++ b/pkg/internal/services/sign.go @@ -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) diff --git a/pkg/internal/services/statuses.go b/pkg/internal/services/statuses.go index 54642fe..2cd8bfe 100644 --- a/pkg/internal/services/statuses.go +++ b/pkg/internal/services/statuses.go @@ -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 diff --git a/pkg/internal/services/ticket.go b/pkg/internal/services/ticket.go index 05eff18..64bd981 100644 --- a/pkg/internal/services/ticket.go +++ b/pkg/internal/services/ticket.go @@ -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) } diff --git a/pkg/internal/services/ticket_token.go b/pkg/internal/services/ticket_token.go index 9603d2f..487c838 100644 --- a/pkg/internal/services/ticket_token.go +++ b/pkg/internal/services/ticket_token.go @@ -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") diff --git a/pkg/main.go b/pkg/main.go index c246613..7534429 100644 --- a/pkg/main.go +++ b/pkg/main.go @@ -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 { diff --git a/settings.toml b/settings.toml index b561e64..5dae74c 100644 --- a/settings.toml +++ b/settings.toml @@ -20,9 +20,8 @@ database = false print_routes = false [security] -issuer = "https://solsynth.dev" -cookie_domain = "localhost" -cookie_samesite = "Lax" -access_token_duration = 300 +access_token_duration = 3000 refresh_token_duration = 2592000 +public_key = "keys/public_key.pem" +private_key = "keys/private_key.pem" internal_public_key = "keys/internal_public_key.pem"