From 3377844dddf56b3b6b21a7fa63eec641a4d55835 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 22 Aug 2024 08:03:04 +0530 Subject: [PATCH 01/35] generalise smtp config --- pro/email/email.go | 8 +++++++- pro/email/smtp.go | 3 ++- servercfg/serverconf.go | 12 +++++++++++- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/pro/email/email.go b/pro/email/email.go index 650548420..bd7c63448 100644 --- a/pro/email/email.go +++ b/pro/email/email.go @@ -18,12 +18,18 @@ const ( func init() { switch EmailSenderType(servercfg.EmailSenderType()) { case Smtp: - client = &SmtpSender{ + smtpSender := &SmtpSender{ SmtpHost: servercfg.GetSmtpHost(), SmtpPort: servercfg.GetSmtpPort(), SenderEmail: servercfg.GetSenderEmail(), + SendUser: servercfg.GetSenderUser(), SenderPass: servercfg.GetEmaiSenderAuth(), } + if smtpSender.SendUser == "" { + smtpSender.SendUser = smtpSender.SenderEmail + } + client = smtpSender + case Resend: client = NewResendEmailSenderFromConfig() } diff --git a/pro/email/smtp.go b/pro/email/smtp.go index 89965ca5e..4c96e5b09 100644 --- a/pro/email/smtp.go +++ b/pro/email/smtp.go @@ -11,6 +11,7 @@ type SmtpSender struct { SmtpHost string SmtpPort int SenderEmail string + SendUser string SenderPass string } @@ -27,7 +28,7 @@ func (s *SmtpSender) SendEmail(ctx context.Context, n Notification, e Mail) erro // Set E-Mail body. You can set plain text or html with text/html m.SetBody("text/html", e.GetBody(n)) // Settings for SMTP server - d := gomail.NewDialer(s.SmtpHost, s.SmtpPort, s.SenderEmail, s.SenderPass) + d := gomail.NewDialer(s.SmtpHost, s.SmtpPort, s.SendUser, s.SenderPass) // This is only needed when SSL/TLS certificate is not valid on server. // In production this should be set to false. diff --git a/servercfg/serverconf.go b/servercfg/serverconf.go index 5a5916d29..f368bb887 100644 --- a/servercfg/serverconf.go +++ b/servercfg/serverconf.go @@ -275,9 +275,19 @@ func GetSenderEmail() string { return v } +func GetSenderUser() string { + v := "" + if fromEnv := os.Getenv("EMAIL_SENDER_USER"); fromEnv != "" { + v = fromEnv + } else if fromCfg := config.Config.Server.EmailSenderAddr; fromCfg != "" { + v = fromCfg + } + return v +} + func GetEmaiSenderAuth() string { v := "" - if fromEnv := os.Getenv("EMAIL_SENDER_AUTH"); fromEnv != "" { + if fromEnv := os.Getenv("EMAIL_SENDER_PASSWORD"); fromEnv != "" { v = fromEnv } else if fromCfg := config.Config.Server.EmailSenderAddr; fromCfg != "" { v = fromCfg From 82eecf566671d170478a70fbd35cd5f03420b2c9 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 22 Aug 2024 08:34:31 +0530 Subject: [PATCH 02/35] copy over smtp vars --- scripts/netmaker.default.env | 6 ++++-- scripts/nm-quick.sh | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/netmaker.default.env b/scripts/netmaker.default.env index 876c2a4b2..d9a31cb0c 100644 --- a/scripts/netmaker.default.env +++ b/scripts/netmaker.default.env @@ -82,7 +82,9 @@ SMTP_HOST=smtp.gmail.com SMTP_PORT=587 # sender email EMAIL_SENDER_ADDR= -# sender email auth -EMAIL_SENDER_AUTH= +# sender smtp user, if unset sender email will be used +EMAIL_SENDER_USER= +# sender smtp password +EMAIL_SENDER_PASSWORD= # mail sender type (smtp or resend) EMAIL_SENDER_TYPE=smtp \ No newline at end of file diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index ab18eed58..2a1d67597 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -253,7 +253,8 @@ save_config() { ( "INSTALL_TYPE" "NODE_ID" "DNS_MODE" "NETCLIENT_AUTO_UPDATE" "API_PORT" "CORS_ALLOWED_ORIGIN" "DISPLAY_KEYS" "DATABASE" "SERVER_BROKER_ENDPOINT" "VERBOSITY" "DEBUG_MODE" "REST_BACKEND" "DISABLE_REMOTE_IP_CHECK" "TELEMETRY" "ALLOWED_EMAIL_DOMAINS" "AUTH_PROVIDER" "CLIENT_ID" "CLIENT_SECRET" - "FRONTEND_URL" "AZURE_TENANT" "OIDC_ISSUER" "EXPORTER_API_PORT" "JWT_VALIDITY_DURATION" "RAC_AUTO_DISABLE" "CACHING_ENABLED" "ENDPOINT_DETECTION") + "FRONTEND_URL" "AZURE_TENANT" "OIDC_ISSUER" "EXPORTER_API_PORT" "JWT_VALIDITY_DURATION" "RAC_AUTO_DISABLE" "CACHING_ENABLED" "ENDPOINT_DETECTION" + "SMTP_HOST" "SMTP_PORT" "EMAIL_SENDER_ADDR" "EMAIL_SENDER_USER" "EMAIL_SENDER_PASSWORD" "EMAIL_SENDER_TYPE") for name in "${toCopy[@]}"; do save_config_item $name "${!name}" done From c8eec1ed0449b0bad455065da4911116af3ffc2a Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 22 Aug 2024 08:35:37 +0530 Subject: [PATCH 03/35] env new line --- scripts/netmaker.default.env | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/netmaker.default.env b/scripts/netmaker.default.env index d9a31cb0c..196ad3668 100644 --- a/scripts/netmaker.default.env +++ b/scripts/netmaker.default.env @@ -87,4 +87,4 @@ EMAIL_SENDER_USER= # sender smtp password EMAIL_SENDER_PASSWORD= # mail sender type (smtp or resend) -EMAIL_SENDER_TYPE=smtp \ No newline at end of file +EMAIL_SENDER_TYPE=smtp From 54e605493d0ddd172a7e17124480c9781572266a Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 22 Aug 2024 11:29:11 +0530 Subject: [PATCH 04/35] fix master key api access --- controllers/hosts.go | 72 ++++++++++++++++------------ controllers/node.go | 112 ++++++++++++++++++++++--------------------- 2 files changed, 99 insertions(+), 85 deletions(-) diff --git a/controllers/hosts.go b/controllers/hosts.go index 9a2d4bc4a..349894331 100644 --- a/controllers/hosts.go +++ b/controllers/hosts.go @@ -81,48 +81,58 @@ func upgradeHost(w http.ResponseWriter, r *http.Request) { func getHosts(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") currentHosts := []models.Host{} - username := r.Header.Get("user") - user, err := logic.GetUser(username) - if err != nil { - return - } - userPlatformRole, err := logic.GetRole(user.PlatformRoleID) - if err != nil { - return - } - respHostsMap := make(map[string]struct{}) - if !userPlatformRole.FullAccess { - nodes, err := logic.GetAllNodes() + var err error + if r.Header.Get("ismaster") == "yes" { + currentHosts, err = logic.GetAllHosts() if err != nil { - logger.Log(0, "error fetching all nodes info: ", err.Error()) + logger.Log(0, r.Header.Get("user"), "failed to fetch hosts: ", err.Error()) logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) return } - filteredNodes := logic.GetFilteredNodesByUserAccess(*user, nodes) - if len(filteredNodes) > 0 { - currentHostsMap, err := logic.GetHostsMap() + } else { + username := r.Header.Get("user") + user, err := logic.GetUser(username) + if err != nil { + return + } + userPlatformRole, err := logic.GetRole(user.PlatformRoleID) + if err != nil { + return + } + respHostsMap := make(map[string]struct{}) + if !userPlatformRole.FullAccess { + nodes, err := logic.GetAllNodes() if err != nil { - logger.Log(0, r.Header.Get("user"), "failed to fetch hosts: ", err.Error()) + logger.Log(0, "error fetching all nodes info: ", err.Error()) logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) return } - for _, node := range filteredNodes { - if _, ok := respHostsMap[node.HostID.String()]; ok { - continue + filteredNodes := logic.GetFilteredNodesByUserAccess(*user, nodes) + if len(filteredNodes) > 0 { + currentHostsMap, err := logic.GetHostsMap() + if err != nil { + logger.Log(0, r.Header.Get("user"), "failed to fetch hosts: ", err.Error()) + logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) + return } - if host, ok := currentHostsMap[node.HostID.String()]; ok { - currentHosts = append(currentHosts, host) - respHostsMap[host.ID.String()] = struct{}{} + for _, node := range filteredNodes { + if _, ok := respHostsMap[node.HostID.String()]; ok { + continue + } + if host, ok := currentHostsMap[node.HostID.String()]; ok { + currentHosts = append(currentHosts, host) + respHostsMap[host.ID.String()] = struct{}{} + } } - } - } - } else { - currentHosts, err = logic.GetAllHosts() - if err != nil { - logger.Log(0, r.Header.Get("user"), "failed to fetch hosts: ", err.Error()) - logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) - return + } + } else { + currentHosts, err = logic.GetAllHosts() + if err != nil { + logger.Log(0, r.Header.Get("user"), "failed to fetch hosts: ", err.Error()) + logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) + return + } } } diff --git a/controllers/node.go b/controllers/node.go index 3790e2f41..fd6f5d902 100644 --- a/controllers/node.go +++ b/controllers/node.go @@ -268,56 +268,59 @@ func getNetworkNodes(w http.ResponseWriter, r *http.Request) { logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) return } - username := r.Header.Get("user") - user, err := logic.GetUser(username) - if err != nil { - logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) - return - } - userPlatformRole, err := logic.GetRole(user.PlatformRoleID) - if err != nil { - logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) - return - } filteredNodes := []models.Node{} - if !userPlatformRole.FullAccess { - nodesMap := make(map[string]struct{}) - networkRoles := user.NetworkRoles[models.NetworkID(networkName)] - for networkRoleID := range networkRoles { - userPermTemplate, err := logic.GetRole(networkRoleID) - if err != nil { - logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) - return - } - if userPermTemplate.FullAccess { - break - } - if rsrcPerms, ok := userPermTemplate.NetworkLevelAccess[models.RemoteAccessGwRsrc]; ok { - if _, ok := rsrcPerms[models.AllRemoteAccessGwRsrcID]; ok { - for _, node := range nodes { - if _, ok := nodesMap[node.ID.String()]; ok { - continue - } - if node.IsIngressGateway { - nodesMap[node.ID.String()] = struct{}{} - filteredNodes = append(filteredNodes, node) - } - } - } else { - for gwID, scope := range rsrcPerms { - if _, ok := nodesMap[gwID.String()]; ok { - continue + if r.Header.Get("ismaster") != "yes" { + username := r.Header.Get("user") + user, err := logic.GetUser(username) + if err != nil { + logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) + return + } + userPlatformRole, err := logic.GetRole(user.PlatformRoleID) + if err != nil { + logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) + return + } + + if !userPlatformRole.FullAccess { + nodesMap := make(map[string]struct{}) + networkRoles := user.NetworkRoles[models.NetworkID(networkName)] + for networkRoleID := range networkRoles { + userPermTemplate, err := logic.GetRole(networkRoleID) + if err != nil { + logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) + return + } + if userPermTemplate.FullAccess { + break + } + if rsrcPerms, ok := userPermTemplate.NetworkLevelAccess[models.RemoteAccessGwRsrc]; ok { + if _, ok := rsrcPerms[models.AllRemoteAccessGwRsrcID]; ok { + for _, node := range nodes { + if _, ok := nodesMap[node.ID.String()]; ok { + continue + } + if node.IsIngressGateway { + nodesMap[node.ID.String()] = struct{}{} + filteredNodes = append(filteredNodes, node) + } } - if scope.Read { - gwNode, err := logic.GetNodeByID(gwID.String()) - if err == nil && gwNode.IsIngressGateway { - filteredNodes = append(filteredNodes, gwNode) + } else { + for gwID, scope := range rsrcPerms { + if _, ok := nodesMap[gwID.String()]; ok { + continue + } + if scope.Read { + gwNode, err := logic.GetNodeByID(gwID.String()) + if err == nil && gwNode.IsIngressGateway { + filteredNodes = append(filteredNodes, gwNode) + } } } } } - } + } } } if len(filteredNodes) > 0 { @@ -348,18 +351,19 @@ func getAllNodes(w http.ResponseWriter, r *http.Request) { return } username := r.Header.Get("user") - user, err := logic.GetUser(username) - if err != nil { - return - } - userPlatformRole, err := logic.GetRole(user.PlatformRoleID) - if err != nil { - return - } - if !userPlatformRole.FullAccess { - nodes = logic.GetFilteredNodesByUserAccess(*user, nodes) + if r.Header.Get("ismaster") == "no" { + user, err := logic.GetUser(username) + if err != nil { + return + } + userPlatformRole, err := logic.GetRole(user.PlatformRoleID) + if err != nil { + return + } + if !userPlatformRole.FullAccess { + nodes = logic.GetFilteredNodesByUserAccess(*user, nodes) + } } - // return all the nodes in JSON/API format apiNodes := logic.GetAllNodesAPI(nodes[:]) logger.Log(3, r.Header.Get("user"), "fetched all nodes they have access to") From 2e945fa7e6d753ed32dd50ba42a03998fbaefce6 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 22 Aug 2024 11:32:38 +0530 Subject: [PATCH 05/35] comment user tests --- controllers/user_test.go | 671 +++++++++++++++++++-------------------- 1 file changed, 328 insertions(+), 343 deletions(-) diff --git a/controllers/user_test.go b/controllers/user_test.go index 6c65fa386..a1041f229 100644 --- a/controllers/user_test.go +++ b/controllers/user_test.go @@ -1,376 +1,361 @@ package controller -import ( - "bytes" - "io" - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-jose/go-jose/v3/json" - "github.com/gorilla/mux" - - "github.com/stretchr/testify/assert" - - "github.com/gravitl/netmaker/logic" - "github.com/gravitl/netmaker/models" -) +// TODO: Need Update Tests for New User Mgmt +// func deleteAllUsers(t *testing.T) { +// t.Helper() +// users, _ := logic.GetUsers() +// for _, user := range users { +// if _, err := logic.DeleteUser(user.UserName); err != nil { +// t.Fatal(err) +// } +// } +// } -func deleteAllUsers(t *testing.T) { - t.Helper() - users, _ := logic.GetUsers() - for _, user := range users { - if _, err := logic.DeleteUser(user.UserName); err != nil { - t.Fatal(err) - } - } -} +// func TestGetUserNoHashedPassword(t *testing.T) { +// // prepare existing user base +// user := models.User{UserName: "freddie", Password: "password"} +// haveOnlyOneUser(t, user) -func TestGetUserNoHashedPassword(t *testing.T) { - // prepare existing user base - user := models.User{UserName: "freddie", Password: "password"} - haveOnlyOneUser(t, user) +// // prepare request +// rec, req := prepareUserRequest(t, models.User{}, user.UserName) - // prepare request - rec, req := prepareUserRequest(t, models.User{}, user.UserName) +// // test response +// getUser(rec, req) +// assertUserNameButNoPassword(t, rec.Body, user.UserName) +// } - // test response - getUser(rec, req) - assertUserNameButNoPassword(t, rec.Body, user.UserName) -} +// func TestCreateAdminNoHashedPassword(t *testing.T) { +// // prepare existing user base +// deleteAllUsers(t) -func TestCreateAdminNoHashedPassword(t *testing.T) { - // prepare existing user base - deleteAllUsers(t) +// // prepare request +// user := models.User{UserName: "jonathan", Password: "password"} +// rec, req := prepareUserRequest(t, user, "") - // prepare request - user := models.User{UserName: "jonathan", Password: "password"} - rec, req := prepareUserRequest(t, user, "") +// // test response +// createSuperAdmin(rec, req) +// assertUserNameButNoPassword(t, rec.Body, user.UserName) +// } - // test response - createSuperAdmin(rec, req) - assertUserNameButNoPassword(t, rec.Body, user.UserName) -} +// func prepareUserRequest(t *testing.T, userForBody models.User, userNameForParam string) (*httptest.ResponseRecorder, *http.Request) { +// bits, err := json.Marshal(userForBody) +// assert.Nil(t, err) +// body := bytes.NewReader(bits) +// rec := httptest.NewRecorder() +// req := httptest.NewRequest("ANY", "https://example.com", body) // only the body matters here +// req = mux.SetURLVars(req, map[string]string{"username": userNameForParam}) +// req.Header.Set("user", userForBody.UserName) +// return rec, req +// } -func prepareUserRequest(t *testing.T, userForBody models.User, userNameForParam string) (*httptest.ResponseRecorder, *http.Request) { - bits, err := json.Marshal(userForBody) - assert.Nil(t, err) - body := bytes.NewReader(bits) - rec := httptest.NewRecorder() - req := httptest.NewRequest("ANY", "https://example.com", body) // only the body matters here - req = mux.SetURLVars(req, map[string]string{"username": userNameForParam}) - req.Header.Set("user", userForBody.UserName) - return rec, req -} +// func haveOnlyOneUser(t *testing.T, user models.User) { +// deleteAllUsers(t) +// var err error +// if user.PlatformRoleID == models.SuperAdminRole { +// err = logic.CreateSuperAdmin(&user) +// } else { +// err = logic.CreateUser(&user) +// } +// assert.Nil(t, err) +// } -func haveOnlyOneUser(t *testing.T, user models.User) { - deleteAllUsers(t) - var err error - if user.PlatformRoleID == models.SuperAdminRole { - err = logic.CreateSuperAdmin(&user) - } else { - err = logic.CreateUser(&user) - } - assert.Nil(t, err) -} +// func assertUserNameButNoPassword(t *testing.T, r io.Reader, userName string) { +// var resp models.User +// err := json.NewDecoder(r).Decode(&resp) +// assert.Nil(t, err) +// assert.Equal(t, userName, resp.UserName) +// assert.Empty(t, resp.Password) +// } -func assertUserNameButNoPassword(t *testing.T, r io.Reader, userName string) { - var resp models.User - err := json.NewDecoder(r).Decode(&resp) - assert.Nil(t, err) - assert.Equal(t, userName, resp.UserName) - assert.Empty(t, resp.Password) -} +// func TestHasSuperAdmin(t *testing.T) { +// // delete all current users +// users, _ := logic.GetUsers() +// for _, user := range users { +// success, err := logic.DeleteUser(user.UserName) +// assert.Nil(t, err) +// assert.True(t, success) +// } +// t.Run("NoUser", func(t *testing.T) { +// found, err := logic.HasSuperAdmin() +// assert.Nil(t, err) +// assert.False(t, found) +// }) +// t.Run("No superadmin user", func(t *testing.T) { +// var user = models.User{UserName: "nosuperadmin", Password: "password"} +// err := logic.CreateUser(&user) +// assert.Nil(t, err) +// found, err := logic.HasSuperAdmin() +// assert.Nil(t, err) +// assert.False(t, found) +// }) +// t.Run("superadmin user", func(t *testing.T) { +// var user = models.User{UserName: "superadmin", Password: "password", PlatformRoleID: models.SuperAdminRole} +// err := logic.CreateUser(&user) +// assert.Nil(t, err) +// found, err := logic.HasSuperAdmin() +// assert.Nil(t, err) +// assert.True(t, found) +// }) +// t.Run("multiple superadmins", func(t *testing.T) { +// var user = models.User{UserName: "superadmin1", Password: "password", PlatformRoleID: models.SuperAdminRole} +// err := logic.CreateUser(&user) +// assert.Nil(t, err) +// found, err := logic.HasSuperAdmin() +// assert.Nil(t, err) +// assert.True(t, found) +// }) +// } -func TestHasSuperAdmin(t *testing.T) { - // delete all current users - users, _ := logic.GetUsers() - for _, user := range users { - success, err := logic.DeleteUser(user.UserName) - assert.Nil(t, err) - assert.True(t, success) - } - t.Run("NoUser", func(t *testing.T) { - found, err := logic.HasSuperAdmin() - assert.Nil(t, err) - assert.False(t, found) - }) - t.Run("No superadmin user", func(t *testing.T) { - var user = models.User{UserName: "nosuperadmin", Password: "password"} - err := logic.CreateUser(&user) - assert.Nil(t, err) - found, err := logic.HasSuperAdmin() - assert.Nil(t, err) - assert.False(t, found) - }) - t.Run("superadmin user", func(t *testing.T) { - var user = models.User{UserName: "superadmin", Password: "password", PlatformRoleID: models.SuperAdminRole} - err := logic.CreateUser(&user) - assert.Nil(t, err) - found, err := logic.HasSuperAdmin() - assert.Nil(t, err) - assert.True(t, found) - }) - t.Run("multiple superadmins", func(t *testing.T) { - var user = models.User{UserName: "superadmin1", Password: "password", PlatformRoleID: models.SuperAdminRole} - err := logic.CreateUser(&user) - assert.Nil(t, err) - found, err := logic.HasSuperAdmin() - assert.Nil(t, err) - assert.True(t, found) - }) -} +// func TestCreateUser(t *testing.T) { +// deleteAllUsers(t) +// user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} +// t.Run("NoUser", func(t *testing.T) { +// err := logic.CreateUser(&user) +// assert.Nil(t, err) +// }) +// t.Run("UserExists", func(t *testing.T) { +// err := logic.CreateUser(&user) +// assert.NotNil(t, err) +// assert.EqualError(t, err, "user exists") +// }) +// } -func TestCreateUser(t *testing.T) { - deleteAllUsers(t) - user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} - t.Run("NoUser", func(t *testing.T) { - err := logic.CreateUser(&user) - assert.Nil(t, err) - }) - t.Run("UserExists", func(t *testing.T) { - err := logic.CreateUser(&user) - assert.NotNil(t, err) - assert.EqualError(t, err, "user exists") - }) -} +// func TestCreateSuperAdmin(t *testing.T) { +// deleteAllUsers(t) +// logic.ClearSuperUserCache() +// var user models.User +// t.Run("NoSuperAdmin", func(t *testing.T) { +// user.UserName = "admin" +// user.Password = "password" +// err := logic.CreateSuperAdmin(&user) +// assert.Nil(t, err) +// }) +// t.Run("SuperAdminExists", func(t *testing.T) { +// user.UserName = "admin2" +// user.Password = "password1" +// err := logic.CreateSuperAdmin(&user) +// assert.EqualError(t, err, "superadmin user already exists") +// }) +// } -func TestCreateSuperAdmin(t *testing.T) { - deleteAllUsers(t) - logic.ClearSuperUserCache() - var user models.User - t.Run("NoSuperAdmin", func(t *testing.T) { - user.UserName = "admin" - user.Password = "password" - err := logic.CreateSuperAdmin(&user) - assert.Nil(t, err) - }) - t.Run("SuperAdminExists", func(t *testing.T) { - user.UserName = "admin2" - user.Password = "password1" - err := logic.CreateSuperAdmin(&user) - assert.EqualError(t, err, "superadmin user already exists") - }) -} +// func TestDeleteUser(t *testing.T) { +// deleteAllUsers(t) +// t.Run("NonExistent User", func(t *testing.T) { +// deleted, err := logic.DeleteUser("admin") +// assert.EqualError(t, err, "user does not exist") +// assert.False(t, deleted) +// }) +// t.Run("Existing User", func(t *testing.T) { +// user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} +// if err := logic.CreateUser(&user); err != nil { +// t.Fatal(err) +// } +// deleted, err := logic.DeleteUser("admin") +// assert.Nil(t, err) +// assert.True(t, deleted) +// }) +// } -func TestDeleteUser(t *testing.T) { - deleteAllUsers(t) - t.Run("NonExistent User", func(t *testing.T) { - deleted, err := logic.DeleteUser("admin") - assert.EqualError(t, err, "user does not exist") - assert.False(t, deleted) - }) - t.Run("Existing User", func(t *testing.T) { - user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} - if err := logic.CreateUser(&user); err != nil { - t.Fatal(err) - } - deleted, err := logic.DeleteUser("admin") - assert.Nil(t, err) - assert.True(t, deleted) - }) -} +// func TestValidateUser(t *testing.T) { +// var user models.User +// t.Run("Valid Create", func(t *testing.T) { +// user.UserName = "admin" +// user.Password = "validpass" +// err := logic.ValidateUser(&user) +// assert.Nil(t, err) +// }) +// t.Run("Valid Update", func(t *testing.T) { +// user.UserName = "admin" +// user.Password = "password" +// err := logic.ValidateUser(&user) +// assert.Nil(t, err) +// }) +// t.Run("Invalid UserName", func(t *testing.T) { +// t.Skip() +// user.UserName = "*invalid" +// err := logic.ValidateUser(&user) +// assert.Error(t, err) +// // assert.Contains(t, err.Error(), "Field validation for 'UserName' failed") +// }) +// t.Run("Short UserName", func(t *testing.T) { +// t.Skip() +// user.UserName = "1" +// err := logic.ValidateUser(&user) +// assert.NotNil(t, err) +// // assert.Contains(t, err.Error(), "Field validation for 'UserName' failed") +// }) +// t.Run("Empty UserName", func(t *testing.T) { +// t.Skip() +// user.UserName = "" +// err := logic.ValidateUser(&user) +// assert.EqualError(t, err, "some string") +// // assert.Contains(t, err.Error(), "Field validation for 'UserName' failed") +// }) +// t.Run("EmptyPassword", func(t *testing.T) { +// user.Password = "" +// err := logic.ValidateUser(&user) +// assert.EqualError(t, err, "Key: 'User.Password' Error:Field validation for 'Password' failed on the 'required' tag") +// }) +// t.Run("ShortPassword", func(t *testing.T) { +// user.Password = "123" +// err := logic.ValidateUser(&user) +// assert.EqualError(t, err, "Key: 'User.Password' Error:Field validation for 'Password' failed on the 'min' tag") +// }) +// } -func TestValidateUser(t *testing.T) { - var user models.User - t.Run("Valid Create", func(t *testing.T) { - user.UserName = "admin" - user.Password = "validpass" - err := logic.ValidateUser(&user) - assert.Nil(t, err) - }) - t.Run("Valid Update", func(t *testing.T) { - user.UserName = "admin" - user.Password = "password" - err := logic.ValidateUser(&user) - assert.Nil(t, err) - }) - t.Run("Invalid UserName", func(t *testing.T) { - t.Skip() - user.UserName = "*invalid" - err := logic.ValidateUser(&user) - assert.Error(t, err) - // assert.Contains(t, err.Error(), "Field validation for 'UserName' failed") - }) - t.Run("Short UserName", func(t *testing.T) { - t.Skip() - user.UserName = "1" - err := logic.ValidateUser(&user) - assert.NotNil(t, err) - // assert.Contains(t, err.Error(), "Field validation for 'UserName' failed") - }) - t.Run("Empty UserName", func(t *testing.T) { - t.Skip() - user.UserName = "" - err := logic.ValidateUser(&user) - assert.EqualError(t, err, "some string") - // assert.Contains(t, err.Error(), "Field validation for 'UserName' failed") - }) - t.Run("EmptyPassword", func(t *testing.T) { - user.Password = "" - err := logic.ValidateUser(&user) - assert.EqualError(t, err, "Key: 'User.Password' Error:Field validation for 'Password' failed on the 'required' tag") - }) - t.Run("ShortPassword", func(t *testing.T) { - user.Password = "123" - err := logic.ValidateUser(&user) - assert.EqualError(t, err, "Key: 'User.Password' Error:Field validation for 'Password' failed on the 'min' tag") - }) -} +// func TestGetUser(t *testing.T) { +// deleteAllUsers(t) -func TestGetUser(t *testing.T) { - deleteAllUsers(t) +// user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} - user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} +// t.Run("NonExistantUser", func(t *testing.T) { +// admin, err := logic.GetUser("admin") +// assert.EqualError(t, err, "could not find any records") +// assert.Equal(t, "", admin.UserName) +// }) +// t.Run("UserExisits", func(t *testing.T) { +// if err := logic.CreateUser(&user); err != nil { +// t.Error(err) +// } +// admin, err := logic.GetUser("admin") +// assert.Nil(t, err) +// assert.Equal(t, user.UserName, admin.UserName) +// }) +// } - t.Run("NonExistantUser", func(t *testing.T) { - admin, err := logic.GetUser("admin") - assert.EqualError(t, err, "could not find any records") - assert.Equal(t, "", admin.UserName) - }) - t.Run("UserExisits", func(t *testing.T) { - if err := logic.CreateUser(&user); err != nil { - t.Error(err) - } - admin, err := logic.GetUser("admin") - assert.Nil(t, err) - assert.Equal(t, user.UserName, admin.UserName) - }) -} +// func TestGetUsers(t *testing.T) { +// deleteAllUsers(t) -func TestGetUsers(t *testing.T) { - deleteAllUsers(t) +// adminUser := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} +// user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} - adminUser := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} - user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} +// t.Run("NonExistantUser", func(t *testing.T) { +// admin, err := logic.GetUsers() +// assert.EqualError(t, err, "could not find any records") +// assert.Equal(t, []models.ReturnUser(nil), admin) +// }) +// t.Run("UserExisits", func(t *testing.T) { +// user.UserName = "anotheruser" +// if err := logic.CreateUser(&adminUser); err != nil { +// t.Error(err) +// } +// admins, err := logic.GetUsers() +// assert.Nil(t, err) +// assert.Equal(t, adminUser.UserName, admins[0].UserName) +// }) +// t.Run("MulipleUsers", func(t *testing.T) { +// if err := logic.CreateUser(&user); err != nil { +// t.Error(err) +// } +// admins, err := logic.GetUsers() +// assert.Nil(t, err) +// for _, u := range admins { +// if u.UserName == "admin" { +// assert.Equal(t, true, u.IsAdmin) +// } else { +// assert.Equal(t, user.UserName, u.UserName) +// assert.Equal(t, user.PlatformRoleID, u.PlatformRoleID) +// } +// } +// }) - t.Run("NonExistantUser", func(t *testing.T) { - admin, err := logic.GetUsers() - assert.EqualError(t, err, "could not find any records") - assert.Equal(t, []models.ReturnUser(nil), admin) - }) - t.Run("UserExisits", func(t *testing.T) { - user.UserName = "anotheruser" - if err := logic.CreateUser(&adminUser); err != nil { - t.Error(err) - } - admins, err := logic.GetUsers() - assert.Nil(t, err) - assert.Equal(t, adminUser.UserName, admins[0].UserName) - }) - t.Run("MulipleUsers", func(t *testing.T) { - if err := logic.CreateUser(&user); err != nil { - t.Error(err) - } - admins, err := logic.GetUsers() - assert.Nil(t, err) - for _, u := range admins { - if u.UserName == "admin" { - assert.Equal(t, true, u.IsAdmin) - } else { - assert.Equal(t, user.UserName, u.UserName) - assert.Equal(t, user.PlatformRoleID, u.PlatformRoleID) - } - } - }) +// } -} +// func TestUpdateUser(t *testing.T) { +// deleteAllUsers(t) +// user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} +// newuser := models.User{UserName: "hello", Password: "world", PlatformRoleID: models.AdminRole} +// t.Run("NonExistantUser", func(t *testing.T) { +// admin, err := logic.UpdateUser(&newuser, &user) +// assert.EqualError(t, err, "could not find any records") +// assert.Equal(t, "", admin.UserName) +// }) -func TestUpdateUser(t *testing.T) { - deleteAllUsers(t) - user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} - newuser := models.User{UserName: "hello", Password: "world", PlatformRoleID: models.AdminRole} - t.Run("NonExistantUser", func(t *testing.T) { - admin, err := logic.UpdateUser(&newuser, &user) - assert.EqualError(t, err, "could not find any records") - assert.Equal(t, "", admin.UserName) - }) +// t.Run("UserExists", func(t *testing.T) { +// if err := logic.CreateUser(&user); err != nil { +// t.Error(err) +// } +// admin, err := logic.UpdateUser(&newuser, &user) +// assert.Nil(t, err) +// assert.Equal(t, newuser.UserName, admin.UserName) +// }) +// } - t.Run("UserExists", func(t *testing.T) { - if err := logic.CreateUser(&user); err != nil { - t.Error(err) - } - admin, err := logic.UpdateUser(&newuser, &user) - assert.Nil(t, err) - assert.Equal(t, newuser.UserName, admin.UserName) - }) -} +// // func TestValidateUserToken(t *testing.T) { +// // t.Run("EmptyToken", func(t *testing.T) { +// // err := ValidateUserToken("", "", false) +// // assert.NotNil(t, err) +// // assert.Equal(t, "Missing Auth Token.", err.Error()) +// // }) +// // t.Run("InvalidToken", func(t *testing.T) { +// // err := ValidateUserToken("Bearer: badtoken", "", false) +// // assert.NotNil(t, err) +// // assert.Equal(t, "Error Verifying Auth Token", err.Error()) +// // }) +// // t.Run("InvalidUser", func(t *testing.T) { +// // t.Skip() +// // err := ValidateUserToken("Bearer: secretkey", "baduser", false) +// // assert.NotNil(t, err) +// // assert.Equal(t, "Error Verifying Auth Token", err.Error()) +// // //need authorization +// // }) +// // t.Run("ValidToken", func(t *testing.T) { +// // err := ValidateUserToken("Bearer: secretkey", "", true) +// // assert.Nil(t, err) +// // }) +// // } -// func TestValidateUserToken(t *testing.T) { -// t.Run("EmptyToken", func(t *testing.T) { -// err := ValidateUserToken("", "", false) -// assert.NotNil(t, err) -// assert.Equal(t, "Missing Auth Token.", err.Error()) +// func TestVerifyAuthRequest(t *testing.T) { +// deleteAllUsers(t) +// user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} +// var authRequest models.UserAuthParams +// t.Run("EmptyUserName", func(t *testing.T) { +// authRequest.UserName = "" +// authRequest.Password = "Password" +// jwt, err := logic.VerifyAuthRequest(authRequest) +// assert.Equal(t, "", jwt) +// assert.EqualError(t, err, "username can't be empty") // }) -// t.Run("InvalidToken", func(t *testing.T) { -// err := ValidateUserToken("Bearer: badtoken", "", false) -// assert.NotNil(t, err) -// assert.Equal(t, "Error Verifying Auth Token", err.Error()) +// t.Run("EmptyPassword", func(t *testing.T) { +// authRequest.UserName = "admin" +// authRequest.Password = "" +// jwt, err := logic.VerifyAuthRequest(authRequest) +// assert.Equal(t, "", jwt) +// assert.EqualError(t, err, "password can't be empty") // }) -// t.Run("InvalidUser", func(t *testing.T) { -// t.Skip() -// err := ValidateUserToken("Bearer: secretkey", "baduser", false) -// assert.NotNil(t, err) -// assert.Equal(t, "Error Verifying Auth Token", err.Error()) -// //need authorization +// t.Run("NonExistantUser", func(t *testing.T) { +// authRequest.UserName = "admin" +// authRequest.Password = "password" +// jwt, err := logic.VerifyAuthRequest(authRequest) +// assert.Equal(t, "", jwt) +// assert.EqualError(t, err, "incorrect credentials") // }) -// t.Run("ValidToken", func(t *testing.T) { -// err := ValidateUserToken("Bearer: secretkey", "", true) +// t.Run("Non-Admin", func(t *testing.T) { +// user.PlatformRoleID = models.ServiceUser +// user.Password = "somepass" +// user.UserName = "nonadmin" +// if err := logic.CreateUser(&user); err != nil { +// t.Error(err) +// } +// authRequest := models.UserAuthParams{UserName: "nonadmin", Password: "somepass"} +// jwt, err := logic.VerifyAuthRequest(authRequest) +// assert.NotNil(t, jwt) // assert.Nil(t, err) // }) +// t.Run("WrongPassword", func(t *testing.T) { +// user := models.User{UserName: "admin", Password: "password"} +// if err := logic.CreateUser(&user); err != nil { +// t.Error(err) +// } +// authRequest := models.UserAuthParams{UserName: "admin", Password: "badpass"} +// jwt, err := logic.VerifyAuthRequest(authRequest) +// assert.Equal(t, "", jwt) +// assert.EqualError(t, err, "incorrect credentials") +// }) +// t.Run("Success", func(t *testing.T) { +// authRequest := models.UserAuthParams{UserName: "admin", Password: "password"} +// jwt, err := logic.VerifyAuthRequest(authRequest) +// assert.Nil(t, err) +// assert.NotNil(t, jwt) +// }) // } - -func TestVerifyAuthRequest(t *testing.T) { - deleteAllUsers(t) - user := models.User{UserName: "admin", Password: "password", PlatformRoleID: models.AdminRole} - var authRequest models.UserAuthParams - t.Run("EmptyUserName", func(t *testing.T) { - authRequest.UserName = "" - authRequest.Password = "Password" - jwt, err := logic.VerifyAuthRequest(authRequest) - assert.Equal(t, "", jwt) - assert.EqualError(t, err, "username can't be empty") - }) - t.Run("EmptyPassword", func(t *testing.T) { - authRequest.UserName = "admin" - authRequest.Password = "" - jwt, err := logic.VerifyAuthRequest(authRequest) - assert.Equal(t, "", jwt) - assert.EqualError(t, err, "password can't be empty") - }) - t.Run("NonExistantUser", func(t *testing.T) { - authRequest.UserName = "admin" - authRequest.Password = "password" - jwt, err := logic.VerifyAuthRequest(authRequest) - assert.Equal(t, "", jwt) - assert.EqualError(t, err, "incorrect credentials") - }) - t.Run("Non-Admin", func(t *testing.T) { - user.PlatformRoleID = models.ServiceUser - user.Password = "somepass" - user.UserName = "nonadmin" - if err := logic.CreateUser(&user); err != nil { - t.Error(err) - } - authRequest := models.UserAuthParams{UserName: "nonadmin", Password: "somepass"} - jwt, err := logic.VerifyAuthRequest(authRequest) - assert.NotNil(t, jwt) - assert.Nil(t, err) - }) - t.Run("WrongPassword", func(t *testing.T) { - user := models.User{UserName: "admin", Password: "password"} - if err := logic.CreateUser(&user); err != nil { - t.Error(err) - } - authRequest := models.UserAuthParams{UserName: "admin", Password: "badpass"} - jwt, err := logic.VerifyAuthRequest(authRequest) - assert.Equal(t, "", jwt) - assert.EqualError(t, err, "incorrect credentials") - }) - t.Run("Success", func(t *testing.T) { - authRequest := models.UserAuthParams{UserName: "admin", Password: "password"} - jwt, err := logic.VerifyAuthRequest(authRequest) - assert.Nil(t, err) - assert.NotNil(t, jwt) - }) -} From e90ad2634f372615ab86b96516b4adb7b0fdee84 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 22 Aug 2024 11:48:20 +0530 Subject: [PATCH 06/35] fix network and user invite for master key access --- controllers/network.go | 15 +++++++++------ pro/controllers/users.go | 37 ++++++++++++++++++++----------------- 2 files changed, 29 insertions(+), 23 deletions(-) diff --git a/controllers/network.go b/controllers/network.go index c94017f21..acb479ec9 100644 --- a/controllers/network.go +++ b/controllers/network.go @@ -58,13 +58,16 @@ func getNetworks(w http.ResponseWriter, r *http.Request) { logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) return } - username := r.Header.Get("user") - user, err := logic.GetUser(username) - if err != nil { - logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) - return + if r.Header.Get("ismaster") != "yes" { + username := r.Header.Get("user") + user, err := logic.GetUser(username) + if err != nil { + logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) + return + } + allnetworks = logic.FilterNetworksByRole(allnetworks, *user) } - allnetworks = logic.FilterNetworksByRole(allnetworks, *user) + logger.Log(2, r.Header.Get("user"), "fetched networks.") logic.SortNetworks(allnetworks[:]) w.WriteHeader(http.StatusOK) diff --git a/pro/controllers/users.go b/pro/controllers/users.go index 9387e1b2f..2a96d03c6 100644 --- a/pro/controllers/users.go +++ b/pro/controllers/users.go @@ -165,24 +165,27 @@ func inviteUsers(w http.ResponseWriter, r *http.Request) { return } callerUserName := r.Header.Get("user") - caller, err := logic.GetUser(callerUserName) - if err != nil { - logic.ReturnErrorResponse(w, r, logic.FormatError(err, "notfound")) - return - } - if inviteReq.PlatformRoleID == models.SuperAdminRole.String() { - logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("super admin cannot be invited"), "badrequest")) - return - } - if inviteReq.PlatformRoleID == "" { - logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("platform role id cannot be empty"), "badrequest")) - return - } - if (inviteReq.PlatformRoleID == models.AdminRole.String() || - inviteReq.PlatformRoleID == models.SuperAdminRole.String()) && caller.PlatformRoleID != models.SuperAdminRole { - logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("only superadmin can invite admin users"), "forbidden")) - return + if r.Header.Get("ismaster") != "yes" { + caller, err := logic.GetUser(callerUserName) + if err != nil { + logic.ReturnErrorResponse(w, r, logic.FormatError(err, "notfound")) + return + } + if inviteReq.PlatformRoleID == models.SuperAdminRole.String() { + logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("super admin cannot be invited"), "badrequest")) + return + } + if inviteReq.PlatformRoleID == "" { + logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("platform role id cannot be empty"), "badrequest")) + return + } + if (inviteReq.PlatformRoleID == models.AdminRole.String() || + inviteReq.PlatformRoleID == models.SuperAdminRole.String()) && caller.PlatformRoleID != models.SuperAdminRole { + logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("only superadmin can invite admin users"), "forbidden")) + return + } } + //validate Req err = proLogic.IsGroupsValid(inviteReq.UserGroups) if err != nil { From e29b4e080ba038441a1fcf209be2832bf5c1a841 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 22 Aug 2024 13:01:38 +0530 Subject: [PATCH 07/35] remove email sender type --- config/config.go | 4 +-- pro/email/email.go | 29 ++++++++----------- pro/email/resend.go | 55 ------------------------------------ scripts/netmaker.default.env | 3 +- scripts/nm-quick.sh | 2 +- servercfg/serverconf.go | 16 ++--------- 6 files changed, 19 insertions(+), 90 deletions(-) delete mode 100644 pro/email/resend.go diff --git a/config/config.go b/config/config.go index 4f390e37a..061109f6d 100644 --- a/config/config.go +++ b/config/config.go @@ -95,8 +95,8 @@ type ServerConfig struct { EndpointDetection bool `json:"endpoint_detection"` AllowedEmailDomains string `yaml:"allowed_email_domains"` EmailSenderAddr string `json:"email_sender_addr"` - EmailSenderAuth string `json:"email_sender_auth"` - EmailSenderType string `json:"email_sender_type"` + EmailSenderUser string `json:"email_sender_user"` + EmailSenderPassword string `json:"email_sender_password"` SmtpHost string `json:"smtp_host"` SmtpPort int `json:"smtp_port"` MetricInterval string `yaml:"metric_interval"` diff --git a/pro/email/email.go b/pro/email/email.go index bd7c63448..f6a3e80a8 100644 --- a/pro/email/email.go +++ b/pro/email/email.go @@ -16,24 +16,19 @@ const ( ) func init() { - switch EmailSenderType(servercfg.EmailSenderType()) { - case Smtp: - smtpSender := &SmtpSender{ - SmtpHost: servercfg.GetSmtpHost(), - SmtpPort: servercfg.GetSmtpPort(), - SenderEmail: servercfg.GetSenderEmail(), - SendUser: servercfg.GetSenderUser(), - SenderPass: servercfg.GetEmaiSenderAuth(), - } - if smtpSender.SendUser == "" { - smtpSender.SendUser = smtpSender.SenderEmail - } - client = smtpSender - - case Resend: - client = NewResendEmailSenderFromConfig() + + smtpSender := &SmtpSender{ + SmtpHost: servercfg.GetSmtpHost(), + SmtpPort: servercfg.GetSmtpPort(), + SenderEmail: servercfg.GetSenderEmail(), + SendUser: servercfg.GetSenderUser(), + SenderPass: servercfg.GetEmaiSenderPassword(), + } + if smtpSender.SendUser == "" { + smtpSender.SendUser = smtpSender.SenderEmail } - client = GetClient() + client = smtpSender + } // EmailSender - an interface for sending emails based on notifications and mail templates diff --git a/pro/email/resend.go b/pro/email/resend.go deleted file mode 100644 index 1125bc7e5..000000000 --- a/pro/email/resend.go +++ /dev/null @@ -1,55 +0,0 @@ -package email - -import ( - "context" - "fmt" - - "github.com/gravitl/netmaker/servercfg" - "github.com/resendlabs/resend-go" -) - -// ResendEmailSender - implementation of EmailSender using Resend (https://resend.com) -type ResendEmailSender struct { - client ResendClient - from string -} - -// ResendClient - dependency interface for resend client -type ResendClient interface { - Send(*resend.SendEmailRequest) (resend.SendEmailResponse, error) -} - -// NewResendEmailSender - constructs a ResendEmailSender -func NewResendEmailSender(client ResendClient, from string) ResendEmailSender { - return ResendEmailSender{client: client, from: from} -} - -// NewResendEmailSender - constructs a ResendEmailSender from config -// TODO let main.go handle this and use dependency injection instead of calling this function -func NewResendEmailSenderFromConfig() ResendEmailSender { - key, from := servercfg.GetEmaiSenderAuth(), servercfg.GetSenderEmail() - resender := resend.NewClient(key) - return NewResendEmailSender(resender.Emails, from) -} - -// SendEmail - sends an email using resend-go (https://github.com/resendlabs/resend-go) -func (es ResendEmailSender) SendEmail(ctx context.Context, notification Notification, email Mail) error { - var ( - from = es.from - to = notification.RecipientMail - subject = email.GetSubject(notification) - body = email.GetBody(notification) - ) - params := resend.SendEmailRequest{ - From: from, - To: []string{to}, - Subject: subject, - Html: body, - } - _, err := es.client.Send(¶ms) - if err != nil { - return fmt.Errorf("failed sending mail via resend: %w", err) - } - - return nil -} diff --git a/scripts/netmaker.default.env b/scripts/netmaker.default.env index 196ad3668..5d24dd8ab 100644 --- a/scripts/netmaker.default.env +++ b/scripts/netmaker.default.env @@ -86,5 +86,4 @@ EMAIL_SENDER_ADDR= EMAIL_SENDER_USER= # sender smtp password EMAIL_SENDER_PASSWORD= -# mail sender type (smtp or resend) -EMAIL_SENDER_TYPE=smtp + diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index 2a1d67597..bf8c2826c 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -254,7 +254,7 @@ save_config() { ( "CORS_ALLOWED_ORIGIN" "DISPLAY_KEYS" "DATABASE" "SERVER_BROKER_ENDPOINT" "VERBOSITY" "DEBUG_MODE" "REST_BACKEND" "DISABLE_REMOTE_IP_CHECK" "TELEMETRY" "ALLOWED_EMAIL_DOMAINS" "AUTH_PROVIDER" "CLIENT_ID" "CLIENT_SECRET" "FRONTEND_URL" "AZURE_TENANT" "OIDC_ISSUER" "EXPORTER_API_PORT" "JWT_VALIDITY_DURATION" "RAC_AUTO_DISABLE" "CACHING_ENABLED" "ENDPOINT_DETECTION" - "SMTP_HOST" "SMTP_PORT" "EMAIL_SENDER_ADDR" "EMAIL_SENDER_USER" "EMAIL_SENDER_PASSWORD" "EMAIL_SENDER_TYPE") + "SMTP_HOST" "SMTP_PORT" "EMAIL_SENDER_ADDR" "EMAIL_SENDER_USER" "EMAIL_SENDER_PASSWORD") for name in "${toCopy[@]}"; do save_config_item $name "${!name}" done diff --git a/servercfg/serverconf.go b/servercfg/serverconf.go index f368bb887..98e5d5b49 100644 --- a/servercfg/serverconf.go +++ b/servercfg/serverconf.go @@ -279,32 +279,22 @@ func GetSenderUser() string { v := "" if fromEnv := os.Getenv("EMAIL_SENDER_USER"); fromEnv != "" { v = fromEnv - } else if fromCfg := config.Config.Server.EmailSenderAddr; fromCfg != "" { + } else if fromCfg := config.Config.Server.EmailSenderUser; fromCfg != "" { v = fromCfg } return v } -func GetEmaiSenderAuth() string { +func GetEmaiSenderPassword() string { v := "" if fromEnv := os.Getenv("EMAIL_SENDER_PASSWORD"); fromEnv != "" { v = fromEnv - } else if fromCfg := config.Config.Server.EmailSenderAddr; fromCfg != "" { + } else if fromCfg := config.Config.Server.EmailSenderPassword; fromCfg != "" { v = fromCfg } return v } -func EmailSenderType() string { - s := "" - if fromEnv := os.Getenv("EMAIL_SENDER_TYPE"); fromEnv != "" { - s = fromEnv - } else if fromCfg := config.Config.Server.EmailSenderType; fromCfg != "" { - s = fromCfg - } - return s -} - // GetOwnerEmail - gets the owner email (saas) func GetOwnerEmail() string { return os.Getenv("SAAS_OWNER_EMAIL") From 0a43b83948120a57ff3b1c08d7f4ab1b0f8127ac Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Fri, 23 Aug 2024 19:36:31 +0530 Subject: [PATCH 08/35] user mgmt commands --- cli/cmd/user/create.go | 33 ++++++++++++++++--- cli/cmd/user/flags.go | 12 ++++--- cli/cmd/user/list.go | 9 ++++-- cli/cmd/user/roles.go | 73 ++++++++++++++++++++++++++++++++++++++++++ cli/cmd/user/update.go | 29 +++++++++++++++-- cli/functions/user.go | 28 ++++++++++++++++ 6 files changed, 171 insertions(+), 13 deletions(-) create mode 100644 cli/cmd/user/roles.go diff --git a/cli/cmd/user/create.go b/cli/cmd/user/create.go index dc1e2a0b5..ac3130727 100644 --- a/cli/cmd/user/create.go +++ b/cli/cmd/user/create.go @@ -1,6 +1,8 @@ package user import ( + "strings" + "github.com/gravitl/netmaker/cli/functions" "github.com/gravitl/netmaker/models" "github.com/spf13/cobra" @@ -12,18 +14,41 @@ var userCreateCmd = &cobra.Command{ Short: "Create a new user", Long: `Create a new user`, Run: func(cmd *cobra.Command, args []string) { - user := &models.User{UserName: username, Password: password, IsAdmin: admin} + user := &models.User{UserName: username, Password: password, PlatformRoleID: models.UserRoleID(platformID)} + if len(networkRoles) > 0 { + netRolesMap := make(map[models.NetworkID]map[models.UserRoleID]struct{}) + for netID, netRoles := range networkRoles { + roleMap := make(map[models.UserRoleID]struct{}) + for _, roleID := range strings.Split(netRoles, ",") { + roleMap[models.UserRoleID(roleID)] = struct{}{} + } + netRolesMap[models.NetworkID(netID)] = roleMap + } + user.NetworkRoles = netRolesMap + } + if len(groups) > 0 { + grMap := make(map[models.UserGroupID]struct{}) + for _, groupID := range groups { + grMap[models.UserGroupID(groupID)] = struct{}{} + } + user.UserGroups = grMap + } + functions.PrettyPrint(functions.CreateUser(user)) }, } func init() { + userCreateCmd.Flags().StringVar(&username, "name", "", "Name of the user") userCreateCmd.Flags().StringVar(&password, "password", "", "Password of the user") + userCreateCmd.Flags().StringVarP(&platformID, "platform-id", "r", models.ServiceUser.String(), + "Platform Role of the user; run `nmctl roles list` to see available user roles") userCreateCmd.MarkFlagRequired("name") userCreateCmd.MarkFlagRequired("password") - userCreateCmd.Flags().BoolVar(&admin, "admin", false, "Make the user an admin ?") - userCreateCmd.Flags().StringVar(&networks, "networks", "", "List of networks the user will access to (comma separated)") - userCreateCmd.Flags().StringVar(&groups, "groups", "", "List of user groups the user will be part of (comma separated)") + userCreateCmd.PersistentFlags().StringToStringVarP(&networkRoles, "network-roles", "n", make(map[string]string), + "Mapping of networkID and list of roles user will be part of (comma separated)") + userCreateCmd.Flags().BoolVar(&admin, "admin", false, "Make the user an admin ? (deprecated v0.25.0 onwards)") + userCreateCmd.Flags().StringArrayVarP(&groups, "groups", "g", nil, "List of user groups the user will be part of (comma separated)") rootCmd.AddCommand(userCreateCmd) } diff --git a/cli/cmd/user/flags.go b/cli/cmd/user/flags.go index 57f07843f..224e8f6f2 100644 --- a/cli/cmd/user/flags.go +++ b/cli/cmd/user/flags.go @@ -1,9 +1,11 @@ package user var ( - username string - password string - admin bool - networks string - groups string + username string + password string + platformID string + admin bool + networks string + networkRoles map[string]string + groups []string ) diff --git a/cli/cmd/user/list.go b/cli/cmd/user/list.go index 694697a28..d1d2fa79d 100644 --- a/cli/cmd/user/list.go +++ b/cli/cmd/user/list.go @@ -3,6 +3,7 @@ package user import ( "os" "strconv" + "strings" "github.com/gravitl/netmaker/cli/cmd/commons" "github.com/gravitl/netmaker/cli/functions" @@ -22,9 +23,13 @@ var userListCmd = &cobra.Command{ functions.PrettyPrint(data) default: table := tablewriter.NewWriter(os.Stdout) - table.SetHeader([]string{"Name", "SuperAdmin", "Admin"}) + table.SetHeader([]string{"Name", "Platform Role", "Groups"}) for _, d := range *data { - table.Append([]string{d.UserName, strconv.FormatBool(d.IsSuperAdmin), strconv.FormatBool(d.IsAdmin)}) + g := []string{} + for gID := range d.UserGroups { + g = append(g, gID.String()) + } + table.Append([]string{d.UserName, d.PlatformRoleID.String(), strconv.FormatBool(d.IsAdmin), strings.Join(g, ",")}) } table.Render() } diff --git a/cli/cmd/user/roles.go b/cli/cmd/user/roles.go new file mode 100644 index 000000000..a9e272e20 --- /dev/null +++ b/cli/cmd/user/roles.go @@ -0,0 +1,73 @@ +package user + +import ( + "fmt" + "os" + "strconv" + + "github.com/gravitl/netmaker/cli/cmd/commons" + "github.com/gravitl/netmaker/cli/functions" + "github.com/gravitl/netmaker/models" + "github.com/guumaster/tablewriter" + "github.com/spf13/cobra" +) + +var userRoleCmd = &cobra.Command{ + Use: "role", + Args: cobra.NoArgs, + Short: "Manage User Roles", + Long: `Manage User Roles`, +} + +// List Roles +var ( + platformRoles bool +) +var userroleListCmd = &cobra.Command{ + Use: "list", + Args: cobra.NoArgs, + Short: "List all user roles", + Long: `List all user roles`, + Run: func(cmd *cobra.Command, args []string) { + data := functions.ListUserRoles() + userRoles := data.Response.([]models.UserRolePermissionTemplate) + switch commons.OutputFormat { + case commons.JsonOutput: + functions.PrettyPrint(data) + default: + table := tablewriter.NewWriter(os.Stdout) + h := []string{"ID", "Default", "Dashboard Access", "Full Access"} + + if !platformRoles { + h = append(h, "Network") + } + table.SetHeader(h) + for _, d := range userRoles { + e := []string{d.ID.String(), strconv.FormatBool(d.Default), strconv.FormatBool(d.DenyDashboardAccess), strconv.FormatBool(d.FullAccess)} + if !platformRoles { + e = append(e, d.NetworkID.String()) + } + table.Append(e) + } + table.Render() + } + }, +} + +var userRoleCreateCmd = &cobra.Command{ + Use: "create", + Args: cobra.NoArgs, + Short: "create user role", + Long: `create user role`, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("CLI doesn't support creation of roles currently") + }, +} + +func init() { + rootCmd.AddCommand(userRoleCmd) + userroleListCmd.Flags().BoolVar(&platformRoles, "platform-roles", true, + "set to false to list network roles. By default it will only list platform roles") + userRoleCmd.AddCommand(userroleListCmd) + userRoleCmd.AddCommand(userCreateCmd) +} diff --git a/cli/cmd/user/update.go b/cli/cmd/user/update.go index 0a79f26a3..f80307618 100644 --- a/cli/cmd/user/update.go +++ b/cli/cmd/user/update.go @@ -1,6 +1,8 @@ package user import ( + "strings" + "github.com/gravitl/netmaker/cli/functions" "github.com/gravitl/netmaker/models" "github.com/spf13/cobra" @@ -12,7 +14,28 @@ var userUpdateCmd = &cobra.Command{ Short: "Update a user", Long: `Update a user`, Run: func(cmd *cobra.Command, args []string) { - user := &models.User{UserName: args[0], IsAdmin: admin} + user := &models.User{UserName: args[0]} + if platformID != "" { + user.PlatformRoleID = models.UserRoleID(platformID) + } + if len(networkRoles) > 0 { + netRolesMap := make(map[models.NetworkID]map[models.UserRoleID]struct{}) + for netID, netRoles := range networkRoles { + roleMap := make(map[models.UserRoleID]struct{}) + for _, roleID := range strings.Split(netRoles, ",") { + roleMap[models.UserRoleID(roleID)] = struct{}{} + } + netRolesMap[models.NetworkID(netID)] = roleMap + } + user.NetworkRoles = netRolesMap + } + if len(groups) > 0 { + grMap := make(map[models.UserGroupID]struct{}) + for _, groupID := range groups { + grMap[models.UserGroupID(groupID)] = struct{}{} + } + user.UserGroups = grMap + } functions.PrettyPrint(functions.UpdateUser(user)) }, } @@ -20,6 +43,8 @@ var userUpdateCmd = &cobra.Command{ func init() { userUpdateCmd.Flags().BoolVar(&admin, "admin", false, "Make the user an admin ?") userUpdateCmd.Flags().StringVar(&networks, "networks", "", "List of networks the user will access to (comma separated)") - userUpdateCmd.Flags().StringVar(&groups, "groups", "", "List of user groups the user will be part of (comma separated)") + userUpdateCmd.Flags().StringVarP(&platformID, "platform-id", "r", "", + "Platform Role of the user; run `nmctl roles list` to see available user roles") + userUpdateCmd.Flags().StringArrayVarP(&groups, "groups", "g", nil, "List of user groups the user will be part of (comma separated)") rootCmd.AddCommand(userUpdateCmd) } diff --git a/cli/functions/user.go b/cli/functions/user.go index b286bc4e8..43416bfd0 100644 --- a/cli/functions/user.go +++ b/cli/functions/user.go @@ -1,6 +1,7 @@ package functions import ( + "fmt" "net/http" "github.com/gravitl/netmaker/models" @@ -35,3 +36,30 @@ func GetUser(username string) *models.User { func ListUsers() *[]models.ReturnUser { return request[[]models.ReturnUser](http.MethodGet, "/api/users", nil) } + +func CreateUserRole(role models.UserRolePermissionTemplate) *models.SuccessResponse { + return request[models.SuccessResponse](http.MethodPost, "/api/v1/users/role", role) +} +func UpdateUserRole(role models.UserRolePermissionTemplate) *models.SuccessResponse { + return request[models.SuccessResponse](http.MethodPut, "/api/v1/users/role", role) +} + +func ListUserRoles() *models.SuccessResponse { + return request[models.SuccessResponse](http.MethodGet, "/api/v1/users/roles", nil) +} + +func DeleteUserRole(roleID string) *models.SuccessResponse { + return request[models.SuccessResponse](http.MethodDelete, fmt.Sprintf("/api/v1/users/role?role_id=%s", roleID), nil) +} +func GetUserRole(roleID string) *models.SuccessResponse { + return request[models.SuccessResponse](http.MethodGet, fmt.Sprintf("/api/v1/users/role?role_id=%s", roleID), nil) +} + +/* + + r.HandleFunc("/api/v1/users/roles", logic.SecurityCheck(true, http.HandlerFunc(listRoles))).Methods(http.MethodGet) + r.HandleFunc("/api/v1/users/role", logic.SecurityCheck(true, http.HandlerFunc(getRole))).Methods(http.MethodGet) + r.HandleFunc("/api/v1/users/role", logic.SecurityCheck(true, http.HandlerFunc(createRole))).Methods(http.MethodPost) + r.HandleFunc("/api/v1/users/role", logic.SecurityCheck(true, http.HandlerFunc(updateRole))).Methods(http.MethodPut) + r.HandleFunc("/api/v1/users/role", logic.SecurityCheck(true, http.HandlerFunc(deleteRole))).Methods(http.MethodDelete) +*/ From d02e2a5f8cfd160e6470249b32092da47e6c634d Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Fri, 23 Aug 2024 19:44:43 +0530 Subject: [PATCH 09/35] check user role on CE --- controllers/user.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/controllers/user.go b/controllers/user.go index 72925bc25..346a9236f 100644 --- a/controllers/user.go +++ b/controllers/user.go @@ -407,6 +407,9 @@ func createUser(w http.ResponseWriter, r *http.Request) { logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest")) return } + if !servercfg.IsPro { + user.PlatformRoleID = models.AdminRole + } if user.PlatformRoleID == "" { logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("platform role is missing"), "badrequest")) From d67fecf27f2aeabb69de62e22a306d79a109b961 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Sat, 24 Aug 2024 12:27:16 +0530 Subject: [PATCH 10/35] user role nmtcl cmds --- cli/cmd/user/roles.go | 50 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/cli/cmd/user/roles.go b/cli/cmd/user/roles.go index a9e272e20..55f643ac8 100644 --- a/cli/cmd/user/roles.go +++ b/cli/cmd/user/roles.go @@ -22,8 +22,9 @@ var userRoleCmd = &cobra.Command{ // List Roles var ( platformRoles bool + roleID string ) -var userroleListCmd = &cobra.Command{ +var userRoleListCmd = &cobra.Command{ Use: "list", Args: cobra.NoArgs, Short: "List all user roles", @@ -60,14 +61,53 @@ var userRoleCreateCmd = &cobra.Command{ Short: "create user role", Long: `create user role`, Run: func(cmd *cobra.Command, args []string) { - fmt.Println("CLI doesn't support creation of roles currently") + fmt.Println("CLI doesn't support creation of roles currently. Visit the dashboard to create one or refer to our api documentation https://docs.v2.netmaker.io/reference") + }, +} + +var userRoleDeleteCmd = &cobra.Command{ + Use: "delete", + Args: cobra.NoArgs, + Short: "delete user role", + Long: `delete user role`, + Run: func(cmd *cobra.Command, args []string) { + resp := functions.DeleteUserRole(roleID) + if resp != nil { + fmt.Println(resp.Message) + } + }, +} + +var userRoleGetCmd = &cobra.Command{ + Use: "get", + Args: cobra.NoArgs, + Short: "get user role", + Long: `get user role`, + Run: func(cmd *cobra.Command, args []string) { + resp := functions.GetUserRole(roleID) + if resp != nil { + fmt.Println(resp.Message) + } }, } func init() { rootCmd.AddCommand(userRoleCmd) - userroleListCmd.Flags().BoolVar(&platformRoles, "platform-roles", true, + // list roles cmd + userRoleListCmd.Flags().BoolVar(&platformRoles, "platform-roles", true, "set to false to list network roles. By default it will only list platform roles") - userRoleCmd.AddCommand(userroleListCmd) - userRoleCmd.AddCommand(userCreateCmd) + userRoleCmd.AddCommand(userRoleListCmd) + + // create roles cmd + userRoleCmd.AddCommand(userRoleCreateCmd) + + // delete role cmd + userRoleDeleteCmd.Flags().StringVar(&roleID, "role-id", "", "user role ID") + userRoleDeleteCmd.MarkFlagRequired("role-id") + userRoleCmd.AddCommand(userRoleDeleteCmd) + + // Get Role + userRoleGetCmd.Flags().StringVar(&roleID, "role-id", "", "user role ID") + userRoleGetCmd.MarkFlagRequired("role-id") + userRoleCmd.AddCommand(userRoleGetCmd) } From a5c66f1b87e8b55af560965ffc6ebe98b721ce69 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Sat, 24 Aug 2024 13:40:41 +0530 Subject: [PATCH 11/35] user groups commands --- cli/cmd/user/groups.go | 112 +++++++++++++++++++++++++++++++++++++++++ cli/functions/user.go | 23 ++++----- 2 files changed, 121 insertions(+), 14 deletions(-) create mode 100644 cli/cmd/user/groups.go diff --git a/cli/cmd/user/groups.go b/cli/cmd/user/groups.go new file mode 100644 index 000000000..771ac3381 --- /dev/null +++ b/cli/cmd/user/groups.go @@ -0,0 +1,112 @@ +package user + +import ( + "fmt" + "os" + "strings" + + "github.com/gravitl/netmaker/cli/cmd/commons" + "github.com/gravitl/netmaker/cli/functions" + "github.com/gravitl/netmaker/models" + "github.com/guumaster/tablewriter" + "github.com/spf13/cobra" +) + +var userGroupCmd = &cobra.Command{ + Use: "group", + Args: cobra.NoArgs, + Short: "Manage User Groups", + Long: `Manage User Groups`, +} + +// List Roles +var ( + groupID string +) +var userGroupListCmd = &cobra.Command{ + Use: "list", + Args: cobra.NoArgs, + Short: "List all user groups", + Long: `List all user groups`, + Run: func(cmd *cobra.Command, args []string) { + data := functions.ListUserGrps() + userGrps := data.Response.([]models.UserGroup) + switch commons.OutputFormat { + case commons.JsonOutput: + functions.PrettyPrint(data) + default: + table := tablewriter.NewWriter(os.Stdout) + h := []string{"ID", "MetaData", "Network Roles"} + table.SetHeader(h) + for _, d := range userGrps { + + roleInfoStr := "" + for netID, netRoleMap := range d.NetworkRoles { + roleList := []string{} + for roleID := range netRoleMap { + roleList = append(roleList, roleID.String()) + } + roleInfoStr += fmt.Sprintf("[%s]: %s", netID, strings.Join(roleList, ",")) + } + e := []string{d.ID.String(), d.MetaData, roleInfoStr} + table.Append(e) + } + table.Render() + } + }, +} + +var userGroupCreateCmd = &cobra.Command{ + Use: "create", + Args: cobra.NoArgs, + Short: "create user group", + Long: `create user group`, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("CLI doesn't support creation of groups currently. Visit the dashboard to create one or refer to our api documentation https://docs.v2.netmaker.io/reference") + }, +} + +var userGroupDeleteCmd = &cobra.Command{ + Use: "delete", + Args: cobra.NoArgs, + Short: "delete user group", + Long: `delete user group`, + Run: func(cmd *cobra.Command, args []string) { + resp := functions.DeleteUserGrp(groupID) + if resp != nil { + fmt.Println(resp.Message) + } + }, +} + +var userGroupGetCmd = &cobra.Command{ + Use: "get", + Args: cobra.NoArgs, + Short: "get user group", + Long: `get user group`, + Run: func(cmd *cobra.Command, args []string) { + resp := functions.GetUserGrp(groupID) + if resp != nil { + fmt.Println(resp.Message) + } + }, +} + +func init() { + rootCmd.AddCommand(userGroupCmd) + // list roles cmd + userGroupCmd.AddCommand(userGroupListCmd) + + // create roles cmd + userGroupCmd.AddCommand(userGroupCreateCmd) + + // delete role cmd + userGroupDeleteCmd.Flags().StringVar(&groupID, "group-id", "", "user role ID") + userGroupDeleteCmd.MarkFlagRequired("role-id") + userGroupCmd.AddCommand(userGroupDeleteCmd) + + // Get Role + userGroupGetCmd.Flags().StringVar(&groupID, "group-id", "", "user role ID") + userGroupGetCmd.MarkFlagRequired("group-id") + userGroupCmd.AddCommand(userGroupGetCmd) +} diff --git a/cli/functions/user.go b/cli/functions/user.go index 43416bfd0..8aa0dbce1 100644 --- a/cli/functions/user.go +++ b/cli/functions/user.go @@ -37,13 +37,6 @@ func ListUsers() *[]models.ReturnUser { return request[[]models.ReturnUser](http.MethodGet, "/api/users", nil) } -func CreateUserRole(role models.UserRolePermissionTemplate) *models.SuccessResponse { - return request[models.SuccessResponse](http.MethodPost, "/api/v1/users/role", role) -} -func UpdateUserRole(role models.UserRolePermissionTemplate) *models.SuccessResponse { - return request[models.SuccessResponse](http.MethodPut, "/api/v1/users/role", role) -} - func ListUserRoles() *models.SuccessResponse { return request[models.SuccessResponse](http.MethodGet, "/api/v1/users/roles", nil) } @@ -55,11 +48,13 @@ func GetUserRole(roleID string) *models.SuccessResponse { return request[models.SuccessResponse](http.MethodGet, fmt.Sprintf("/api/v1/users/role?role_id=%s", roleID), nil) } -/* +func ListUserGrps() *models.SuccessResponse { + return request[models.SuccessResponse](http.MethodGet, "/api/v1/users/groups", nil) +} - r.HandleFunc("/api/v1/users/roles", logic.SecurityCheck(true, http.HandlerFunc(listRoles))).Methods(http.MethodGet) - r.HandleFunc("/api/v1/users/role", logic.SecurityCheck(true, http.HandlerFunc(getRole))).Methods(http.MethodGet) - r.HandleFunc("/api/v1/users/role", logic.SecurityCheck(true, http.HandlerFunc(createRole))).Methods(http.MethodPost) - r.HandleFunc("/api/v1/users/role", logic.SecurityCheck(true, http.HandlerFunc(updateRole))).Methods(http.MethodPut) - r.HandleFunc("/api/v1/users/role", logic.SecurityCheck(true, http.HandlerFunc(deleteRole))).Methods(http.MethodDelete) -*/ +func DeleteUserGrp(grpID string) *models.SuccessResponse { + return request[models.SuccessResponse](http.MethodDelete, fmt.Sprintf("/api/v1/users/group?group_id=%s", grpID), nil) +} +func GetUserGrp(grpID string) *models.SuccessResponse { + return request[models.SuccessResponse](http.MethodGet, fmt.Sprintf("/api/v1/users/group?group_id=%s", grpID), nil) +} From ddb8f6fa068db64b331592db2c11d74cc3604edd Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Sat, 24 Aug 2024 18:12:19 +0530 Subject: [PATCH 12/35] fix role and groups command --- cli/cmd/user/create.go | 2 +- cli/cmd/user/groups.go | 26 ++++++++++++++++++++------ cli/cmd/user/list.go | 3 +-- cli/cmd/user/roles.go | 25 +++++++++++++++++++------ cli/config/config.go | 2 +- cli/functions/user.go | 30 ++++++++++++++++++++++-------- 6 files changed, 64 insertions(+), 24 deletions(-) diff --git a/cli/cmd/user/create.go b/cli/cmd/user/create.go index ac3130727..acfa27d4a 100644 --- a/cli/cmd/user/create.go +++ b/cli/cmd/user/create.go @@ -46,7 +46,7 @@ func init() { "Platform Role of the user; run `nmctl roles list` to see available user roles") userCreateCmd.MarkFlagRequired("name") userCreateCmd.MarkFlagRequired("password") - userCreateCmd.PersistentFlags().StringToStringVarP(&networkRoles, "network-roles", "n", make(map[string]string), + userCreateCmd.PersistentFlags().StringToStringVarP(&networkRoles, "network-roles", "n", nil, "Mapping of networkID and list of roles user will be part of (comma separated)") userCreateCmd.Flags().BoolVar(&admin, "admin", false, "Make the user an admin ? (deprecated v0.25.0 onwards)") userCreateCmd.Flags().StringArrayVarP(&groups, "groups", "g", nil, "List of user groups the user will be part of (comma separated)") diff --git a/cli/cmd/user/groups.go b/cli/cmd/user/groups.go index 771ac3381..5a874aa73 100644 --- a/cli/cmd/user/groups.go +++ b/cli/cmd/user/groups.go @@ -7,7 +7,6 @@ import ( "github.com/gravitl/netmaker/cli/cmd/commons" "github.com/gravitl/netmaker/cli/functions" - "github.com/gravitl/netmaker/models" "github.com/guumaster/tablewriter" "github.com/spf13/cobra" ) @@ -30,7 +29,6 @@ var userGroupListCmd = &cobra.Command{ Long: `List all user groups`, Run: func(cmd *cobra.Command, args []string) { data := functions.ListUserGrps() - userGrps := data.Response.([]models.UserGroup) switch commons.OutputFormat { case commons.JsonOutput: functions.PrettyPrint(data) @@ -38,7 +36,7 @@ var userGroupListCmd = &cobra.Command{ table := tablewriter.NewWriter(os.Stdout) h := []string{"ID", "MetaData", "Network Roles"} table.SetHeader(h) - for _, d := range userGrps { + for _, d := range data { roleInfoStr := "" for netID, netRoleMap := range d.NetworkRoles { @@ -85,9 +83,25 @@ var userGroupGetCmd = &cobra.Command{ Short: "get user group", Long: `get user group`, Run: func(cmd *cobra.Command, args []string) { - resp := functions.GetUserGrp(groupID) - if resp != nil { - fmt.Println(resp.Message) + data := functions.GetUserGrp(groupID) + switch commons.OutputFormat { + case commons.JsonOutput: + functions.PrettyPrint(data) + default: + table := tablewriter.NewWriter(os.Stdout) + h := []string{"ID", "MetaData", "Network Roles"} + table.SetHeader(h) + roleInfoStr := "" + for netID, netRoleMap := range data.NetworkRoles { + roleList := []string{} + for roleID := range netRoleMap { + roleList = append(roleList, roleID.String()) + } + roleInfoStr += fmt.Sprintf("[%s]: %s", netID, strings.Join(roleList, ",")) + } + e := []string{data.ID.String(), data.MetaData, roleInfoStr} + table.Append(e) + table.Render() } }, } diff --git a/cli/cmd/user/list.go b/cli/cmd/user/list.go index d1d2fa79d..68308f62a 100644 --- a/cli/cmd/user/list.go +++ b/cli/cmd/user/list.go @@ -2,7 +2,6 @@ package user import ( "os" - "strconv" "strings" "github.com/gravitl/netmaker/cli/cmd/commons" @@ -29,7 +28,7 @@ var userListCmd = &cobra.Command{ for gID := range d.UserGroups { g = append(g, gID.String()) } - table.Append([]string{d.UserName, d.PlatformRoleID.String(), strconv.FormatBool(d.IsAdmin), strings.Join(g, ",")}) + table.Append([]string{d.UserName, d.PlatformRoleID.String(), strings.Join(g, ",")}) } table.Render() } diff --git a/cli/cmd/user/roles.go b/cli/cmd/user/roles.go index 55f643ac8..c638640fd 100644 --- a/cli/cmd/user/roles.go +++ b/cli/cmd/user/roles.go @@ -7,7 +7,6 @@ import ( "github.com/gravitl/netmaker/cli/cmd/commons" "github.com/gravitl/netmaker/cli/functions" - "github.com/gravitl/netmaker/models" "github.com/guumaster/tablewriter" "github.com/spf13/cobra" ) @@ -31,7 +30,6 @@ var userRoleListCmd = &cobra.Command{ Long: `List all user roles`, Run: func(cmd *cobra.Command, args []string) { data := functions.ListUserRoles() - userRoles := data.Response.([]models.UserRolePermissionTemplate) switch commons.OutputFormat { case commons.JsonOutput: functions.PrettyPrint(data) @@ -43,7 +41,7 @@ var userRoleListCmd = &cobra.Command{ h = append(h, "Network") } table.SetHeader(h) - for _, d := range userRoles { + for _, d := range data { e := []string{d.ID.String(), strconv.FormatBool(d.Default), strconv.FormatBool(d.DenyDashboardAccess), strconv.FormatBool(d.FullAccess)} if !platformRoles { e = append(e, d.NetworkID.String()) @@ -84,9 +82,24 @@ var userRoleGetCmd = &cobra.Command{ Short: "get user role", Long: `get user role`, Run: func(cmd *cobra.Command, args []string) { - resp := functions.GetUserRole(roleID) - if resp != nil { - fmt.Println(resp.Message) + d := functions.GetUserRole(roleID) + switch commons.OutputFormat { + case commons.JsonOutput: + functions.PrettyPrint(d) + default: + table := tablewriter.NewWriter(os.Stdout) + h := []string{"ID", "Default Role", "Dashboard Access", "Full Access"} + + if d.NetworkID != "" { + h = append(h, "Network") + } + table.SetHeader(h) + e := []string{d.ID.String(), strconv.FormatBool(d.Default), strconv.FormatBool(!d.DenyDashboardAccess), strconv.FormatBool(d.FullAccess)} + if !platformRoles { + e = append(e, d.NetworkID.String()) + } + table.Append(e) + table.Render() } }, } diff --git a/cli/config/config.go b/cli/config/config.go index ba32c48dd..444ad1664 100644 --- a/cli/config/config.go +++ b/cli/config/config.go @@ -86,7 +86,7 @@ func GetCurrentContext() (name string, ctx Context) { return } } - log.Fatalf("No current context set, do so via `netmaker context use `") + log.Fatalf("No current context set, do so via `nmctl context use `") return } diff --git a/cli/functions/user.go b/cli/functions/user.go index 8aa0dbce1..6f435ea4c 100644 --- a/cli/functions/user.go +++ b/cli/functions/user.go @@ -1,6 +1,7 @@ package functions import ( + "encoding/json" "fmt" "net/http" @@ -37,24 +38,37 @@ func ListUsers() *[]models.ReturnUser { return request[[]models.ReturnUser](http.MethodGet, "/api/users", nil) } -func ListUserRoles() *models.SuccessResponse { - return request[models.SuccessResponse](http.MethodGet, "/api/v1/users/roles", nil) +func ListUserRoles() (roles []models.UserRolePermissionTemplate) { + resp := request[models.SuccessResponse](http.MethodGet, "/api/v1/users/roles", nil) + d, _ := json.Marshal(resp.Response) + json.Unmarshal(d, &roles) + return } func DeleteUserRole(roleID string) *models.SuccessResponse { return request[models.SuccessResponse](http.MethodDelete, fmt.Sprintf("/api/v1/users/role?role_id=%s", roleID), nil) } -func GetUserRole(roleID string) *models.SuccessResponse { - return request[models.SuccessResponse](http.MethodGet, fmt.Sprintf("/api/v1/users/role?role_id=%s", roleID), nil) +func GetUserRole(roleID string) (role models.UserRolePermissionTemplate) { + resp := request[models.SuccessResponse](http.MethodGet, fmt.Sprintf("/api/v1/users/role?role_id=%s", roleID), nil) + d, _ := json.Marshal(resp.Response) + json.Unmarshal(d, &role) + return } -func ListUserGrps() *models.SuccessResponse { - return request[models.SuccessResponse](http.MethodGet, "/api/v1/users/groups", nil) +func ListUserGrps() (groups []models.UserGroup) { + resp := request[models.SuccessResponse](http.MethodGet, "/api/v1/users/groups", nil) + d, _ := json.Marshal(resp.Response) + json.Unmarshal(d, &groups) + return } func DeleteUserGrp(grpID string) *models.SuccessResponse { return request[models.SuccessResponse](http.MethodDelete, fmt.Sprintf("/api/v1/users/group?group_id=%s", grpID), nil) } -func GetUserGrp(grpID string) *models.SuccessResponse { - return request[models.SuccessResponse](http.MethodGet, fmt.Sprintf("/api/v1/users/group?group_id=%s", grpID), nil) + +func GetUserGrp(grpID string) (group models.UserGroup) { + resp := request[models.SuccessResponse](http.MethodGet, fmt.Sprintf("/api/v1/users/group?group_id=%s", grpID), nil) + d, _ := json.Marshal(resp.Response) + json.Unmarshal(d, &group) + return } From ec1cf7914e9c9c33994f5d1d5ce0477f5d7042ed Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Sat, 24 Aug 2024 20:30:44 +0530 Subject: [PATCH 13/35] fix user create cmd --- cli/cmd/user/create.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/cmd/user/create.go b/cli/cmd/user/create.go index acfa27d4a..0413213fe 100644 --- a/cli/cmd/user/create.go +++ b/cli/cmd/user/create.go @@ -19,7 +19,7 @@ var userCreateCmd = &cobra.Command{ netRolesMap := make(map[models.NetworkID]map[models.UserRoleID]struct{}) for netID, netRoles := range networkRoles { roleMap := make(map[models.UserRoleID]struct{}) - for _, roleID := range strings.Split(netRoles, ",") { + for _, roleID := range strings.Split(netRoles, " ") { roleMap[models.UserRoleID(roleID)] = struct{}{} } netRolesMap[models.NetworkID(netID)] = roleMap From 1ffc1f220b1d4041dd997e9c3ed36c871681787d Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Sat, 24 Aug 2024 21:32:41 +0530 Subject: [PATCH 14/35] add usage info --- cli/cmd/user/groups.go | 20 ++++++-------------- cli/cmd/user/roles.go | 17 ++++++----------- 2 files changed, 12 insertions(+), 25 deletions(-) diff --git a/cli/cmd/user/groups.go b/cli/cmd/user/groups.go index 5a874aa73..0406083e1 100644 --- a/cli/cmd/user/groups.go +++ b/cli/cmd/user/groups.go @@ -18,10 +18,6 @@ var userGroupCmd = &cobra.Command{ Long: `Manage User Groups`, } -// List Roles -var ( - groupID string -) var userGroupListCmd = &cobra.Command{ Use: "list", Args: cobra.NoArgs, @@ -65,12 +61,12 @@ var userGroupCreateCmd = &cobra.Command{ } var userGroupDeleteCmd = &cobra.Command{ - Use: "delete", - Args: cobra.NoArgs, + Use: "delete [groupID]", + Args: cobra.ExactArgs(1), Short: "delete user group", Long: `delete user group`, Run: func(cmd *cobra.Command, args []string) { - resp := functions.DeleteUserGrp(groupID) + resp := functions.DeleteUserGrp(args[0]) if resp != nil { fmt.Println(resp.Message) } @@ -78,12 +74,12 @@ var userGroupDeleteCmd = &cobra.Command{ } var userGroupGetCmd = &cobra.Command{ - Use: "get", - Args: cobra.NoArgs, + Use: "get [groupID]", + Args: cobra.ExactArgs(1), Short: "get user group", Long: `get user group`, Run: func(cmd *cobra.Command, args []string) { - data := functions.GetUserGrp(groupID) + data := functions.GetUserGrp(args[0]) switch commons.OutputFormat { case commons.JsonOutput: functions.PrettyPrint(data) @@ -115,12 +111,8 @@ func init() { userGroupCmd.AddCommand(userGroupCreateCmd) // delete role cmd - userGroupDeleteCmd.Flags().StringVar(&groupID, "group-id", "", "user role ID") - userGroupDeleteCmd.MarkFlagRequired("role-id") userGroupCmd.AddCommand(userGroupDeleteCmd) // Get Role - userGroupGetCmd.Flags().StringVar(&groupID, "group-id", "", "user role ID") - userGroupGetCmd.MarkFlagRequired("group-id") userGroupCmd.AddCommand(userGroupGetCmd) } diff --git a/cli/cmd/user/roles.go b/cli/cmd/user/roles.go index c638640fd..2bb880ef5 100644 --- a/cli/cmd/user/roles.go +++ b/cli/cmd/user/roles.go @@ -21,7 +21,6 @@ var userRoleCmd = &cobra.Command{ // List Roles var ( platformRoles bool - roleID string ) var userRoleListCmd = &cobra.Command{ Use: "list", @@ -64,12 +63,12 @@ var userRoleCreateCmd = &cobra.Command{ } var userRoleDeleteCmd = &cobra.Command{ - Use: "delete", - Args: cobra.NoArgs, + Use: "delete [roleID]", + Args: cobra.ExactArgs(1), Short: "delete user role", Long: `delete user role`, Run: func(cmd *cobra.Command, args []string) { - resp := functions.DeleteUserRole(roleID) + resp := functions.DeleteUserRole(args[0]) if resp != nil { fmt.Println(resp.Message) } @@ -77,12 +76,12 @@ var userRoleDeleteCmd = &cobra.Command{ } var userRoleGetCmd = &cobra.Command{ - Use: "get", - Args: cobra.NoArgs, + Use: "get [roleID]", + Args: cobra.ExactArgs(1), Short: "get user role", Long: `get user role`, Run: func(cmd *cobra.Command, args []string) { - d := functions.GetUserRole(roleID) + d := functions.GetUserRole(args[0]) switch commons.OutputFormat { case commons.JsonOutput: functions.PrettyPrint(d) @@ -115,12 +114,8 @@ func init() { userRoleCmd.AddCommand(userRoleCreateCmd) // delete role cmd - userRoleDeleteCmd.Flags().StringVar(&roleID, "role-id", "", "user role ID") - userRoleDeleteCmd.MarkFlagRequired("role-id") userRoleCmd.AddCommand(userRoleDeleteCmd) // Get Role - userRoleGetCmd.Flags().StringVar(&roleID, "role-id", "", "user role ID") - userRoleGetCmd.MarkFlagRequired("role-id") userRoleCmd.AddCommand(userRoleGetCmd) } From 3352fc9714cd84b31c0965e5c3895190eedff8f0 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Sun, 25 Aug 2024 06:37:42 +0530 Subject: [PATCH 15/35] rm user role check --- controllers/user.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/controllers/user.go b/controllers/user.go index 346a9236f..72925bc25 100644 --- a/controllers/user.go +++ b/controllers/user.go @@ -407,9 +407,6 @@ func createUser(w http.ResponseWriter, r *http.Request) { logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest")) return } - if !servercfg.IsPro { - user.PlatformRoleID = models.AdminRole - } if user.PlatformRoleID == "" { logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("platform role is missing"), "badrequest")) From afa199b79b9a61ab15b4b0a4b8d3d6252a2302f0 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Sun, 25 Aug 2024 06:58:32 +0530 Subject: [PATCH 16/35] fix user update cmd --- cli/cmd/user/create.go | 2 +- cli/cmd/user/update.go | 9 ++++++--- cli/functions/user.go | 2 +- logic/auth.go | 6 ++++-- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/cli/cmd/user/create.go b/cli/cmd/user/create.go index 0413213fe..16af503d5 100644 --- a/cli/cmd/user/create.go +++ b/cli/cmd/user/create.go @@ -42,7 +42,7 @@ func init() { userCreateCmd.Flags().StringVar(&username, "name", "", "Name of the user") userCreateCmd.Flags().StringVar(&password, "password", "", "Password of the user") - userCreateCmd.Flags().StringVarP(&platformID, "platform-id", "r", models.ServiceUser.String(), + userCreateCmd.Flags().StringVarP(&platformID, "platform-role", "r", models.ServiceUser.String(), "Platform Role of the user; run `nmctl roles list` to see available user roles") userCreateCmd.MarkFlagRequired("name") userCreateCmd.MarkFlagRequired("password") diff --git a/cli/cmd/user/update.go b/cli/cmd/user/update.go index f80307618..31e9cceef 100644 --- a/cli/cmd/user/update.go +++ b/cli/cmd/user/update.go @@ -41,10 +41,13 @@ var userUpdateCmd = &cobra.Command{ } func init() { - userUpdateCmd.Flags().BoolVar(&admin, "admin", false, "Make the user an admin ?") - userUpdateCmd.Flags().StringVar(&networks, "networks", "", "List of networks the user will access to (comma separated)") - userUpdateCmd.Flags().StringVarP(&platformID, "platform-id", "r", "", + + userUpdateCmd.Flags().StringVar(&password, "password", "", "Password of the user") + userUpdateCmd.Flags().StringVarP(&platformID, "platform-role", "r", "", "Platform Role of the user; run `nmctl roles list` to see available user roles") + userUpdateCmd.PersistentFlags().StringToStringVarP(&networkRoles, "network-roles", "n", nil, + "Mapping of networkID and list of roles user will be part of (comma separated)") + userUpdateCmd.Flags().BoolVar(&admin, "admin", false, "Make the user an admin ? (deprecated v0.25.0 onwards)") userUpdateCmd.Flags().StringArrayVarP(&groups, "groups", "g", nil, "List of user groups the user will be part of (comma separated)") rootCmd.AddCommand(userUpdateCmd) } diff --git a/cli/functions/user.go b/cli/functions/user.go index 6f435ea4c..e5572bae1 100644 --- a/cli/functions/user.go +++ b/cli/functions/user.go @@ -20,7 +20,7 @@ func CreateUser(payload *models.User) *models.User { // UpdateUser - update a user func UpdateUser(payload *models.User) *models.User { - return request[models.User](http.MethodPut, "/api/users/networks/"+payload.UserName, payload) + return request[models.User](http.MethodPut, "/api/users/"+payload.UserName, payload) } // DeleteUser - delete a user diff --git a/logic/auth.go b/logic/auth.go index 3e2623ff2..7486d310e 100644 --- a/logic/auth.go +++ b/logic/auth.go @@ -297,7 +297,9 @@ func UpdateUser(userchange, user *models.User) (*models.User, error) { } // Reset Gw Access for service users go UpdateUserGwAccess(*user, *userchange) - user.PlatformRoleID = userchange.PlatformRoleID + if userchange.PlatformRoleID != "" { + user.PlatformRoleID = userchange.PlatformRoleID + } user.UserGroups = userchange.UserGroups user.NetworkRoles = userchange.NetworkRoles err := ValidateUser(user) @@ -325,7 +327,7 @@ func ValidateUser(user *models.User) error { // check if role is valid _, err := GetRole(user.PlatformRoleID) if err != nil { - return err + return errors.New("failed to fetch platform role " + user.PlatformRoleID.String()) } v := validator.New() _ = v.RegisterValidation("in_charset", func(fl validator.FieldLevel) bool { From 31d361e58d2cf1424a802823e7bb3e53cc3ffa06 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Sun, 25 Aug 2024 07:23:03 +0530 Subject: [PATCH 17/35] fix static check --- cli/cmd/user/flags.go | 1 - 1 file changed, 1 deletion(-) diff --git a/cli/cmd/user/flags.go b/cli/cmd/user/flags.go index 224e8f6f2..061e8f32b 100644 --- a/cli/cmd/user/flags.go +++ b/cli/cmd/user/flags.go @@ -5,7 +5,6 @@ var ( password string platformID string admin bool - networks string networkRoles map[string]string groups []string ) From c9e593038e06ff528de244fd528528739aaa8754 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Mon, 26 Aug 2024 14:41:18 +0530 Subject: [PATCH 18/35] add backwards comptability support for extclient api for mobile --- controllers/middleware.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/controllers/middleware.go b/controllers/middleware.go index 733db69d3..f359f9bc3 100644 --- a/controllers/middleware.go +++ b/controllers/middleware.go @@ -19,6 +19,12 @@ func userMiddleWare(handler http.Handler) http.Handler { logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest")) return } + if r.Method == http.MethodPost && route == "/api/extclients/{network}/{nodeid}" { + node, err := logic.GetNodeByID(params["nodeid"]) + if err == nil { + params["network"] = node.Network + } + } r.Header.Set("IS_GLOBAL_ACCESS", "no") r.Header.Set("TARGET_RSRC", "") r.Header.Set("RSRC_TYPE", "") From 6faeec243794fc29582f81a9d322e0b90f9c9df8 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Mon, 26 Aug 2024 17:39:00 +0530 Subject: [PATCH 19/35] rm debug logs --- controllers/middleware.go | 2 -- pro/auth/google.go | 8 -------- pro/controllers/users.go | 9 --------- pro/logic/security.go | 7 ------- pro/logic/user_mgmt.go | 2 +- 5 files changed, 1 insertion(+), 27 deletions(-) diff --git a/controllers/middleware.go b/controllers/middleware.go index f359f9bc3..bfc88aa46 100644 --- a/controllers/middleware.go +++ b/controllers/middleware.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/gorilla/mux" - "github.com/gravitl/netmaker/logger" "github.com/gravitl/netmaker/logic" "github.com/gravitl/netmaker/models" ) @@ -105,7 +104,6 @@ func userMiddleWare(handler http.Handler) http.Handler { } r.Header.Set("RSRC_TYPE", r.Header.Get("TARGET_RSRC")) - logger.Log(0, "URL ------> ", route) handler.ServeHTTP(w, r) }) } diff --git a/pro/auth/google.go b/pro/auth/google.go index e4dbc2ae6..94db3a7c9 100644 --- a/pro/auth/google.go +++ b/pro/auth/google.go @@ -69,22 +69,17 @@ func handleGoogleCallback(w http.ResponseWriter, r *http.Request) { handleOauthNotConfigured(w) return } - logger.Log(0, "CALLBACK ----> 1") - - logger.Log(0, "CALLBACK ----> 2") var inviteExists bool // check if invite exists for User in, err := logic.GetUserInvite(content.Email) if err == nil { inviteExists = true } - logger.Log(0, fmt.Sprintf("CALLBACK ----> 3 %v", inviteExists)) // check if user approval is already pending if !inviteExists && logic.IsPendingUser(content.Email) { handleOauthUserSignUpApprovalPending(w) return } - logger.Log(0, "CALLBACK ----> 4") _, err = logic.GetUser(content.Email) if err != nil { if database.IsEmptyRecord(err) { // user must not exist, so try to make one @@ -95,7 +90,6 @@ func handleGoogleCallback(w http.ResponseWriter, r *http.Request) { logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) return } - logger.Log(0, "CALLBACK ----> 4.0") if err = logic.CreateUser(&user); err != nil { handleSomethingWentWrong(w) @@ -124,7 +118,6 @@ func handleGoogleCallback(w http.ResponseWriter, r *http.Request) { return } } - logger.Log(0, "CALLBACK ----> 6") user, err := logic.GetUser(content.Email) if err != nil { logger.Log(0, "error fetching user: ", err.Error()) @@ -186,7 +179,6 @@ func getGoogleUserInfo(state string, code string) (*OAuthUser, error) { if err != nil { return nil, fmt.Errorf("failed reading response body: %s", err.Error()) } - logger.Log(0, fmt.Sprintf("---------------> USERINFO: %v, token: %s", string(contents), token.AccessToken)) var userInfo = &OAuthUser{} if err = json.Unmarshal(contents, userInfo); err != nil { return nil, fmt.Errorf("failed parsing email from response data: %s", err.Error()) diff --git a/pro/controllers/users.go b/pro/controllers/users.go index 2a96d03c6..564def586 100644 --- a/pro/controllers/users.go +++ b/pro/controllers/users.go @@ -808,21 +808,18 @@ func removeUserFromRemoteAccessGW(w http.ResponseWriter, r *http.Request) { func getUserRemoteAccessGwsV1(w http.ResponseWriter, r *http.Request) { // set header. w.Header().Set("Content-Type", "application/json") - logger.Log(0, "------------> 1. getUserRemoteAccessGwsV1") var params = mux.Vars(r) username := params["username"] if username == "" { logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("required params username"), "badrequest")) return } - logger.Log(0, "------------> 2. getUserRemoteAccessGwsV1") user, err := logic.GetUser(username) if err != nil { logger.Log(0, username, "failed to fetch user: ", err.Error()) logic.ReturnErrorResponse(w, r, logic.FormatError(fmt.Errorf("failed to fetch user %s, error: %v", username, err), "badrequest")) return } - logger.Log(0, "------------> 3. getUserRemoteAccessGwsV1") remoteAccessClientID := r.URL.Query().Get("remote_access_clientid") var req models.UserRemoteGwsReq if remoteAccessClientID == "" { @@ -833,7 +830,6 @@ func getUserRemoteAccessGwsV1(w http.ResponseWriter, r *http.Request) { return } } - logger.Log(0, "------------> 4. getUserRemoteAccessGwsV1") reqFromMobile := r.URL.Query().Get("from_mobile") == "true" if req.RemoteAccessClientID == "" && remoteAccessClientID == "" { logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("remote access client id cannot be empty"), "badrequest")) @@ -843,13 +839,11 @@ func getUserRemoteAccessGwsV1(w http.ResponseWriter, r *http.Request) { req.RemoteAccessClientID = remoteAccessClientID } userGws := make(map[string][]models.UserRemoteGws) - logger.Log(0, "------------> 5. getUserRemoteAccessGwsV1") allextClients, err := logic.GetAllExtClients() if err != nil { logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) return } - logger.Log(0, "------------> 6. getUserRemoteAccessGwsV1") userGwNodes := proLogic.GetUserRAGNodes(*user) logger.Log(0, fmt.Sprintf("1. User Gw Nodes: %+v", userGwNodes)) for _, extClient := range allextClients { @@ -890,7 +884,6 @@ func getUserRemoteAccessGwsV1(w http.ResponseWriter, r *http.Request) { logger.Log(0, fmt.Sprintf("2. User Gw Nodes: %+v", userGwNodes)) // add remaining gw nodes to resp for gwID := range userGwNodes { - logger.Log(0, "RAG ---> 1") node, err := logic.GetNodeByID(gwID) if err != nil { continue @@ -901,7 +894,6 @@ func getUserRemoteAccessGwsV1(w http.ResponseWriter, r *http.Request) { if node.PendingDelete { continue } - logger.Log(0, "RAG ---> 2") host, err := logic.GetHost(node.HostID.String()) if err != nil { continue @@ -910,7 +902,6 @@ func getUserRemoteAccessGwsV1(w http.ResponseWriter, r *http.Request) { if err != nil { slog.Error("failed to get node network", "error", err) } - logger.Log(0, "RAG ---> 3") gws := userGws[node.Network] gws = append(gws, models.UserRemoteGws{ diff --git a/pro/logic/security.go b/pro/logic/security.go index 3225c269e..508ac656e 100644 --- a/pro/logic/security.go +++ b/pro/logic/security.go @@ -5,7 +5,6 @@ import ( "fmt" "net/http" - "github.com/gravitl/netmaker/logger" "github.com/gravitl/netmaker/logic" "github.com/gravitl/netmaker/models" ) @@ -16,7 +15,6 @@ func NetworkPermissionsCheck(username string, r *http.Request) error { if err != nil { return err } - logger.Log(0, "NET MIDDL----> 1") userRole, err := logic.GetRole(user.PlatformRoleID) if err != nil { return errors.New("access denied") @@ -24,7 +22,6 @@ func NetworkPermissionsCheck(username string, r *http.Request) error { if userRole.FullAccess { return nil } - logger.Log(0, "NET MIDDL----> 2") // get info from header to determine the target rsrc targetRsrc := r.Header.Get("TARGET_RSRC") targetRsrcID := r.Header.Get("TARGET_RSRC_ID") @@ -81,7 +78,6 @@ func checkNetworkAccessPermissions(netRoleID models.UserRoleID, username, reqSco if err != nil { return err } - logger.Log(0, "NET MIDDL----> 3", string(netRoleID)) if networkPermissionScope.FullAccess { return nil } @@ -92,7 +88,6 @@ func checkNetworkAccessPermissions(netRoleID models.UserRoleID, username, reqSco if !ok { return errors.New("access denied") } - logger.Log(0, "NET MIDDL----> 4", string(netRoleID)) if allRsrcsTypePermissionScope, ok := rsrcPermissionScope[models.RsrcID(fmt.Sprintf("all_%s", targetRsrc))]; ok { // handle extclient apis here if models.RsrcType(targetRsrc) == models.ExtClientsRsrc && allRsrcsTypePermissionScope.SelfOnly && targetRsrcID != "" { @@ -118,7 +113,6 @@ func checkNetworkAccessPermissions(netRoleID models.UserRoleID, username, reqSco } } } - logger.Log(0, "NET MIDDL----> 5", string(netRoleID)) if targetRsrcID == "" { return errors.New("target rsrc id is empty") } @@ -128,7 +122,6 @@ func checkNetworkAccessPermissions(netRoleID models.UserRoleID, username, reqSco return nil } } - logger.Log(0, "NET MIDDL----> 6", string(netRoleID)) return errors.New("access denied") } diff --git a/pro/logic/user_mgmt.go b/pro/logic/user_mgmt.go index 243f3a97e..5ff20fe99 100644 --- a/pro/logic/user_mgmt.go +++ b/pro/logic/user_mgmt.go @@ -533,7 +533,7 @@ func HasNetworkRsrcScope(permissionTemplate models.UserRolePermissionTemplate, n func GetUserRAGNodes(user models.User) (gws map[string]models.Node) { gws = make(map[string]models.Node) userGwAccessScope := GetUserNetworkRolesWithRemoteVPNAccess(user) - logger.Log(0, fmt.Sprintf("User Gw Access Scope: %+v", userGwAccessScope)) + logger.Log(3, fmt.Sprintf("User Gw Access Scope: %+v", userGwAccessScope)) _, allNetAccess := userGwAccessScope["*"] nodes, err := logic.GetAllNodes() if err != nil { From b3df74807b064bf65fa160d9b512cc7e9b871f7b Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Mon, 26 Aug 2024 18:25:42 +0530 Subject: [PATCH 20/35] set frontend url from base domain if empty --- pro/controllers/users.go | 7 ++++++- servercfg/serverconf.go | 5 +++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/pro/controllers/users.go b/pro/controllers/users.go index 564def586..91af1ad11 100644 --- a/pro/controllers/users.go +++ b/pro/controllers/users.go @@ -7,6 +7,7 @@ import ( "fmt" "net/http" "net/url" + "strings" "github.com/gorilla/mux" "github.com/gravitl/netmaker/database" @@ -218,8 +219,12 @@ func inviteUsers(w http.ResponseWriter, r *http.Request) { NetworkRoles: inviteReq.NetworkRoles, InviteCode: logic.RandomString(8), } + frontendURL := strings.TrimSuffix(servercfg.GetFrontendURL(), "/") + if frontendURL == "" { + frontendURL = fmt.Sprintf("https://dashboard.%s", servercfg.GetNmBaseDomain()) + } u, err := url.Parse(fmt.Sprintf("%s/invite?email=%s&invite_code=%s", - servercfg.GetFrontendURL(), url.QueryEscape(invite.Email), url.QueryEscape(invite.InviteCode))) + frontendURL, url.QueryEscape(invite.Email), url.QueryEscape(invite.InviteCode))) if err != nil { slog.Error("failed to parse to invite url", "error", err) return diff --git a/servercfg/serverconf.go b/servercfg/serverconf.go index 98e5d5b49..6736d0c59 100644 --- a/servercfg/serverconf.go +++ b/servercfg/serverconf.go @@ -809,3 +809,8 @@ func GetAllowedEmailDomains() string { } return allowedDomains } + +// GetNmBaseDomain - fetches nm base domain +func GetNmBaseDomain() string { + return os.Getenv("NM_DOMAIN") +} From f25ee0aab47aab653553e4c13eec7faf77a84aad Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Tue, 27 Aug 2024 08:53:37 +0530 Subject: [PATCH 21/35] add flag to install pro --- scripts/nm-quick.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index bf8c2826c..e811af468 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -889,6 +889,9 @@ main (){ downgrade exit 0 ;; + p) + INSTALL_TYPE="pro" + ;; v) usage exit 0 From c6ebc004c600b9f35b4b3e4bece86b10395d99e6 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Tue, 27 Aug 2024 09:19:16 +0530 Subject: [PATCH 22/35] collect tenant id and license on pro install --- scripts/nm-quick.sh | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index e811af468..6fe6da101 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -19,6 +19,7 @@ unset BUILD_TAG unset IMAGE_TAG unset NETMAKER_BASE_DOMAIN unset UPGRADE_FLAG +unset COLLECT_PRO_VARS # usage - displays usage instructions usage() { echo "nm-quick.sh v$NM_QUICK_VERSION" @@ -568,7 +569,17 @@ set_install_vars() { EMAIL="$GET_EMAIL" wait_seconds 1 - + if [ "$COLLECT_PRO_VARS" = "true" ]; then + unset LICENSE_KEY + while [ -z "$LICENSE_KEY" ]; do + read -p "License Key: " LICENSE_KEY + done + unset TENANT_ID + while [ -z ${TENANT_ID} ]; do + read -p "Tenant ID: " TENANT_ID + done + fi + wait_seconds 1 unset GET_MQ_USERNAME unset GET_MQ_PASSWORD unset CONFIRM_MQ_PASSWORD @@ -891,6 +902,7 @@ main (){ ;; p) INSTALL_TYPE="pro" + COLLECT_PRO_VARS="true ;; v) usage From 3e35dfcc9a499fdbe93df16e7b924299b50b6e6c Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Tue, 27 Aug 2024 09:20:00 +0530 Subject: [PATCH 23/35] collect tenant id and license on pro install --- scripts/nm-quick.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index 6fe6da101..5b3eca880 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -902,7 +902,7 @@ main (){ ;; p) INSTALL_TYPE="pro" - COLLECT_PRO_VARS="true + COLLECT_PRO_VARS="true" ;; v) usage From 5bded324ef8f40374145e110361b9835db949a75 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Tue, 27 Aug 2024 09:21:45 +0530 Subject: [PATCH 24/35] add install log --- scripts/nm-quick.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index 5b3eca880..6ad2490fb 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -901,6 +901,7 @@ main (){ exit 0 ;; p) + echo "installing pro version..." INSTALL_TYPE="pro" COLLECT_PRO_VARS="true" ;; From ece5951625b0db977873a787311b5ca9e59884c3 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Tue, 27 Aug 2024 09:31:47 +0530 Subject: [PATCH 25/35] add pro arg to usage --- scripts/nm-quick.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index 6ad2490fb..62b160879 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -25,6 +25,7 @@ usage() { echo "nm-quick.sh v$NM_QUICK_VERSION" echo "usage: ./nm-quick.sh [-c]" echo " -c if specified, will install netmaker community version" + echo " -p if specified, will install netmaker pro version" echo " -u if specified, will upgrade netmaker to pro version" echo " -d if specified, will downgrade netmaker to community version" exit 1 From 883902d91e94df0ed346c552e0be7d7d2505aae1 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Wed, 4 Sep 2024 12:55:40 +0530 Subject: [PATCH 26/35] add pro arg --- scripts/nm-quick.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index 2b539b91f..f83ed93b3 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -883,7 +883,7 @@ main (){ fi INSTALL_TYPE="pro" - while getopts :cudv flag; do + while getopts :cudpv flag; do case "${flag}" in c) INSTALL_TYPE="ce" From f467dda7738d72322078e3c66032d6b52888063e Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Wed, 4 Sep 2024 13:12:16 +0530 Subject: [PATCH 27/35] get token if exists already --- scripts/nm-quick.sh | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index f83ed93b3..76c0b6fa1 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -747,16 +747,21 @@ setup_mesh() { fi echo "Obtaining a netmaker enrollment key..." - - local tokenJson=$(nmctl enrollment_key create --tags netmaker --unlimited --networks netmaker) - TOKEN=$(jq -r '.token' <<<${tokenJson}) - if test -z "$TOKEN"; then - echo "Error creating an enrollment key" - exit 1 + local netmakerTag=$(nmctl enrollment_key list | jq '.[] | .tags[0]') + if [ "$netmakerTag" = "netmaker" ]; then + # key exists already, fetch token + TOKEN=$(nmctl enrollment_key list | jq '.[] | select(.tags[0]=="netmaker") | .token') else - echo "Enrollment key ready" + local tokenJson=$(nmctl enrollment_key create --tags netmaker --unlimited --networks netmaker) + TOKEN=$(jq -r '.token' <<<${tokenJson}) + if test -z "$TOKEN"; then + echo "Error creating an enrollment key" + exit 1 + else + echo "Enrollment key ready" + fi fi - + wait_seconds 3 } From f475abafecc303d827eeb619090b2ee78cc16217 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Fri, 6 Sep 2024 06:27:54 +0400 Subject: [PATCH 28/35] trim double quotes from netmaker tag --- scripts/nm-quick.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index 76c0b6fa1..9852c4e10 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -741,14 +741,14 @@ setup_mesh() { echo "Creating netmaker network (10.101.0.0/16)" # TODO causes "Error Status: 400 Response: {"Code":400,"Message":"could not find any records"}" - nmctl network create --name netmaker --ipv4_addr 10.101.0.0/16 + nmctl network create --name netmaker --ipv4_addr 100.172.188.0/24 wait_seconds 5 fi echo "Obtaining a netmaker enrollment key..." - local netmakerTag=$(nmctl enrollment_key list | jq '.[] | .tags[0]') - if [ "$netmakerTag" = "netmaker" ]; then + local netmakerTag=$(nmctl enrollment_key list | jq '.[] | .tags[0]' | tr -d '"') + if [ ${netmakerTag} = "netmaker" ]; then # key exists already, fetch token TOKEN=$(nmctl enrollment_key list | jq '.[] | select(.tags[0]=="netmaker") | .token') else From cc003c8f73942aa84b53fbba876c6d37e40c62fd Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Fri, 6 Sep 2024 06:43:51 +0400 Subject: [PATCH 29/35] trim double quotes from netmaker token --- scripts/nm-quick.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index 9852c4e10..e1ab99f35 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -750,7 +750,7 @@ setup_mesh() { local netmakerTag=$(nmctl enrollment_key list | jq '.[] | .tags[0]' | tr -d '"') if [ ${netmakerTag} = "netmaker" ]; then # key exists already, fetch token - TOKEN=$(nmctl enrollment_key list | jq '.[] | select(.tags[0]=="netmaker") | .token') + TOKEN=$(nmctl enrollment_key list | jq '.[] | select(.tags[0]=="netmaker") | .token' | tr -d '"') else local tokenJson=$(nmctl enrollment_key create --tags netmaker --unlimited --networks netmaker) TOKEN=$(jq -r '.token' <<<${tokenJson}) From 57434423a59f0e5cd520683ef4a56dc0730fcd20 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Fri, 6 Sep 2024 12:03:35 +0400 Subject: [PATCH 30/35] use jq -r --- scripts/nm-quick.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index e1ab99f35..72fe32f67 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -747,10 +747,10 @@ setup_mesh() { fi echo "Obtaining a netmaker enrollment key..." - local netmakerTag=$(nmctl enrollment_key list | jq '.[] | .tags[0]' | tr -d '"') + local netmakerTag=$(nmctl enrollment_key list | jq -r '.[] | .tags[0]') if [ ${netmakerTag} = "netmaker" ]; then # key exists already, fetch token - TOKEN=$(nmctl enrollment_key list | jq '.[] | select(.tags[0]=="netmaker") | .token' | tr -d '"') + TOKEN=$(nmctl enrollment_key list | jq -r '.[] | select(.tags[0]=="netmaker") | .token') else local tokenJson=$(nmctl enrollment_key create --tags netmaker --unlimited --networks netmaker) TOKEN=$(jq -r '.token' <<<${tokenJson}) From ac6c99b6a8b3ee46a4de56ac378f23e2fbc935e7 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Fri, 6 Sep 2024 16:53:17 +0400 Subject: [PATCH 31/35] copy license and tenant id from previous config --- scripts/nm-quick.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index 72fe32f67..9c9359c60 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -251,7 +251,7 @@ save_config() { ( save_config_item SERVER_IMAGE_TAG "$IMAGE_TAG" fi # copy entries from the previous config - local toCopy=("SERVER_HOST" "MASTER_KEY" "MQ_USERNAME" "MQ_PASSWORD" + local toCopy=("SERVER_HOST" "MASTER_KEY" "MQ_USERNAME" "MQ_PASSWORD" "LICENSE_KEY" "NETMAKER_TENANT_ID" "INSTALL_TYPE" "NODE_ID" "DNS_MODE" "NETCLIENT_AUTO_UPDATE" "API_PORT" "CORS_ALLOWED_ORIGIN" "DISPLAY_KEYS" "DATABASE" "SERVER_BROKER_ENDPOINT" "VERBOSITY" "DEBUG_MODE" "REST_BACKEND" "DISABLE_REMOTE_IP_CHECK" "TELEMETRY" "ALLOWED_EMAIL_DOMAINS" "AUTH_PROVIDER" "CLIENT_ID" "CLIENT_SECRET" From e2f0bf5a0f3ed449da5f2486acaaf200f8ef47e9 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Fri, 6 Sep 2024 20:10:42 +0400 Subject: [PATCH 32/35] rename used tenant id var in script --- scripts/nm-quick.sh | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index 9c9359c60..17f2600ab 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -238,7 +238,7 @@ save_config() { ( save_config_item UI_IMAGE_TAG "$IMAGE_TAG" # version-specific entries if [ "$INSTALL_TYPE" = "pro" ]; then - save_config_item NETMAKER_TENANT_ID "$TENANT_ID" + save_config_item NETMAKER_TENANT_ID "$NETMAKER_TENANT_ID" save_config_item LICENSE_KEY "$LICENSE_KEY" if [ "$UPGRADE_FLAG" = "yes" ];then save_config_item METRICS_EXPORTER "on" @@ -575,9 +575,9 @@ set_install_vars() { while [ -z "$LICENSE_KEY" ]; do read -p "License Key: " LICENSE_KEY done - unset TENANT_ID - while [ -z ${TENANT_ID} ]; do - read -p "Tenant ID: " TENANT_ID + unset NETMAKER_TENANT_ID + while [ -z ${NETMAKER_TENANT_ID} ]; do + read -p "Tenant ID: " NETMAKER_TENANT_ID done fi wait_seconds 1 @@ -830,9 +830,9 @@ upgrade() { while [ -z "$LICENSE_KEY" ]; do read -p "License Key: " LICENSE_KEY done - unset TENANT_ID - while [ -z ${TENANT_ID} ]; do - read -p "Tenant ID: " TENANT_ID + unset NETMAKER_TENANT_ID + while [ -z ${NETMAKER_TENANT_ID} ]; do + read -p "Tenant ID: " NETMAKER_TENANT_ID done save_config # start docker and rebuild containers / networks From 8eb0e5bfaef277bca6f95b316c838fbbbfb8b4bf Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Mon, 30 Sep 2024 11:26:08 +0400 Subject: [PATCH 33/35] change network log --- scripts/nm-quick.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index 17f2600ab..b9d2cbd83 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -738,7 +738,7 @@ setup_mesh() { # add a network if none present if [ "$networkCount" -lt 1 ]; then - echo "Creating netmaker network (10.101.0.0/16)" + echo "Creating netmaker network (100.172.188.0/24)" # TODO causes "Error Status: 400 Response: {"Code":400,"Message":"could not find any records"}" nmctl network create --name netmaker --ipv4_addr 100.172.188.0/24 From de1b5f51ed97cf5f1caf0b34e36a5e1030779f7d Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Mon, 30 Sep 2024 12:06:40 +0400 Subject: [PATCH 34/35] change cidr to /16 --- scripts/nm-quick.sh | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index b9d2cbd83..503581bbd 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -738,17 +738,16 @@ setup_mesh() { # add a network if none present if [ "$networkCount" -lt 1 ]; then - echo "Creating netmaker network (100.172.188.0/24)" - + echo "Creating netmaker network (100.172.0.0/16)" # TODO causes "Error Status: 400 Response: {"Code":400,"Message":"could not find any records"}" - nmctl network create --name netmaker --ipv4_addr 100.172.188.0/24 + nmctl network create --name netmaker --ipv4_addr 100.172.0.0/16 wait_seconds 5 fi echo "Obtaining a netmaker enrollment key..." local netmakerTag=$(nmctl enrollment_key list | jq -r '.[] | .tags[0]') - if [ ${netmakerTag} = "netmaker" ]; then + if [[ ${netmakerTag} = "netmaker" ]]; then # key exists already, fetch token TOKEN=$(nmctl enrollment_key list | jq -r '.[] | select(.tags[0]=="netmaker") | .token') else From 61e2b46f9deca719be98e16a77947f403f2dc366 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Mon, 30 Sep 2024 12:43:51 +0400 Subject: [PATCH 35/35] change network to carrier grade reserved range --- scripts/nm-quick.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/nm-quick.sh b/scripts/nm-quick.sh index 503581bbd..bf94aa8c1 100755 --- a/scripts/nm-quick.sh +++ b/scripts/nm-quick.sh @@ -738,9 +738,9 @@ setup_mesh() { # add a network if none present if [ "$networkCount" -lt 1 ]; then - echo "Creating netmaker network (100.172.0.0/16)" + echo "Creating netmaker network (100.64.0.0/16)" # TODO causes "Error Status: 400 Response: {"Code":400,"Message":"could not find any records"}" - nmctl network create --name netmaker --ipv4_addr 100.172.0.0/16 + nmctl network create --name netmaker --ipv4_addr 100.64.0.0/16 wait_seconds 5 fi