52 lines
1.2 KiB
Go
52 lines
1.2 KiB
Go
package gapi
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/FernandoJVideira/simple_bank/internal/auth"
|
|
"github.com/FernandoJVideira/simple_bank/internal/domain/role"
|
|
"google.golang.org/grpc/metadata"
|
|
)
|
|
|
|
const (
|
|
authHeaderKey = "authorization"
|
|
authTypeBearer = "bearer"
|
|
)
|
|
|
|
func (s *Server) authorizeUser(ctx context.Context, accessibleRoles []string) (*auth.Payload, error) {
|
|
md, ok := metadata.FromIncomingContext(ctx)
|
|
if !ok {
|
|
return nil, fmt.Errorf("missing metadata")
|
|
}
|
|
|
|
values := md.Get(authHeaderKey)
|
|
if len(values) == 0 {
|
|
return nil, fmt.Errorf("missing authorization header")
|
|
}
|
|
|
|
authHeader := values[0]
|
|
fields := strings.Fields(authHeader)
|
|
if len(fields) < 2 {
|
|
return nil, fmt.Errorf("invalid authorization header format")
|
|
}
|
|
|
|
authType := strings.ToLower(fields[0])
|
|
if authType != authTypeBearer {
|
|
return nil, fmt.Errorf("unsupported authorization type: %s", authType)
|
|
}
|
|
|
|
accessToken := fields[1]
|
|
payload, err := s.tokenMaker.VerifyToken(accessToken)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid token: %v", err)
|
|
}
|
|
|
|
if !role.HasPermission(payload.Role, accessibleRoles) {
|
|
return nil, fmt.Errorf("permission denied")
|
|
}
|
|
|
|
return payload, nil
|
|
}
|