github.com/annwntech/go-micro/v2@v2.9.5/auth/namespace/namespace.go (about)

     1  package namespace
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  
     7  	"github.com/annwntech/go-micro/v2/auth"
     8  )
     9  
    10  var (
    11  	// ErrUnauthorized is returned by Authorize when a context without a blank account tries to access
    12  	// a restricted namespace
    13  	ErrUnauthorized = errors.New("An account is required")
    14  	// ErrForbidden is returned by Authorize when a context is trying to access a namespace it doesn't
    15  	// have access to
    16  	ErrForbidden = errors.New("Access denied to namespace")
    17  )
    18  
    19  const (
    20  	// DefaultNamespace used by the server
    21  	DefaultNamespace = "micro"
    22  )
    23  
    24  // Authorize will return an error if the context cannot access the given namespace
    25  func Authorize(ctx context.Context, namespace string, opts ...AuthorizeOption) error {
    26  	// parse the options
    27  	var options AuthorizeOptions
    28  	for _, o := range opts {
    29  		o(&options)
    30  	}
    31  
    32  	// check to see if the namespace was made public
    33  	if namespace == options.PublicNamespace {
    34  		return nil
    35  	}
    36  
    37  	// accounts are always required so we can identify the caller. If auth is not configured, the noop
    38  	// auth implementation will return a blank account with the default namespace set, allowing the caller
    39  	// access to all resources
    40  	acc, ok := auth.AccountFromContext(ctx)
    41  	if !ok {
    42  		return ErrUnauthorized
    43  	}
    44  
    45  	// the server can access all namespaces
    46  	if acc.Issuer == DefaultNamespace {
    47  		return nil
    48  	}
    49  
    50  	// ensure the account is requesing access to it's own namespace
    51  	if acc.Issuer != namespace {
    52  		return ErrForbidden
    53  	}
    54  
    55  	return nil
    56  }
    57  
    58  // AuthorizeOptions are used to configure the Authorize method
    59  type AuthorizeOptions struct {
    60  	PublicNamespace string
    61  }
    62  
    63  // AuthorizeOption sets an attribute on AuthorizeOptions
    64  type AuthorizeOption func(o *AuthorizeOptions)
    65  
    66  // Public indicates a namespace is public and can be accessed by anyone
    67  func Public(ns string) AuthorizeOption {
    68  	return func(o *AuthorizeOptions) {
    69  		o.PublicNamespace = ns
    70  	}
    71  }