github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/apiserver/common/interfaces.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package common
     5  
     6  import (
     7  	"github.com/juju/errors"
     8  	"gopkg.in/juju/names.v2"
     9  )
    10  
    11  // AuthFunc returns whether the given entity is available to some operation.
    12  type AuthFunc func(tag names.Tag) bool
    13  
    14  // GetAuthFunc returns an AuthFunc.
    15  type GetAuthFunc func() (AuthFunc, error)
    16  
    17  // AuthEither returns an AuthFunc generator that returns an AuthFunc
    18  // that accepts any tag authorized by either of its arguments.
    19  func AuthEither(a, b GetAuthFunc) GetAuthFunc {
    20  	return func() (AuthFunc, error) {
    21  		f1, err := a()
    22  		if err != nil {
    23  			return nil, err
    24  		}
    25  		f2, err := b()
    26  		if err != nil {
    27  			return nil, err
    28  		}
    29  		return func(tag names.Tag) bool {
    30  			return f1(tag) || f2(tag)
    31  		}, nil
    32  	}
    33  }
    34  
    35  // AuthAlways returns an authentication function that always returns true iff it is passed a valid tag.
    36  func AuthAlways() GetAuthFunc {
    37  	return func() (AuthFunc, error) {
    38  		return func(tag names.Tag) bool {
    39  			return true
    40  		}, nil
    41  	}
    42  }
    43  
    44  // AuthNever returns an authentication function that never returns true.
    45  func AuthNever() GetAuthFunc {
    46  	return func() (AuthFunc, error) {
    47  		return func(tag names.Tag) bool {
    48  			return false
    49  		}, nil
    50  	}
    51  }
    52  
    53  // AuthFuncForTag returns an authentication function that always returns true iff it is passed a specific tag.
    54  func AuthFuncForTag(valid names.Tag) GetAuthFunc {
    55  	return func() (AuthFunc, error) {
    56  		return func(tag names.Tag) bool {
    57  			return tag == valid
    58  		}, nil
    59  	}
    60  }
    61  
    62  // AuthFuncForTagKind returns a GetAuthFunc which creates an AuthFunc
    63  // allowing only the given tag kind and denies all others. Passing an
    64  // empty kind is an error.
    65  func AuthFuncForTagKind(kind string) GetAuthFunc {
    66  	return func() (AuthFunc, error) {
    67  		if kind == "" {
    68  			return nil, errors.Errorf("tag kind cannot be empty")
    69  		}
    70  		return func(tag names.Tag) bool {
    71  			// Allow only the given tag kind.
    72  			if tag == nil {
    73  				return false
    74  			}
    75  			return tag.Kind() == kind
    76  		}, nil
    77  	}
    78  }