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
+57
View File
@@ -0,0 +1,57 @@
package sessions
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
@@ -0,0 +1,43 @@
package sessions
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)
}