♻️ Refactored more modules into nexus
This commit is contained in:
@ -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,
|
||||
|
Reference in New Issue
Block a user