This commit is contained in:
Vladislav Kunetskiy
2026-10-15 20:52:43 +03:00
parent 4300d49c20
commit 4e84354642
125 changed files with 12049 additions and 2120 deletions
+24 -20
View File
@@ -7,50 +7,54 @@ import (
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/transport/rest/oas"
"mtusi-messenger/internal/transport/rest/internal/oas"
)
var ErrUnauthenticated = errors.New("caller is not identified")
type callerKey struct{}
type (
callerKey struct{}
tokenKey struct{}
credentialsKey struct{}
)
func CallerFromContext(ctx context.Context) (uuid.UUID, bool) {
id, ok := ctx.Value(callerKey{}).(uuid.UUID)
return id, ok
}
func caller(ctx context.Context) uuid.UUID {
id, _ := CallerFromContext(ctx)
return id
}
type UserLookup interface {
GetByID(ctx context.Context, id uuid.UUID) (domain.User, error)
type SecSessionService interface {
Authenticate(ctx context.Context, username, password string) (domain.User, error)
Resolve(ctx context.Context, token string) (domain.User, error)
}
type SecurityHandler struct {
users UserLookup
sessions SecSessionService
}
func NewSecurityHandler(users UserLookup) *SecurityHandler {
return &SecurityHandler{users: users}
func NewSecurityHandler(sessions SecSessionService) *SecurityHandler {
return &SecurityHandler{sessions: sessions}
}
func (h *SecurityHandler) HandleDevUser(
ctx context.Context,
_ oas.OperationName,
t oas.DevUser,
) (context.Context, error) {
id, err := uuid.Parse(t.APIKey)
func (h *SecurityHandler) HandleBasicAuth(ctx context.Context, _ oas.OperationName, auth oas.BasicAuth) (context.Context, error) {
user, err := h.sessions.Authenticate(ctx, auth.Username, auth.Password)
if err != nil {
return ctx, ErrUnauthenticated
return ctx, err
}
ctx = context.WithValue(ctx, callerKey{}, user.ID)
return context.WithValue(ctx, credentialsKey{}, user), nil
}
if _, err := h.users.GetByID(ctx, id); err != nil {
return ctx, ErrUnauthenticated
func (h *SecurityHandler) HandleBearerAuth(ctx context.Context, _ oas.OperationName, auth oas.BearerAuth) (context.Context, error) {
user, err := h.sessions.Resolve(ctx, auth.Token)
if err != nil {
return ctx, err
}
return context.WithValue(ctx, callerKey{}, id), nil
ctx = context.WithValue(ctx, callerKey{}, user.ID)
return context.WithValue(ctx, tokenKey{}, auth.Token), nil
}