feat: 0.0.1
This commit is contained in:
146 files changed
+10444
No files matched your search
@@ -0,0 +1,51 @@
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user