sonr/internal/dwn/middleware/middleware.go
Prad Nukala 96e6486c43
feature/migrate models (#16)
* feat: add new supported attestation formats to genesis

* feat: refactor keyType to keytype enum

* refactor: remove unused imports and code

* refactor: update main.go to use src package

* refactor: move web-related structs from  to

* refactor: move client middleware package to root

* refactor: remove unused IndexedDB dependency

* feat: update worker implementation to use

* feat: add Caddyfile and Caddy configuration for vault service

* refactor(config): move keyshare and address to Motr config

* fix: validate service origin in AllocateVault

* chore: remove IndexedDB configuration

* feat: add support for IPNS-based vault access
2024-09-19 02:04:22 -04:00

64 lines
1.7 KiB
Go

package middleware
import (
"net/http"
"github.com/labstack/echo/v4"
"gopkg.in/macaroon.v2"
)
// GetSession returns the current Session
func GetSession(c echo.Context) *Session {
return c.(*Session)
}
// UseSession establishes a Session Cookie.
func UseSession(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
sc := initSession(c)
headers := new(RequestHeaders)
sc.Bind(headers)
return next(sc)
}
}
func MacaroonMiddleware(secretKeyStr string, location string) echo.MiddlewareFunc {
secretKey := []byte(secretKeyStr)
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// Extract the macaroon from the Authorization header
auth := c.Request().Header.Get("Authorization")
if auth == "" {
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "Missing Authorization header"})
}
// Decode the macaroon
mac, err := macaroon.Base64Decode([]byte(auth))
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid macaroon encoding"})
}
token, err := macaroon.New(secretKey, mac, location, macaroon.LatestVersion)
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid macaroon"})
}
// Verify the macaroon
err = token.Verify(secretKey, func(caveat string) error {
for _, c := range MacroonCaveats {
if c.String() == caveat {
return nil
}
}
return nil // Return nil if the caveat is valid
}, nil)
if err != nil {
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "Invalid macaroon"})
}
// Macaroon is valid, proceed to the next handler
return next(c)
}
}
}