39 lines
728 B
Go
39 lines
728 B
Go
package contextlib
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"gitrepo.ru/neonxp/nquest/pkg/models"
|
|
"gitrepo.ru/neonxp/nquest/pkg/service"
|
|
)
|
|
|
|
type userKeyCtx struct{}
|
|
|
|
func GetUser(c echo.Context) *models.User {
|
|
user, ok := c.Request().Context().Value(userKeyCtx{}).(*models.User)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
|
|
return user
|
|
}
|
|
|
|
func User(userService *service.User) echo.MiddlewareFunc {
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
user := userService.GetUser(c)
|
|
if user == nil {
|
|
return next(c)
|
|
}
|
|
|
|
ctx := c.Request().Context()
|
|
|
|
ctx = context.WithValue(ctx, userKeyCtx{}, user)
|
|
|
|
c.SetRequest(c.Request().WithContext(ctx))
|
|
|
|
return next(c)
|
|
}
|
|
}
|
|
}
|