61 lines
1.6 KiB
Go
61 lines
1.6 KiB
Go
package rest
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"mtusi-messenger/internal/domain"
|
|
"mtusi-messenger/internal/transport/rest/internal/oas"
|
|
)
|
|
|
|
var ErrUnauthenticated = errors.New("caller is not identified")
|
|
|
|
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 SecSessionService interface {
|
|
Authenticate(ctx context.Context, username, password string) (domain.User, error)
|
|
Resolve(ctx context.Context, token string) (domain.User, error)
|
|
}
|
|
|
|
type SecurityHandler struct {
|
|
sessions SecSessionService
|
|
}
|
|
|
|
func NewSecurityHandler(sessions SecSessionService) *SecurityHandler {
|
|
return &SecurityHandler{sessions: sessions}
|
|
}
|
|
|
|
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, err
|
|
}
|
|
ctx = context.WithValue(ctx, callerKey{}, user.ID)
|
|
return context.WithValue(ctx, credentialsKey{}, user), nil
|
|
}
|
|
|
|
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
|
|
}
|
|
ctx = context.WithValue(ctx, callerKey{}, user.ID)
|
|
return context.WithValue(ctx, tokenKey{}, auth.Token), nil
|
|
}
|