forked from mtusi2026/mtusi2026lab6
ЛР 6 — БПИ2302 — Нурлыгаянова — на 3
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const AuthTokenKey = "auth_token"
|
||||
|
||||
const (
|
||||
BearerChallenge = `Bearer realm="messenger"`
|
||||
BasicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
)
|
||||
|
||||
type Authenticator interface {
|
||||
Authenticate(ctx context.Context, token string) (userID string, err error)
|
||||
}
|
||||
|
||||
func Bearer(auth Authenticator) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
tok, ok := BearerToken(c.Request().Header.Get(echo.HeaderAuthorization))
|
||||
if !ok {
|
||||
return unauthorized(c, BearerChallenge, "Bearer token required")
|
||||
}
|
||||
userID, err := auth.Authenticate(c.Request().Context(), tok)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrUnauthorized) {
|
||||
return unauthorized(c, BearerChallenge, "Invalid or expired session")
|
||||
}
|
||||
return err
|
||||
}
|
||||
c.Set(AuthUserIDKey, userID)
|
||||
c.Set(AuthTokenKey, tok)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BearerToken(header string) (string, bool) {
|
||||
scheme, tok, found := strings.Cut(header, " ")
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") {
|
||||
return "", false
|
||||
}
|
||||
tok = strings.TrimSpace(tok)
|
||||
return tok, tok != ""
|
||||
}
|
||||
|
||||
func unauthorized(c echo.Context, challenge, msg string) error {
|
||||
c.Response().Header().Set(echo.HeaderWWWAuthenticate, challenge)
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, msg)
|
||||
}
|
||||
|
||||
func Unauthorized(c echo.Context, challenge, msg string) error {
|
||||
return unauthorized(c, challenge, msg)
|
||||
}
|
||||
Reference in New Issue
Block a user