github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/environs/authenticationprovider.go (about) 1 // Copyright 2012, 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package environs 5 6 import ( 7 "fmt" 8 9 "launchpad.net/juju-core/state" 10 "launchpad.net/juju-core/state/api" 11 apiprovisioner "launchpad.net/juju-core/state/api/provisioner" 12 "launchpad.net/juju-core/utils" 13 ) 14 15 // TaggedPasswordChanger defines an interface for a entity with a 16 // Tag() and SetPassword() methods. 17 type TaggedPasswordChanger interface { 18 SetPassword(string) error 19 Tag() string 20 } 21 22 // AuthenticationProvider defines the single method that the provisioner 23 // task needs to set up authentication for a machine. 24 type AuthenticationProvider interface { 25 SetupAuthentication(machine TaggedPasswordChanger) (*state.Info, *api.Info, error) 26 } 27 28 // NewEnvironAuthenticator gets the state and api info once from the environ. 29 func NewEnvironAuthenticator(environ Environ) (AuthenticationProvider, error) { 30 stateInfo, apiInfo, err := environ.StateInfo() 31 if err != nil { 32 return nil, err 33 } 34 return &simpleAuth{stateInfo, apiInfo}, nil 35 } 36 37 // NewAPIAuthenticator gets the state and api info once from the 38 // provisioner API. 39 func NewAPIAuthenticator(st *apiprovisioner.State) (AuthenticationProvider, error) { 40 stateAddresses, err := st.StateAddresses() 41 if err != nil { 42 return nil, err 43 } 44 apiAddresses, err := st.APIAddresses() 45 if err != nil { 46 return nil, err 47 } 48 caCert, err := st.CACert() 49 if err != nil { 50 return nil, err 51 } 52 stateInfo := &state.Info{ 53 Addrs: stateAddresses, 54 CACert: caCert, 55 } 56 apiInfo := &api.Info{ 57 Addrs: apiAddresses, 58 CACert: caCert, 59 } 60 return &simpleAuth{stateInfo, apiInfo}, nil 61 } 62 63 type simpleAuth struct { 64 stateInfo *state.Info 65 apiInfo *api.Info 66 } 67 68 func (auth *simpleAuth) SetupAuthentication(machine TaggedPasswordChanger) (*state.Info, *api.Info, error) { 69 password, err := utils.RandomPassword() 70 if err != nil { 71 return nil, nil, fmt.Errorf("cannot make password for machine %v: %v", machine, err) 72 } 73 if err := machine.SetPassword(password); err != nil { 74 return nil, nil, fmt.Errorf("cannot set API password for machine %v: %v", machine, err) 75 } 76 stateInfo := *auth.stateInfo 77 stateInfo.Tag = machine.Tag() 78 stateInfo.Password = password 79 apiInfo := *auth.apiInfo 80 apiInfo.Tag = machine.Tag() 81 apiInfo.Password = password 82 return &stateInfo, &apiInfo, nil 83 }