Browse Source

encrypt and save hostpass on HostCreate

Matthew R. Kasun 2 years ago
parent
commit
bc47ef4868
3 changed files with 22 additions and 13 deletions
  1. 4 2
      controllers/node.go
  2. 18 3
      logic/hosts.go
  3. 0 8
      logic/nodes.go

+ 4 - 2
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

+ 18 - 3
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)
+}

+ 0 - 8
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