Files
sonr/internal/dwn/middleware/server.go
T

65 lines
1.8 KiB
Go
Raw Normal View History

2024-09-18 02:22:17 -04:00
package middleware
2024-09-11 15:10:54 -04:00
import (
"net/http"
"github.com/labstack/echo/v4"
2024-09-18 02:22:17 -04:00
"github.com/onsonr/sonr/internal/dwn/middleware/client"
2024-09-11 15:10:54 -04:00
"gopkg.in/macaroon.v2"
)
2024-09-18 02:22:17 -04:00
// GetSession returns the current Session
func GetSession(c echo.Context) *client.Session {
return c.(*client.Session)
2024-09-11 15:10:54 -04:00
}
2024-09-18 02:22:17 -04:00
// UseSession establishes a Session Cookie.
func UseSession(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
sc := client.NewSession(c)
headers := new(client.RequestHeaders)
sc.Bind(headers)
return next(sc)
2024-09-14 12:47:25 -04:00
}
2024-09-11 15:10:54 -04:00
}
2024-09-14 12:47:25 -04:00
func MacaroonMiddleware(secretKeyStr string, location string) echo.MiddlewareFunc {
secretKey := []byte(secretKeyStr)
2024-09-11 15:10:54 -04:00
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 {
2024-09-18 02:22:17 -04:00
for _, c := range client.MacroonCaveats {
2024-09-14 12:47:25 -04:00
if c.String() == caveat {
return nil
}
}
2024-09-11 15:10:54 -04:00
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)
}
}
}