github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/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 // AuthAny returns an AuthFunc generator that returns an AuthFunc that 18 // accepts any tag authorized by any of its arguments. If no arguments 19 // are passed this is equivalent to AuthNever. 20 func AuthAny(getFuncs ...GetAuthFunc) GetAuthFunc { 21 return func() (AuthFunc, error) { 22 funcs := make([]AuthFunc, len(getFuncs)) 23 for i, getFunc := range getFuncs { 24 f, err := getFunc() 25 if err != nil { 26 return nil, errors.Trace(err) 27 } 28 funcs[i] = f 29 } 30 combined := func(tag names.Tag) bool { 31 for _, f := range funcs { 32 if f(tag) { 33 return true 34 } 35 } 36 return false 37 } 38 return combined, nil 39 } 40 } 41 42 // AuthAlways returns an authentication function that always returns true iff it is passed a valid tag. 43 func AuthAlways() GetAuthFunc { 44 return func() (AuthFunc, error) { 45 return func(tag names.Tag) bool { 46 return true 47 }, nil 48 } 49 } 50 51 // AuthFuncForTag returns an authentication function that always returns true iff it is passed a specific tag. 52 func AuthFuncForTag(valid names.Tag) GetAuthFunc { 53 return func() (AuthFunc, error) { 54 return func(tag names.Tag) bool { 55 return tag == valid 56 }, nil 57 } 58 } 59 60 // AuthFuncForTagKind returns a GetAuthFunc which creates an AuthFunc 61 // allowing only the given tag kind and denies all others. Passing an 62 // empty kind is an error. 63 func AuthFuncForTagKind(kind string) GetAuthFunc { 64 return func() (AuthFunc, error) { 65 if kind == "" { 66 return nil, errors.Errorf("tag kind cannot be empty") 67 } 68 return func(tag names.Tag) bool { 69 // Allow only the given tag kind. 70 if tag == nil { 71 return false 72 } 73 return tag.Kind() == kind 74 }, nil 75 } 76 }