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
@@ -1,11 +1,11 @@
package session
package context
import (
"regexp"
"strings"
"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/segmentio/ksuid"
)
@@ -15,12 +15,12 @@ func (s *HTTPContext) InitSession() error {
sessionID := s.getOrCreateSessionID()
// Try to load existing session
var sess database.Session
var sess sessions.Session
result := s.db.Where("id = ?", sessionID).First(&sess)
if result.Error != nil {
// Create new session if not found
bn, bv, arch, plat, platVer, model := extractBrowserInfo(s.Context)
sess = database.Session{
sess = sessions.Session{
ID: sessionID,
BrowserName: bn,
BrowserVersion: bv,
@@ -1,11 +1,11 @@
package session
package context
import (
"net/http"
"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/database"
"gorm.io/gorm"
)
@@ -26,7 +26,7 @@ func Middleware(db *gorm.DB, env config.Env) echo.MiddlewareFunc {
type HTTPContext struct {
echo.Context
db *gorm.DB
sess *database.Session
sess *sessions.Session
env config.Env
}
@@ -48,6 +48,6 @@ func NewHTTPContext(c echo.Context, db *gorm.DB) *HTTPContext {
}
// Session returns the current session
func (s *HTTPContext) Session() *database.Session {
func (s *HTTPContext) Session() *sessions.Session {
return s.sess
}
@@ -1,8 +1,8 @@
package session
package context
import (
"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
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
}
-57
View File
@@ -1,57 +0,0 @@
package database
import (
"net/http"
"github.com/labstack/echo/v4"
"gorm.io/gorm"
)
var (
ErrInvalidCredentials = echo.NewHTTPError(http.StatusUnauthorized, "Invalid credentials")
ErrInvalidSubject = echo.NewHTTPError(http.StatusBadRequest, "Invalid subject")
ErrInvalidUser = echo.NewHTTPError(http.StatusBadRequest, "Invalid user")
ErrUserAlreadyExists = echo.NewHTTPError(http.StatusConflict, "User already exists")
ErrUserNotFound = echo.NewHTTPError(http.StatusNotFound, "User not found")
)
// Define the credential structure matching our frontend data
type Credential struct {
ID string `json:"id"`
RawID string `json:"rawId"`
Type string `json:"type"`
AuthenticatorAttachment string `json:"authenticatorAttachment"`
Transports []string `json:"transports"`
ClientExtensionResults map[string]interface{} `json:"clientExtensionResults"`
Response struct {
AttestationObject string `json:"attestationObject"`
ClientDataJSON string `json:"clientDataJSON"`
} `json:"response"`
}
type User struct {
gorm.Model
Address string `json:"address"`
Handle string `json:"handle"`
Name string `json:"name"`
CID string `json:"cid"`
Credentials []*Credential `json:"credentials"`
}
type Session struct {
gorm.Model
ID string `json:"id" gorm:"primaryKey"`
BrowserName string `json:"browserName"`
BrowserVersion string `json:"browserVersion"`
UserArchitecture string `json:"userArchitecture"`
Platform string `json:"platform"`
PlatformVersion string `json:"platformVersion"`
DeviceModel string `json:"deviceModel"`
UserHandle string `json:"userHandle"`
FirstName string `json:"firstName"`
LastInitial string `json:"lastInitial"`
VaultAddress string `json:"vaultAddress"`
HumanSum int `json:"humanSum"`
Challenge string `json:"challenge"`
}
-43
View File
@@ -1,43 +0,0 @@
package database
import (
"os"
"path/filepath"
"github.com/onsonr/sonr/internal/gateway/config"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// InitDB initializes and returns a configured database connection
func InitDB(env config.Env) (*gorm.DB, error) {
path := formatDBPath(env.GetSqliteFile())
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{})
if err != nil {
return nil, err
}
// Migrate the schema
db.AutoMigrate(&Session{})
db.AutoMigrate(&User{})
return db, nil
}
func formatDBPath(path string) string {
home := os.Getenv("HOME")
if home == "" {
home = os.Getenv("USERPROFILE")
}
if home == "" {
home = "."
}
configDir := filepath.Join(home, ".config", "hway")
if err := os.MkdirAll(configDir, 0o755); err != nil {
// If we can't create the directory, fall back to current directory
return path
}
return filepath.Join(configDir, path)
}
+4 -4
View File
@@ -2,12 +2,12 @@ package index
import (
"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
func isInitial(c echo.Context) bool {
sess, err := session.Get(c)
sess, err := context.Get(c)
if err != nil {
return false
}
@@ -17,7 +17,7 @@ func isInitial(c echo.Context) bool {
// Expired users have either a user handle or vault address
func isExpired(c echo.Context) bool {
sess, err := session.Get(c)
sess, err := context.Get(c)
if err != nil {
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
func isReturning(c echo.Context) bool {
sess, err := session.Get(c)
sess, err := context.Get(c)
if err != nil {
return false
}
+3 -3
View File
@@ -6,7 +6,7 @@ import (
"net/http"
"github.com/labstack/echo/v4"
"github.com/onsonr/sonr/internal/gateway/database"
"github.com/onsonr/sonr/internal/database/sessions"
)
type CreateProfileData struct {
@@ -35,8 +35,8 @@ func (d CreateProfileData) IsHumanLabel() string {
return fmt.Sprintf("What is %d + %d?", d.FirstNumber, d.LastNumber)
}
func extractCredentialDescriptor(jsonString string) (*database.Credential, error) {
cred := &database.Credential{}
func extractCredentialDescriptor(jsonString string) (*sessions.Credential, error) {
cred := &sessions.Credential{}
// Unmarshal the credential JSON
if err := json.Unmarshal([]byte(jsonString), cred); err != nil {
return nil, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("invalid credential format: %v", err))
+4 -10
View File
@@ -4,25 +4,19 @@ package gateway
import (
"github.com/labstack/echo/v4"
"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/register"
"github.com/onsonr/sonr/internal/gateway/session"
"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
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
e.Use(session.Middleware(db, env))
e.Use(context.Middleware(db, env))
// Register routes
e.GET("/", index.Handler)
-19
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
}