busybar / internal / auth / middleware.go
middleware.go
Raw
package auth

import (
	"errors"
	"net/http"

	"github.com/danielrhuynh/busybar/internal/models"
	"github.com/danielrhuynh/busybar/internal/services"
	"github.com/labstack/echo/v4"
)

func GetUser(ctx echo.Context) (*models.UserSession, error) {
	user, ok := ctx.Get("user").(*models.UserSession)
	if !ok {
		return nil, errors.New("user not found in context")
	}
	return user, nil
}

func Authenticate(next echo.HandlerFunc) echo.HandlerFunc {
	return func(ctx echo.Context) error {
		token := ctx.Request().Header.Get("Authorization")

		user, err := services.AuthGetUserSessionFromToken(token)
		if err != nil {
			return echo.NewHTTPError(http.StatusUnauthorized, "unauthorized")
		}

		ctx.Set("user", user)
		return next(ctx)
	}
}

func RequireAdmin(next echo.HandlerFunc) echo.HandlerFunc {
	return func(ctx echo.Context) error {
		user, err := GetUser(ctx)
		if err != nil {
			return echo.NewHTTPError(http.StatusUnauthorized, "unauthorized")
		}

		if !user.IsAdmin {
			return echo.NewHTTPError(http.StatusForbidden, "forbidden")
		}

		return next(ctx)
	}
}