Rename the module, proto service, and all identifiers from simple_bank/ SimpleBank to api_tmpl/ApiTmpl, and regenerate the gRPC/gateway/swagger/ mock code accordingly. - Scrub real secrets (SMTP password, auth token secret) from api.env/ api_test.env, untrack them, and add api.env.example/api_test.env.example - Remove committed build artifacts (tmp/main, tmp/build-errors.log, dbml-error.log) and gitignore them going forward - Fix Dockerfile paths (build target, migrations copy) that referenced a stale project layout - Rewrite README to match the actual cmd/ + internal/ structure and add a "using this as a template" section
52 lines
1.2 KiB
Go
52 lines
1.2 KiB
Go
package gapi
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/FernandoJVideira/api_tmpl/internal/auth"
|
|
"github.com/FernandoJVideira/api_tmpl/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
|
|
}
|