fixing runtime panic on user delete

This commit is contained in:
afeiszli 2021-04-14 22:59:25 -04:00
parent 675a6ad284
commit 3a2eb1411a
10 changed files with 83 additions and 19 deletions

Binary file not shown.

Binary file not shown.

View file

@ -538,7 +538,7 @@ func createAccessKey(w http.ResponseWriter, r *http.Request) {
if accesskey.Uses == 0 {
accesskey.Uses = 1
}
gconf, err := functions.GetGlobalConfig()
_, gconf, err := functions.GetGlobalConfig()
if err != nil {
returnErrorResponse(w,r,formatError(err, "internal"))
return

View file

@ -7,6 +7,7 @@ import (
"github.com/gravitl/netmaker/mongoconn"
"golang.org/x/crypto/bcrypt"
"time"
"errors"
"strings"
"fmt"
"context"
@ -444,11 +445,16 @@ func deleteUser(w http.ResponseWriter, r *http.Request) {
success, err := DeleteUser(params["username"])
if err != nil || !success {
http.Error(w, err.Error(), 400)
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
json.NewEncoder(w).Encode("Could not delete user " + params["username"])
return
}
} else if !success {
returnErrorResponse(w, r, formatError(errors.New("Delete unsuccessful."), "internal"))
json.NewEncoder(w).Encode("Could not delete user " + params["username"])
return
}
json.NewEncoder(w).Encode(params["username"] + " deleted.")
}

View file

@ -37,7 +37,7 @@ func CreateServerToken(netID string) (string, error) {
accesskey.Name = GenKeyName()
accesskey.Value = GenKey()
accesskey.Uses = 1
gconf, errG := GetGlobalConfig()
_, gconf, errG := GetGlobalConfig()
if errG != nil {
return "", errG
}
@ -504,7 +504,9 @@ func UniqueAddress(networkName string) (string, error){
}
//pretty simple get
func GetGlobalConfig() ( models.GlobalConfig, error) {
func GetGlobalConfig() (bool, models.GlobalConfig, error) {
create := false
filter := bson.M{}
@ -518,12 +520,16 @@ func GetGlobalConfig() ( models.GlobalConfig, error) {
defer cancel()
if err != nil {
if err == mongo.ErrNoDocuments {
fmt.Println("Global config does not exist. Need to create.")
create = true
return create, globalconf, err
} else if err != nil {
fmt.Println(err)
fmt.Println("Could not get global config")
return globalconf, err
return create, globalconf, err
}
return globalconf, err
return create, globalconf, err
}

View file

@ -50,6 +50,10 @@ func CreateUserJWT(username string, isadmin bool) (response string, err error) {
func VerifyUserToken(tokenString string) (username string, isadmin bool, err error) {
claims := &models.UserClaims{}
if tokenString == config.Config.Server.MasterKey {
return "masteradministrator", true, nil
}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtSecretKey, nil
})

26
main.go
View file

@ -16,6 +16,7 @@ import (
"fmt"
"time"
"net/http"
"strings"
"errors"
"io/ioutil"
"os"
@ -25,6 +26,7 @@ import (
"strconv"
"sync"
"os/signal"
"go.mongodb.org/mongo-driver/mongo"
service "github.com/gravitl/netmaker/controllers"
nodepb "github.com/gravitl/netmaker/grpc"
"google.golang.org/grpc"
@ -127,7 +129,7 @@ func runGRPC(wg *sync.WaitGroup, installserver bool) {
gconf.Name = "netmaker"
err := setGlobalConfig(gconf)
if err != nil {
if err != nil && err != mongo.ErrNoDocuments{
log.Fatalf("Unable to set global config: %v", err)
}
@ -159,11 +161,13 @@ func runGRPC(wg *sync.WaitGroup, installserver bool) {
fmt.Println("Agent Server succesfully started on port " + grpcport + " (gRPC)")
if installserver {
fmt.Println("Adding server to default network")
fmt.Println("Adding server to " + config.Config.Server.DefaultNetName)
success, err := serverctl.AddNetwork(config.Config.Server.DefaultNetName)
if err != nil || !success {
fmt.Printf("Error adding to default network: %v", err)
fmt.Println("")
fmt.Println("Unable to add server to network. Continuing.")
fmt.Println("Please investigate client installation on server.")
} else {
fmt.Println("Server successfully added to default network.")
}
@ -198,12 +202,16 @@ func setGlobalConfig(globalconf models.GlobalConfig) (error) {
collection := mongoconn.Client.Database("netmaker").Collection("config")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err := functions.GetGlobalConfig()
if err != nil {
create, _, err := functions.GetGlobalConfig()
if create {
_, err := collection.InsertOne(ctx, globalconf)
defer cancel()
if err != nil {
return err
if err == mongo.ErrNoDocuments || strings.Contains(err.Error(), "no documents in result"){
return nil
} else {
return err
}
}
} else {
filter := bson.M{"name": "netmaker"}
@ -213,9 +221,13 @@ func setGlobalConfig(globalconf models.GlobalConfig) (error) {
{"portgrpc", globalconf.PortGRPC},
}},
}
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&globalconf)
err := collection.FindOneAndUpdate(ctx, filter, update).Decode(&globalconf)
if err == mongo.ErrNoDocuments {
//if err == mongo.ErrNoDocuments || strings.Contains(err.Error(), "no documents in result"){
return nil
}
}
return nil
return err
}
func createDefaultNetwork() (bool, error) {

View file

@ -196,6 +196,8 @@ func Install(accesskey string, password string, server string, network string, n
var privatekey wgtypes.Key
var privkeystring string
var endpoint string
var postup string
var postdown string
var name string
var wginterface string
@ -274,6 +276,17 @@ func Install(accesskey string, password string, server string, network string, n
}
fmt.Println(" Interface: " + wginterface)
if nodecfg.PostUp != "" {
postup = nodecfg.PostUp
}
fmt.Println(" PostUp: " + postup)
if nodecfg.PostDown!= "" {
postdown = nodecfg.PostDown
}
fmt.Println(" PostDown: " + postdown)
if nodecfg.KeepAlive != 0 {
keepalive = nodecfg.KeepAlive
}
@ -347,6 +360,8 @@ func Install(accesskey string, password string, server string, network string, n
Accesskey: accesskey,
Nodenetwork: network,
Listenport: listenport,
Postup: postup,
Postdown: postdown,
Keepalive: keepalive,
Localaddress: localaddress,
Interface: wginterface,
@ -384,6 +399,8 @@ func Install(accesskey string, password string, server string, network string, n
fmt.Println(" Local Address: " + node.Localaddress)
fmt.Println(" Name: " + node.Name)
fmt.Println(" Interface: " + node.Interface)
fmt.Println(" PostUp: " + node.Postup)
fmt.Println(" PostDown: " + node.Postdown)
fmt.Println(" Port: " + strconv.FormatInt(int64(node.Listenport), 10))
fmt.Println(" KeepAlive: " + strconv.FormatInt(int64(node.Keepalive), 10))
fmt.Println(" Public Key: " + node.Publickey)
@ -483,6 +500,12 @@ func modConfig(node *nodepb.Node) error{
if node.Localaddress != ""{
nodecfg.LocalAddress = node.Localaddress
}
if node.Postup != ""{
nodecfg.PostUp = node.Postup
}
if node.Postdown != ""{
nodecfg.PostDown = node.Postdown
}
if node.Listenport != 0{
nodecfg.Port = node.Listenport
}

View file

@ -15,6 +15,7 @@ func DownloadNetclient() error {
// Get the data
resp, err := http.Get("https://github.com/gravitl/netmaker/releases/download/latest/netclient")
if err != nil {
fmt.Println("could not download netclient")
return err
}
defer resp.Body.Close()
@ -22,6 +23,7 @@ func DownloadNetclient() error {
// Create the file
out, err := os.Create("/etc/netclient/netclient")
if err != nil {
fmt.Println("could not create /etc/netclient")
return err
}
defer out.Close()
@ -33,6 +35,7 @@ func DownloadNetclient() error {
func RemoveNetwork(network string) (bool, error) {
_, err := os.Stat("/etc/netclient/netclient")
if err != nil {
fmt.Println("could not find /etc/netclient")
return false, err
}
cmdoutput, err := exec.Command("/etc/netclient/netclient","-c","remove","-n",network).Output()
@ -50,22 +53,25 @@ func AddNetwork(network string) (bool, error) {
if os.IsNotExist(err) {
os.Mkdir("/etc/netclient", 744)
} else if err != nil {
fmt.Println("couldnt find or create /etc/netclient")
fmt.Println("could not find or create /etc/netclient")
return false, err
}
token, err := functions.CreateServerToken(network)
if err != nil {
return false, err
fmt.Println("could not create server token for " + network)
return false, err
}
_, err = os.Stat("/etc/netclient/netclient")
if os.IsNotExist(err) {
err = DownloadNetclient()
fmt.Println("could not download netclient")
if err != nil {
return false, err
}
}
err = os.Chmod("/etc/netclient/netclient", 0755)
if err != nil {
fmt.Println("could not change netclient directory permissions")
return false, err
}
cmdoutput, err := exec.Command("/etc/netclient/netclient","-c","install","-t",token,"-name","netmaker").Output()
@ -73,8 +79,8 @@ func AddNetwork(network string) (bool, error) {
fmt.Println(string(cmdoutput))
return false, err
}
fmt.Println(string(cmdoutput))
fmt.Println("Server added to network " + network)
return true, err
}

7
test/restartmongo.sh Normal file
View file

@ -0,0 +1,7 @@
#!/bin/bash
sudo docker kill mongodb
sudo docker rm mongodb
sudo docker volume rm mongovol
docker volume create mongovol && docker run -d --name mongodb -v mongovol:/data/db --network host -e MONGO_INITDB_ROOT_USERNAME=mongoadmin -e MONGO_INITDB_ROOT_PASSWORD=mongopass mongo --bind_ip 0.0.0.0