♻️ Refactored more modules into nexus
This commit is contained in:
parent
b4fb7b53af
commit
4c44af74b5
1
.gitignore
vendored
1
.gitignore
vendored
@ -1,4 +1,5 @@
|
||||
/dist
|
||||
/uploads
|
||||
/keys
|
||||
|
||||
.DS_Store
|
||||
|
26
.idea/workspace.xml
generated
26
.idea/workspace.xml
generated
@ -4,26 +4,18 @@
|
||||
<option name="autoReloadType" value="ALL" />
|
||||
</component>
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="3fefb2c4-b6f9-466b-a523-53352e8d6f95" name="更改" comment=":bug: Trying to fix panic">
|
||||
<change afterPath="$PROJECT_DIR$/pkg/proto/notify.proto" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pkg/proto/realm.proto" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pkg/proto/record.proto" afterDir="false" />
|
||||
<list default="true" id="3fefb2c4-b6f9-466b-a523-53352e8d6f95" name="更改" comment=":recycle: Remove most of the dealer deps and move to nexus">
|
||||
<change beforePath="$PROJECT_DIR$/.gitignore" beforeDir="false" afterPath="$PROJECT_DIR$/.gitignore" 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.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/events.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/events.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/grpc/realms.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/realms.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/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/server/exts/auth.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/server/exts/auth.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/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/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/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" />
|
||||
@ -75,7 +67,7 @@
|
||||
"git-widget-placeholder": "refactor/nexus",
|
||||
"go.import.settings.migrated": "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.selected.package.eslint": "(autodetect)",
|
||||
"nodejs_package_manager_path": "npm",
|
||||
@ -92,11 +84,11 @@
|
||||
}]]></component>
|
||||
<component name="RecentsManager">
|
||||
<key name="CopyFile.RECENT_KEYS">
|
||||
<recent name="$PROJECT_DIR$/keys" />
|
||||
<recent name="$PROJECT_DIR$/pkg/proto" />
|
||||
<recent name="$PROJECT_DIR$/web/src/components/admin" />
|
||||
<recent name="$PROJECT_DIR$/web/src/views" />
|
||||
<recent name="$PROJECT_DIR$/pkg/internal/server/api" />
|
||||
<recent name="$PROJECT_DIR$/web" />
|
||||
</key>
|
||||
<key name="MoveFile.RECENT_KEYS">
|
||||
<recent name="$PROJECT_DIR$/web/src/views/flow" />
|
||||
@ -174,7 +166,6 @@
|
||||
</option>
|
||||
</component>
|
||||
<component name="VcsManagerConfiguration">
|
||||
<MESSAGE value=":sparkles: Daily signs" />
|
||||
<MESSAGE value=":bug: Fix daily check issue" />
|
||||
<MESSAGE value=":sparkles: Can get today's daily sign record" />
|
||||
<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... again" />
|
||||
<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 name="VgoProject">
|
||||
<settings-migrated>true</settings-migrated>
|
||||
|
5
go.mod
5
go.mod
@ -6,7 +6,7 @@ toolchain go1.23.2
|
||||
|
||||
require (
|
||||
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/eko/gocache/lib/v4 v4.1.6
|
||||
github.com/eko/gocache/store/ristretto/v4 v4.2.2
|
||||
@ -22,6 +22,7 @@ require (
|
||||
github.com/sujit-baniya/flash v0.1.8
|
||||
golang.org/x/crypto v0.28.0
|
||||
google.golang.org/grpc v1.67.1
|
||||
google.golang.org/protobuf v1.35.1
|
||||
gorm.io/datatypes v1.2.4
|
||||
gorm.io/driver/postgres v1.5.4
|
||||
gorm.io/gorm v1.25.12
|
||||
@ -41,6 +42,7 @@ require (
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.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/mock v1.6.0 // 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/text v0.19.0 // 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/yaml.v3 v3.0.1 // indirect
|
||||
gorm.io/driver/mysql v1.5.7 // indirect
|
||||
|
4
go.sum
4
go.sum
@ -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/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-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/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=
|
||||
@ -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/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
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/gofiber/fiber/v2 v2.36.0/go.mod h1:tgCr+lierLwLoVHHO/jn3Niannv34WRkQETU8wiL9fQ=
|
||||
github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo=
|
||||
|
@ -2,6 +2,7 @@ package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex"
|
||||
|
||||
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
|
||||
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
|
||||
@ -18,56 +19,32 @@ type authenticateServer struct {
|
||||
}
|
||||
|
||||
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 {
|
||||
return &proto.AuthReply{
|
||||
IsValid: false,
|
||||
}, nil
|
||||
} else {
|
||||
user := ctx.Account
|
||||
rawPerms, _ := jsoniter.Marshal(perms)
|
||||
|
||||
user := ticket.Account
|
||||
userinfo := &proto.UserInfo{
|
||||
Id: uint64(user.ID),
|
||||
Name: user.Name,
|
||||
Nick: user.Nick,
|
||||
Email: user.GetPrimaryEmail().Content,
|
||||
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))
|
||||
Id: uint64(user.ID),
|
||||
Name: user.Name,
|
||||
PermNodes: nex.EncodeMap(perms),
|
||||
Metadata: nex.EncodeMap(user),
|
||||
}
|
||||
|
||||
return &proto.AuthReply{
|
||||
IsValid: true,
|
||||
Info: &proto.AuthInfo{
|
||||
NewAccessToken: &atk,
|
||||
NewRefreshToken: &rtk,
|
||||
Permissions: rawPerms,
|
||||
TicketId: uint64(ctx.Ticket.ID),
|
||||
Info: userinfo,
|
||||
SessionId: uint64(ticket.ID),
|
||||
Info: userinfo,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Server) EnsurePermGranted(_ context.Context, in *proto.CheckPermRequest) (*proto.CheckPermResponse, error) {
|
||||
claims, err := services.DecodeJwt(in.GetToken())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, err := services.GetAuthContext(claims.ID)
|
||||
ctx, err := services.GetAuthContext(uint(in.GetSessionId()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -78,7 +55,7 @@ func (v *Server) EnsurePermGranted(_ context.Context, in *proto.CheckPermRequest
|
||||
|
||||
var value any
|
||||
_ = 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)
|
||||
|
||||
return &proto.CheckPermResponse{
|
||||
@ -120,18 +97,10 @@ func (v *Server) ListUserFriends(_ context.Context, in *proto.ListUserRelativeRe
|
||||
}
|
||||
|
||||
return &proto.ListUserRelativeResponse{
|
||||
Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.SimpleUserInfo {
|
||||
val := &proto.SimpleUserInfo{
|
||||
Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.UserInfo {
|
||||
val := &proto.UserInfo{
|
||||
Id: uint64(item.AccountID),
|
||||
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
|
||||
@ -154,18 +123,10 @@ func (v *Server) ListUserBlocklist(_ context.Context, in *proto.ListUserRelative
|
||||
}
|
||||
|
||||
return &proto.ListUserRelativeResponse{
|
||||
Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.SimpleUserInfo {
|
||||
val := &proto.SimpleUserInfo{
|
||||
Data: lo.Map(data, func(item models.AccountRelationship, index int) *proto.UserInfo {
|
||||
val := &proto.UserInfo{
|
||||
Id: uint64(item.AccountID),
|
||||
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
|
||||
|
@ -151,8 +151,6 @@ func getToken(c *fiber.Ctx) error {
|
||||
idk = atk
|
||||
}
|
||||
|
||||
exts.SetAuthCookies(c, atk, rtk)
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"id_token": idk,
|
||||
"access_token": atk,
|
||||
|
@ -2,40 +2,11 @@ package exts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.solsynth.dev/hydrogen/dealer/pkg/hyper"
|
||||
"git.solsynth.dev/hydrogen/passport/pkg/internal/models"
|
||||
"git.solsynth.dev/hydrogen/passport/pkg/internal/services"
|
||||
"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 {
|
||||
if _, ok := c.Locals("user").(models.Account); !ok {
|
||||
return fiber.NewError(fiber.StatusUnauthorized)
|
||||
|
@ -1,12 +1,11 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"strings"
|
||||
|
||||
"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/exts"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
"github.com/gofiber/fiber/v2/middleware/idempotency"
|
||||
@ -20,6 +19,8 @@ type HTTPApp struct {
|
||||
app *fiber.App
|
||||
}
|
||||
|
||||
var IReader *sec.InternalTokenReader
|
||||
|
||||
func NewServer() *HTTPApp {
|
||||
app := fiber.New(fiber.Config{
|
||||
DisableStartupMessage: true,
|
||||
@ -54,7 +55,7 @@ func NewServer() *HTTPApp {
|
||||
Output: log.Logger,
|
||||
}))
|
||||
|
||||
app.Use(exts.AuthMiddleware)
|
||||
app.Use(sec.ContextMiddleware(IReader))
|
||||
|
||||
admin.MapAdminAPIs(app, "/api/admin")
|
||||
api.MapAPIs(app, "/api")
|
||||
|
@ -312,7 +312,7 @@ func DeleteAccount(id uint) error {
|
||||
return err
|
||||
} else {
|
||||
InvalidAuthCacheWithUser(id)
|
||||
_, _ = proto.NewServiceDirectoryClient(gap.Nx.GetDealerGrpcConn()).BroadcastDeletion(context.Background(), &proto.DeletionRequest{
|
||||
_, _ = proto.NewServiceDirectoryClient(gap.Nx.GetNexusGrpcConn()).BroadcastDeletion(context.Background(), &proto.DeletionRequest{
|
||||
ResourceType: "account",
|
||||
ResourceId: fmt.Sprintf("%d", id),
|
||||
})
|
||||
|
@ -3,6 +3,7 @@ package services
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.solsynth.dev/hydrogen/passport/pkg/internal/database"
|
||||
"time"
|
||||
|
||||
"github.com/eko/gocache/lib/v4/cache"
|
||||
@ -16,13 +17,13 @@ import (
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func Authenticate(atk, rtk string, rty int) (ctx models.AuthContext, perms map[string]any, err error) {
|
||||
if ctx, err = GetAuthContext(claims.ID); err == nil {
|
||||
func Authenticate(sessionId uint) (ctx models.AuthTicket, perms map[string]any, err error) {
|
||||
if ctx, err = GetAuthContext(sessionId); err == nil {
|
||||
var heldPerms map[string]any
|
||||
rawHeldPerms, _ := jsoniter.Marshal(ctx.Account.PermNodes)
|
||||
_ = jsoniter.Unmarshal(rawHeldPerms, &heldPerms)
|
||||
|
||||
perms = FilterPermNodes(heldPerms, ctx.Ticket.Claims)
|
||||
perms = FilterPermNodes(heldPerms, ctx.Claims)
|
||||
return
|
||||
}
|
||||
|
||||
@ -30,46 +31,47 @@ func Authenticate(atk, rtk string, rty int) (ctx models.AuthContext, perms map[s
|
||||
return
|
||||
}
|
||||
|
||||
func GetAuthContextCacheKey(jti string) string {
|
||||
return fmt.Sprintf("auth-context#%s", jti)
|
||||
func GetAuthContextCacheKey(sessionId uint) string {
|
||||
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 ctx models.AuthContext
|
||||
var ctx models.AuthTicket
|
||||
|
||||
cacheManager := cache.New[any](localCache.S)
|
||||
marshal := marshaler.New(cacheManager)
|
||||
contx := context.Background()
|
||||
|
||||
if val, err := marshal.Get(contx, GetAuthContextCacheKey(jti), new(models.AuthContext)); err == nil {
|
||||
ctx = *val.(*models.AuthContext)
|
||||
if val, err := marshal.Get(contx, GetAuthContextCacheKey(sessionId), new(models.AuthTicket)); err == nil {
|
||||
ctx = *val.(*models.AuthTicket)
|
||||
} else {
|
||||
ctx, err = CacheAuthContext(jti)
|
||||
log.Debug().Str("jti", jti).Msg("Created a new auth context cache")
|
||||
ctx, err = CacheAuthContext(sessionId)
|
||||
log.Debug().Uint("session", sessionId).Msg("Created a new auth context cache")
|
||||
}
|
||||
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
func CacheAuthContext(jti string) (models.AuthContext, error) {
|
||||
var ctx models.AuthContext
|
||||
|
||||
func CacheAuthContext(sessionId uint) (models.AuthTicket, error) {
|
||||
// Query data from primary database
|
||||
ticket, err := GetTicketWithToken(jti)
|
||||
if err != nil {
|
||||
return ctx, fmt.Errorf("invalid auth ticket: %v", err)
|
||||
var ticket models.AuthTicket
|
||||
if err := database.C.
|
||||
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 {
|
||||
return ctx, fmt.Errorf("unavailable auth ticket: %v", err)
|
||||
return ticket, fmt.Errorf("unavailable auth ticket: %v", err)
|
||||
}
|
||||
|
||||
user, err := GetAccount(ticket.AccountID)
|
||||
if err != nil {
|
||||
return ctx, fmt.Errorf("invalid account: %v", err)
|
||||
return ticket, fmt.Errorf("invalid account: %v", err)
|
||||
}
|
||||
groups, err := GetUserAccountGroup(user)
|
||||
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 {
|
||||
@ -80,33 +82,28 @@ func CacheAuthContext(jti string) (models.AuthContext, error) {
|
||||
}
|
||||
}
|
||||
|
||||
ctx = models.AuthContext{
|
||||
Ticket: ticket,
|
||||
Account: user,
|
||||
}
|
||||
|
||||
// Put the data into cache
|
||||
// Put the data into the cache
|
||||
cacheManager := cache.New[any](localCache.S)
|
||||
marshal := marshaler.New(cacheManager)
|
||||
contx := context.Background()
|
||||
ctx := context.Background()
|
||||
|
||||
marshal.Set(
|
||||
contx,
|
||||
GetAuthContextCacheKey(jti),
|
||||
_ = marshal.Set(
|
||||
ctx,
|
||||
GetAuthContextCacheKey(sessionId),
|
||||
ticket,
|
||||
store.WithExpiration(3*time.Minute),
|
||||
store.WithTags([]string{"auth-context", fmt.Sprintf("user#%d", user.ID)}),
|
||||
)
|
||||
|
||||
return ctx, nil
|
||||
return ticket, nil
|
||||
}
|
||||
|
||||
func InvalidAuthCacheWithUser(userId uint) {
|
||||
cacheManager := cache.New[any](localCache.S)
|
||||
contx := context.Background()
|
||||
ctx := context.Background()
|
||||
|
||||
cacheManager.Invalidate(
|
||||
contx,
|
||||
ctx,
|
||||
store.WithInvalidateTags([]string{"auth-context", fmt.Sprintf("user#%d", userId)}),
|
||||
)
|
||||
}
|
||||
|
@ -88,7 +88,7 @@ func GetFactorCode(factor models.AuthFactor) (bool, error) {
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
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,
|
||||
Email: &proto.EmailRequest{
|
||||
Subject: subject,
|
||||
|
@ -60,7 +60,7 @@ func CacheUserStatus(uid uint, status models.Status) {
|
||||
}
|
||||
|
||||
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)
|
||||
defer cancel()
|
||||
resp, err := pc.CountStreamConnection(ctx, &proto.CountConnectionRequest{
|
||||
|
@ -145,7 +145,7 @@ func NotifyMagicToken(token models.MagicToken) error {
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
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,
|
||||
Email: &proto.EmailRequest{
|
||||
Subject: subject,
|
||||
|
@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
@ -42,6 +43,14 @@ func main() {
|
||||
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
|
||||
if err := database.NewGorm(); err != nil {
|
||||
log.Fatal().Err(err).Msg("An error occurred when connect to database.")
|
||||
|
@ -26,3 +26,4 @@ cookie_domain = "localhost"
|
||||
cookie_samesite = "Lax"
|
||||
access_token_duration = 300
|
||||
refresh_token_duration = 2592000
|
||||
internal_public_key = "keys/internal_public_key.pem"
|
||||
|
Loading…
Reference in New Issue
Block a user