lab1
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/transport/rest/oas"
|
||||
)
|
||||
|
||||
var ErrUnauthenticated = errors.New("caller is not identified")
|
||||
|
||||
type callerKey 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 SecurityHandler struct {
|
||||
users UserLookup
|
||||
}
|
||||
|
||||
func NewSecurityHandler(users UserLookup) *SecurityHandler {
|
||||
return &SecurityHandler{users: users}
|
||||
}
|
||||
|
||||
func (h *SecurityHandler) HandleDevUser(
|
||||
ctx context.Context,
|
||||
_ oas.OperationName,
|
||||
t oas.DevUser,
|
||||
) (context.Context, error) {
|
||||
id, err := uuid.Parse(t.APIKey)
|
||||
if err != nil {
|
||||
return ctx, ErrUnauthenticated
|
||||
}
|
||||
|
||||
if _, err := h.users.GetByID(ctx, id); err != nil {
|
||||
return ctx, ErrUnauthenticated
|
||||
}
|
||||
|
||||
return context.WithValue(ctx, callerKey{}, id), nil
|
||||
}
|
||||
Reference in New Issue
Block a user