2024-12-10 13:40:41 -05:00
|
|
|
package context
|
2024-12-05 20:36:58 -05:00
|
|
|
|
|
|
|
import (
|
2024-12-08 19:46:19 -05:00
|
|
|
"net/http"
|
2024-12-08 16:17:21 -05:00
|
|
|
|
2024-12-05 20:36:58 -05:00
|
|
|
"github.com/labstack/echo/v4"
|
2024-12-11 12:24:04 -05:00
|
|
|
config "github.com/onsonr/sonr/pkg/config/hway"
|
2024-12-11 12:07:39 -05:00
|
|
|
"github.com/onsonr/sonr/pkg/database/sessions"
|
2024-12-06 21:31:20 -05:00
|
|
|
"gorm.io/gorm"
|
2024-12-05 20:36:58 -05:00
|
|
|
)
|
|
|
|
|
2024-12-06 21:31:20 -05:00
|
|
|
// Middleware creates a new session middleware
|
2024-12-11 12:24:04 -05:00
|
|
|
func Middleware(db *gorm.DB, env config.Hway) echo.MiddlewareFunc {
|
2024-12-05 20:36:58 -05:00
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
2024-12-06 21:31:20 -05:00
|
|
|
cc := NewHTTPContext(c, db)
|
|
|
|
if err := cc.InitSession(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-12-05 20:36:58 -05:00
|
|
|
return next(cc)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-12-08 16:17:21 -05:00
|
|
|
|
2024-12-08 19:46:19 -05:00
|
|
|
// HTTPContext is the context for HTTP endpoints.
|
|
|
|
type HTTPContext struct {
|
|
|
|
echo.Context
|
|
|
|
db *gorm.DB
|
2024-12-10 13:40:41 -05:00
|
|
|
sess *sessions.Session
|
2024-12-11 12:24:04 -05:00
|
|
|
env config.Hway
|
2024-12-08 19:46:19 -05:00
|
|
|
}
|
2024-12-08 19:45:14 -05:00
|
|
|
|
2024-12-08 19:46:19 -05:00
|
|
|
// Get returns the HTTPContext from the echo context
|
|
|
|
func Get(c echo.Context) (*HTTPContext, error) {
|
|
|
|
ctx, ok := c.(*HTTPContext)
|
|
|
|
if !ok {
|
|
|
|
return nil, echo.NewHTTPError(http.StatusInternalServerError, "Session Context not found")
|
2024-12-08 19:45:14 -05:00
|
|
|
}
|
2024-12-08 19:46:19 -05:00
|
|
|
return ctx, nil
|
|
|
|
}
|
2024-12-08 19:45:14 -05:00
|
|
|
|
2024-12-08 19:46:19 -05:00
|
|
|
// NewHTTPContext creates a new session context
|
|
|
|
func NewHTTPContext(c echo.Context, db *gorm.DB) *HTTPContext {
|
|
|
|
return &HTTPContext{
|
|
|
|
Context: c,
|
|
|
|
db: db,
|
2024-12-08 16:17:21 -05:00
|
|
|
}
|
2024-12-08 19:46:19 -05:00
|
|
|
}
|
2024-12-08 19:45:14 -05:00
|
|
|
|
2024-12-08 19:46:19 -05:00
|
|
|
// Session returns the current session
|
2024-12-10 13:40:41 -05:00
|
|
|
func (s *HTTPContext) Session() *sessions.Session {
|
2024-12-08 19:46:19 -05:00
|
|
|
return s.sess
|
2024-12-08 16:17:21 -05:00
|
|
|
}
|