diff --git a/controllers/node.go b/controllers/node.go index 863f53a1..2ace3008 100644 --- a/controllers/node.go +++ b/controllers/node.go @@ -607,8 +607,10 @@ func createNode(w http.ResponseWriter, r *http.Request) { // consume password before hashing for mq client creation nodePassword := data.Host.HostPass data.Node.Server = servercfg.GetServer() - if _, err := logic.GetHost(data.Node.HostID.String()); err != nil { - if err := logic.CreateHost(&data.Host); err != nil { + if err := logic.CreateHost(&data.Host); err != nil { + if errors.Is(err, logic.ErrHostExists) { + logger.Log(3, "host exists .. no need to create") + } else { logger.Log(0, "error creating host", err.Error()) logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest")) return diff --git a/logic/hosts.go b/logic/hosts.go index 25f28491..4f0774ca 100644 --- a/logic/hosts.go +++ b/logic/hosts.go @@ -2,12 +2,15 @@ package logic import ( "encoding/json" - "fmt" + "errors" "github.com/gravitl/netmaker/database" "github.com/gravitl/netmaker/models" + "golang.org/x/crypto/bcrypt" ) +var ErrHostExists error = errors.New("host already exists") + // GetAllHosts - returns all hosts in flat list or error func GetAllHosts() ([]models.Host, error) { currHostMap, err := GetHostsMap() @@ -61,9 +64,14 @@ func GetHost(hostid string) (*models.Host, error) { func CreateHost(h *models.Host) error { _, err := GetHost(h.ID.String()) if (err != nil && !database.IsEmptyRecord(err)) || (err == nil) { - return fmt.Errorf("host already exists") + return ErrHostExists } - + //encrypt that password so we never see it + hash, err := bcrypt.GenerateFromPassword([]byte(h.HostPass), 5) + if err != nil { + return err + } + h.HostPass = string(hash) return UpsertHost(h) } @@ -136,3 +144,10 @@ func RemoveHost(h *models.Host) error { } return database.DeleteRecord(database.HOSTS_TABLE_NAME, h.ID.String()) } + +// host.UpdatePass updates and saves host.HostPass +// Password saved on server needs to be the hashedPassword, whereas the raw password belongs to client +func UpdatePass(h *models.Host, pass string) error { + h.HostPass = pass + return UpsertHost(h) +} diff --git a/logic/nodes.go b/logic/nodes.go index f206aff2..ed3069e4 100644 --- a/logic/nodes.go +++ b/logic/nodes.go @@ -20,7 +20,6 @@ import ( "github.com/gravitl/netmaker/netclient/ncutils" "github.com/gravitl/netmaker/servercfg" "github.com/gravitl/netmaker/validation" - "golang.org/x/crypto/bcrypt" ) const ( @@ -191,13 +190,6 @@ func CreateNode(node *models.Node) error { return err } - //encrypt that password so we never see it - hash, err := bcrypt.GenerateFromPassword([]byte(host.HostPass), 5) - if err != nil { - return err - } - //set password to encrypted password - host.HostPass = string(hash) if !node.DNSOn { if servercfg.IsDNSMode() { node.DNSOn = true