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