refactor: move session management to dedicated database module

This commit is contained in:
Prad Nukala 2024-12-10 13:40:41 -05:00
parent 518109e9df
commit c67a7823a6
16 changed files with 39 additions and 57 deletions

View File

@ -10,6 +10,7 @@ import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware" "github.com/labstack/echo/v4/middleware"
"github.com/onsonr/sonr/crypto/ucan" "github.com/onsonr/sonr/crypto/ucan"
"github.com/onsonr/sonr/internal/database/sessions"
"github.com/onsonr/sonr/internal/gateway" "github.com/onsonr/sonr/internal/gateway"
"github.com/onsonr/sonr/internal/gateway/config" "github.com/onsonr/sonr/internal/gateway/config"
"github.com/onsonr/sonr/pkg/common/ipfs" "github.com/onsonr/sonr/pkg/common/ipfs"
@ -29,12 +30,16 @@ func setupServer(env config.Env) (*echo.Echo, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
db, err := sessions.InitDB(env)
if err != nil {
return nil, err
}
e := echo.New() e := echo.New()
e.IPExtractor = echo.ExtractIPDirect() e.IPExtractor = echo.ExtractIPDirect()
e.Use(middleware.Logger()) e.Use(middleware.Logger())
e.Use(middleware.Recover()) e.Use(middleware.Recover())
e.Use(producer.Middleware(ipc, ucan.ServicePermissions)) e.Use(producer.Middleware(ipc, ucan.ServicePermissions))
gateway.RegisterRoutes(e, env) gateway.RegisterRoutes(e, env, db)
return e, nil return e, nil
} }

View File

@ -1,4 +1,4 @@
package database package sessions
import ( import (
"net/http" "net/http"

View File

@ -1,4 +1,4 @@
package database package sessions
import ( import (
"os" "os"

View File

@ -1,11 +1,11 @@
package session package context
import ( import (
"regexp" "regexp"
"strings" "strings"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/onsonr/sonr/internal/gateway/database" "github.com/onsonr/sonr/internal/database/sessions"
"github.com/onsonr/sonr/pkg/common" "github.com/onsonr/sonr/pkg/common"
"github.com/segmentio/ksuid" "github.com/segmentio/ksuid"
) )
@ -15,12 +15,12 @@ func (s *HTTPContext) InitSession() error {
sessionID := s.getOrCreateSessionID() sessionID := s.getOrCreateSessionID()
// Try to load existing session // Try to load existing session
var sess database.Session var sess sessions.Session
result := s.db.Where("id = ?", sessionID).First(&sess) result := s.db.Where("id = ?", sessionID).First(&sess)
if result.Error != nil { if result.Error != nil {
// Create new session if not found // Create new session if not found
bn, bv, arch, plat, platVer, model := extractBrowserInfo(s.Context) bn, bv, arch, plat, platVer, model := extractBrowserInfo(s.Context)
sess = database.Session{ sess = sessions.Session{
ID: sessionID, ID: sessionID,
BrowserName: bn, BrowserName: bn,
BrowserVersion: bv, BrowserVersion: bv,

View File

@ -1,11 +1,11 @@
package session package context
import ( import (
"net/http" "net/http"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/onsonr/sonr/internal/database/sessions"
"github.com/onsonr/sonr/internal/gateway/config" "github.com/onsonr/sonr/internal/gateway/config"
"github.com/onsonr/sonr/internal/gateway/database"
"gorm.io/gorm" "gorm.io/gorm"
) )
@ -26,7 +26,7 @@ func Middleware(db *gorm.DB, env config.Env) echo.MiddlewareFunc {
type HTTPContext struct { type HTTPContext struct {
echo.Context echo.Context
db *gorm.DB db *gorm.DB
sess *database.Session sess *sessions.Session
env config.Env env config.Env
} }
@ -48,6 +48,6 @@ func NewHTTPContext(c echo.Context, db *gorm.DB) *HTTPContext {
} }
// Session returns the current session // Session returns the current session
func (s *HTTPContext) Session() *database.Session { func (s *HTTPContext) Session() *sessions.Session {
return s.sess return s.sess
} }

View File

@ -1,8 +1,8 @@
package session package context
import ( import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/onsonr/sonr/internal/gateway/database" "github.com/onsonr/sonr/internal/database/sessions"
) )
// ╭───────────────────────────────────────────────────────╮ // ╭───────────────────────────────────────────────────────╮
@ -160,7 +160,7 @@ func HandleExists(c echo.Context, handle string) (bool, error) {
} }
var count int64 var count int64
if err := sess.db.Model(&database.Session{}).Where("user_handle = ?", handle).Count(&count).Error; err != nil { if err := sess.db.Model(&sessions.Session{}).Where("user_handle = ?", handle).Count(&count).Error; err != nil {
return false, err return false, err
} }

View File

@ -2,12 +2,12 @@ package index
import ( import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/onsonr/sonr/internal/gateway/session" "github.com/onsonr/sonr/internal/gateway/context"
) )
// Initial users have no authorization, user handle, or vault address // Initial users have no authorization, user handle, or vault address
func isInitial(c echo.Context) bool { func isInitial(c echo.Context) bool {
sess, err := session.Get(c) sess, err := context.Get(c)
if err != nil { if err != nil {
return false return false
} }
@ -17,7 +17,7 @@ func isInitial(c echo.Context) bool {
// Expired users have either a user handle or vault address // Expired users have either a user handle or vault address
func isExpired(c echo.Context) bool { func isExpired(c echo.Context) bool {
sess, err := session.Get(c) sess, err := context.Get(c)
if err != nil { if err != nil {
return false return false
} }
@ -27,7 +27,7 @@ func isExpired(c echo.Context) bool {
// Returning users have a valid authorization, and either a user handle or vault address // Returning users have a valid authorization, and either a user handle or vault address
func isReturning(c echo.Context) bool { func isReturning(c echo.Context) bool {
sess, err := session.Get(c) sess, err := context.Get(c)
if err != nil { if err != nil {
return false return false
} }

View File

@ -6,7 +6,7 @@ import (
"net/http" "net/http"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/onsonr/sonr/internal/gateway/database" "github.com/onsonr/sonr/internal/database/sessions"
) )
type CreateProfileData struct { type CreateProfileData struct {
@ -35,8 +35,8 @@ func (d CreateProfileData) IsHumanLabel() string {
return fmt.Sprintf("What is %d + %d?", d.FirstNumber, d.LastNumber) return fmt.Sprintf("What is %d + %d?", d.FirstNumber, d.LastNumber)
} }
func extractCredentialDescriptor(jsonString string) (*database.Credential, error) { func extractCredentialDescriptor(jsonString string) (*sessions.Credential, error) {
cred := &database.Credential{} cred := &sessions.Credential{}
// Unmarshal the credential JSON // Unmarshal the credential JSON
if err := json.Unmarshal([]byte(jsonString), cred); err != nil { if err := json.Unmarshal([]byte(jsonString), cred); err != nil {
return nil, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("invalid credential format: %v", err)) return nil, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("invalid credential format: %v", err))

View File

@ -4,25 +4,19 @@ package gateway
import ( import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/onsonr/sonr/internal/gateway/config" "github.com/onsonr/sonr/internal/gateway/config"
"github.com/onsonr/sonr/internal/gateway/database" "github.com/onsonr/sonr/internal/gateway/context"
"github.com/onsonr/sonr/internal/gateway/handlers/index" "github.com/onsonr/sonr/internal/gateway/handlers/index"
"github.com/onsonr/sonr/internal/gateway/handlers/register" "github.com/onsonr/sonr/internal/gateway/handlers/register"
"github.com/onsonr/sonr/internal/gateway/session"
"github.com/onsonr/sonr/pkg/common/response" "github.com/onsonr/sonr/pkg/common/response"
"gorm.io/gorm"
) )
func RegisterRoutes(e *echo.Echo, env config.Env) error { func RegisterRoutes(e *echo.Echo, env config.Env, db *gorm.DB) error {
// Custom error handler for gateway // Custom error handler for gateway
e.HTTPErrorHandler = response.RedirectOnError("http://localhost:3000") e.HTTPErrorHandler = response.RedirectOnError("http://localhost:3000")
// Initialize database
db, err := database.InitDB(env)
if err != nil {
return err
}
// Inject session middleware with database connection // Inject session middleware with database connection
e.Use(session.Middleware(db, env)) e.Use(context.Middleware(db, env))
// Register routes // Register routes
e.GET("/", index.Handler) e.GET("/", index.Handler)

View File

@ -1,19 +0,0 @@
package session
import "github.com/labstack/echo/v4"
func IsUniqueHandle(c echo.Context, handle string) bool {
return true
}
func IsValidFirstName(c echo.Context, firstName string) bool {
return true
}
func IsValidLastInitial(c echo.Context, lastInitial string) bool {
return true
}
func IsHuman(c echo.Context, sum int) bool {
return true
}

View File

@ -1,4 +1,4 @@
package session package context
import ( import (
"regexp" "regexp"

View File

@ -1,4 +1,4 @@
package session package context
import ( import (
"encoding/json" "encoding/json"

View File

@ -1,4 +1,4 @@
package session package context
import ( import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"

View File

@ -6,6 +6,6 @@ import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
) )
func HandleDash(c echo.Context) error { func Handler(c echo.Context) error {
return c.Render(http.StatusOK, "index.templ", nil) return c.Render(http.StatusOK, "index.templ", nil)
} }

View File

@ -7,10 +7,12 @@ import (
session "github.com/onsonr/sonr/internal/vault/session" session "github.com/onsonr/sonr/internal/vault/session"
) )
func HandleIndex(c echo.Context) error { func Handler(c echo.Context) error {
// TODO: Create views
if isInitial(c) { if isInitial(c) {
// return response.TemplEcho(c, index.InitialView()) // return response.TemplEcho(c, index.InitialView())
} }
// TODO: Add authorization check
if isExpired(c) { if isExpired(c) {
// return response.TemplEcho(c, index.ReturningView()) // return response.TemplEcho(c, index.ReturningView())
} }

View File

@ -7,11 +7,11 @@ package vault
import ( import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
session "github.com/onsonr/sonr/internal/vault/session" "github.com/onsonr/sonr/internal/vault/context"
"github.com/onsonr/sonr/internal/vault/types" "github.com/onsonr/sonr/internal/vault/types"
) )
// RegisterRoutes registers the Decentralized Web Node API routes. // RegisterRoutes registers the Decentralized Web Node API routes.
func RegisterRoutes(e *echo.Echo, config *types.Config) { func RegisterRoutes(e *echo.Echo, config *types.Config) {
e.Use(session.Middleware(config)) e.Use(context.Middleware(config))
} }