♻️ Refactored more modules into nexus

This commit is contained in:
LittleSheep 2024-10-24 00:46:59 +08:00
parent b4fb7b53af
commit 4c44af74b5
15 changed files with 80 additions and 144 deletions

1
.gitignore vendored
View File

@ -1,4 +1,5 @@
/dist /dist
/uploads /uploads
/keys
.DS_Store .DS_Store

View File

@ -4,26 +4,18 @@
<option name="autoReloadType" value="ALL" /> <option name="autoReloadType" value="ALL" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="3fefb2c4-b6f9-466b-a523-53352e8d6f95" name="更改" comment=":bug: Trying to fix panic"> <list default="true" id="3fefb2c4-b6f9-466b-a523-53352e8d6f95" name="更改" comment=":recycle: Remove most of the dealer deps and move to nexus">
<change afterPath="$PROJECT_DIR$/pkg/proto/notify.proto" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gitignore" beforeDir="false" afterPath="$PROJECT_DIR$/.gitignore" afterDir="false" />
<change afterPath="$PROJECT_DIR$/pkg/proto/realm.proto" afterDir="false" />
<change afterPath="$PROJECT_DIR$/pkg/proto/record.proto" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/go.mod" beforeDir="false" afterPath="$PROJECT_DIR$/go.mod" afterDir="false" /> <change beforePath="$PROJECT_DIR$/go.mod" beforeDir="false" afterPath="$PROJECT_DIR$/go.mod" afterDir="false" />
<change beforePath="$PROJECT_DIR$/go.sum" beforeDir="false" afterPath="$PROJECT_DIR$/go.sum" afterDir="false" /> <change beforePath="$PROJECT_DIR$/go.sum" beforeDir="false" afterPath="$PROJECT_DIR$/go.sum" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/database/source.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/database/source.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/gap/server.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/gap/server.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/grpc/auth.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/auth.go" afterDir="false" /> <change beforePath="$PROJECT_DIR$/pkg/internal/grpc/auth.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/auth.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/grpc/events.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/events.go" afterDir="false" /> <change beforePath="$PROJECT_DIR$/pkg/internal/server/api/auth_api.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/server/api/auth_api.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/grpc/notifier.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/notifier.go" afterDir="false" /> <change beforePath="$PROJECT_DIR$/pkg/internal/server/exts/auth.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/server/exts/auth.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/grpc/realms.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/realms.go" afterDir="false" /> <change beforePath="$PROJECT_DIR$/pkg/internal/server/server.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/server/server.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/grpc/server.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/server.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/grpc/stream.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/stream.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/server/exts/cookies.go" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/accounts.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/accounts.go" afterDir="false" /> <change beforePath="$PROJECT_DIR$/pkg/internal/services/accounts.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/accounts.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/auth.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/auth.go" afterDir="false" /> <change beforePath="$PROJECT_DIR$/pkg/internal/services/auth.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/auth.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/factors.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/factors.go" afterDir="false" /> <change beforePath="$PROJECT_DIR$/pkg/internal/services/factors.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/factors.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/notifications.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/notifications.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/statuses.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/statuses.go" afterDir="false" /> <change beforePath="$PROJECT_DIR$/pkg/internal/services/statuses.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/statuses.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/tokens.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/tokens.go" afterDir="false" /> <change beforePath="$PROJECT_DIR$/pkg/internal/services/tokens.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/tokens.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/main.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/main.go" afterDir="false" /> <change beforePath="$PROJECT_DIR$/pkg/main.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/main.go" afterDir="false" />
@ -75,7 +67,7 @@
"git-widget-placeholder": "refactor/nexus", "git-widget-placeholder": "refactor/nexus",
"go.import.settings.migrated": "true", "go.import.settings.migrated": "true",
"go.sdk.automatically.set": "true", "go.sdk.automatically.set": "true",
"last_opened_file_path": "/Users/littlesheep/Documents/Projects/Hydrogen/Passport/pkg/proto", "last_opened_file_path": "/Users/littlesheep/Documents/Projects/Hydrogen/Passport/keys",
"node.js.detected.package.eslint": "true", "node.js.detected.package.eslint": "true",
"node.js.selected.package.eslint": "(autodetect)", "node.js.selected.package.eslint": "(autodetect)",
"nodejs_package_manager_path": "npm", "nodejs_package_manager_path": "npm",
@ -92,11 +84,11 @@
}]]></component> }]]></component>
<component name="RecentsManager"> <component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS"> <key name="CopyFile.RECENT_KEYS">
<recent name="$PROJECT_DIR$/keys" />
<recent name="$PROJECT_DIR$/pkg/proto" /> <recent name="$PROJECT_DIR$/pkg/proto" />
<recent name="$PROJECT_DIR$/web/src/components/admin" /> <recent name="$PROJECT_DIR$/web/src/components/admin" />
<recent name="$PROJECT_DIR$/web/src/views" /> <recent name="$PROJECT_DIR$/web/src/views" />
<recent name="$PROJECT_DIR$/pkg/internal/server/api" /> <recent name="$PROJECT_DIR$/pkg/internal/server/api" />
<recent name="$PROJECT_DIR$/web" />
</key> </key>
<key name="MoveFile.RECENT_KEYS"> <key name="MoveFile.RECENT_KEYS">
<recent name="$PROJECT_DIR$/web/src/views/flow" /> <recent name="$PROJECT_DIR$/web/src/views/flow" />
@ -174,7 +166,6 @@
</option> </option>
</component> </component>
<component name="VcsManagerConfiguration"> <component name="VcsManagerConfiguration">
<MESSAGE value=":sparkles: Daily signs" />
<MESSAGE value=":bug: Fix daily check issue" /> <MESSAGE value=":bug: Fix daily check issue" />
<MESSAGE value=":sparkles: Can get today's daily sign record" /> <MESSAGE value=":sparkles: Can get today's daily sign record" />
<MESSAGE value=":bug: Fix auto maintain range missing models" /> <MESSAGE value=":bug: Fix auto maintain range missing models" />
@ -199,7 +190,8 @@
<MESSAGE value=":bug: Fix notification order" /> <MESSAGE value=":bug: Fix notification order" />
<MESSAGE value=":bug: Fix notification order... again" /> <MESSAGE value=":bug: Fix notification order... again" />
<MESSAGE value=":bug: Trying to fix panic" /> <MESSAGE value=":bug: Trying to fix panic" />
<option name="LAST_COMMIT_MESSAGE" value=":bug: Trying to fix panic" /> <MESSAGE value=":recycle: Remove most of the dealer deps and move to nexus" />
<option name="LAST_COMMIT_MESSAGE" value=":recycle: Remove most of the dealer deps and move to nexus" />
</component> </component>
<component name="VgoProject"> <component name="VgoProject">
<settings-migrated>true</settings-migrated> <settings-migrated>true</settings-migrated>

5
go.mod
View File

@ -6,7 +6,7 @@ toolchain go1.23.2
require ( require (
git.solsynth.dev/hydrogen/dealer v0.0.0-20241015165700-60e4bbfd9782 git.solsynth.dev/hydrogen/dealer v0.0.0-20241015165700-60e4bbfd9782
git.solsynth.dev/hypernet/nexus v0.0.0-20241022152358-a1412acc9084 git.solsynth.dev/hypernet/nexus v0.0.0-20241023163829-f51b22f0e880
github.com/dgraph-io/ristretto v0.1.1 github.com/dgraph-io/ristretto v0.1.1
github.com/eko/gocache/lib/v4 v4.1.6 github.com/eko/gocache/lib/v4 v4.1.6
github.com/eko/gocache/store/ristretto/v4 v4.2.2 github.com/eko/gocache/store/ristretto/v4 v4.2.2
@ -22,6 +22,7 @@ require (
github.com/sujit-baniya/flash v0.1.8 github.com/sujit-baniya/flash v0.1.8
golang.org/x/crypto v0.28.0 golang.org/x/crypto v0.28.0
google.golang.org/grpc v1.67.1 google.golang.org/grpc v1.67.1
google.golang.org/protobuf v1.35.1
gorm.io/datatypes v1.2.4 gorm.io/datatypes v1.2.4
gorm.io/driver/postgres v1.5.4 gorm.io/driver/postgres v1.5.4
gorm.io/gorm v1.25.12 gorm.io/gorm v1.25.12
@ -41,6 +42,7 @@ require (
github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-sql-driver/mysql v1.8.1 // indirect github.com/go-sql-driver/mysql v1.8.1 // indirect
github.com/goccy/go-json v0.10.3 // indirect
github.com/golang/glog v1.2.2 // indirect github.com/golang/glog v1.2.2 // indirect
github.com/golang/mock v1.6.0 // indirect github.com/golang/mock v1.6.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect github.com/golang/protobuf v1.5.4 // indirect
@ -101,7 +103,6 @@ require (
golang.org/x/sys v0.26.0 // indirect golang.org/x/sys v0.26.0 // indirect
golang.org/x/text v0.19.0 // indirect golang.org/x/text v0.19.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 // indirect
google.golang.org/protobuf v1.35.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/mysql v1.5.7 // indirect gorm.io/driver/mysql v1.5.7 // indirect

4
go.sum
View File

@ -37,6 +37,8 @@ git.solsynth.dev/hydrogen/dealer v0.0.0-20241015165700-60e4bbfd9782 h1:HUgt8RmDp
git.solsynth.dev/hydrogen/dealer v0.0.0-20241015165700-60e4bbfd9782/go.mod h1:Q51JPkKnV0UoOT/IRmdBh5CyfSlp7s8BRGzgooYHqkI= git.solsynth.dev/hydrogen/dealer v0.0.0-20241015165700-60e4bbfd9782/go.mod h1:Q51JPkKnV0UoOT/IRmdBh5CyfSlp7s8BRGzgooYHqkI=
git.solsynth.dev/hypernet/nexus v0.0.0-20241022152358-a1412acc9084 h1:e+G3H8Hrzk3VaYwbppxIXATq8I4u/5K/g4BkqWv2L2Y= git.solsynth.dev/hypernet/nexus v0.0.0-20241022152358-a1412acc9084 h1:e+G3H8Hrzk3VaYwbppxIXATq8I4u/5K/g4BkqWv2L2Y=
git.solsynth.dev/hypernet/nexus v0.0.0-20241022152358-a1412acc9084/go.mod h1:BKF6Fv/TdfMaxiRHoLjT5AxTsbVBU6VKAZbWxGAMxe4= git.solsynth.dev/hypernet/nexus v0.0.0-20241022152358-a1412acc9084/go.mod h1:BKF6Fv/TdfMaxiRHoLjT5AxTsbVBU6VKAZbWxGAMxe4=
git.solsynth.dev/hypernet/nexus v0.0.0-20241023163829-f51b22f0e880 h1:l6IKIMfm0XRHQSrCoTVQTrOoE3NxIhd+h/OodXGSz3g=
git.solsynth.dev/hypernet/nexus v0.0.0-20241023163829-f51b22f0e880/go.mod h1:BKF6Fv/TdfMaxiRHoLjT5AxTsbVBU6VKAZbWxGAMxe4=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
@ -126,6 +128,8 @@ github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gofiber/fiber/v2 v2.36.0/go.mod h1:tgCr+lierLwLoVHHO/jn3Niannv34WRkQETU8wiL9fQ= github.com/gofiber/fiber/v2 v2.36.0/go.mod h1:tgCr+lierLwLoVHHO/jn3Niannv34WRkQETU8wiL9fQ=
github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo= github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo=

View File

@ -2,6 +2,7 @@ package grpc
import ( import (
"context" "context"
"git.solsynth.dev/hypernet/nexus/pkg/nex"
"git.solsynth.dev/hydrogen/passport/pkg/internal/database" "git.solsynth.dev/hydrogen/passport/pkg/internal/database"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models" "git.solsynth.dev/hydrogen/passport/pkg/internal/models"
@ -18,44 +19,24 @@ type authenticateServer struct {
} }
func (v *Server) Authenticate(_ context.Context, in *proto.AuthRequest) (*proto.AuthReply, error) { func (v *Server) Authenticate(_ context.Context, in *proto.AuthRequest) (*proto.AuthReply, error) {
ctx, perms, atk, rtk, err := services.Authenticate(in.GetAccessToken(), in.GetRefreshToken(), 0) ticket, perms, err := services.Authenticate(uint(in.GetSessionId()))
if err != nil { if err != nil {
return &proto.AuthReply{ return &proto.AuthReply{
IsValid: false, IsValid: false,
}, nil }, nil
} else { } else {
user := ctx.Account user := ticket.Account
rawPerms, _ := jsoniter.Marshal(perms)
userinfo := &proto.UserInfo{ userinfo := &proto.UserInfo{
Id: uint64(user.ID), Id: uint64(user.ID),
Name: user.Name, Name: user.Name,
Nick: user.Nick, PermNodes: nex.EncodeMap(perms),
Email: user.GetPrimaryEmail().Content, Metadata: nex.EncodeMap(user),
Description: &user.Description,
}
if user.Avatar != nil {
userinfo.Avatar = *user.GetAvatar()
}
if user.Banner != nil {
userinfo.Banner = *user.GetBanner()
}
if user.AffiliatedID != nil {
userinfo.AffiliatedTo = lo.ToPtr(uint64(*user.AffiliatedID))
}
if user.AutomatedID != nil {
userinfo.AutomatedBy = lo.ToPtr(uint64(*user.AutomatedID))
} }
return &proto.AuthReply{ return &proto.AuthReply{
IsValid: true, IsValid: true,
Info: &proto.AuthInfo{ Info: &proto.AuthInfo{
NewAccessToken: &atk, SessionId: uint64(ticket.ID),
NewRefreshToken: &rtk,
Permissions: rawPerms,
TicketId: uint64(ctx.Ticket.ID),
Info: userinfo, Info: userinfo,
}, },
}, nil }, nil
@ -63,11 +44,7 @@ func (v *Server) Authenticate(_ context.Context, in *proto.AuthRequest) (*proto.
} }
func (v *Server) EnsurePermGranted(_ context.Context, in *proto.CheckPermRequest) (*proto.CheckPermResponse, error) { func (v *Server) EnsurePermGranted(_ context.Context, in *proto.CheckPermRequest) (*proto.CheckPermResponse, error) {
claims, err := services.DecodeJwt(in.GetToken()) ctx, err := services.GetAuthContext(uint(in.GetSessionId()))
if err != nil {
return nil, err
}
ctx, err := services.GetAuthContext(claims.ID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -78,7 +55,7 @@ func (v *Server) EnsurePermGranted(_ context.Context, in *proto.CheckPermRequest
var value any var value any
_ = jsoniter.Unmarshal(in.GetValue(), &value) _ = jsoniter.Unmarshal(in.GetValue(), &value)
perms := services.FilterPermNodes(heldPerms, ctx.Ticket.Claims) perms := services.FilterPermNodes(heldPerms, ctx.Claims)
valid := services.HasPermNode(perms, in.GetKey(), value) valid := services.HasPermNode(perms, in.GetKey(), value)
return &proto.CheckPermResponse{ return &proto.CheckPermResponse{
@ -120,18 +97,10 @@ func (v *Server) ListUserFriends(_ context.Context, in *proto.ListUserRelativeRe
} }
return &proto.ListUserRelativeResponse{ return &proto.ListUserRelativeResponse{
Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.SimpleUserInfo { Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.UserInfo {
val := &proto.SimpleUserInfo{ val := &proto.UserInfo{
Id: uint64(item.AccountID), Id: uint64(item.AccountID),
Name: item.Account.Name, Name: item.Account.Name,
Nick: item.Account.Nick,
}
if item.Account.AffiliatedID != nil {
val.AffiliatedTo = lo.ToPtr(uint64(*item.Account.AffiliatedID))
}
if item.Account.AutomatedID != nil {
val.AutomatedBy = lo.ToPtr(uint64(*item.Account.AutomatedID))
} }
return val return val
@ -154,18 +123,10 @@ func (v *Server) ListUserBlocklist(_ context.Context, in *proto.ListUserRelative
} }
return &proto.ListUserRelativeResponse{ return &proto.ListUserRelativeResponse{
Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.SimpleUserInfo { Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.UserInfo {
val := &proto.SimpleUserInfo{ val := &proto.UserInfo{
Id: uint64(item.AccountID), Id: uint64(item.AccountID),
Name: item.Account.Name, Name: item.Account.Name,
Nick: item.Account.Nick,
}
if item.Account.AffiliatedID != nil {
val.AffiliatedTo = lo.ToPtr(uint64(*item.Account.AffiliatedID))
}
if item.Account.AutomatedID != nil {
val.AutomatedBy = lo.ToPtr(uint64(*item.Account.AutomatedID))
} }
return val return val

View File

@ -151,8 +151,6 @@ func getToken(c *fiber.Ctx) error {
idk = atk idk = atk
} }
exts.SetAuthCookies(c, atk, rtk)
return c.JSON(fiber.Map{ return c.JSON(fiber.Map{
"id_token": idk, "id_token": idk,
"access_token": atk, "access_token": atk,

View File

@ -2,40 +2,11 @@ package exts
import ( import (
"fmt" "fmt"
"git.solsynth.dev/hydrogen/dealer/pkg/hyper"
"git.solsynth.dev/hydrogen/passport/pkg/internal/models" "git.solsynth.dev/hydrogen/passport/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/internal/services" "git.solsynth.dev/hydrogen/passport/pkg/internal/services"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"strings"
) )
func AuthMiddleware(c *fiber.Ctx) error {
var atk string
if cookie := c.Cookies(hyper.CookieAtk); len(cookie) > 0 {
atk = cookie
}
if header := c.Get(fiber.HeaderAuthorization); len(header) > 0 {
tk := strings.Replace(header, "Bearer", "", 1)
atk = strings.TrimSpace(tk)
}
if tk := c.Query("tk"); len(tk) > 0 {
atk = strings.TrimSpace(tk)
}
c.Locals("p_token", atk)
rtk := c.Cookies(hyper.CookieRtk)
if ctx, perms, newAtk, newRtk, err := services.Authenticate(atk, rtk, 0); err == nil {
if newAtk != atk {
SetAuthCookies(c, newAtk, newRtk)
}
c.Locals("permissions", perms)
c.Locals("user", ctx.Account)
}
return c.Next()
}
func EnsureAuthenticated(c *fiber.Ctx) error { func EnsureAuthenticated(c *fiber.Ctx) error {
if _, ok := c.Locals("user").(models.Account); !ok { if _, ok := c.Locals("user").(models.Account); !ok {
return fiber.NewError(fiber.StatusUnauthorized) return fiber.NewError(fiber.StatusUnauthorized)

View File

@ -1,12 +1,11 @@
package server package server
import ( import (
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"strings" "strings"
"git.solsynth.dev/hydrogen/passport/pkg/internal/server/admin" "git.solsynth.dev/hydrogen/passport/pkg/internal/server/admin"
"git.solsynth.dev/hydrogen/passport/pkg/internal/server/api" "git.solsynth.dev/hydrogen/passport/pkg/internal/server/api"
"git.solsynth.dev/hydrogen/passport/pkg/internal/server/exts"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/idempotency" "github.com/gofiber/fiber/v2/middleware/idempotency"
@ -20,6 +19,8 @@ type HTTPApp struct {
app *fiber.App app *fiber.App
} }
var IReader *sec.InternalTokenReader
func NewServer() *HTTPApp { func NewServer() *HTTPApp {
app := fiber.New(fiber.Config{ app := fiber.New(fiber.Config{
DisableStartupMessage: true, DisableStartupMessage: true,
@ -54,7 +55,7 @@ func NewServer() *HTTPApp {
Output: log.Logger, Output: log.Logger,
})) }))
app.Use(exts.AuthMiddleware) app.Use(sec.ContextMiddleware(IReader))
admin.MapAdminAPIs(app, "/api/admin") admin.MapAdminAPIs(app, "/api/admin")
api.MapAPIs(app, "/api") api.MapAPIs(app, "/api")

View File

@ -312,7 +312,7 @@ func DeleteAccount(id uint) error {
return err return err
} else { } else {
InvalidAuthCacheWithUser(id) InvalidAuthCacheWithUser(id)
_, _ = proto.NewServiceDirectoryClient(gap.Nx.GetDealerGrpcConn()).BroadcastDeletion(context.Background(), &proto.DeletionRequest{ _, _ = proto.NewServiceDirectoryClient(gap.Nx.GetNexusGrpcConn()).BroadcastDeletion(context.Background(), &proto.DeletionRequest{
ResourceType: "account", ResourceType: "account",
ResourceId: fmt.Sprintf("%d", id), ResourceId: fmt.Sprintf("%d", id),
}) })

View File

@ -3,6 +3,7 @@ package services
import ( import (
"context" "context"
"fmt" "fmt"
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
"time" "time"
"github.com/eko/gocache/lib/v4/cache" "github.com/eko/gocache/lib/v4/cache"
@ -16,13 +17,13 @@ import (
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
func Authenticate(atk, rtk string, rty int) (ctx models.AuthContext, perms map[string]any, err error) { func Authenticate(sessionId uint) (ctx models.AuthTicket, perms map[string]any, err error) {
if ctx, err = GetAuthContext(claims.ID); err == nil { if ctx, err = GetAuthContext(sessionId); err == nil {
var heldPerms map[string]any var heldPerms map[string]any
rawHeldPerms, _ := jsoniter.Marshal(ctx.Account.PermNodes) rawHeldPerms, _ := jsoniter.Marshal(ctx.Account.PermNodes)
_ = jsoniter.Unmarshal(rawHeldPerms, &heldPerms) _ = jsoniter.Unmarshal(rawHeldPerms, &heldPerms)
perms = FilterPermNodes(heldPerms, ctx.Ticket.Claims) perms = FilterPermNodes(heldPerms, ctx.Claims)
return return
} }
@ -30,46 +31,47 @@ func Authenticate(atk, rtk string, rty int) (ctx models.AuthContext, perms map[s
return return
} }
func GetAuthContextCacheKey(jti string) string { func GetAuthContextCacheKey(sessionId uint) string {
return fmt.Sprintf("auth-context#%s", jti) return fmt.Sprintf("auth-context#%d", sessionId)
} }
func GetAuthContext(jti string) (models.AuthContext, error) { func GetAuthContext(sessionId uint) (models.AuthTicket, error) {
var err error var err error
var ctx models.AuthContext var ctx models.AuthTicket
cacheManager := cache.New[any](localCache.S) cacheManager := cache.New[any](localCache.S)
marshal := marshaler.New(cacheManager) marshal := marshaler.New(cacheManager)
contx := context.Background() contx := context.Background()
if val, err := marshal.Get(contx, GetAuthContextCacheKey(jti), new(models.AuthContext)); err == nil { if val, err := marshal.Get(contx, GetAuthContextCacheKey(sessionId), new(models.AuthTicket)); err == nil {
ctx = *val.(*models.AuthContext) ctx = *val.(*models.AuthTicket)
} else { } else {
ctx, err = CacheAuthContext(jti) ctx, err = CacheAuthContext(sessionId)
log.Debug().Str("jti", jti).Msg("Created a new auth context cache") log.Debug().Uint("session", sessionId).Msg("Created a new auth context cache")
} }
return ctx, err return ctx, err
} }
func CacheAuthContext(jti string) (models.AuthContext, error) { func CacheAuthContext(sessionId uint) (models.AuthTicket, error) {
var ctx models.AuthContext
// Query data from primary database // Query data from primary database
ticket, err := GetTicketWithToken(jti) var ticket models.AuthTicket
if err != nil { if err := database.C.
return ctx, fmt.Errorf("invalid auth ticket: %v", err) Where("id = ?", sessionId).
Preload("Account").
First(&ticket).Error; err != nil {
return ticket, fmt.Errorf("invalid auth ticket: %v", err)
} else if err := ticket.IsAvailable(); err != nil { } else if err := ticket.IsAvailable(); err != nil {
return ctx, fmt.Errorf("unavailable auth ticket: %v", err) return ticket, fmt.Errorf("unavailable auth ticket: %v", err)
} }
user, err := GetAccount(ticket.AccountID) user, err := GetAccount(ticket.AccountID)
if err != nil { if err != nil {
return ctx, fmt.Errorf("invalid account: %v", err) return ticket, fmt.Errorf("invalid account: %v", err)
} }
groups, err := GetUserAccountGroup(user) groups, err := GetUserAccountGroup(user)
if err != nil { if err != nil {
return ctx, fmt.Errorf("unable to get account groups: %v", err) return ticket, fmt.Errorf("unable to get account groups: %v", err)
} }
for _, group := range groups { for _, group := range groups {
@ -80,33 +82,28 @@ func CacheAuthContext(jti string) (models.AuthContext, error) {
} }
} }
ctx = models.AuthContext{ // Put the data into the cache
Ticket: ticket,
Account: user,
}
// Put the data into cache
cacheManager := cache.New[any](localCache.S) cacheManager := cache.New[any](localCache.S)
marshal := marshaler.New(cacheManager) marshal := marshaler.New(cacheManager)
contx := context.Background() ctx := context.Background()
marshal.Set( _ = marshal.Set(
contx,
GetAuthContextCacheKey(jti),
ctx, ctx,
GetAuthContextCacheKey(sessionId),
ticket,
store.WithExpiration(3*time.Minute), store.WithExpiration(3*time.Minute),
store.WithTags([]string{"auth-context", fmt.Sprintf("user#%d", user.ID)}), store.WithTags([]string{"auth-context", fmt.Sprintf("user#%d", user.ID)}),
) )
return ctx, nil return ticket, nil
} }
func InvalidAuthCacheWithUser(userId uint) { func InvalidAuthCacheWithUser(userId uint) {
cacheManager := cache.New[any](localCache.S) cacheManager := cache.New[any](localCache.S)
contx := context.Background() ctx := context.Background()
cacheManager.Invalidate( cacheManager.Invalidate(
contx, ctx,
store.WithInvalidateTags([]string{"auth-context", fmt.Sprintf("user#%d", userId)}), store.WithInvalidateTags([]string{"auth-context", fmt.Sprintf("user#%d", userId)}),
) )
} }

View File

@ -88,7 +88,7 @@ func GetFactorCode(factor models.AuthFactor) (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() defer cancel()
_, err := proto.NewPostmanClient(gap.Nx.GetDealerGrpcConn()).DeliverEmail(ctx, &proto.DeliverEmailRequest{ _, err := proto.NewPostmanClient(gap.Nx.GetNexusGrpcConn()).DeliverEmail(ctx, &proto.DeliverEmailRequest{
To: user.GetPrimaryEmail().Content, To: user.GetPrimaryEmail().Content,
Email: &proto.EmailRequest{ Email: &proto.EmailRequest{
Subject: subject, Subject: subject,

View File

@ -60,7 +60,7 @@ func CacheUserStatus(uid uint, status models.Status) {
} }
func GetUserOnline(uid uint) bool { func GetUserOnline(uid uint) bool {
pc := proto.NewStreamControllerClient(gap.Nx.GetDealerGrpcConn()) pc := proto.NewStreamControllerClient(gap.Nx.GetNexusGrpcConn())
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() defer cancel()
resp, err := pc.CountStreamConnection(ctx, &proto.CountConnectionRequest{ resp, err := pc.CountStreamConnection(ctx, &proto.CountConnectionRequest{

View File

@ -145,7 +145,7 @@ func NotifyMagicToken(token models.MagicToken) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() defer cancel()
_, err := proto.NewPostmanClient(gap.Nx.GetDealerGrpcConn()).DeliverEmail(ctx, &proto.DeliverEmailRequest{ _, err := proto.NewPostmanClient(gap.Nx.GetNexusGrpcConn()).DeliverEmail(ctx, &proto.DeliverEmailRequest{
To: user.GetPrimaryEmail().Content, To: user.GetPrimaryEmail().Content,
Email: &proto.EmailRequest{ Email: &proto.EmailRequest{
Subject: subject, Subject: subject,

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"os" "os"
"os/signal" "os/signal"
"syscall" "syscall"
@ -42,6 +43,14 @@ func main() {
log.Fatal().Err(err).Msg("An error occurred when connecting to nexus...") log.Fatal().Err(err).Msg("An error occurred when connecting to nexus...")
} }
// Load keypair
if reader, err := sec.NewInternalTokenReader(viper.GetString("security.internal_public_key")); err != nil {
log.Error().Err(err).Msg("An error occurred when reading internal public key for jwt. Authentication related features will be disabled.")
} else {
server.IReader = reader
log.Info().Msg("Internal jwt public key loaded.")
}
// Connect to database // Connect to database
if err := database.NewGorm(); err != nil { if err := database.NewGorm(); err != nil {
log.Fatal().Err(err).Msg("An error occurred when connect to database.") log.Fatal().Err(err).Msg("An error occurred when connect to database.")

View File

@ -26,3 +26,4 @@ cookie_domain = "localhost"
cookie_samesite = "Lax" cookie_samesite = "Lax"
access_token_duration = 300 access_token_duration = 300
refresh_token_duration = 2592000 refresh_token_duration = 2592000
internal_public_key = "keys/internal_public_key.pem"