nquest/pkg/contextlib/user.go

40 lines
728 B
Go
Raw Normal View History

2023-11-01 23:21:12 +03:00
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)
}
}
}