package middleware import ( "database/sql" "fmt" "net/http" "strconv" "github.com/labstack/echo/v4" "git.grosinger.net/tgrosinger/saasitone/pkg/context" "git.grosinger.net/tgrosinger/saasitone/pkg/services" ) // LoadUser loads the user based on the ID provided as a path parameter func LoadUser(db *services.DBClient) echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { userID, err := strconv.Atoi(c.Param("user")) if err != nil { return echo.NewHTTPError(http.StatusNotFound) } u, err := db.C.GetUserByID(c.Request().Context(), userID) if err == nil { c.Set(context.UserKey, &u) return next(c) } if err == sql.ErrNoRows { return echo.NewHTTPError(http.StatusNotFound) } return echo.NewHTTPError( http.StatusInternalServerError, fmt.Sprintf("error querying user: %v", err), ) } } }