mirror of
https://github.com/gravitl/netmaker.git
synced 2025-10-05 08:47:35 +08:00
massive number of changes to schema and error handling.
This commit is contained in:
@@ -72,27 +72,27 @@ func grpcAuthorize(ctx context.Context) error {
|
|||||||
|
|
||||||
authToken := authHeader[0]
|
authToken := authHeader[0]
|
||||||
|
|
||||||
mac, group, err := functions.VerifyToken(authToken)
|
mac, network, err := functions.VerifyToken(authToken)
|
||||||
|
|
||||||
if err != nil { return err }
|
if err != nil { return err }
|
||||||
|
|
||||||
groupexists, err := functions.GroupExists(group)
|
networkexists, err := functions.NetworkExists(network)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return status.Errorf(codes.Unauthenticated, "Unauthorized. Group does not exist: " + group)
|
return status.Errorf(codes.Unauthenticated, "Unauthorized. Network does not exist: " + network)
|
||||||
|
|
||||||
}
|
}
|
||||||
emptynode := models.Node{}
|
emptynode := models.Node{}
|
||||||
node, err := functions.GetNodeByMacAddress(group, mac)
|
node, err := functions.GetNodeByMacAddress(network, mac)
|
||||||
if err != nil || node == emptynode {
|
if err != nil || node == emptynode {
|
||||||
return status.Errorf(codes.Unauthenticated, "Node does not exist.")
|
return status.Errorf(codes.Unauthenticated, "Node does not exist.")
|
||||||
}
|
}
|
||||||
|
|
||||||
//check that the request is for a valid group
|
//check that the request is for a valid network
|
||||||
//if (groupCheck && !groupexists) || err != nil {
|
//if (networkCheck && !networkexists) || err != nil {
|
||||||
if (!groupexists) {
|
if (!networkexists) {
|
||||||
|
|
||||||
return status.Errorf(codes.Unauthenticated, "Group does not exist.")
|
return status.Errorf(codes.Unauthenticated, "Network does not exist.")
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
return nil
|
return nil
|
||||||
@@ -124,7 +124,7 @@ func (s *NodeServiceServer) Login(ctx context.Context, req *nodepb.LoginRequest)
|
|||||||
//Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved).
|
//Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved).
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
var err = collection.FindOne(ctx, bson.M{ "macaddress": macaddress, "group": network}).Decode(&result)
|
var err = collection.FindOne(ctx, bson.M{ "macaddress": macaddress, "network": network}).Decode(&result)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
@@ -140,7 +140,7 @@ func (s *NodeServiceServer) Login(ctx context.Context, req *nodepb.LoginRequest)
|
|||||||
return nil, err
|
return nil, err
|
||||||
} else {
|
} else {
|
||||||
//Create a new JWT for the node
|
//Create a new JWT for the node
|
||||||
tokenString, err := functions.CreateJWT(macaddress, result.Group)
|
tokenString, err := functions.CreateJWT(macaddress, result.Network)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@@ -16,7 +16,7 @@ import (
|
|||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetPeersList(groupName string) ([]models.PeersResponse, error) {
|
func GetPeersList(networkName string) ([]models.PeersResponse, error) {
|
||||||
|
|
||||||
var peers []models.PeersResponse
|
var peers []models.PeersResponse
|
||||||
|
|
||||||
@@ -25,8 +25,8 @@ func GetPeersList(groupName string) ([]models.PeersResponse, error) {
|
|||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
//Get all nodes in the relevant group which are NOT in pending state
|
//Get all nodes in the relevant network which are NOT in pending state
|
||||||
filter := bson.M{"group": groupName, "ispending": false}
|
filter := bson.M{"network": networkName, "ispending": false}
|
||||||
cur, err := collection.Find(ctx, filter)
|
cur, err := collection.Find(ctx, filter)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -59,18 +59,18 @@ func GetPeersList(groupName string) ([]models.PeersResponse, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func ValidateNode(operation string, groupName string, node models.Node) error {
|
func ValidateNode(operation string, networkName string, node models.Node) error {
|
||||||
|
|
||||||
v := validator.New()
|
v := validator.New()
|
||||||
|
|
||||||
_ = v.RegisterValidation("endpoint_check", func(fl validator.FieldLevel) bool {
|
_ = v.RegisterValidation("endpoint_check", func(fl validator.FieldLevel) bool {
|
||||||
//var isFieldUnique bool = functions.IsFieldUnique(groupName, "endpoint", node.Endpoint)
|
//var isFieldUnique bool = functions.IsFieldUnique(networkName, "endpoint", node.Endpoint)
|
||||||
isIpv4 := functions.IsIpv4Net(node.Endpoint)
|
isIpv4 := functions.IsIpv4Net(node.Endpoint)
|
||||||
notEmptyCheck := node.Endpoint != ""
|
notEmptyCheck := node.Endpoint != ""
|
||||||
return (notEmptyCheck && isIpv4) || operation == "update"
|
return (notEmptyCheck && isIpv4) || operation == "update"
|
||||||
})
|
})
|
||||||
_ = v.RegisterValidation("localaddress_check", func(fl validator.FieldLevel) bool {
|
_ = v.RegisterValidation("localaddress_check", func(fl validator.FieldLevel) bool {
|
||||||
//var isFieldUnique bool = functions.IsFieldUnique(groupName, "endpoint", node.Endpoint)
|
//var isFieldUnique bool = functions.IsFieldUnique(networkName, "endpoint", node.Endpoint)
|
||||||
isIpv4 := functions.IsIpv4Net(node.LocalAddress)
|
isIpv4 := functions.IsIpv4Net(node.LocalAddress)
|
||||||
notEmptyCheck := node.LocalAddress != ""
|
notEmptyCheck := node.LocalAddress != ""
|
||||||
return (notEmptyCheck && isIpv4) || operation == "update"
|
return (notEmptyCheck && isIpv4) || operation == "update"
|
||||||
@@ -78,7 +78,7 @@ func ValidateNode(operation string, groupName string, node models.Node) error {
|
|||||||
|
|
||||||
|
|
||||||
_ = v.RegisterValidation("macaddress_unique", func(fl validator.FieldLevel) bool {
|
_ = v.RegisterValidation("macaddress_unique", func(fl validator.FieldLevel) bool {
|
||||||
var isFieldUnique bool = functions.IsFieldUnique(groupName, "macaddress", node.MacAddress)
|
var isFieldUnique bool = functions.IsFieldUnique(networkName, "macaddress", node.MacAddress)
|
||||||
return isFieldUnique || operation == "update"
|
return isFieldUnique || operation == "update"
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -92,8 +92,8 @@ func ValidateNode(operation string, groupName string, node models.Node) error {
|
|||||||
return isvalid
|
return isvalid
|
||||||
})
|
})
|
||||||
|
|
||||||
_ = v.RegisterValidation("group_exists", func(fl validator.FieldLevel) bool {
|
_ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
|
||||||
_, err := node.GetGroup()
|
_, err := node.GetNetwork()
|
||||||
return err == nil
|
return err == nil
|
||||||
})
|
})
|
||||||
_ = v.RegisterValidation("pubkey_check", func(fl validator.FieldLevel) bool {
|
_ = v.RegisterValidation("pubkey_check", func(fl validator.FieldLevel) bool {
|
||||||
@@ -122,12 +122,12 @@ func UpdateNode(nodechange models.Node, node models.Node) (models.Node, error) {
|
|||||||
//Question: Is there a better way of doing this than a bunch of "if" statements? probably...
|
//Question: Is there a better way of doing this than a bunch of "if" statements? probably...
|
||||||
//Eventually, lets have a better way to check if any of the fields are filled out...
|
//Eventually, lets have a better way to check if any of the fields are filled out...
|
||||||
queryMac := node.MacAddress
|
queryMac := node.MacAddress
|
||||||
queryGroup := node.Group
|
queryNetwork := node.Network
|
||||||
notifygroup := false
|
notifynetwork := false
|
||||||
|
|
||||||
if nodechange.Address != "" {
|
if nodechange.Address != "" {
|
||||||
node.Address = nodechange.Address
|
node.Address = nodechange.Address
|
||||||
notifygroup = true
|
notifynetwork = true
|
||||||
}
|
}
|
||||||
if nodechange.Name != "" {
|
if nodechange.Name != "" {
|
||||||
node.Name = nodechange.Name
|
node.Name = nodechange.Name
|
||||||
@@ -155,7 +155,7 @@ func UpdateNode(nodechange models.Node, node models.Node) (models.Node, error) {
|
|||||||
}
|
}
|
||||||
if nodechange.Endpoint != "" {
|
if nodechange.Endpoint != "" {
|
||||||
node.Endpoint = nodechange.Endpoint
|
node.Endpoint = nodechange.Endpoint
|
||||||
notifygroup = true
|
notifynetwork = true
|
||||||
}
|
}
|
||||||
if nodechange.SaveConfig != nil {
|
if nodechange.SaveConfig != nil {
|
||||||
node.SaveConfig = nodechange.SaveConfig
|
node.SaveConfig = nodechange.SaveConfig
|
||||||
@@ -180,7 +180,7 @@ func UpdateNode(nodechange models.Node, node models.Node) (models.Node, error) {
|
|||||||
if nodechange.PublicKey != "" {
|
if nodechange.PublicKey != "" {
|
||||||
node.PublicKey = nodechange.PublicKey
|
node.PublicKey = nodechange.PublicKey
|
||||||
node.KeyUpdateTimeStamp = time.Now().Unix()
|
node.KeyUpdateTimeStamp = time.Now().Unix()
|
||||||
notifygroup = true
|
notifynetwork = true
|
||||||
}
|
}
|
||||||
|
|
||||||
//collection := mongoconn.ConnectDB()
|
//collection := mongoconn.ConnectDB()
|
||||||
@@ -189,7 +189,7 @@ func UpdateNode(nodechange models.Node, node models.Node) (models.Node, error) {
|
|||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
// Create filter
|
// Create filter
|
||||||
filter := bson.M{"macaddress": queryMac, "group": queryGroup}
|
filter := bson.M{"macaddress": queryMac, "network": queryNetwork}
|
||||||
|
|
||||||
node.SetLastModified()
|
node.SetLastModified()
|
||||||
|
|
||||||
@@ -221,24 +221,24 @@ func UpdateNode(nodechange models.Node, node models.Node) (models.Node, error) {
|
|||||||
return nodeupdate, errN
|
return nodeupdate, errN
|
||||||
}
|
}
|
||||||
|
|
||||||
returnnode, errN := GetNode(node.MacAddress, node.Group)
|
returnnode, errN := GetNode(node.MacAddress, node.Network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
if notifygroup {
|
if notifynetwork {
|
||||||
errN = SetGroupNodesLastModified(node.Group)
|
errN = SetNetworkNodesLastModified(node.Network)
|
||||||
}
|
}
|
||||||
|
|
||||||
return returnnode, errN
|
return returnnode, errN
|
||||||
}
|
}
|
||||||
|
|
||||||
func DeleteNode(macaddress string, group string) (bool, error) {
|
func DeleteNode(macaddress string, network string) (bool, error) {
|
||||||
|
|
||||||
deleted := false
|
deleted := false
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||||
|
|
||||||
filter := bson.M{"macaddress": macaddress, "group": group}
|
filter := bson.M{"macaddress": macaddress, "network": network}
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
@@ -252,13 +252,13 @@ func DeleteNode(macaddress string, group string) (bool, error) {
|
|||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
err = SetGroupNodesLastModified(group)
|
err = SetNetworkNodesLastModified(network)
|
||||||
fmt.Println("Deleted node " + macaddress + " from group " + group)
|
fmt.Println("Deleted node " + macaddress + " from network " + network)
|
||||||
|
|
||||||
return deleted, err
|
return deleted, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetNode(macaddress string, group string) (models.Node, error) {
|
func GetNode(macaddress string, network string) (models.Node, error) {
|
||||||
|
|
||||||
var node models.Node
|
var node models.Node
|
||||||
|
|
||||||
@@ -266,7 +266,7 @@ func GetNode(macaddress string, group string) (models.Node, error) {
|
|||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"macaddress": macaddress, "group": group}
|
filter := bson.M{"macaddress": macaddress, "network": network}
|
||||||
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&node)
|
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&node)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -274,7 +274,7 @@ func GetNode(macaddress string, group string) (models.Node, error) {
|
|||||||
return node, err
|
return node, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateNode(node models.Node, groupName string) (models.Node, error) {
|
func CreateNode(node models.Node, networkName string) (models.Node, error) {
|
||||||
|
|
||||||
//encrypt that password so we never see it again
|
//encrypt that password so we never see it again
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(node.Password), 5)
|
hash, err := bcrypt.GenerateFromPassword([]byte(node.Password), 5)
|
||||||
@@ -286,7 +286,7 @@ func CreateNode(node models.Node, groupName string) (models.Node, error) {
|
|||||||
node.Password = string(hash)
|
node.Password = string(hash)
|
||||||
|
|
||||||
|
|
||||||
node.Group = groupName
|
node.Network = networkName
|
||||||
|
|
||||||
//node.SetDefaults()
|
//node.SetDefaults()
|
||||||
//Umm, why am I doing this again?
|
//Umm, why am I doing this again?
|
||||||
@@ -296,9 +296,9 @@ func CreateNode(node models.Node, groupName string) (models.Node, error) {
|
|||||||
node.SetDefaults()
|
node.SetDefaults()
|
||||||
|
|
||||||
//Another DB call here...Inefficient
|
//Another DB call here...Inefficient
|
||||||
//Anyways, this scrolls through all the IP Addresses in the group range and checks against nodes
|
//Anyways, this scrolls through all the IP Addresses in the network range and checks against nodes
|
||||||
//until one is open and then returns it
|
//until one is open and then returns it
|
||||||
node.Address, err = functions.UniqueAddress(groupName)
|
node.Address, err = functions.UniqueAddress(networkName)
|
||||||
|
|
||||||
if err != nil {/*
|
if err != nil {/*
|
||||||
errorResponse := models.ErrorResponse{
|
errorResponse := models.ErrorResponse{
|
||||||
@@ -317,7 +317,7 @@ func CreateNode(node models.Node, groupName string) (models.Node, error) {
|
|||||||
node.KeyUpdateTimeStamp = time.Now().Unix()
|
node.KeyUpdateTimeStamp = time.Now().Unix()
|
||||||
|
|
||||||
//Create a JWT for the node
|
//Create a JWT for the node
|
||||||
tokenString, _ := functions.CreateJWT(node.MacAddress, groupName)
|
tokenString, _ := functions.CreateJWT(node.MacAddress, networkName)
|
||||||
|
|
||||||
if tokenString == "" {
|
if tokenString == "" {
|
||||||
//returnErrorResponse(w, r, errorResponse)
|
//returnErrorResponse(w, r, errorResponse)
|
||||||
@@ -341,26 +341,26 @@ func CreateNode(node models.Node, groupName string) (models.Node, error) {
|
|||||||
//return response for if node is pending
|
//return response for if node is pending
|
||||||
if !node.IsPending {
|
if !node.IsPending {
|
||||||
|
|
||||||
functions.DecrimentKey(node.Group, node.AccessKey)
|
functions.DecrimentKey(node.Network, node.AccessKey)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
SetGroupNodesLastModified(node.Group)
|
SetNetworkNodesLastModified(node.Network)
|
||||||
|
|
||||||
return node, err
|
return node, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func NodeCheckIn(node models.Node, groupName string) (models.CheckInResponse, error) {
|
func NodeCheckIn(node models.Node, networkName string) (models.CheckInResponse, error) {
|
||||||
|
|
||||||
var response models.CheckInResponse
|
var response models.CheckInResponse
|
||||||
|
|
||||||
parentgroup, err := functions.GetParentGroup(groupName)
|
parentnetwork, err := functions.GetParentNetwork(networkName)
|
||||||
if err != nil{
|
if err != nil{
|
||||||
err = fmt.Errorf("%w; Couldnt retrieve Group " + groupName + ": ", err)
|
err = fmt.Errorf("%w; Couldnt retrieve Network " + networkName + ": ", err)
|
||||||
return response, err
|
return response, err
|
||||||
}
|
}
|
||||||
|
|
||||||
parentnode, err := functions.GetNodeByMacAddress(groupName, node.MacAddress)
|
parentnode, err := functions.GetNodeByMacAddress(networkName, node.MacAddress)
|
||||||
if err != nil{
|
if err != nil{
|
||||||
err = fmt.Errorf("%w; Couldnt Get Node " + node.MacAddress, err)
|
err = fmt.Errorf("%w; Couldnt Get Node " + node.MacAddress, err)
|
||||||
return response, err
|
return response, err
|
||||||
@@ -371,9 +371,9 @@ func NodeCheckIn(node models.Node, groupName string) (models.CheckInResponse, er
|
|||||||
return response, err
|
return response, err
|
||||||
}
|
}
|
||||||
|
|
||||||
grouplm := parentgroup.GroupLastModified
|
networklm := parentnetwork.NetworkLastModified
|
||||||
peerslm := parentgroup.NodesLastModified
|
peerslm := parentnetwork.NodesLastModified
|
||||||
gkeyupdate := parentgroup.KeyUpdateTimeStamp
|
gkeyupdate := parentnetwork.KeyUpdateTimeStamp
|
||||||
nkeyupdate := parentnode.KeyUpdateTimeStamp
|
nkeyupdate := parentnode.KeyUpdateTimeStamp
|
||||||
peerlistlm := parentnode.LastPeerUpdate
|
peerlistlm := parentnode.LastPeerUpdate
|
||||||
parentnodelm := parentnode.LastModified
|
parentnodelm := parentnode.LastModified
|
||||||
@@ -383,7 +383,7 @@ func NodeCheckIn(node models.Node, groupName string) (models.CheckInResponse, er
|
|||||||
response.NeedConfigUpdate = true
|
response.NeedConfigUpdate = true
|
||||||
}
|
}
|
||||||
|
|
||||||
if parentnodelm < grouplm {
|
if parentnodelm < networklm {
|
||||||
response.NeedConfigUpdate = true
|
response.NeedConfigUpdate = true
|
||||||
}
|
}
|
||||||
if peerlistlm < peerslm {
|
if peerlistlm < peerslm {
|
||||||
@@ -394,7 +394,7 @@ func NodeCheckIn(node models.Node, groupName string) (models.CheckInResponse, er
|
|||||||
}
|
}
|
||||||
if time.Now().Unix() > parentnode.ExpirationDateTime {
|
if time.Now().Unix() > parentnode.ExpirationDateTime {
|
||||||
response.NeedDelete = true
|
response.NeedDelete = true
|
||||||
_, err = DeleteNode(node.MacAddress, groupName)
|
_, err = DeleteNode(node.MacAddress, networkName)
|
||||||
} else {
|
} else {
|
||||||
err = TimestampNode(parentnode, true, false, false)
|
err = TimestampNode(parentnode, true, false, false)
|
||||||
|
|
||||||
@@ -408,16 +408,16 @@ func NodeCheckIn(node models.Node, groupName string) (models.CheckInResponse, er
|
|||||||
return response, err
|
return response, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetGroupNodesLastModified(groupName string) error {
|
func SetNetworkNodesLastModified(networkName string) error {
|
||||||
|
|
||||||
timestamp := time.Now().Unix()
|
timestamp := time.Now().Unix()
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
// Create filter
|
// Create filter
|
||||||
filter := bson.M{"nameid": groupName}
|
filter := bson.M{"netid": networkName}
|
||||||
|
|
||||||
// prepare update model.
|
// prepare update model.
|
||||||
update := bson.D{
|
update := bson.D{
|
||||||
@@ -453,7 +453,7 @@ func TimestampNode(node models.Node, updatecheckin bool, updatepeers bool, updat
|
|||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
// Create filter
|
// Create filter
|
||||||
filter := bson.M{"macaddress": node.MacAddress, "group": node.Group}
|
filter := bson.M{"macaddress": node.MacAddress, "network": node.Network}
|
||||||
|
|
||||||
// prepare update model.
|
// prepare update model.
|
||||||
update := bson.D{
|
update := bson.D{
|
||||||
|
@@ -27,7 +27,7 @@ func HandleRESTRequests(wg *sync.WaitGroup) {
|
|||||||
|
|
||||||
nodeHandlers(r)
|
nodeHandlers(r)
|
||||||
userHandlers(r)
|
userHandlers(r)
|
||||||
groupHandlers(r)
|
networkHandlers(r)
|
||||||
fileHandlers(r)
|
fileHandlers(r)
|
||||||
serverHandlers(r)
|
serverHandlers(r)
|
||||||
|
|
||||||
|
@@ -19,20 +19,20 @@ import (
|
|||||||
"github.com/gravitl/netmaker/config"
|
"github.com/gravitl/netmaker/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func groupHandlers(r *mux.Router) {
|
func networkHandlers(r *mux.Router) {
|
||||||
r.HandleFunc("/api/groups", securityCheck(http.HandlerFunc(getGroups))).Methods("GET")
|
r.HandleFunc("/api/networks", securityCheck(http.HandlerFunc(getNetworks))).Methods("GET")
|
||||||
r.HandleFunc("/api/groups", securityCheck(http.HandlerFunc(createGroup))).Methods("POST")
|
r.HandleFunc("/api/networks", securityCheck(http.HandlerFunc(createNetwork))).Methods("POST")
|
||||||
r.HandleFunc("/api/groups/{groupname}", securityCheck(http.HandlerFunc(getGroup))).Methods("GET")
|
r.HandleFunc("/api/networks/{networkname}", securityCheck(http.HandlerFunc(getNetwork))).Methods("GET")
|
||||||
r.HandleFunc("/api/groups/{groupname}", securityCheck(http.HandlerFunc(updateGroup))).Methods("PUT")
|
r.HandleFunc("/api/networks/{networkname}", securityCheck(http.HandlerFunc(updateNetwork))).Methods("PUT")
|
||||||
r.HandleFunc("/api/groups/{groupname}", securityCheck(http.HandlerFunc(deleteGroup))).Methods("DELETE")
|
r.HandleFunc("/api/networks/{networkname}", securityCheck(http.HandlerFunc(deleteNetwork))).Methods("DELETE")
|
||||||
r.HandleFunc("/api/groups/{groupname}/keyupdate", securityCheck(http.HandlerFunc(keyUpdate))).Methods("POST")
|
r.HandleFunc("/api/networks/{networkname}/keyupdate", securityCheck(http.HandlerFunc(keyUpdate))).Methods("POST")
|
||||||
r.HandleFunc("/api/groups/{groupname}/keys", securityCheck(http.HandlerFunc(createAccessKey))).Methods("POST")
|
r.HandleFunc("/api/networks/{networkname}/keys", securityCheck(http.HandlerFunc(createAccessKey))).Methods("POST")
|
||||||
r.HandleFunc("/api/groups/{groupname}/keys", securityCheck(http.HandlerFunc(getAccessKeys))).Methods("GET")
|
r.HandleFunc("/api/networks/{networkname}/keys", securityCheck(http.HandlerFunc(getAccessKeys))).Methods("GET")
|
||||||
r.HandleFunc("/api/groups/{groupname}/keys/{name}", securityCheck(http.HandlerFunc(deleteAccessKey))).Methods("DELETE")
|
r.HandleFunc("/api/networks/{networkname}/keys/{name}", securityCheck(http.HandlerFunc(deleteAccessKey))).Methods("DELETE")
|
||||||
}
|
}
|
||||||
|
|
||||||
//Security check is middleware for every function and just checks to make sure that its the master calling
|
//Security check is middleware for every function and just checks to make sure that its the master calling
|
||||||
//Only admin should have access to all these group-level actions
|
//Only admin should have access to all these network-level actions
|
||||||
//or maybe some Users once implemented
|
//or maybe some Users once implemented
|
||||||
func securityCheck(next http.Handler) http.HandlerFunc {
|
func securityCheck(next http.Handler) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -41,14 +41,14 @@ func securityCheck(next http.Handler) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
hasgroup := params["groupname"] != ""
|
hasnetwork := params["networkname"] != ""
|
||||||
groupexists, err := functions.GroupExists(params["groupname"])
|
networkexists, err := functions.NetworkExists(params["networkname"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w, r, formatError(err, "internal"))
|
returnErrorResponse(w, r, formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
} else if hasgroup && !groupexists {
|
} else if hasnetwork && !networkexists {
|
||||||
errorResponse = models.ErrorResponse{
|
errorResponse = models.ErrorResponse{
|
||||||
Code: http.StatusNotFound, Message: "W1R3: This group does not exist.",
|
Code: http.StatusNotFound, Message: "W1R3: This network does not exist.",
|
||||||
}
|
}
|
||||||
returnErrorResponse(w, r, errorResponse)
|
returnErrorResponse(w, r, errorResponse)
|
||||||
return
|
return
|
||||||
@@ -87,22 +87,22 @@ func authenticateMaster(tokenString string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
//simple get all groups function
|
//simple get all networks function
|
||||||
func getGroups(w http.ResponseWriter, r *http.Request) {
|
func getNetworks(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
groups, err := functions.ListGroups()
|
networks, err := functions.ListNetworks()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w, r, formatError(err, "internal"))
|
returnErrorResponse(w, r, formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
} else {
|
} else {
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
json.NewEncoder(w).Encode(groups)
|
json.NewEncoder(w).Encode(networks)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateGroup(operation string, group models.Group) error {
|
func validateNetwork(operation string, network models.Network) error {
|
||||||
|
|
||||||
v := validator.New()
|
v := validator.New()
|
||||||
|
|
||||||
@@ -112,26 +112,26 @@ func validateGroup(operation string, group models.Group) error {
|
|||||||
})
|
})
|
||||||
|
|
||||||
_ = v.RegisterValidation("privaterange_valid", func(fl validator.FieldLevel) bool {
|
_ = v.RegisterValidation("privaterange_valid", func(fl validator.FieldLevel) bool {
|
||||||
isvalid := !*group.IsPrivate || functions.IsIpv4CIDR(fl.Field().String())
|
isvalid := !*network.IsPrivate || functions.IsIpv4CIDR(fl.Field().String())
|
||||||
return isvalid
|
return isvalid
|
||||||
})
|
})
|
||||||
|
|
||||||
_ = v.RegisterValidation("nameid_valid", func(fl validator.FieldLevel) bool {
|
_ = v.RegisterValidation("netid_valid", func(fl validator.FieldLevel) bool {
|
||||||
isFieldUnique := false
|
isFieldUnique := false
|
||||||
inCharSet := false
|
inCharSet := false
|
||||||
if operation == "update" { isFieldUnique = true } else{
|
if operation == "update" { isFieldUnique = true } else{
|
||||||
isFieldUnique, _ = functions.IsGroupNameUnique(fl.Field().String())
|
isFieldUnique, _ = functions.IsNetworkNameUnique(fl.Field().String())
|
||||||
inCharSet = functions.NameInGroupCharSet(fl.Field().String())
|
inCharSet = functions.NameInNetworkCharSet(fl.Field().String())
|
||||||
}
|
}
|
||||||
return isFieldUnique && inCharSet
|
return isFieldUnique && inCharSet
|
||||||
})
|
})
|
||||||
|
|
||||||
_ = v.RegisterValidation("displayname_unique", func(fl validator.FieldLevel) bool {
|
_ = v.RegisterValidation("displayname_unique", func(fl validator.FieldLevel) bool {
|
||||||
isFieldUnique, _ := functions.IsGroupDisplayNameUnique(fl.Field().String())
|
isFieldUnique, _ := functions.IsNetworkDisplayNameUnique(fl.Field().String())
|
||||||
return isFieldUnique || operation == "update"
|
return isFieldUnique || operation == "update"
|
||||||
})
|
})
|
||||||
|
|
||||||
err := v.Struct(group)
|
err := v.Struct(network)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
for _, e := range err.(validator.ValidationErrors) {
|
for _, e := range err.(validator.ValidationErrors) {
|
||||||
@@ -141,22 +141,22 @@ func validateGroup(operation string, group models.Group) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Simple get group function
|
//Simple get network function
|
||||||
func getGroup(w http.ResponseWriter, r *http.Request) {
|
func getNetwork(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
// set header.
|
// set header.
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"nameid": params["groupname"]}
|
filter := bson.M{"netid": params["networkname"]}
|
||||||
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&group)
|
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
@@ -165,7 +165,7 @@ func getGroup(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
json.NewEncoder(w).Encode(group)
|
json.NewEncoder(w).Encode(network)
|
||||||
}
|
}
|
||||||
|
|
||||||
func keyUpdate(w http.ResponseWriter, r *http.Request) {
|
func keyUpdate(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -174,43 +174,43 @@ func keyUpdate(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
|
|
||||||
group, err := functions.GetParentGroup(params["groupname"])
|
network, err := functions.GetParentNetwork(params["networkname"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
group.KeyUpdateTimeStamp = time.Now().Unix()
|
network.KeyUpdateTimeStamp = time.Now().Unix()
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"nameid": params["groupname"]}
|
filter := bson.M{"netid": params["networkname"]}
|
||||||
|
|
||||||
// prepare update model.
|
// prepare update model.
|
||||||
update := bson.D{
|
update := bson.D{
|
||||||
{"$set", bson.D{
|
{"$set", bson.D{
|
||||||
{"addressrange", group.AddressRange},
|
{"addressrange", network.AddressRange},
|
||||||
{"displayname", group.DisplayName},
|
{"displayname", network.DisplayName},
|
||||||
{"defaultlistenport", group.DefaultListenPort},
|
{"defaultlistenport", network.DefaultListenPort},
|
||||||
{"defaultpostup", group.DefaultPostUp},
|
{"defaultpostup", network.DefaultPostUp},
|
||||||
{"defaultpreup", group.DefaultPreUp},
|
{"defaultpreup", network.DefaultPreUp},
|
||||||
{"defaultkeepalive", group.DefaultKeepalive},
|
{"defaultkeepalive", network.DefaultKeepalive},
|
||||||
{"keyupdatetimestamp", group.KeyUpdateTimeStamp},
|
{"keyupdatetimestamp", network.KeyUpdateTimeStamp},
|
||||||
{"defaultsaveconfig", group.DefaultSaveConfig},
|
{"defaultsaveconfig", network.DefaultSaveConfig},
|
||||||
{"defaultinterface", group.DefaultInterface},
|
{"defaultinterface", network.DefaultInterface},
|
||||||
{"nodeslastmodified", group.NodesLastModified},
|
{"nodeslastmodified", network.NodesLastModified},
|
||||||
{"grouplastmodified", group.GroupLastModified},
|
{"networklastmodified", network.NetworkLastModified},
|
||||||
{"allowmanualsignup", group.AllowManualSignUp},
|
{"allowmanualsignup", network.AllowManualSignUp},
|
||||||
{"defaultcheckininterval", group.DefaultCheckInInterval},
|
{"defaultcheckininterval", network.DefaultCheckInInterval},
|
||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
|
|
||||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
@@ -220,56 +220,56 @@ func keyUpdate(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
json.NewEncoder(w).Encode(group)
|
json.NewEncoder(w).Encode(network)
|
||||||
}
|
}
|
||||||
|
|
||||||
//Update a group
|
//Update a network
|
||||||
func updateGroup(w http.ResponseWriter, r *http.Request) {
|
func updateNetwork(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
|
|
||||||
group, err := functions.GetParentGroup(params["groupname"])
|
network, err := functions.GetParentNetwork(params["networkname"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var groupChange models.Group
|
var networkChange models.Network
|
||||||
|
|
||||||
haschange := false
|
haschange := false
|
||||||
hasrangeupdate := false
|
hasrangeupdate := false
|
||||||
hasprivaterangeupdate := false
|
hasprivaterangeupdate := false
|
||||||
|
|
||||||
_ = json.NewDecoder(r.Body).Decode(&groupChange)
|
_ = json.NewDecoder(r.Body).Decode(&networkChange)
|
||||||
|
|
||||||
if groupChange.AddressRange == "" {
|
if networkChange.AddressRange == "" {
|
||||||
groupChange.AddressRange = group.AddressRange
|
networkChange.AddressRange = network.AddressRange
|
||||||
}
|
}
|
||||||
if groupChange.NameID == "" {
|
if networkChange.NetID == "" {
|
||||||
groupChange.NameID = group.NameID
|
networkChange.NetID = network.NetID
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
err = validateGroup("update", groupChange)
|
err = validateNetwork("update", networkChange)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
//NOTE: Group.NameID is intentionally NOT editable. It acts as a static ID for the group.
|
//NOTE: Network.NetID is intentionally NOT editable. It acts as a static ID for the network.
|
||||||
//DisplayName can be changed instead, which is what shows on the front end
|
//DisplayName can be changed instead, which is what shows on the front end
|
||||||
|
|
||||||
if groupChange.AddressRange != "" {
|
if networkChange.AddressRange != "" {
|
||||||
|
|
||||||
group.AddressRange = groupChange.AddressRange
|
network.AddressRange = networkChange.AddressRange
|
||||||
|
|
||||||
var isAddressOK bool = functions.IsIpv4CIDR(groupChange.AddressRange)
|
var isAddressOK bool = functions.IsIpv4CIDR(networkChange.AddressRange)
|
||||||
if !isAddressOK {
|
if !isAddressOK {
|
||||||
err := errors.New("Invalid Range of " + groupChange.AddressRange + " for addresses.")
|
err := errors.New("Invalid Range of " + networkChange.AddressRange + " for addresses.")
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -277,83 +277,83 @@ func updateGroup(w http.ResponseWriter, r *http.Request) {
|
|||||||
hasrangeupdate = true
|
hasrangeupdate = true
|
||||||
|
|
||||||
}
|
}
|
||||||
if groupChange.PrivateRange != "" {
|
if networkChange.PrivateRange != "" {
|
||||||
group.PrivateRange = groupChange.PrivateRange
|
network.PrivateRange = networkChange.PrivateRange
|
||||||
|
|
||||||
var isAddressOK bool = functions.IsIpv4CIDR(groupChange.PrivateRange)
|
var isAddressOK bool = functions.IsIpv4CIDR(networkChange.PrivateRange)
|
||||||
if !isAddressOK {
|
if !isAddressOK {
|
||||||
err := errors.New("Invalid Range of " + groupChange.PrivateRange + " for internal addresses.")
|
err := errors.New("Invalid Range of " + networkChange.PrivateRange + " for internal addresses.")
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
haschange = true
|
haschange = true
|
||||||
hasprivaterangeupdate = true
|
hasprivaterangeupdate = true
|
||||||
}
|
}
|
||||||
if groupChange.IsPrivate != nil {
|
if networkChange.IsPrivate != nil {
|
||||||
group.IsPrivate = groupChange.IsPrivate
|
network.IsPrivate = networkChange.IsPrivate
|
||||||
}
|
}
|
||||||
if groupChange.DefaultListenPort != 0 {
|
if networkChange.DefaultListenPort != 0 {
|
||||||
group.DefaultListenPort = groupChange.DefaultListenPort
|
network.DefaultListenPort = networkChange.DefaultListenPort
|
||||||
haschange = true
|
haschange = true
|
||||||
}
|
}
|
||||||
if groupChange.DefaultPreUp != "" {
|
if networkChange.DefaultPreUp != "" {
|
||||||
group.DefaultPreUp = groupChange.DefaultPreUp
|
network.DefaultPreUp = networkChange.DefaultPreUp
|
||||||
haschange = true
|
haschange = true
|
||||||
}
|
}
|
||||||
if groupChange.DefaultInterface != "" {
|
if networkChange.DefaultInterface != "" {
|
||||||
group.DefaultInterface = groupChange.DefaultInterface
|
network.DefaultInterface = networkChange.DefaultInterface
|
||||||
haschange = true
|
haschange = true
|
||||||
}
|
}
|
||||||
if groupChange.DefaultPostUp != "" {
|
if networkChange.DefaultPostUp != "" {
|
||||||
group.DefaultPostUp = groupChange.DefaultPostUp
|
network.DefaultPostUp = networkChange.DefaultPostUp
|
||||||
haschange = true
|
haschange = true
|
||||||
}
|
}
|
||||||
if groupChange.DefaultKeepalive != 0 {
|
if networkChange.DefaultKeepalive != 0 {
|
||||||
group.DefaultKeepalive = groupChange.DefaultKeepalive
|
network.DefaultKeepalive = networkChange.DefaultKeepalive
|
||||||
haschange = true
|
haschange = true
|
||||||
}
|
}
|
||||||
if groupChange.DisplayName != "" {
|
if networkChange.DisplayName != "" {
|
||||||
group.DisplayName = groupChange.DisplayName
|
network.DisplayName = networkChange.DisplayName
|
||||||
haschange = true
|
haschange = true
|
||||||
}
|
}
|
||||||
if groupChange.DefaultCheckInInterval != 0 {
|
if networkChange.DefaultCheckInInterval != 0 {
|
||||||
group.DefaultCheckInInterval = groupChange.DefaultCheckInInterval
|
network.DefaultCheckInInterval = networkChange.DefaultCheckInInterval
|
||||||
haschange = true
|
haschange = true
|
||||||
}
|
}
|
||||||
if groupChange.AllowManualSignUp != nil {
|
if networkChange.AllowManualSignUp != nil {
|
||||||
group.AllowManualSignUp = groupChange.AllowManualSignUp
|
network.AllowManualSignUp = networkChange.AllowManualSignUp
|
||||||
haschange = true
|
haschange = true
|
||||||
}
|
}
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
filter := bson.M{"nameid": params["groupname"]}
|
filter := bson.M{"netid": params["networkname"]}
|
||||||
|
|
||||||
if haschange {
|
if haschange {
|
||||||
group.SetGroupLastModified()
|
network.SetNetworkLastModified()
|
||||||
}
|
}
|
||||||
|
|
||||||
// prepare update model.
|
// prepare update model.
|
||||||
update := bson.D{
|
update := bson.D{
|
||||||
{"$set", bson.D{
|
{"$set", bson.D{
|
||||||
{"addressrange", group.AddressRange},
|
{"addressrange", network.AddressRange},
|
||||||
{"displayname", group.DisplayName},
|
{"displayname", network.DisplayName},
|
||||||
{"defaultlistenport", group.DefaultListenPort},
|
{"defaultlistenport", network.DefaultListenPort},
|
||||||
{"defaultpostup", group.DefaultPostUp},
|
{"defaultpostup", network.DefaultPostUp},
|
||||||
{"defaultpreup", group.DefaultPreUp},
|
{"defaultpreup", network.DefaultPreUp},
|
||||||
{"defaultkeepalive", group.DefaultKeepalive},
|
{"defaultkeepalive", network.DefaultKeepalive},
|
||||||
{"defaultsaveconfig", group.DefaultSaveConfig},
|
{"defaultsaveconfig", network.DefaultSaveConfig},
|
||||||
{"defaultinterface", group.DefaultInterface},
|
{"defaultinterface", network.DefaultInterface},
|
||||||
{"nodeslastmodified", group.NodesLastModified},
|
{"nodeslastmodified", network.NodesLastModified},
|
||||||
{"grouplastmodified", group.GroupLastModified},
|
{"networklastmodified", network.NetworkLastModified},
|
||||||
{"allowmanualsignup", group.AllowManualSignUp},
|
{"allowmanualsignup", network.AllowManualSignUp},
|
||||||
{"privaterange", group.PrivateRange},
|
{"privaterange", network.PrivateRange},
|
||||||
{"isprivate", group.IsPrivate},
|
{"isprivate", network.IsPrivate},
|
||||||
{"defaultcheckininterval", group.DefaultCheckInInterval},
|
{"defaultcheckininterval", network.DefaultCheckInInterval},
|
||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
|
|
||||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -364,52 +364,52 @@ func updateGroup(w http.ResponseWriter, r *http.Request) {
|
|||||||
//Cycles through nodes and gives them new IP's based on the new range
|
//Cycles through nodes and gives them new IP's based on the new range
|
||||||
//Pretty cool, but also pretty inefficient currently
|
//Pretty cool, but also pretty inefficient currently
|
||||||
if hasrangeupdate {
|
if hasrangeupdate {
|
||||||
err = functions.UpdateGroupNodeAddresses(params["groupname"])
|
err = functions.UpdateNetworkNodeAddresses(params["networkname"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if hasprivaterangeupdate {
|
if hasprivaterangeupdate {
|
||||||
err = functions.UpdateGroupPrivateAddresses(params["groupname"])
|
err = functions.UpdateNetworkPrivateAddresses(params["networkname"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
returngroup, err := functions.GetParentGroup(group.NameID)
|
returnnetwork, err := functions.GetParentNetwork(network.NetID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
json.NewEncoder(w).Encode(returngroup)
|
json.NewEncoder(w).Encode(returnnetwork)
|
||||||
}
|
}
|
||||||
|
|
||||||
//Delete a group
|
//Delete a network
|
||||||
//Will stop you if there's any nodes associated
|
//Will stop you if there's any nodes associated
|
||||||
func deleteGroup(w http.ResponseWriter, r *http.Request) {
|
func deleteNetwork(w http.ResponseWriter, r *http.Request) {
|
||||||
// Set header
|
// Set header
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
nodecount, err := functions.GetGroupNodeNumber(params["groupname"])
|
nodecount, err := functions.GetNetworkNodeNumber(params["networkname"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w, r, formatError(err, "internal"))
|
returnErrorResponse(w, r, formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
} else if nodecount > 0 {
|
} else if nodecount > 0 {
|
||||||
errorResponse := models.ErrorResponse{
|
errorResponse := models.ErrorResponse{
|
||||||
Code: http.StatusForbidden, Message: "W1R3: Node check failed. All nodes must be deleted before deleting group.",
|
Code: http.StatusForbidden, Message: "W1R3: Node check failed. All nodes must be deleted before deleting network.",
|
||||||
}
|
}
|
||||||
returnErrorResponse(w, r, errorResponse)
|
returnErrorResponse(w, r, errorResponse)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
filter := bson.M{"nameid": params["groupname"]}
|
filter := bson.M{"netid": params["networkname"]}
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
@@ -426,44 +426,44 @@ func deleteGroup(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(deleteResult)
|
json.NewEncoder(w).Encode(deleteResult)
|
||||||
}
|
}
|
||||||
|
|
||||||
//Create a group
|
//Create a network
|
||||||
//Pretty simple
|
//Pretty simple
|
||||||
func createGroup(w http.ResponseWriter, r *http.Request) {
|
func createNetwork(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
|
|
||||||
// we decode our body request params
|
// we decode our body request params
|
||||||
err := json.NewDecoder(r.Body).Decode(&group)
|
err := json.NewDecoder(r.Body).Decode(&network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO: Not really doing good validation here. Same as createNode, updateNode, and updateGroup
|
//TODO: Not really doing good validation here. Same as createNode, updateNode, and updateNetwork
|
||||||
//Need to implement some better validation across the board
|
//Need to implement some better validation across the board
|
||||||
if group.IsPrivate == nil {
|
if network.IsPrivate == nil {
|
||||||
falsevar := false
|
falsevar := false
|
||||||
group.IsPrivate = &falsevar
|
network.IsPrivate = &falsevar
|
||||||
}
|
}
|
||||||
|
|
||||||
err = validateGroup("create", group)
|
err = validateNetwork("create", network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
group.SetDefaults()
|
network.SetDefaults()
|
||||||
group.SetNodesLastModified()
|
network.SetNodesLastModified()
|
||||||
group.SetGroupLastModified()
|
network.SetNetworkLastModified()
|
||||||
group.KeyUpdateTimeStamp = time.Now().Unix()
|
network.KeyUpdateTimeStamp = time.Now().Unix()
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
|
|
||||||
// insert our group into the group table
|
// insert our network into the network table
|
||||||
result, err := collection.InsertOne(ctx, group)
|
result, err := collection.InsertOne(ctx, network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
@@ -479,18 +479,18 @@ func createGroup(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
|
|
||||||
//TODO: Very little error handling
|
//TODO: Very little error handling
|
||||||
//accesskey is created as a json string inside the Group collection item in mongo
|
//accesskey is created as a json string inside the Network collection item in mongo
|
||||||
func createAccessKey(w http.ResponseWriter, r *http.Request) {
|
func createAccessKey(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
var accesskey models.AccessKey
|
var accesskey models.AccessKey
|
||||||
|
|
||||||
//start here
|
//start here
|
||||||
group, err := functions.GetParentGroup(params["groupname"])
|
network, err := functions.GetParentNetwork(params["networkname"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
@@ -517,32 +517,38 @@ func createAccessKey(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
network := params["groupname"]
|
privAddr := ""
|
||||||
|
if *network.IsPrivate {
|
||||||
|
privAddr = network.PrivateRange
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
netID := params["networkname"]
|
||||||
address := gconf.ServerGRPC + gconf.PortGRPC
|
address := gconf.ServerGRPC + gconf.PortGRPC
|
||||||
|
|
||||||
accessstringdec := address + "." + network + "." + accesskey.Value
|
accessstringdec := address + "." + netID + "." + accesskey.Value + "." + privAddr
|
||||||
accesskey.AccessString = base64.StdEncoding.EncodeToString([]byte(accessstringdec))
|
accesskey.AccessString = base64.StdEncoding.EncodeToString([]byte(accessstringdec))
|
||||||
|
|
||||||
group.AccessKeys = append(group.AccessKeys, accesskey)
|
network.AccessKeys = append(network.AccessKeys, accesskey)
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
// Create filter
|
// Create filter
|
||||||
filter := bson.M{"nameid": params["groupname"]}
|
filter := bson.M{"netid": params["networkname"]}
|
||||||
|
|
||||||
// Read update model from body request
|
// Read update model from body request
|
||||||
fmt.Println("Adding key to " + group.NameID)
|
fmt.Println("Adding key to " + network.NetID)
|
||||||
|
|
||||||
// prepare update model.
|
// prepare update model.
|
||||||
update := bson.D{
|
update := bson.D{
|
||||||
{"$set", bson.D{
|
{"$set", bson.D{
|
||||||
{"accesskeys", group.AccessKeys},
|
{"accesskeys", network.AccessKeys},
|
||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
|
|
||||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
@@ -563,15 +569,15 @@ func getAccessKeys(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
//var keys []models.DisplayKey
|
//var keys []models.DisplayKey
|
||||||
var keys []models.AccessKey
|
var keys []models.AccessKey
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"nameid": params["groupname"]}
|
filter := bson.M{"netid": params["networkname"]}
|
||||||
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&group)
|
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
@@ -579,7 +585,7 @@ func getAccessKeys(w http.ResponseWriter, r *http.Request) {
|
|||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
keydata, err := json.Marshal(group.AccessKeys)
|
keydata, err := json.Marshal(network.AccessKeys)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
@@ -600,41 +606,41 @@ func deleteAccessKey(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
keyname := params["name"]
|
keyname := params["name"]
|
||||||
|
|
||||||
//start here
|
//start here
|
||||||
group, err := functions.GetParentGroup(params["groupname"])
|
network, err := functions.GetParentNetwork(params["networkname"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
//basically, turn the list of access keys into the list of access keys before and after the item
|
//basically, turn the list of access keys into the list of access keys before and after the item
|
||||||
//have not done any error handling for if there's like...1 item. I think it works? need to test.
|
//have not done any error handling for if there's like...1 item. I think it works? need to test.
|
||||||
for i := len(group.AccessKeys) - 1; i >= 0; i-- {
|
for i := len(network.AccessKeys) - 1; i >= 0; i-- {
|
||||||
|
|
||||||
currentkey:= group.AccessKeys[i]
|
currentkey:= network.AccessKeys[i]
|
||||||
if currentkey.Name == keyname {
|
if currentkey.Name == keyname {
|
||||||
group.AccessKeys = append(group.AccessKeys[:i],
|
network.AccessKeys = append(network.AccessKeys[:i],
|
||||||
group.AccessKeys[i+1:]...)
|
network.AccessKeys[i+1:]...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
// Create filter
|
// Create filter
|
||||||
filter := bson.M{"nameid": params["groupname"]}
|
filter := bson.M{"netid": params["networkname"]}
|
||||||
|
|
||||||
// prepare update model.
|
// prepare update model.
|
||||||
update := bson.D{
|
update := bson.D{
|
||||||
{"$set", bson.D{
|
{"$set", bson.D{
|
||||||
{"accesskeys", group.AccessKeys},
|
{"accesskeys", network.AccessKeys},
|
||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
|
|
||||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
@@ -643,7 +649,7 @@ func deleteAccessKey(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
var keys []models.AccessKey
|
var keys []models.AccessKey
|
||||||
keydata, err := json.Marshal(group.AccessKeys)
|
keydata, err := json.Marshal(network.AccessKeys)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
@@ -19,9 +19,9 @@ type NodeServiceServer struct {
|
|||||||
func (s *NodeServiceServer) ReadNode(ctx context.Context, req *nodepb.ReadNodeReq) (*nodepb.ReadNodeRes, error) {
|
func (s *NodeServiceServer) ReadNode(ctx context.Context, req *nodepb.ReadNodeReq) (*nodepb.ReadNodeRes, error) {
|
||||||
// convert string id (from proto) to mongoDB ObjectId
|
// convert string id (from proto) to mongoDB ObjectId
|
||||||
macaddress := req.GetMacaddress()
|
macaddress := req.GetMacaddress()
|
||||||
groupName := req.GetGroup()
|
networkName := req.GetNetwork()
|
||||||
|
|
||||||
node, err := GetNode(macaddress, groupName)
|
node, err := GetNode(macaddress, networkName)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("Something went wrong: %v", err))
|
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("Something went wrong: %v", err))
|
||||||
@@ -40,7 +40,7 @@ func (s *NodeServiceServer) ReadNode(ctx context.Context, req *nodepb.ReadNodeRe
|
|||||||
Address: node.Address,
|
Address: node.Address,
|
||||||
Endpoint: node.Endpoint,
|
Endpoint: node.Endpoint,
|
||||||
Password: node.Password,
|
Password: node.Password,
|
||||||
Nodegroup: node.Group,
|
Nodenetwork: node.Network,
|
||||||
Interface: node.Interface,
|
Interface: node.Interface,
|
||||||
Localaddress: node.LocalAddress,
|
Localaddress: node.LocalAddress,
|
||||||
Preup: node.PreUp,
|
Preup: node.PreUp,
|
||||||
@@ -71,13 +71,13 @@ func (s *NodeServiceServer) CreateNode(ctx context.Context, req *nodepb.CreateNo
|
|||||||
PersistentKeepalive: data.GetKeepalive(),
|
PersistentKeepalive: data.GetKeepalive(),
|
||||||
Password: data.GetPassword(),
|
Password: data.GetPassword(),
|
||||||
Interface: data.GetInterface(),
|
Interface: data.GetInterface(),
|
||||||
Group: data.GetNodegroup(),
|
Network: data.GetNodenetwork(),
|
||||||
IsPending: data.GetIspending(),
|
IsPending: data.GetIspending(),
|
||||||
PublicKey: data.GetPublickey(),
|
PublicKey: data.GetPublickey(),
|
||||||
ListenPort: data.GetListenport(),
|
ListenPort: data.GetListenport(),
|
||||||
}
|
}
|
||||||
|
|
||||||
err := ValidateNode("create", node.Group, node)
|
err := ValidateNode("create", node.Network, node)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// return internal gRPC error to be handled later
|
// return internal gRPC error to be handled later
|
||||||
@@ -85,24 +85,24 @@ func (s *NodeServiceServer) CreateNode(ctx context.Context, req *nodepb.CreateNo
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Check to see if key is valid
|
//Check to see if key is valid
|
||||||
//TODO: Triple inefficient!!! This is the third call to the DB we make for groups
|
//TODO: Triple inefficient!!! This is the third call to the DB we make for networks
|
||||||
validKey := functions.IsKeyValid(node.Group, node.AccessKey)
|
validKey := functions.IsKeyValid(node.Network, node.AccessKey)
|
||||||
|
|
||||||
if !validKey {
|
if !validKey {
|
||||||
group, _ := functions.GetParentGroup(node.Group)
|
network, _ := functions.GetParentNetwork(node.Network)
|
||||||
//Check to see if group will allow manual sign up
|
//Check to see if network will allow manual sign up
|
||||||
//may want to switch this up with the valid key check and avoid a DB call that way.
|
//may want to switch this up with the valid key check and avoid a DB call that way.
|
||||||
if *group.AllowManualSignUp {
|
if *network.AllowManualSignUp {
|
||||||
node.IsPending = true
|
node.IsPending = true
|
||||||
} else {
|
} else {
|
||||||
return nil, status.Errorf(
|
return nil, status.Errorf(
|
||||||
codes.Internal,
|
codes.Internal,
|
||||||
fmt.Sprintf("Invalid key, and group does not allow no-key signups"),
|
fmt.Sprintf("Invalid key, and network does not allow no-key signups"),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
node, err = CreateNode(node, node.Group)
|
node, err = CreateNode(node, node.Network)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// return internal gRPC error to be handled later
|
// return internal gRPC error to be handled later
|
||||||
@@ -121,16 +121,16 @@ func (s *NodeServiceServer) CreateNode(ctx context.Context, req *nodepb.CreateNo
|
|||||||
Endpoint: node.Endpoint,
|
Endpoint: node.Endpoint,
|
||||||
Password: node.Password,
|
Password: node.Password,
|
||||||
Interface: node.Interface,
|
Interface: node.Interface,
|
||||||
Nodegroup: node.Group,
|
Nodenetwork: node.Network,
|
||||||
Ispending: node.IsPending,
|
Ispending: node.IsPending,
|
||||||
Publickey: node.PublicKey,
|
Publickey: node.PublicKey,
|
||||||
Listenport: node.ListenPort,
|
Listenport: node.ListenPort,
|
||||||
Keepalive: node.PersistentKeepalive,
|
Keepalive: node.PersistentKeepalive,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
err = SetGroupNodesLastModified(node.Group)
|
err = SetNetworkNodesLastModified(node.Network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not update group last modified date: %v", err))
|
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not update network last modified date: %v", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
return response, nil
|
return response, nil
|
||||||
@@ -147,7 +147,7 @@ func (s *NodeServiceServer) CheckIn(ctx context.Context, req *nodepb.CheckInReq)
|
|||||||
MacAddress: data.GetMacaddress(),
|
MacAddress: data.GetMacaddress(),
|
||||||
Address: data.GetAddress(),
|
Address: data.GetAddress(),
|
||||||
Endpoint: data.GetEndpoint(),
|
Endpoint: data.GetEndpoint(),
|
||||||
Group: data.GetNodegroup(),
|
Network: data.GetNodenetwork(),
|
||||||
Password: data.GetPassword(),
|
Password: data.GetPassword(),
|
||||||
LocalAddress: data.GetLocaladdress(),
|
LocalAddress: data.GetLocaladdress(),
|
||||||
ListenPort: data.GetListenport(),
|
ListenPort: data.GetListenport(),
|
||||||
@@ -155,7 +155,7 @@ func (s *NodeServiceServer) CheckIn(ctx context.Context, req *nodepb.CheckInReq)
|
|||||||
PublicKey: data.GetPublickey(),
|
PublicKey: data.GetPublickey(),
|
||||||
}
|
}
|
||||||
|
|
||||||
checkinresponse, err := NodeCheckIn(node, node.Group)
|
checkinresponse, err := NodeCheckIn(node, node.Network)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// return internal gRPC error to be handled later
|
// return internal gRPC error to be handled later
|
||||||
@@ -195,7 +195,7 @@ func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.UpdateNo
|
|||||||
Endpoint: data.GetEndpoint(),
|
Endpoint: data.GetEndpoint(),
|
||||||
Password: data.GetPassword(),
|
Password: data.GetPassword(),
|
||||||
PersistentKeepalive: data.GetKeepalive(),
|
PersistentKeepalive: data.GetKeepalive(),
|
||||||
Group: data.GetNodegroup(),
|
Network: data.GetNodenetwork(),
|
||||||
Interface: data.GetInterface(),
|
Interface: data.GetInterface(),
|
||||||
PreUp: data.GetPreup(),
|
PreUp: data.GetPreup(),
|
||||||
PostUp: data.GetPostup(),
|
PostUp: data.GetPostup(),
|
||||||
@@ -207,14 +207,14 @@ func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.UpdateNo
|
|||||||
|
|
||||||
// Convert the Id string to a MongoDB ObjectId
|
// Convert the Id string to a MongoDB ObjectId
|
||||||
macaddress := nodechange.MacAddress
|
macaddress := nodechange.MacAddress
|
||||||
groupName := nodechange.Group
|
networkName := nodechange.Network
|
||||||
|
|
||||||
err := ValidateNode("update", groupName, nodechange)
|
err := ValidateNode("update", networkName, nodechange)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
node, err := functions.GetNodeByMacAddress(groupName, macaddress)
|
node, err := functions.GetNodeByMacAddress(networkName, macaddress)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, status.Errorf(
|
return nil, status.Errorf(
|
||||||
codes.NotFound,
|
codes.NotFound,
|
||||||
@@ -242,7 +242,7 @@ func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.UpdateNo
|
|||||||
Interface: newnode.Interface,
|
Interface: newnode.Interface,
|
||||||
Preup: newnode.PreUp,
|
Preup: newnode.PreUp,
|
||||||
Postup: newnode.PostUp,
|
Postup: newnode.PostUp,
|
||||||
Nodegroup: newnode.Group,
|
Nodenetwork: newnode.Network,
|
||||||
Ispending: newnode.IsPending,
|
Ispending: newnode.IsPending,
|
||||||
Publickey: newnode.PublicKey,
|
Publickey: newnode.PublicKey,
|
||||||
Listenport: newnode.ListenPort,
|
Listenport: newnode.ListenPort,
|
||||||
@@ -255,9 +255,9 @@ func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.UpdateNo
|
|||||||
func (s *NodeServiceServer) DeleteNode(ctx context.Context, req *nodepb.DeleteNodeReq) (*nodepb.DeleteNodeRes, error) {
|
func (s *NodeServiceServer) DeleteNode(ctx context.Context, req *nodepb.DeleteNodeReq) (*nodepb.DeleteNodeRes, error) {
|
||||||
fmt.Println("beginning node delete")
|
fmt.Println("beginning node delete")
|
||||||
macaddress := req.GetMacaddress()
|
macaddress := req.GetMacaddress()
|
||||||
group := req.GetGroupName()
|
network := req.GetNetworkName()
|
||||||
|
|
||||||
success, err := DeleteNode(macaddress, group)
|
success, err := DeleteNode(macaddress, network)
|
||||||
|
|
||||||
if err != nil || !success {
|
if err != nil || !success {
|
||||||
fmt.Println("Error deleting node.")
|
fmt.Println("Error deleting node.")
|
||||||
@@ -265,12 +265,12 @@ func (s *NodeServiceServer) DeleteNode(ctx context.Context, req *nodepb.DeleteNo
|
|||||||
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not find/delete node with mac address %s", macaddress))
|
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not find/delete node with mac address %s", macaddress))
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println("updating group last modified of " + req.GetGroupName())
|
fmt.Println("updating network last modified of " + req.GetNetworkName())
|
||||||
err = SetGroupNodesLastModified(req.GetGroupName())
|
err = SetNetworkNodesLastModified(req.GetNetworkName())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Error updating Group")
|
fmt.Println("Error updating Network")
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not update group last modified date: %v", err))
|
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not update network last modified date: %v", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -284,7 +284,7 @@ func (s *NodeServiceServer) GetPeers(req *nodepb.GetPeersReq, stream nodepb.Node
|
|||||||
//data := &models.PeersResponse{}
|
//data := &models.PeersResponse{}
|
||||||
// collection.Find returns a cursor for our (empty) query
|
// collection.Find returns a cursor for our (empty) query
|
||||||
//cursor, err := s.NodeDB.Find(context.Background(), bson.M{})
|
//cursor, err := s.NodeDB.Find(context.Background(), bson.M{})
|
||||||
peers, err := GetPeersList(req.GetGroup())
|
peers, err := GetPeersList(req.GetNetwork())
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return status.Errorf(codes.Internal, fmt.Sprintf("Unknown internal error: %v", err))
|
return status.Errorf(codes.Internal, fmt.Sprintf("Unknown internal error: %v", err))
|
||||||
@@ -305,7 +305,7 @@ func (s *NodeServiceServer) GetPeers(req *nodepb.GetPeersReq, stream nodepb.Node
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
node, err := functions.GetNodeByMacAddress(req.GetGroup(), req.GetMacaddress())
|
node, err := functions.GetNodeByMacAddress(req.GetNetwork(), req.GetMacaddress())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return status.Errorf(codes.Internal, fmt.Sprintf("Could not get node: %v", err))
|
return status.Errorf(codes.Internal, fmt.Sprintf("Could not get node: %v", err))
|
||||||
}
|
}
|
||||||
|
@@ -21,17 +21,17 @@ import (
|
|||||||
func nodeHandlers(r *mux.Router) {
|
func nodeHandlers(r *mux.Router) {
|
||||||
|
|
||||||
r.HandleFunc("/api/nodes", authorize(false, "master", http.HandlerFunc(getAllNodes))).Methods("GET")
|
r.HandleFunc("/api/nodes", authorize(false, "master", http.HandlerFunc(getAllNodes))).Methods("GET")
|
||||||
r.HandleFunc("/api/nodes/{group}", authorize(true, "group", http.HandlerFunc(getGroupNodes))).Methods("GET")
|
r.HandleFunc("/api/nodes/{network}", authorize(true, "network", http.HandlerFunc(getNetworkNodes))).Methods("GET")
|
||||||
r.HandleFunc("/api/nodes/{group}/{macaddress}", authorize(true, "node", http.HandlerFunc(getNode))).Methods("GET")
|
r.HandleFunc("/api/nodes/{network}/{macaddress}", authorize(true, "node", http.HandlerFunc(getNode))).Methods("GET")
|
||||||
r.HandleFunc("/api/nodes/{group}/{macaddress}", authorize(true, "node", http.HandlerFunc(updateNode))).Methods("PUT")
|
r.HandleFunc("/api/nodes/{network}/{macaddress}", authorize(true, "node", http.HandlerFunc(updateNode))).Methods("PUT")
|
||||||
r.HandleFunc("/api/nodes/{group}/{macaddress}", authorize(true, "node", http.HandlerFunc(deleteNode))).Methods("DELETE")
|
r.HandleFunc("/api/nodes/{network}/{macaddress}", authorize(true, "node", http.HandlerFunc(deleteNode))).Methods("DELETE")
|
||||||
r.HandleFunc("/api/nodes/{group}/{macaddress}/checkin", authorize(true, "node", http.HandlerFunc(checkIn))).Methods("POST")
|
r.HandleFunc("/api/nodes/{network}/{macaddress}/checkin", authorize(true, "node", http.HandlerFunc(checkIn))).Methods("POST")
|
||||||
// r.HandleFunc("/api/nodes/{group}/{macaddress}/creategateway", authorize(true, "master", http.HandlerFunc(createGateway))).Methods("POST")
|
// r.HandleFunc("/api/nodes/{network}/{macaddress}/creategateway", authorize(true, "master", http.HandlerFunc(createGateway))).Methods("POST")
|
||||||
// r.HandleFunc("/api/nodes/{group}/{macaddress}/deletegateway", authorize(true, "master", http.HandlerFunc(deleteGateway))).Methods("POST")
|
// r.HandleFunc("/api/nodes/{network}/{macaddress}/deletegateway", authorize(true, "master", http.HandlerFunc(deleteGateway))).Methods("POST")
|
||||||
r.HandleFunc("/api/nodes/{group}/{macaddress}/uncordon", authorize(true, "master", http.HandlerFunc(uncordonNode))).Methods("POST")
|
r.HandleFunc("/api/nodes/{network}/{macaddress}/uncordon", authorize(true, "master", http.HandlerFunc(uncordonNode))).Methods("POST")
|
||||||
r.HandleFunc("/api/nodes/{group}/nodes", createNode).Methods("POST")
|
r.HandleFunc("/api/nodes/{network}/nodes", createNode).Methods("POST")
|
||||||
r.HandleFunc("/api/nodes/adm/{group}/lastmodified", authorize(true, "group", http.HandlerFunc(getLastModified))).Methods("GET")
|
r.HandleFunc("/api/nodes/adm/{network}/lastmodified", authorize(true, "network", http.HandlerFunc(getLastModified))).Methods("GET")
|
||||||
r.HandleFunc("/api/nodes/adm/{group}/authenticate", authenticate).Methods("POST")
|
r.HandleFunc("/api/nodes/adm/{network}/authenticate", authenticate).Methods("POST")
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,7 +88,7 @@ func authenticate(response http.ResponseWriter, request *http.Request) {
|
|||||||
return
|
return
|
||||||
} else {
|
} else {
|
||||||
//Create a new JWT for the node
|
//Create a new JWT for the node
|
||||||
tokenString, _ := functions.CreateJWT(authRequest.MacAddress, result.Group)
|
tokenString, _ := functions.CreateJWT(authRequest.MacAddress, result.Network)
|
||||||
|
|
||||||
if tokenString == "" {
|
if tokenString == "" {
|
||||||
returnErrorResponse(response, request, errorResponse)
|
returnErrorResponse(response, request, errorResponse)
|
||||||
@@ -121,11 +121,11 @@ func authenticate(response http.ResponseWriter, request *http.Request) {
|
|||||||
//The middleware for most requests to the API
|
//The middleware for most requests to the API
|
||||||
//They all pass through here first
|
//They all pass through here first
|
||||||
//This will validate the JWT (or check for master token)
|
//This will validate the JWT (or check for master token)
|
||||||
//This will also check against the authGroup and make sure the node should be accessing that endpoint,
|
//This will also check against the authNetwork and make sure the node should be accessing that endpoint,
|
||||||
//even if it's technically ok
|
//even if it's technically ok
|
||||||
//This is kind of a poor man's RBAC. There's probably a better/smarter way.
|
//This is kind of a poor man's RBAC. There's probably a better/smarter way.
|
||||||
//TODO: Consider better RBAC implementations
|
//TODO: Consider better RBAC implementations
|
||||||
func authorize(groupCheck bool, authGroup string, next http.Handler) http.HandlerFunc {
|
func authorize(networkCheck bool, authNetwork string, next http.Handler) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
var errorResponse = models.ErrorResponse{
|
var errorResponse = models.ErrorResponse{
|
||||||
@@ -134,13 +134,13 @@ func authorize(groupCheck bool, authGroup string, next http.Handler) http.Handle
|
|||||||
|
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
groupexists, _ := functions.GroupExists(params["group"])
|
networkexists, _ := functions.NetworkExists(params["network"])
|
||||||
|
|
||||||
//check that the request is for a valid group
|
//check that the request is for a valid network
|
||||||
//if (groupCheck && !groupexists) || err != nil {
|
//if (networkCheck && !networkexists) || err != nil {
|
||||||
if (groupCheck && !groupexists) {
|
if (networkCheck && !networkexists) {
|
||||||
errorResponse = models.ErrorResponse{
|
errorResponse = models.ErrorResponse{
|
||||||
Code: http.StatusNotFound, Message: "W1R3: This group does not exist. ",
|
Code: http.StatusNotFound, Message: "W1R3: This network does not exist. ",
|
||||||
}
|
}
|
||||||
returnErrorResponse(w, r, errorResponse)
|
returnErrorResponse(w, r, errorResponse)
|
||||||
return
|
return
|
||||||
@@ -190,15 +190,15 @@ func authorize(groupCheck bool, authGroup string, next http.Handler) http.Handle
|
|||||||
isAuthorized = true
|
isAuthorized = true
|
||||||
|
|
||||||
//for everyone else, there's poor man's RBAC. The "cases" are defined in the routes in the handlers
|
//for everyone else, there's poor man's RBAC. The "cases" are defined in the routes in the handlers
|
||||||
//So each route defines which access group should be allowed to access it
|
//So each route defines which access network should be allowed to access it
|
||||||
} else {
|
} else {
|
||||||
switch authGroup {
|
switch authNetwork {
|
||||||
case "all":
|
case "all":
|
||||||
isAuthorized = true
|
isAuthorized = true
|
||||||
case "nodes":
|
case "nodes":
|
||||||
isAuthorized = (macaddress != "")
|
isAuthorized = (macaddress != "")
|
||||||
case "group":
|
case "network":
|
||||||
node, err := functions.GetNodeByMacAddress(params["group"], macaddress)
|
node, err := functions.GetNodeByMacAddress(params["network"], macaddress)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errorResponse = models.ErrorResponse{
|
errorResponse = models.ErrorResponse{
|
||||||
Code: http.StatusUnauthorized, Message: "W1R3: Missing Auth Token.",
|
Code: http.StatusUnauthorized, Message: "W1R3: Missing Auth Token.",
|
||||||
@@ -206,7 +206,7 @@ func authorize(groupCheck bool, authGroup string, next http.Handler) http.Handle
|
|||||||
returnErrorResponse(w, r, errorResponse)
|
returnErrorResponse(w, r, errorResponse)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
isAuthorized = (node.Group == params["group"])
|
isAuthorized = (node.Network == params["network"])
|
||||||
case "node":
|
case "node":
|
||||||
isAuthorized = (macaddress == params["macaddress"])
|
isAuthorized = (macaddress == params["macaddress"])
|
||||||
case "master":
|
case "master":
|
||||||
@@ -229,8 +229,8 @@ func authorize(groupCheck bool, authGroup string, next http.Handler) http.Handle
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Gets all nodes associated with group, including pending nodes
|
//Gets all nodes associated with network, including pending nodes
|
||||||
func getGroupNodes(w http.ResponseWriter, r *http.Request) {
|
func getNetworkNodes(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
@@ -241,7 +241,7 @@ func getGroupNodes(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"group": params["group"]}
|
filter := bson.M{"network": params["network"]}
|
||||||
|
|
||||||
//Filtering out the ID field cuz Dillon doesn't like it. May want to filter out other fields in the future
|
//Filtering out the ID field cuz Dillon doesn't like it. May want to filter out other fields in the future
|
||||||
cur, err := collection.Find(ctx, filter, options.Find().SetProjection(bson.M{"_id": 0}))
|
cur, err := collection.Find(ctx, filter, options.Find().SetProjection(bson.M{"_id": 0}))
|
||||||
@@ -256,7 +256,7 @@ func getGroupNodes(w http.ResponseWriter, r *http.Request) {
|
|||||||
for cur.Next(context.TODO()) {
|
for cur.Next(context.TODO()) {
|
||||||
|
|
||||||
//Using a different model for the ReturnNode (other than regular node).
|
//Using a different model for the ReturnNode (other than regular node).
|
||||||
//Either we should do this for ALL structs (so Groups and Keys)
|
//Either we should do this for ALL structs (so Networks and Keys)
|
||||||
//OR we should just use the original struct
|
//OR we should just use the original struct
|
||||||
//My preference is to make some new return structs
|
//My preference is to make some new return structs
|
||||||
//TODO: Think about this. Not an immediate concern. Just need to get some consistency eventually
|
//TODO: Think about this. Not an immediate concern. Just need to get some consistency eventually
|
||||||
@@ -284,7 +284,7 @@ func getGroupNodes(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//A separate function to get all nodes, not just nodes for a particular group.
|
//A separate function to get all nodes, not just nodes for a particular network.
|
||||||
//Not quite sure if this is necessary. Probably necessary based on front end but may want to review after iteration 1 if it's being used or not
|
//Not quite sure if this is necessary. Probably necessary based on front end but may want to review after iteration 1 if it's being used or not
|
||||||
func getAllNodes(w http.ResponseWriter, r *http.Request) {
|
func getAllNodes(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
@@ -332,15 +332,15 @@ func getAllNodes(w http.ResponseWriter, r *http.Request) {
|
|||||||
//This function get's called when a node "checks in" at check in interval
|
//This function get's called when a node "checks in" at check in interval
|
||||||
//Honestly I'm not sure what all it should be doing
|
//Honestly I'm not sure what all it should be doing
|
||||||
//TODO: Implement the necessary stuff, including the below
|
//TODO: Implement the necessary stuff, including the below
|
||||||
//Check the last modified of the group
|
//Check the last modified of the network
|
||||||
//Check the last modified of the nodes
|
//Check the last modified of the nodes
|
||||||
//Write functions for responding to these two thingies
|
//Write functions for responding to these two thingies
|
||||||
func checkIn(w http.ResponseWriter, r *http.Request) {
|
func checkIn(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
//TODO: Current thoughts:
|
//TODO: Current thoughts:
|
||||||
//Dont bother with a grouplastmodified
|
//Dont bother with a networklastmodified
|
||||||
//Instead, implement a "configupdate" boolean on nodes
|
//Instead, implement a "configupdate" boolean on nodes
|
||||||
//when there is a group update that requrires a config update, then the node will pull its new config
|
//when there is a network update that requrires a config update, then the node will pull its new config
|
||||||
|
|
||||||
// set header.
|
// set header.
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
@@ -351,13 +351,13 @@ func checkIn(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
|
|
||||||
//Retrieves node with DB Call which is inefficient. Let's just get the time and set it.
|
//Retrieves node with DB Call which is inefficient. Let's just get the time and set it.
|
||||||
//node = functions.GetNodeByMacAddress(params["group"], params["macaddress"])
|
//node = functions.GetNodeByMacAddress(params["network"], params["macaddress"])
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"macaddress": params["macaddress"], "group": params["group"]}
|
filter := bson.M{"macaddress": params["macaddress"], "network": params["network"]}
|
||||||
|
|
||||||
//old code was inefficient, this is all we need.
|
//old code was inefficient, this is all we need.
|
||||||
time := time.Now().String()
|
time := time.Now().String()
|
||||||
@@ -380,7 +380,7 @@ func checkIn(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO: check node last modified vs group last modified
|
//TODO: check node last modified vs network last modified
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
json.NewEncoder(w).Encode(node)
|
json.NewEncoder(w).Encode(node)
|
||||||
|
|
||||||
@@ -393,7 +393,7 @@ func getNode(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
node, err := GetNode(params["macaddress"], params["group"])
|
node, err := GetNode(params["macaddress"], params["network"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
@@ -402,23 +402,23 @@ func getNode(w http.ResponseWriter, r *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(node)
|
json.NewEncoder(w).Encode(node)
|
||||||
}
|
}
|
||||||
|
|
||||||
//Get the time that a group of nodes was last modified.
|
//Get the time that a network of nodes was last modified.
|
||||||
//TODO: This needs to be refactored
|
//TODO: This needs to be refactored
|
||||||
//Potential way to do this: On UpdateNode, set a new field for "LastModified"
|
//Potential way to do this: On UpdateNode, set a new field for "LastModified"
|
||||||
//If we go with the existing way, we need to at least set group.NodesLastModified on UpdateNode
|
//If we go with the existing way, we need to at least set network.NodesLastModified on UpdateNode
|
||||||
func getLastModified(w http.ResponseWriter, r *http.Request) {
|
func getLastModified(w http.ResponseWriter, r *http.Request) {
|
||||||
// set header.
|
// set header.
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"nameid": params["group"]}
|
filter := bson.M{"netid": params["network"]}
|
||||||
err := collection.FindOne(ctx, filter).Decode(&group)
|
err := collection.FindOne(ctx, filter).Decode(&network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
@@ -428,7 +428,7 @@ func getLastModified(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
w.Write([]byte(string(group.NodesLastModified)))
|
w.Write([]byte(string(network.NodesLastModified)))
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -444,19 +444,19 @@ func createNode(w http.ResponseWriter, r *http.Request) {
|
|||||||
Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
|
Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
|
||||||
}
|
}
|
||||||
|
|
||||||
groupName := params["group"]
|
networkName := params["network"]
|
||||||
|
|
||||||
//Check if group exists first
|
//Check if network exists first
|
||||||
//TODO: This is inefficient. Let's find a better way.
|
//TODO: This is inefficient. Let's find a better way.
|
||||||
//Just a few rows down we grab the group anyway
|
//Just a few rows down we grab the network anyway
|
||||||
groupexists, err := functions.GroupExists(groupName)
|
networkexists, err := functions.NetworkExists(networkName)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
} else if !groupexists {
|
} else if !networkexists {
|
||||||
errorResponse = models.ErrorResponse{
|
errorResponse = models.ErrorResponse{
|
||||||
Code: http.StatusNotFound, Message: "W1R3: Group does not exist! ",
|
Code: http.StatusNotFound, Message: "W1R3: Network does not exist! ",
|
||||||
}
|
}
|
||||||
returnErrorResponse(w, r, errorResponse)
|
returnErrorResponse(w, r, errorResponse)
|
||||||
return
|
return
|
||||||
@@ -471,23 +471,23 @@ func createNode(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
node.Group = groupName
|
node.Network = networkName
|
||||||
|
|
||||||
|
|
||||||
group, err := node.GetGroup()
|
network, err := node.GetNetwork()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
//Check to see if key is valid
|
//Check to see if key is valid
|
||||||
//TODO: Triple inefficient!!! This is the third call to the DB we make for groups
|
//TODO: Triple inefficient!!! This is the third call to the DB we make for networks
|
||||||
validKey := functions.IsKeyValid(groupName, node.AccessKey)
|
validKey := functions.IsKeyValid(networkName, node.AccessKey)
|
||||||
|
|
||||||
if !validKey {
|
if !validKey {
|
||||||
//Check to see if group will allow manual sign up
|
//Check to see if network will allow manual sign up
|
||||||
//may want to switch this up with the valid key check and avoid a DB call that way.
|
//may want to switch this up with the valid key check and avoid a DB call that way.
|
||||||
if *group.AllowManualSignUp {
|
if *network.AllowManualSignUp {
|
||||||
node.IsPending = true
|
node.IsPending = true
|
||||||
} else {
|
} else {
|
||||||
errorResponse = models.ErrorResponse{
|
errorResponse = models.ErrorResponse{
|
||||||
@@ -498,13 +498,13 @@ func createNode(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err = ValidateNode("create", groupName, node)
|
err = ValidateNode("create", networkName, node)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
node, err = CreateNode(node, groupName)
|
node, err = CreateNode(node, networkName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
@@ -522,7 +522,7 @@ func uncordonNode(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
var node models.Node
|
var node models.Node
|
||||||
|
|
||||||
node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
|
node, err := functions.GetNodeByMacAddress(params["network"], params["macaddress"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
@@ -533,7 +533,7 @@ func uncordonNode(w http.ResponseWriter, r *http.Request) {
|
|||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
// Create filter
|
// Create filter
|
||||||
filter := bson.M{"macaddress": params["macaddress"], "group": params["group"]}
|
filter := bson.M{"macaddress": params["macaddress"], "network": params["network"]}
|
||||||
|
|
||||||
node.SetLastModified()
|
node.SetLastModified()
|
||||||
|
|
||||||
@@ -567,7 +567,7 @@ func createGateway(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
var node models.Node
|
var node models.Node
|
||||||
|
|
||||||
node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
|
node, err := functions.GetNodeByMacAddress(params["network"], params["macaddress"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
@@ -578,11 +578,11 @@ func createGateway(w http.ResponseWriter, r *http.Request) {
|
|||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
// Create filter
|
// Create filter
|
||||||
filter := bson.M{"macaddress": params["macaddress"], "group": params["group"]}
|
filter := bson.M{"macaddress": params["macaddress"], "network": params["network"]}
|
||||||
|
|
||||||
node.SetLastModified()
|
node.SetLastModified()
|
||||||
|
|
||||||
err = ValidateNode("create", params["group"], node)
|
err = ValidateNode("create", params["network"], node)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
@@ -622,7 +622,7 @@ func updateNode(w http.ResponseWriter, r *http.Request) {
|
|||||||
var node models.Node
|
var node models.Node
|
||||||
|
|
||||||
//start here
|
//start here
|
||||||
node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
|
node, err := functions.GetNodeByMacAddress(params["network"], params["macaddress"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
@@ -634,14 +634,14 @@ func updateNode(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// we decode our body request params
|
// we decode our body request params
|
||||||
_ = json.NewDecoder(r.Body).Decode(&nodechange)
|
_ = json.NewDecoder(r.Body).Decode(&nodechange)
|
||||||
if nodechange.Group == "" {
|
if nodechange.Network == "" {
|
||||||
nodechange.Group = node.Group
|
nodechange.Network = node.Network
|
||||||
}
|
}
|
||||||
if nodechange.MacAddress == "" {
|
if nodechange.MacAddress == "" {
|
||||||
nodechange.MacAddress = node.MacAddress
|
nodechange.MacAddress = node.MacAddress
|
||||||
}
|
}
|
||||||
|
|
||||||
err = ValidateNode("update", params["group"], nodechange)
|
err = ValidateNode("update", params["network"], nodechange)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
return
|
return
|
||||||
@@ -665,7 +665,7 @@ func deleteNode(w http.ResponseWriter, r *http.Request) {
|
|||||||
// get params
|
// get params
|
||||||
var params = mux.Vars(r)
|
var params = mux.Vars(r)
|
||||||
|
|
||||||
success, err := DeleteNode(params["macaddress"], params["group"])
|
success, err := DeleteNode(params["macaddress"], params["network"])
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||||
|
@@ -16,7 +16,7 @@ func serverHandlers(r *mux.Router) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Security check is middleware for every function and just checks to make sure that its the master calling
|
//Security check is middleware for every function and just checks to make sure that its the master calling
|
||||||
//Only admin should have access to all these group-level actions
|
//Only admin should have access to all these network-level actions
|
||||||
//or maybe some Users once implemented
|
//or maybe some Users once implemented
|
||||||
func securityCheckServer(next http.Handler) http.HandlerFunc {
|
func securityCheckServer(next http.Handler) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
@@ -116,7 +116,7 @@ func authenticateUser(response http.ResponseWriter, request *http.Request) {
|
|||||||
//The middleware for most requests to the API
|
//The middleware for most requests to the API
|
||||||
//They all pass through here first
|
//They all pass through here first
|
||||||
//This will validate the JWT (or check for master token)
|
//This will validate the JWT (or check for master token)
|
||||||
//This will also check against the authGroup and make sure the node should be accessing that endpoint,
|
//This will also check against the authNetwork and make sure the node should be accessing that endpoint,
|
||||||
//even if it's technically ok
|
//even if it's technically ok
|
||||||
//This is kind of a poor man's RBAC. There's probably a better/smarter way.
|
//This is kind of a poor man's RBAC. There's probably a better/smarter way.
|
||||||
//TODO: Consider better RBAC implementations
|
//TODO: Consider better RBAC implementations
|
||||||
|
52
docs/API.md
52
docs/API.md
@@ -1,30 +1,30 @@
|
|||||||
# API Reference Doc
|
# API Reference Doc
|
||||||
|
|
||||||
### Nodes
|
### Nodes
|
||||||
**Get Peer List:** "/api/{group}/peerlist", "GET"
|
**Get Peer List:** "/api/{network}/peerlist", "GET"
|
||||||
**Get List Last Modified Date:** "/api/{group}/lastmodified", "GET"
|
**Get List Last Modified Date:** "/api/{network}/lastmodified", "GET"
|
||||||
**Get Node Details:** "/api/{group}/nodes/{macaddress}", "GET"
|
**Get Node Details:** "/api/{network}/nodes/{macaddress}", "GET"
|
||||||
**Create Node:** "/api/{group}/nodes", "POST"
|
**Create Node:** "/api/{network}/nodes", "POST"
|
||||||
**Uncordon Node:** "/api/{group}/nodes/{macaddress}/uncordon", "POST"
|
**Uncordon Node:** "/api/{network}/nodes/{macaddress}/uncordon", "POST"
|
||||||
**Check In Node:** "/api/{group}/nodes/{macaddress}/checkin", "POST"
|
**Check In Node:** "/api/{network}/nodes/{macaddress}/checkin", "POST"
|
||||||
**Update Node:** "/api/{group}/nodes/{macaddress}", "PUT"
|
**Update Node:** "/api/{network}/nodes/{macaddress}", "PUT"
|
||||||
**Delete Node:** "/api/{group}/nodes/{macaddress}", "DELETE"
|
**Delete Node:** "/api/{network}/nodes/{macaddress}", "DELETE"
|
||||||
**Get Group Nodes:** "/api/{group}/nodes", "GET"
|
**Get Network Nodes:** "/api/{network}/nodes", "GET"
|
||||||
**Get All Nodes:** "/api/nodes", "GET"
|
**Get All Nodes:** "/api/nodes", "GET"
|
||||||
**Authenticate:** "/api/{group}/authenticate", "POST"
|
**Authenticate:** "/api/{network}/authenticate", "POST"
|
||||||
|
|
||||||
|
|
||||||
### Groups
|
### Networks
|
||||||
**Get Groups:** "/api/groups", "GET"
|
**Get Networks:** "/api/networks", "GET"
|
||||||
**Get Group Details:** "/api/group/{groupname}", "GET"
|
**Get Network Details:** "/api/network/{networkname}", "GET"
|
||||||
**Get Number of Nodes in Group:** "/api/group/{groupname}/numnodes", "GET"
|
**Get Number of Nodes in Network:** "/api/network/{networkname}/numnodes", "GET"
|
||||||
**Create Group:** "/api/groups", "POST"
|
**Create Network:** "/api/networks", "POST"
|
||||||
**Update Group:** "/api/groups/{groupname}", "PUT"
|
**Update Network:** "/api/networks/{networkname}", "PUT"
|
||||||
**Delete Group:** "/api/groups/{groupname}", "DELETE"
|
**Delete Network:** "/api/networks/{networkname}", "DELETE"
|
||||||
|
|
||||||
**Create Access Key:** "/api/groups/{groupname}/keys", "POST"
|
**Create Access Key:** "/api/networks/{networkname}/keys", "POST"
|
||||||
**Get Access Key:** "/api/groups/{groupname}/keys", "GET"
|
**Get Access Key:** "/api/networks/{networkname}/keys", "GET"
|
||||||
**Delete Access Key:** "/api/groups/{groupname}/keys/{keyname}", "DELETE"
|
**Delete Access Key:** "/api/networks/{networkname}/keys/{keyname}", "DELETE"
|
||||||
|
|
||||||
### Users (only used for interface admin user at this time)
|
### Users (only used for interface admin user at this time)
|
||||||
**Create Admin User:** "/users/createadmin", "POST"
|
**Create Admin User:** "/users/createadmin", "POST"
|
||||||
@@ -44,19 +44,19 @@
|
|||||||
|
|
||||||
**Note About Token:** This is a configurable value stored under config/environments/dev.yaml and can be changed before startup. It's a hack for testing, just provides an easy way to authorize, and should be removed and changed in the future.
|
**Note About Token:** This is a configurable value stored under config/environments/dev.yaml and can be changed before startup. It's a hack for testing, just provides an easy way to authorize, and should be removed and changed in the future.
|
||||||
|
|
||||||
#### Create a Group
|
#### Create a Network
|
||||||
curl -d '{"addressrange":"10.70.0.0/16","nameid":"skynet"}' -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/groups
|
curl -d '{"addressrange":"10.70.0.0/16","netid":"skynet"}' -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/networks
|
||||||
|
|
||||||
#### Create a Key
|
#### Create a Key
|
||||||
curl -d '{"uses":10}' -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/groups localhost:8081/api/groups/skynet/keys
|
curl -d '{"uses":10}' -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/networks localhost:8081/api/networks/skynet/keys
|
||||||
|
|
||||||
#### Create a Node
|
#### Create a Node
|
||||||
curl -d '{ "endpoint": 100.200.100.200, "publickey": aorijqalrik3ajflaqrdajhkr,"macaddress": "8c:90:b5:06:f1:d9","password": "reallysecret","localaddress": "172.16.16.1","accesskey": "aA3bVG0rnItIRXDx","listenport": 6400}' -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/skynet/nodes
|
curl -d '{ "endpoint": 100.200.100.200, "publickey": aorijqalrik3ajflaqrdajhkr,"macaddress": "8c:90:b5:06:f1:d9","password": "reallysecret","localaddress": "172.16.16.1","accesskey": "aA3bVG0rnItIRXDx","listenport": 6400}' -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/skynet/nodes
|
||||||
|
|
||||||
#### Get Groups
|
#### Get Networks
|
||||||
curl -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/groups | jq
|
curl -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/networks | jq
|
||||||
|
|
||||||
#### Get Group Nodes
|
#### Get Network Nodes
|
||||||
curl -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/skynet/nodes | jq
|
curl -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/skynet/nodes | jq
|
||||||
|
|
||||||
#### Update Node Settings
|
#### Update Node Settings
|
||||||
|
@@ -5,9 +5,9 @@
|
|||||||
3. Pull this repo: `git clone https://github.com/gravitl/netmaker.git`
|
3. Pull this repo: `git clone https://github.com/gravitl/netmaker.git`
|
||||||
4. Switch to the directory and source the default env vars `cd netmaker && source defaultvars.sh`
|
4. Switch to the directory and source the default env vars `cd netmaker && source defaultvars.sh`
|
||||||
5. Run the server: `go run ./`
|
5. Run the server: `go run ./`
|
||||||
### Optional (For Testing): Create Groups and Nodes
|
### Optional (For Testing): Create Networks and Nodes
|
||||||
|
|
||||||
1. Create Group: `./test/groupcreate.sh`
|
1. Create Network: `./test/networkcreate.sh`
|
||||||
2. Create Key: `./test/keycreate.sh` (save the response for step 3)
|
2. Create Key: `./test/keycreate.sh` (save the response for step 3)
|
||||||
3. Open ./test/nodescreate.sh and replace ACCESSKEY with value from #2
|
3. Open ./test/nodescreate.sh and replace ACCESSKEY with value from #2
|
||||||
4. Create Nodes: `./test/nodescreate.sh`
|
4. Create Nodes: `./test/nodescreate.sh`
|
||||||
@@ -21,10 +21,10 @@ On each machine you would like to add to the network, do the following:
|
|||||||
|
|
||||||
1. Confirm wireguard is installed: `sudo apt install wireguard-tools`
|
1. Confirm wireguard is installed: `sudo apt install wireguard-tools`
|
||||||
2. Confirm ipv4 forwarding is enabled: `sysctl -w net.ipv4.ip_forward=1`
|
2. Confirm ipv4 forwarding is enabled: `sysctl -w net.ipv4.ip_forward=1`
|
||||||
3. Create a key or enable manual node signup at the group level
|
3. Create a key or enable manual node signup at the network level
|
||||||
4. Get the binary: `sudo wget 52.55.6.84:8081/meshclient/files/meshclient`
|
4. Get the binary: `sudo wget 52.55.6.84:8081/meshclient/files/meshclient`
|
||||||
5. Make it executable: `sudo chmod +x meshclient`
|
5. Make it executable: `sudo chmod +x meshclient`
|
||||||
6. Run the install command: `sudo ./meshclient -c install -g <group name> -s <server:port> -k <key value>`
|
6. Run the install command: `sudo ./meshclient -c install -g <network name> -s <server:port> -k <key value>`
|
||||||
|
|
||||||
This will install netclient.service and netclient.timer in systemd, which will run periodically to call the netclient binary, which will check to see if there are any updates that it needs and update WireGuard appropriately.
|
This will install netclient.service and netclient.timer in systemd, which will run periodically to call the netclient binary, which will check to see if there are any updates that it needs and update WireGuard appropriately.
|
||||||
|
|
||||||
|
@@ -2,12 +2,12 @@
|
|||||||
|
|
||||||
### 0.1
|
### 0.1
|
||||||
**Server:**
|
**Server:**
|
||||||
- [x] Create Groups (virtual networks)
|
- [x] Create Networks (virtual networks)
|
||||||
- [x] Allow default settings for nodes from groups
|
- [x] Allow default settings for nodes from networks
|
||||||
- [x] Admin/Superuser key
|
- [x] Admin/Superuser key
|
||||||
- [x] Create multiuse keys for node signup
|
- [x] Create multiuse keys for node signup
|
||||||
- [x] JWT-based auth for post-signup
|
- [x] JWT-based auth for post-signup
|
||||||
- [x] CRUD for groups
|
- [x] CRUD for networks
|
||||||
- [x] CRUD for nodes
|
- [x] CRUD for nodes
|
||||||
- [x] Track all important info about node for networking (port, endpoints, pub key, etc)
|
- [x] Track all important info about node for networking (port, endpoints, pub key, etc)
|
||||||
- [x] Timestamps for determining if nodes need updates
|
- [x] Timestamps for determining if nodes need updates
|
||||||
@@ -31,21 +31,21 @@
|
|||||||
- [ ] Troubleshooting
|
- [ ] Troubleshooting
|
||||||
|
|
||||||
**Server:**
|
**Server:**
|
||||||
- [ ] Allow tracking multiple groups per node
|
- [ ] Allow tracking multiple networks per node
|
||||||
- [ ] Configure Check-in thresholds
|
- [ ] Configure Check-in thresholds
|
||||||
- [ ] Separate sign-up endpoint to allow VPN-only comms after joining network
|
- [ ] Separate sign-up endpoint to allow VPN-only comms after joining network
|
||||||
- [ ] Swagger Docs
|
- [ ] Swagger Docs
|
||||||
- [ ] Build Out README
|
- [ ] Build Out README
|
||||||
- [ ] Encode Server, Port, and Group into Keys
|
- [ ] Encode Server, Port, and Network into Keys
|
||||||
- [ ] Switch to Unique ID for nodes instead of MacAddress
|
- [ ] Switch to Unique ID for nodes instead of MacAddress
|
||||||
- [ ] Public Key refresh
|
- [ ] Public Key refresh
|
||||||
- [ ] Enable ipv6 addresses
|
- [ ] Enable ipv6 addresses
|
||||||
- [ ] Have a "default" group created at startup
|
- [ ] Have a "default" network created at startup
|
||||||
|
|
||||||
**Agent:**
|
**Agent:**
|
||||||
- [ ] Test / get working on multiple linux platforms
|
- [ ] Test / get working on multiple linux platforms
|
||||||
- [ ] Set private DNS via etc hosts (node name + ip). Make it optional flag on agent.
|
- [ ] Set private DNS via etc hosts (node name + ip). Make it optional flag on agent.
|
||||||
- [ ] Decode Server, Port, and Group from Key
|
- [ ] Decode Server, Port, and Network from Key
|
||||||
- [ ] Service ID / unit file for SystemD Service
|
- [ ] Service ID / unit file for SystemD Service
|
||||||
- [ ] Allow multiple interfaces
|
- [ ] Allow multiple interfaces
|
||||||
- [ ] Use "Check in interval" from server
|
- [ ] Use "Check in interval" from server
|
||||||
@@ -55,7 +55,7 @@
|
|||||||
### 0.3
|
### 0.3
|
||||||
**Server:**
|
**Server:**
|
||||||
- [ ] Swagger Docs
|
- [ ] Swagger Docs
|
||||||
- [ ] Group/Node labels
|
- [ ] Network/Node labels
|
||||||
- [ ] "Read Only" mode for nodes (can't update their settings centrally, only read)
|
- [ ] "Read Only" mode for nodes (can't update their settings centrally, only read)
|
||||||
- [ ] "No-GUI mode:" Similar to existing, just do more e2e testing and make sure flow makes sense
|
- [ ] "No-GUI mode:" Similar to existing, just do more e2e testing and make sure flow makes sense
|
||||||
- [ ] Let users set prefixes (node, interface)
|
- [ ] Let users set prefixes (node, interface)
|
||||||
@@ -87,7 +87,7 @@
|
|||||||
- [ ] Load balance / fault tolerant server
|
- [ ] Load balance / fault tolerant server
|
||||||
- [ ] Change DB / make more scaleable (SQL?)
|
- [ ] Change DB / make more scaleable (SQL?)
|
||||||
- [ ] Redis
|
- [ ] Redis
|
||||||
- [ ] Group/Node labels
|
- [ ] Network/Node labels
|
||||||
|
|
||||||
**Agent:**
|
**Agent:**
|
||||||
- [ ] userspace via Docker or Golang
|
- [ ] userspace via Docker or Golang
|
||||||
|
@@ -22,14 +22,14 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
//Takes in an arbitrary field and value for field and checks to see if any other
|
//Takes in an arbitrary field and value for field and checks to see if any other
|
||||||
//node has that value for the same field within the group
|
//node has that value for the same field within the network
|
||||||
|
|
||||||
func CreateServerToken(network string) (string, error) {
|
func CreateServerToken(netID string) (string, error) {
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
var accesskey models.AccessKey
|
var accesskey models.AccessKey
|
||||||
|
|
||||||
group, err := GetParentGroup(network)
|
network, err := GetParentNetwork(netID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -43,29 +43,29 @@ func CreateServerToken(network string) (string, error) {
|
|||||||
}
|
}
|
||||||
address := "localhost" + gconf.PortGRPC
|
address := "localhost" + gconf.PortGRPC
|
||||||
|
|
||||||
accessstringdec := address + "." + network + "." + accesskey.Value
|
accessstringdec := address + "." + netID + "." + accesskey.Value
|
||||||
accesskey.AccessString = base64.StdEncoding.EncodeToString([]byte(accessstringdec))
|
accesskey.AccessString = base64.StdEncoding.EncodeToString([]byte(accessstringdec))
|
||||||
|
|
||||||
group.AccessKeys = append(group.AccessKeys, accesskey)
|
network.AccessKeys = append(network.AccessKeys, accesskey)
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
// Create filter
|
// Create filter
|
||||||
filter := bson.M{"nameid": network}
|
filter := bson.M{"netid": netID}
|
||||||
|
|
||||||
// Read update model from body request
|
// Read update model from body request
|
||||||
fmt.Println("Adding key to " + group.NameID)
|
fmt.Println("Adding key to " + network.NetID)
|
||||||
|
|
||||||
// prepare update model.
|
// prepare update model.
|
||||||
update := bson.D{
|
update := bson.D{
|
||||||
{"$set", bson.D{
|
{"$set", bson.D{
|
||||||
{"accesskeys", group.AccessKeys},
|
{"accesskeys", network.AccessKeys},
|
||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
|
|
||||||
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
@@ -75,7 +75,7 @@ func CreateServerToken(network string) (string, error) {
|
|||||||
return accesskey.AccessString, nil
|
return accesskey.AccessString, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func IsFieldUnique(group string, field string, value string) bool {
|
func IsFieldUnique(network string, field string, value string) bool {
|
||||||
|
|
||||||
var node models.Node
|
var node models.Node
|
||||||
isunique := true
|
isunique := true
|
||||||
@@ -83,7 +83,7 @@ func IsFieldUnique(group string, field string, value string) bool {
|
|||||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{field: value, "group": group}
|
filter := bson.M{field: value, "network": network}
|
||||||
|
|
||||||
err := collection.FindOne(ctx, filter).Decode(&node)
|
err := collection.FindOne(ctx, filter).Decode(&node)
|
||||||
|
|
||||||
@@ -100,13 +100,13 @@ func IsFieldUnique(group string, field string, value string) bool {
|
|||||||
return isunique
|
return isunique
|
||||||
}
|
}
|
||||||
|
|
||||||
func GroupExists(name string) (bool, error) {
|
func NetworkExists(name string) (bool, error) {
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"nameid": name}
|
filter := bson.M{"netid": name}
|
||||||
|
|
||||||
var result bson.M
|
var result bson.M
|
||||||
err := collection.FindOne(ctx, filter).Decode(&result)
|
err := collection.FindOne(ctx, filter).Decode(&result)
|
||||||
@@ -124,16 +124,16 @@ func GroupExists(name string) (bool, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//TODO: This is very inefficient (N-squared). Need to find a better way.
|
//TODO: This is very inefficient (N-squared). Need to find a better way.
|
||||||
//Takes a list of nodes in a group and iterates through
|
//Takes a list of nodes in a network and iterates through
|
||||||
//for each node, it gets a unique address. That requires checking against all other nodes once more
|
//for each node, it gets a unique address. That requires checking against all other nodes once more
|
||||||
func UpdateGroupNodeAddresses(groupName string) error {
|
func UpdateNetworkNodeAddresses(networkName string) error {
|
||||||
|
|
||||||
//Connection mongoDB with mongoconn class
|
//Connection mongoDB with mongoconn class
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"group": groupName}
|
filter := bson.M{"network": networkName}
|
||||||
cur, err := collection.Find(ctx, filter)
|
cur, err := collection.Find(ctx, filter)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -151,7 +151,7 @@ func UpdateGroupNodeAddresses(groupName string) error {
|
|||||||
fmt.Println("error in node address assignment!")
|
fmt.Println("error in node address assignment!")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
ipaddr, iperr := UniqueAddress(groupName)
|
ipaddr, iperr := UniqueAddress(networkName)
|
||||||
if iperr != nil {
|
if iperr != nil {
|
||||||
fmt.Println("error in node address assignment!")
|
fmt.Println("error in node address assignment!")
|
||||||
return iperr
|
return iperr
|
||||||
@@ -171,14 +171,14 @@ func UpdateGroupNodeAddresses(groupName string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
//TODO TODO TODO!!!!!
|
//TODO TODO TODO!!!!!
|
||||||
func UpdateGroupPrivateAddresses(groupName string) error {
|
func UpdateNetworkPrivateAddresses(networkName string) error {
|
||||||
|
|
||||||
//Connection mongoDB with mongoconn class
|
//Connection mongoDB with mongoconn class
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"group": groupName}
|
filter := bson.M{"network": networkName}
|
||||||
cur, err := collection.Find(ctx, filter)
|
cur, err := collection.Find(ctx, filter)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -196,7 +196,7 @@ func UpdateGroupPrivateAddresses(groupName string) error {
|
|||||||
fmt.Println("error in node address assignment!")
|
fmt.Println("error in node address assignment!")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
ipaddr, iperr := UniqueAddress(groupName)
|
ipaddr, iperr := UniqueAddress(networkName)
|
||||||
if iperr != nil {
|
if iperr != nil {
|
||||||
fmt.Println("error in node address assignment!")
|
fmt.Println("error in node address assignment!")
|
||||||
return iperr
|
return iperr
|
||||||
@@ -216,12 +216,12 @@ func UpdateGroupPrivateAddresses(groupName string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Checks to see if any other groups have the same name (id)
|
//Checks to see if any other networks have the same name (id)
|
||||||
func IsGroupNameUnique(name string) (bool, error ){
|
func IsNetworkNameUnique(name string) (bool, error ){
|
||||||
|
|
||||||
isunique := true
|
isunique := true
|
||||||
|
|
||||||
dbs, err := ListGroups()
|
dbs, err := ListNetworks()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
@@ -229,7 +229,7 @@ func IsGroupNameUnique(name string) (bool, error ){
|
|||||||
|
|
||||||
for i := 0; i < len(dbs); i++ {
|
for i := 0; i < len(dbs); i++ {
|
||||||
|
|
||||||
if name == dbs[i].NameID {
|
if name == dbs[i].NetID {
|
||||||
isunique = false
|
isunique = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -237,11 +237,11 @@ func IsGroupNameUnique(name string) (bool, error ){
|
|||||||
return isunique, nil
|
return isunique, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func IsGroupDisplayNameUnique(name string) (bool, error){
|
func IsNetworkDisplayNameUnique(name string) (bool, error){
|
||||||
|
|
||||||
isunique := true
|
isunique := true
|
||||||
|
|
||||||
dbs, err := ListGroups()
|
dbs, err := ListNetworks()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
@@ -257,13 +257,13 @@ func IsGroupDisplayNameUnique(name string) (bool, error){
|
|||||||
return isunique, nil
|
return isunique, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetGroupNodeNumber(groupName string) (int, error){
|
func GetNetworkNodeNumber(networkName string) (int, error){
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("wirecat").Collection("nodes")
|
collection := mongoconn.Client.Database("wirecat").Collection("nodes")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"group": groupName}
|
filter := bson.M{"network": networkName}
|
||||||
count, err := collection.CountDocuments(ctx, filter)
|
count, err := collection.CountDocuments(ctx, filter)
|
||||||
returncount := int(count)
|
returncount := int(count)
|
||||||
|
|
||||||
@@ -278,56 +278,56 @@ func GetGroupNodeNumber(groupName string) (int, error){
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//Kind of a weird name. Should just be GetGroups I think. Consider changing.
|
//Kind of a weird name. Should just be GetNetworks I think. Consider changing.
|
||||||
//Anyway, returns all the groups
|
//Anyway, returns all the networks
|
||||||
func ListGroups() ([]models.Group, error){
|
func ListNetworks() ([]models.Network, error){
|
||||||
|
|
||||||
var groups []models.Group
|
var networks []models.Network
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
|
cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return groups, err
|
return networks, err
|
||||||
}
|
}
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
for cur.Next(context.TODO()) {
|
for cur.Next(context.TODO()) {
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
err := cur.Decode(&group)
|
err := cur.Decode(&network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return groups, err
|
return networks, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// add group our array
|
// add network our array
|
||||||
groups = append(groups, group)
|
networks = append(networks, network)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := cur.Err(); err != nil {
|
if err := cur.Err(); err != nil {
|
||||||
return groups, err
|
return networks, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return groups, err
|
return networks, err
|
||||||
}
|
}
|
||||||
|
|
||||||
//Checks to see if access key is valid
|
//Checks to see if access key is valid
|
||||||
//Does so by checking against all keys and seeing if any have the same value
|
//Does so by checking against all keys and seeing if any have the same value
|
||||||
//may want to hash values before comparing...consider this
|
//may want to hash values before comparing...consider this
|
||||||
//TODO: No error handling!!!!
|
//TODO: No error handling!!!!
|
||||||
func IsKeyValid(groupname string, keyvalue string) bool{
|
func IsKeyValid(networkname string, keyvalue string) bool{
|
||||||
|
|
||||||
group, _ := GetParentGroup(groupname)
|
network, _ := GetParentNetwork(networkname)
|
||||||
var key models.AccessKey
|
var key models.AccessKey
|
||||||
foundkey := false
|
foundkey := false
|
||||||
isvalid := false
|
isvalid := false
|
||||||
|
|
||||||
for i := len(group.AccessKeys) - 1; i >= 0; i-- {
|
for i := len(network.AccessKeys) - 1; i >= 0; i-- {
|
||||||
currentkey:= group.AccessKeys[i]
|
currentkey:= network.AccessKeys[i]
|
||||||
if currentkey.Value == keyvalue {
|
if currentkey.Value == keyvalue {
|
||||||
key = currentkey
|
key = currentkey
|
||||||
foundkey = true
|
foundkey = true
|
||||||
@@ -341,27 +341,27 @@ func IsKeyValid(groupname string, keyvalue string) bool{
|
|||||||
return isvalid
|
return isvalid
|
||||||
}
|
}
|
||||||
//TODO: Contains a fatal error return. Need to change
|
//TODO: Contains a fatal error return. Need to change
|
||||||
//This just gets a group object from a group name
|
//This just gets a network object from a network name
|
||||||
//Should probably just be GetGroup. kind of a dumb name.
|
//Should probably just be GetNetwork. kind of a dumb name.
|
||||||
//Used in contexts where it's not the Parent group.
|
//Used in contexts where it's not the Parent network.
|
||||||
func GetParentGroup(groupname string) (models.Group, error) {
|
func GetParentNetwork(networkname string) (models.Network, error) {
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"nameid": groupname}
|
filter := bson.M{"netid": networkname}
|
||||||
err := collection.FindOne(ctx, filter).Decode(&group)
|
err := collection.FindOne(ctx, filter).Decode(&network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return group, err
|
return network, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return group, nil
|
return network, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//Check for valid IPv4 address
|
//Check for valid IPv4 address
|
||||||
@@ -418,9 +418,9 @@ func GetNodeObj(id primitive.ObjectID) models.Node {
|
|||||||
return node
|
return node
|
||||||
}
|
}
|
||||||
|
|
||||||
//This checks to make sure a group name is valid.
|
//This checks to make sure a network name is valid.
|
||||||
//Switch to REGEX?
|
//Switch to REGEX?
|
||||||
func NameInGroupCharSet(name string) bool{
|
func NameInNetworkCharSet(name string) bool{
|
||||||
|
|
||||||
charset := "abcdefghijklmnopqrstuvwxyz1234567890-_"
|
charset := "abcdefghijklmnopqrstuvwxyz1234567890-_"
|
||||||
|
|
||||||
@@ -449,11 +449,11 @@ func NameInNodeCharSet(name string) bool{
|
|||||||
//The mac address acts as the Unique ID for nodes.
|
//The mac address acts as the Unique ID for nodes.
|
||||||
//Is this a dumb thing to do? I thought it was cool but maybe it's dumb.
|
//Is this a dumb thing to do? I thought it was cool but maybe it's dumb.
|
||||||
//It doesn't really provide a tangible benefit over a random ID
|
//It doesn't really provide a tangible benefit over a random ID
|
||||||
func GetNodeByMacAddress(group string, macaddress string) (models.Node, error) {
|
func GetNodeByMacAddress(network string, macaddress string) (models.Node, error) {
|
||||||
|
|
||||||
var node models.Node
|
var node models.Node
|
||||||
|
|
||||||
filter := bson.M{"macaddress": macaddress, "group": group}
|
filter := bson.M{"macaddress": macaddress, "network": network}
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||||
|
|
||||||
@@ -474,17 +474,17 @@ func GetNodeByMacAddress(group string, macaddress string) (models.Node, error) {
|
|||||||
//and checks against all nodes to see if it's taken, until it finds one.
|
//and checks against all nodes to see if it's taken, until it finds one.
|
||||||
//TODO: We do not handle a case where we run out of addresses.
|
//TODO: We do not handle a case where we run out of addresses.
|
||||||
//We will need to handle that eventually
|
//We will need to handle that eventually
|
||||||
func UniqueAddress(groupName string) (string, error){
|
func UniqueAddress(networkName string) (string, error){
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
group, err := GetParentGroup(groupName)
|
network, err := GetParentNetwork(networkName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("UniqueAddress encountered an error")
|
fmt.Println("UniqueAddress encountered an error")
|
||||||
return "666", err
|
return "666", err
|
||||||
}
|
}
|
||||||
|
|
||||||
offset := true
|
offset := true
|
||||||
ip, ipnet, err := net.ParseCIDR(group.AddressRange)
|
ip, ipnet, err := net.ParseCIDR(network.AddressRange)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("UniqueAddress encountered an error")
|
fmt.Println("UniqueAddress encountered an error")
|
||||||
return "666", err
|
return "666", err
|
||||||
@@ -494,12 +494,12 @@ func UniqueAddress(groupName string) (string, error){
|
|||||||
offset = false
|
offset = false
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if IsIPUnique(groupName, ip.String()){
|
if IsIPUnique(networkName, ip.String()){
|
||||||
return ip.String(), err
|
return ip.String(), err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//TODO
|
//TODO
|
||||||
err1 := errors.New("ERROR: No unique addresses available. Check group subnet.")
|
err1 := errors.New("ERROR: No unique addresses available. Check network subnet.")
|
||||||
return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
|
return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -565,7 +565,7 @@ func GenKeyName() string {
|
|||||||
|
|
||||||
//checks if IP is unique in the address range
|
//checks if IP is unique in the address range
|
||||||
//used by UniqueAddress
|
//used by UniqueAddress
|
||||||
func IsIPUnique(group string, ip string) bool {
|
func IsIPUnique(network string, ip string) bool {
|
||||||
|
|
||||||
var node models.Node
|
var node models.Node
|
||||||
|
|
||||||
@@ -574,7 +574,7 @@ func IsIPUnique(group string, ip string) bool {
|
|||||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"address": ip, "group": group}
|
filter := bson.M{"address": ip, "network": network}
|
||||||
|
|
||||||
err := collection.FindOne(ctx, filter).Decode(&node)
|
err := collection.FindOne(ctx, filter).Decode(&node)
|
||||||
|
|
||||||
@@ -593,41 +593,41 @@ func IsIPUnique(group string, ip string) bool {
|
|||||||
|
|
||||||
//called once key has been used by createNode
|
//called once key has been used by createNode
|
||||||
//reduces value by one and deletes if necessary
|
//reduces value by one and deletes if necessary
|
||||||
func DecrimentKey(groupName string, keyvalue string) {
|
func DecrimentKey(networkName string, keyvalue string) {
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
|
|
||||||
group, err := GetParentGroup(groupName)
|
network, err := GetParentNetwork(networkName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := len(group.AccessKeys) - 1; i >= 0; i-- {
|
for i := len(network.AccessKeys) - 1; i >= 0; i-- {
|
||||||
|
|
||||||
currentkey := group.AccessKeys[i]
|
currentkey := network.AccessKeys[i]
|
||||||
if currentkey.Value == keyvalue {
|
if currentkey.Value == keyvalue {
|
||||||
group.AccessKeys[i].Uses--
|
network.AccessKeys[i].Uses--
|
||||||
if group.AccessKeys[i].Uses < 1 {
|
if network.AccessKeys[i].Uses < 1 {
|
||||||
//this is the part where it will call the delete
|
//this is the part where it will call the delete
|
||||||
//not sure if there's edge cases I'm missing
|
//not sure if there's edge cases I'm missing
|
||||||
DeleteKey(group, i)
|
DeleteKey(network, i)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"nameid": group.NameID}
|
filter := bson.M{"netid": network.NetID}
|
||||||
|
|
||||||
update := bson.D{
|
update := bson.D{
|
||||||
{"$set", bson.D{
|
{"$set", bson.D{
|
||||||
{"accesskeys", group.AccessKeys},
|
{"accesskeys", network.AccessKeys},
|
||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
@@ -636,26 +636,26 @@ func DecrimentKey(groupName string, keyvalue string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
//takes the logic from controllers.deleteKey
|
//takes the logic from controllers.deleteKey
|
||||||
func DeleteKey(group models.Group, i int) {
|
func DeleteKey(network models.Network, i int) {
|
||||||
|
|
||||||
group.AccessKeys = append(group.AccessKeys[:i],
|
network.AccessKeys = append(network.AccessKeys[:i],
|
||||||
group.AccessKeys[i+1:]...)
|
network.AccessKeys[i+1:]...)
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
// Create filter
|
// Create filter
|
||||||
filter := bson.M{"nameid": group.NameID}
|
filter := bson.M{"netid": network.NetID}
|
||||||
|
|
||||||
// prepare update model.
|
// prepare update model.
|
||||||
update := bson.D{
|
update := bson.D{
|
||||||
{"$set", bson.D{
|
{"$set", bson.D{
|
||||||
{"accesskeys", group.AccessKeys},
|
{"accesskeys", network.AccessKeys},
|
||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
|
|
||||||
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
|
@@ -10,11 +10,11 @@ import (
|
|||||||
var jwtSecretKey = []byte("(BytesOverTheWire)")
|
var jwtSecretKey = []byte("(BytesOverTheWire)")
|
||||||
|
|
||||||
// CreateJWT func will used to create the JWT while signing in and signing out
|
// CreateJWT func will used to create the JWT while signing in and signing out
|
||||||
func CreateJWT(macaddress string, group string) (response string, err error) {
|
func CreateJWT(macaddress string, network string) (response string, err error) {
|
||||||
expirationTime := time.Now().Add(5 * time.Minute)
|
expirationTime := time.Now().Add(5 * time.Minute)
|
||||||
claims := &models.Claims{
|
claims := &models.Claims{
|
||||||
MacAddress: macaddress,
|
MacAddress: macaddress,
|
||||||
Group: group,
|
Network: network,
|
||||||
StandardClaims: jwt.StandardClaims{
|
StandardClaims: jwt.StandardClaims{
|
||||||
ExpiresAt: expirationTime.Unix(),
|
ExpiresAt: expirationTime.Unix(),
|
||||||
},
|
},
|
||||||
@@ -61,7 +61,7 @@ func VerifyUserToken(tokenString string) (username string, isadmin bool, err err
|
|||||||
}
|
}
|
||||||
|
|
||||||
// VerifyToken func will used to Verify the JWT Token while using APIS
|
// VerifyToken func will used to Verify the JWT Token while using APIS
|
||||||
func VerifyToken(tokenString string) (macaddress string, group string, err error) {
|
func VerifyToken(tokenString string) (macaddress string, network string, err error) {
|
||||||
claims := &models.Claims{}
|
claims := &models.Claims{}
|
||||||
|
|
||||||
//this may be a stupid way of serving up a master key
|
//this may be a stupid way of serving up a master key
|
||||||
@@ -75,7 +75,7 @@ func VerifyToken(tokenString string) (macaddress string, group string, err error
|
|||||||
})
|
})
|
||||||
|
|
||||||
if token != nil {
|
if token != nil {
|
||||||
return claims.MacAddress, claims.Group, nil
|
return claims.MacAddress, claims.Network, nil
|
||||||
}
|
}
|
||||||
return "", "", err
|
return "", "", err
|
||||||
}
|
}
|
||||||
|
344
group_test.go
344
group_test.go
@@ -11,19 +11,19 @@ import (
|
|||||||
"go.mongodb.org/mongo-driver/mongo"
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Groups []models.Group
|
var Networks []models.Network
|
||||||
|
|
||||||
func TestCreateGroup(t *testing.T) {
|
func TestCreateNetwork(t *testing.T) {
|
||||||
group := models.Group{}
|
network := models.Network{}
|
||||||
group.NameID = "skynet"
|
network.NetID = "skynet"
|
||||||
group.AddressRange = "10.71.0.0/16"
|
network.AddressRange = "10.71.0.0/16"
|
||||||
t.Run("CreateGroup", func(t *testing.T) {
|
t.Run("CreateNetwork", func(t *testing.T) {
|
||||||
response, err := api(t, group, http.MethodPost, "http://localhost:8081/api/groups", "secretkey")
|
response, err := api(t, network, http.MethodPost, "http://localhost:8081/api/networks", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("InvalidToken", func(t *testing.T) {
|
t.Run("InvalidToken", func(t *testing.T) {
|
||||||
response, err := api(t, group, http.MethodPost, "http://localhost:8081/api/groups", "badkey")
|
response, err := api(t, network, http.MethodPost, "http://localhost:8081/api/networks", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -41,23 +41,23 @@ func TestCreateGroup(t *testing.T) {
|
|||||||
//issue #42
|
//issue #42
|
||||||
t.Skip()
|
t.Skip()
|
||||||
})
|
})
|
||||||
t.Run("DuplicateGroup", func(t *testing.T) {
|
t.Run("DuplicateNetwork", func(t *testing.T) {
|
||||||
//issue #42
|
//issue #42
|
||||||
t.Skip()
|
t.Skip()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetGroups(t *testing.T) {
|
func TestGetNetworks(t *testing.T) {
|
||||||
t.Run("ValidToken", func(t *testing.T) {
|
t.Run("ValidToken", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
err = json.NewDecoder(response.Body).Decode(&Groups)
|
err = json.NewDecoder(response.Body).Decode(&Networks)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
})
|
})
|
||||||
t.Run("InvalidToken", func(t *testing.T) {
|
t.Run("InvalidToken", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "badkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
@@ -69,19 +69,19 @@ func TestGetGroups(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetGroup(t *testing.T) {
|
func TestGetNetwork(t *testing.T) {
|
||||||
t.Run("ValidToken", func(t *testing.T) {
|
t.Run("ValidToken", func(t *testing.T) {
|
||||||
var group models.Group
|
var network models.Network
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
err = json.NewDecoder(response.Body).Decode(&group)
|
err = json.NewDecoder(response.Body).Decode(&network)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "skynet", group.DisplayName)
|
assert.Equal(t, "skynet", network.DisplayName)
|
||||||
})
|
})
|
||||||
t.Run("InvalidToken", func(t *testing.T) {
|
t.Run("InvalidToken", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet", "badkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
@@ -91,31 +91,31 @@ func TestGetGroup(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||||
})
|
})
|
||||||
t.Run("InvalidGroup", func(t *testing.T) {
|
t.Run("InvalidNetwork", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetGroupNodeNumber(t *testing.T) {
|
func TestGetNetworkNodeNumber(t *testing.T) {
|
||||||
t.Run("ValidKey", func(t *testing.T) {
|
t.Run("ValidKey", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/numnodes", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/numnodes", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message int
|
var message int
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
//assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
//assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("InvalidKey", func(t *testing.T) {
|
t.Run("InvalidKey", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/numnodes", "badkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/numnodes", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
@@ -125,21 +125,21 @@ func TestGetGroupNodeNumber(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||||
})
|
})
|
||||||
t.Run("BadGroup", func(t *testing.T) {
|
t.Run("BadNetwork", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup/numnodes", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork/numnodes", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDeleteGroup(t *testing.T) {
|
func TestDeleteNetwork(t *testing.T) {
|
||||||
t.Run("InvalidKey", func(t *testing.T) {
|
t.Run("InvalidKey", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet", "badkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
@@ -150,7 +150,7 @@ func TestDeleteGroup(t *testing.T) {
|
|||||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||||
})
|
})
|
||||||
t.Run("ValidKey", func(t *testing.T) {
|
t.Run("ValidKey", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message mongo.DeleteResult
|
var message mongo.DeleteResult
|
||||||
@@ -160,21 +160,21 @@ func TestDeleteGroup(t *testing.T) {
|
|||||||
assert.Equal(t, int64(1), message.DeletedCount)
|
assert.Equal(t, int64(1), message.DeletedCount)
|
||||||
|
|
||||||
})
|
})
|
||||||
t.Run("BadGroup", func(t *testing.T) {
|
t.Run("BadNetwork", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("NodesExist", func(t *testing.T) {
|
t.Run("NodesExist", func(t *testing.T) {
|
||||||
t.Skip()
|
t.Skip()
|
||||||
})
|
})
|
||||||
//Create Group for follow-on tests
|
//Create Network for follow-on tests
|
||||||
createGroup(t)
|
createNetwork(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCreateAccessKey(t *testing.T) {
|
func TestCreateAccessKey(t *testing.T) {
|
||||||
@@ -182,7 +182,7 @@ func TestCreateAccessKey(t *testing.T) {
|
|||||||
key.Name = "skynet"
|
key.Name = "skynet"
|
||||||
key.Uses = 10
|
key.Uses = 10
|
||||||
t.Run("MultiUse", func(t *testing.T) {
|
t.Run("MultiUse", func(t *testing.T) {
|
||||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -197,7 +197,7 @@ func TestCreateAccessKey(t *testing.T) {
|
|||||||
t.Run("ZeroUse", func(t *testing.T) {
|
t.Run("ZeroUse", func(t *testing.T) {
|
||||||
//t.Skip()
|
//t.Skip()
|
||||||
key.Uses = 0
|
key.Uses = 0
|
||||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -211,14 +211,14 @@ func TestCreateAccessKey(t *testing.T) {
|
|||||||
t.Run("DuplicateAccessKey", func(t *testing.T) {
|
t.Run("DuplicateAccessKey", func(t *testing.T) {
|
||||||
//t.Skip()
|
//t.Skip()
|
||||||
//this will fail
|
//this will fail
|
||||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
deleteKey(t, key.Name, "skynet")
|
deleteKey(t, key.Name, "skynet")
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("InvalidToken", func(t *testing.T) {
|
t.Run("InvalidToken", func(t *testing.T) {
|
||||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "badkey")
|
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -228,14 +228,14 @@ func TestCreateAccessKey(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||||
})
|
})
|
||||||
t.Run("BadGroup", func(t *testing.T) {
|
t.Run("BadNetwork", func(t *testing.T) {
|
||||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/badgroup/keys", "secretkey")
|
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/badnetwork/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -243,7 +243,7 @@ func TestCreateAccessKey(t *testing.T) {
|
|||||||
func TestDeleteKey(t *testing.T) {
|
func TestDeleteKey(t *testing.T) {
|
||||||
t.Run("KeyValid", func(t *testing.T) {
|
t.Run("KeyValid", func(t *testing.T) {
|
||||||
//fails -- deletecount not returned
|
//fails -- deletecount not returned
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/skynet", "secretkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message mongo.DeleteResult
|
var message mongo.DeleteResult
|
||||||
@@ -254,7 +254,7 @@ func TestDeleteKey(t *testing.T) {
|
|||||||
})
|
})
|
||||||
t.Run("InValidKey", func(t *testing.T) {
|
t.Run("InValidKey", func(t *testing.T) {
|
||||||
//fails -- status message not returned
|
//fails -- status message not returned
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/badkey", "secretkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/badkey", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
@@ -263,18 +263,18 @@ func TestDeleteKey(t *testing.T) {
|
|||||||
assert.Equal(t, "W1R3: This key does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This key does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("KeyInValidGroup", func(t *testing.T) {
|
t.Run("KeyInValidNetwork", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/badgroup/keys/skynet", "secretkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/badnetwork/keys/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("InvalidCredentials", func(t *testing.T) {
|
t.Run("InvalidCredentials", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/skynet", "badkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/skynet", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -289,7 +289,7 @@ func TestDeleteKey(t *testing.T) {
|
|||||||
func TestGetKeys(t *testing.T) {
|
func TestGetKeys(t *testing.T) {
|
||||||
createKey(t)
|
createKey(t)
|
||||||
t.Run("Valid", func(t *testing.T) {
|
t.Run("Valid", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -298,18 +298,18 @@ func TestGetKeys(t *testing.T) {
|
|||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
})
|
})
|
||||||
//deletekeys
|
//deletekeys
|
||||||
t.Run("InvalidGroup", func(t *testing.T) {
|
t.Run("InvalidNetwork", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup/keys", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("InvalidCredentials", func(t *testing.T) {
|
t.Run("InvalidCredentials", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/keys", "badkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/keys", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -321,29 +321,29 @@ func TestGetKeys(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestUpdateGroup(t *testing.T) {
|
func TestUpdateNetwork(t *testing.T) {
|
||||||
var returnedGroup models.Group
|
var returnedNetwork models.Network
|
||||||
t.Run("UpdateNameID", func(t *testing.T) {
|
t.Run("UpdateNetID", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
NameID string
|
NetID string
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.NameID = "wirecat"
|
network.NetID = "wirecat"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.NameID, returnedGroup.NameID)
|
assert.Equal(t, network.NetID, returnedNetwork.NetID)
|
||||||
})
|
})
|
||||||
t.Run("NameIDInvalidCredentials", func(t *testing.T) {
|
t.Run("NetIDInvalidCredentials", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
NameID string
|
NetID string
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.NameID = "wirecat"
|
network.NetID = "wirecat"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "badkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
@@ -352,83 +352,83 @@ func TestUpdateGroup(t *testing.T) {
|
|||||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("InvalidGroup", func(t *testing.T) {
|
t.Run("InvalidNetwork", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
NameID string
|
NetID string
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.NameID = "wirecat"
|
network.NetID = "wirecat"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusNotFound, message.Code)
|
assert.Equal(t, http.StatusNotFound, message.Code)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("UpdateNameIDTooLong", func(t *testing.T) {
|
t.Run("UpdateNetIDTooLong", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
NameID string
|
NetID string
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.NameID = "wirecat-skynet"
|
network.NetID = "wirecat-skynet"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("UpdateAddress", func(t *testing.T) {
|
t.Run("UpdateAddress", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
AddressRange string
|
AddressRange string
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.AddressRange = "10.0.0.1/24"
|
network.AddressRange = "10.0.0.1/24"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.AddressRange, returnedGroup.AddressRange)
|
assert.Equal(t, network.AddressRange, returnedNetwork.AddressRange)
|
||||||
})
|
})
|
||||||
t.Run("UpdateAddressInvalid", func(t *testing.T) {
|
t.Run("UpdateAddressInvalid", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
AddressRange string
|
AddressRange string
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.AddressRange = "10.0.0.1/36"
|
network.AddressRange = "10.0.0.1/36"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("UpdateDisplayName", func(t *testing.T) {
|
t.Run("UpdateDisplayName", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DisplayName string
|
DisplayName string
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.DisplayName = "wirecat"
|
network.DisplayName = "wirecat"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DisplayName, returnedGroup.DisplayName)
|
assert.Equal(t, network.DisplayName, returnedNetwork.DisplayName)
|
||||||
|
|
||||||
})
|
})
|
||||||
t.Run("UpdateDisplayNameInvalidName", func(t *testing.T) {
|
t.Run("UpdateDisplayNameInvalidName", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DisplayName string
|
DisplayName string
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
//create name that is longer than 100 chars
|
//create name that is longer than 100 chars
|
||||||
name := ""
|
name := ""
|
||||||
for i := 0; i < 101; i++ {
|
for i := 0; i < 101; i++ {
|
||||||
name = name + "a"
|
name = name + "a"
|
||||||
}
|
}
|
||||||
group.DisplayName = name
|
network.DisplayName = name
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
@@ -438,41 +438,41 @@ func TestUpdateGroup(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("UpdateInterface", func(t *testing.T) {
|
t.Run("UpdateInterface", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DefaultInterface string
|
DefaultInterface string
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.DefaultInterface = "netmaker"
|
network.DefaultInterface = "netmaker"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultInterface, returnedGroup.DefaultInterface)
|
assert.Equal(t, network.DefaultInterface, returnedNetwork.DefaultInterface)
|
||||||
|
|
||||||
})
|
})
|
||||||
t.Run("UpdateListenPort", func(t *testing.T) {
|
t.Run("UpdateListenPort", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DefaultListenPort int32
|
DefaultListenPort int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.DefaultListenPort = 6000
|
network.DefaultListenPort = 6000
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultListenPort, returnedGroup.DefaultListenPort)
|
assert.Equal(t, network.DefaultListenPort, returnedNetwork.DefaultListenPort)
|
||||||
})
|
})
|
||||||
t.Run("UpdateListenPortInvalidPort", func(t *testing.T) {
|
t.Run("UpdateListenPortInvalidPort", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DefaultListenPort int32
|
DefaultListenPort int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.DefaultListenPort = 1023
|
network.DefaultListenPort = 1023
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
@@ -482,54 +482,54 @@ func TestUpdateGroup(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("UpdatePostUP", func(t *testing.T) {
|
t.Run("UpdatePostUP", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DefaultPostUp string
|
DefaultPostUp string
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.DefaultPostUp = "sudo wg add-conf wc-netmaker /etc/wireguard/peers/conf"
|
network.DefaultPostUp = "sudo wg add-conf wc-netmaker /etc/wireguard/peers/conf"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultPostUp, returnedGroup.DefaultPostUp)
|
assert.Equal(t, network.DefaultPostUp, returnedNetwork.DefaultPostUp)
|
||||||
})
|
})
|
||||||
t.Run("UpdatePreUP", func(t *testing.T) {
|
t.Run("UpdatePreUP", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DefaultPreUp string
|
DefaultPreUp string
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.DefaultPreUp = "test string"
|
network.DefaultPreUp = "test string"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultPreUp, returnedGroup.DefaultPreUp)
|
assert.Equal(t, network.DefaultPreUp, returnedNetwork.DefaultPreUp)
|
||||||
})
|
})
|
||||||
t.Run("UpdateKeepAlive", func(t *testing.T) {
|
t.Run("UpdateKeepAlive", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DefaultKeepalive int32
|
DefaultKeepalive int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.DefaultKeepalive = 60
|
network.DefaultKeepalive = 60
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultKeepalive, returnedGroup.DefaultKeepalive)
|
assert.Equal(t, network.DefaultKeepalive, returnedNetwork.DefaultKeepalive)
|
||||||
})
|
})
|
||||||
t.Run("UpdateKeepAliveTooBig", func(t *testing.T) {
|
t.Run("UpdateKeepAliveTooBig", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DefaultKeepAlive int32
|
DefaultKeepAlive int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.DefaultKeepAlive = 1001
|
network.DefaultKeepAlive = 1001
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
@@ -541,57 +541,57 @@ func TestUpdateGroup(t *testing.T) {
|
|||||||
t.Run("UpdateSaveConfig", func(t *testing.T) {
|
t.Run("UpdateSaveConfig", func(t *testing.T) {
|
||||||
//causes panic
|
//causes panic
|
||||||
t.Skip()
|
t.Skip()
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DefaultSaveConfig *bool
|
DefaultSaveConfig *bool
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
value := false
|
value := false
|
||||||
group.DefaultSaveConfig = &value
|
network.DefaultSaveConfig = &value
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, *group.DefaultSaveConfig, *returnedGroup.DefaultSaveConfig)
|
assert.Equal(t, *network.DefaultSaveConfig, *returnedNetwork.DefaultSaveConfig)
|
||||||
})
|
})
|
||||||
t.Run("UpdateManualSignUP", func(t *testing.T) {
|
t.Run("UpdateManualSignUP", func(t *testing.T) {
|
||||||
t.Skip()
|
t.Skip()
|
||||||
type Group struct {
|
type Network struct {
|
||||||
AllowManualSignUp *bool
|
AllowManualSignUp *bool
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
value := true
|
value := true
|
||||||
group.AllowManualSignUp = &value
|
network.AllowManualSignUp = &value
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, *group.AllowManualSignUp, *returnedGroup.AllowManualSignUp)
|
assert.Equal(t, *network.AllowManualSignUp, *returnedNetwork.AllowManualSignUp)
|
||||||
})
|
})
|
||||||
t.Run("DefaultCheckInterval", func(t *testing.T) {
|
t.Run("DefaultCheckInterval", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DefaultCheckInInterval int32
|
DefaultCheckInInterval int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.DefaultCheckInInterval = 6000
|
network.DefaultCheckInInterval = 6000
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultCheckInInterval, returnedGroup.DefaultCheckInInterval)
|
assert.Equal(t, network.DefaultCheckInInterval, returnedNetwork.DefaultCheckInInterval)
|
||||||
})
|
})
|
||||||
t.Run("DefaultCheckIntervalTooBig", func(t *testing.T) {
|
t.Run("DefaultCheckIntervalTooBig", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DefaultCheckInInterval int32
|
DefaultCheckInInterval int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.DefaultCheckInInterval = 100001
|
network.DefaultCheckInInterval = 100001
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
@@ -601,20 +601,20 @@ func TestUpdateGroup(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("MultipleFields", func(t *testing.T) {
|
t.Run("MultipleFields", func(t *testing.T) {
|
||||||
type Group struct {
|
type Network struct {
|
||||||
DisplayName string
|
DisplayName string
|
||||||
DefaultListenPort int32
|
DefaultListenPort int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network Network
|
||||||
group.DefaultListenPort = 7777
|
network.DefaultListenPort = 7777
|
||||||
group.DisplayName = "multi"
|
network.DisplayName = "multi"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DisplayName, returnedGroup.DisplayName)
|
assert.Equal(t, network.DisplayName, returnedNetwork.DisplayName)
|
||||||
assert.Equal(t, group.DefaultListenPort, returnedGroup.DefaultListenPort)
|
assert.Equal(t, network.DefaultListenPort, returnedNetwork.DefaultListenPort)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
133
grpc/node.pb.go
133
grpc/node.pb.go
@@ -123,7 +123,7 @@ type Node struct {
|
|||||||
Endpoint string `protobuf:"bytes,6,opt,name=endpoint,proto3" json:"endpoint,omitempty"`
|
Endpoint string `protobuf:"bytes,6,opt,name=endpoint,proto3" json:"endpoint,omitempty"`
|
||||||
Macaddress string `protobuf:"bytes,7,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
Macaddress string `protobuf:"bytes,7,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
||||||
Password string `protobuf:"bytes,8,opt,name=password,proto3" json:"password,omitempty"`
|
Password string `protobuf:"bytes,8,opt,name=password,proto3" json:"password,omitempty"`
|
||||||
Nodegroup string `protobuf:"bytes,9,opt,name=nodegroup,proto3" json:"nodegroup,omitempty"`
|
Nodenetwork string `protobuf:"bytes,9,opt,name=nodenetwork,proto3" json:"nodenetwork,omitempty"`
|
||||||
Ispending bool `protobuf:"varint,10,opt,name=ispending,proto3" json:"ispending,omitempty"`
|
Ispending bool `protobuf:"varint,10,opt,name=ispending,proto3" json:"ispending,omitempty"`
|
||||||
Postup string `protobuf:"bytes,11,opt,name=postup,proto3" json:"postup,omitempty"`
|
Postup string `protobuf:"bytes,11,opt,name=postup,proto3" json:"postup,omitempty"`
|
||||||
Preup string `protobuf:"bytes,12,opt,name=preup,proto3" json:"preup,omitempty"`
|
Preup string `protobuf:"bytes,12,opt,name=preup,proto3" json:"preup,omitempty"`
|
||||||
@@ -222,9 +222,9 @@ func (m *Node) GetPassword() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Node) GetNodegroup() string {
|
func (m *Node) GetNodenetwork() string {
|
||||||
if m != nil {
|
if m != nil {
|
||||||
return m.Nodegroup
|
return m.Nodenetwork
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -637,7 +637,7 @@ func (m *UpdateNodeRes) GetNode() *Node {
|
|||||||
|
|
||||||
type ReadNodeReq struct {
|
type ReadNodeReq struct {
|
||||||
Macaddress string `protobuf:"bytes,1,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
Macaddress string `protobuf:"bytes,1,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
||||||
Group string `protobuf:"bytes,2,opt,name=group,proto3" json:"group,omitempty"`
|
Network string `protobuf:"bytes,2,opt,name=network,proto3" json:"network,omitempty"`
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||||
XXX_unrecognized []byte `json:"-"`
|
XXX_unrecognized []byte `json:"-"`
|
||||||
XXX_sizecache int32 `json:"-"`
|
XXX_sizecache int32 `json:"-"`
|
||||||
@@ -675,9 +675,9 @@ func (m *ReadNodeReq) GetMacaddress() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *ReadNodeReq) GetGroup() string {
|
func (m *ReadNodeReq) GetNetwork() string {
|
||||||
if m != nil {
|
if m != nil {
|
||||||
return m.Group
|
return m.Network
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -723,7 +723,7 @@ func (m *ReadNodeRes) GetNode() *Node {
|
|||||||
|
|
||||||
type DeleteNodeReq struct {
|
type DeleteNodeReq struct {
|
||||||
Macaddress string `protobuf:"bytes,1,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
Macaddress string `protobuf:"bytes,1,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
||||||
GroupName string `protobuf:"bytes,2,opt,name=groupName,proto3" json:"groupName,omitempty"`
|
NetworkName string `protobuf:"bytes,2,opt,name=networkName,proto3" json:"networkName,omitempty"`
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||||
XXX_unrecognized []byte `json:"-"`
|
XXX_unrecognized []byte `json:"-"`
|
||||||
XXX_sizecache int32 `json:"-"`
|
XXX_sizecache int32 `json:"-"`
|
||||||
@@ -761,9 +761,9 @@ func (m *DeleteNodeReq) GetMacaddress() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *DeleteNodeReq) GetGroupName() string {
|
func (m *DeleteNodeReq) GetNetworkName() string {
|
||||||
if m != nil {
|
if m != nil {
|
||||||
return m.GroupName
|
return m.NetworkName
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -809,7 +809,7 @@ func (m *DeleteNodeRes) GetSuccess() bool {
|
|||||||
|
|
||||||
type GetPeersReq struct {
|
type GetPeersReq struct {
|
||||||
Macaddress string `protobuf:"bytes,1,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
Macaddress string `protobuf:"bytes,1,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
||||||
Group string `protobuf:"bytes,2,opt,name=group,proto3" json:"group,omitempty"`
|
Network string `protobuf:"bytes,2,opt,name=network,proto3" json:"network,omitempty"`
|
||||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||||
XXX_unrecognized []byte `json:"-"`
|
XXX_unrecognized []byte `json:"-"`
|
||||||
XXX_sizecache int32 `json:"-"`
|
XXX_sizecache int32 `json:"-"`
|
||||||
@@ -847,9 +847,9 @@ func (m *GetPeersReq) GetMacaddress() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *GetPeersReq) GetGroup() string {
|
func (m *GetPeersReq) GetNetwork() string {
|
||||||
if m != nil {
|
if m != nil {
|
||||||
return m.Group
|
return m.Network
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -994,59 +994,58 @@ func init() {
|
|||||||
func init() { proto.RegisterFile("grpc/node.proto", fileDescriptor_d13bd996b67da4ef) }
|
func init() { proto.RegisterFile("grpc/node.proto", fileDescriptor_d13bd996b67da4ef) }
|
||||||
|
|
||||||
var fileDescriptor_d13bd996b67da4ef = []byte{
|
var fileDescriptor_d13bd996b67da4ef = []byte{
|
||||||
// 850 bytes of a gzipped FileDescriptorProto
|
// 847 bytes of a gzipped FileDescriptorProto
|
||||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x56, 0xdd, 0x6a, 0xe3, 0x46,
|
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x96, 0xdd, 0x6e, 0xe3, 0x44,
|
||||||
0x14, 0xc6, 0x5e, 0x3b, 0x96, 0x8f, 0xe3, 0x24, 0x3b, 0xc9, 0x96, 0x41, 0x84, 0x10, 0x44, 0x29,
|
0x14, 0xc7, 0x95, 0x6c, 0xd2, 0xb8, 0x27, 0x4d, 0xdb, 0x9d, 0xee, 0xa2, 0x91, 0x85, 0xaa, 0xc8,
|
||||||
0xd9, 0xd2, 0xc4, 0x69, 0x0a, 0xa5, 0x77, 0x85, 0xa6, 0x50, 0x0a, 0xed, 0x52, 0x54, 0x7a, 0xd3,
|
0x42, 0xa8, 0x8b, 0x68, 0x53, 0x8a, 0x84, 0xb8, 0x43, 0x62, 0x91, 0x56, 0x48, 0xb0, 0x02, 0x23,
|
||||||
0xbb, 0x89, 0xe6, 0x44, 0x2b, 0xac, 0xcc, 0x8c, 0x35, 0x92, 0x43, 0x1e, 0xa0, 0x8f, 0xd6, 0x37,
|
0x6e, 0xb8, 0x9b, 0x7a, 0x4e, 0xbd, 0x56, 0x9c, 0x99, 0xa9, 0xc7, 0x49, 0xd5, 0x07, 0xe0, 0xd1,
|
||||||
0xea, 0x65, 0x2f, 0xca, 0xfc, 0xc8, 0xfa, 0x89, 0x9b, 0x64, 0x73, 0xe7, 0xf3, 0xcd, 0xf9, 0x3f,
|
0x78, 0x27, 0x2e, 0xb8, 0x40, 0xf3, 0xe1, 0x78, 0xec, 0x86, 0x76, 0xd9, 0xbd, 0xcb, 0xfc, 0xe6,
|
||||||
0xdf, 0x39, 0x16, 0xec, 0xa7, 0x85, 0x4a, 0x16, 0x42, 0x72, 0xbc, 0x50, 0x85, 0x2c, 0x25, 0x19,
|
0x7c, 0xcc, 0x39, 0xf3, 0x9f, 0x13, 0xc3, 0x51, 0x5e, 0xa9, 0x6c, 0x21, 0x24, 0xc7, 0x0b, 0x55,
|
||||||
0x99, 0xdf, 0x11, 0x87, 0xdd, 0x5f, 0x64, 0x9a, 0x89, 0x18, 0x57, 0x15, 0xea, 0x92, 0x9c, 0x00,
|
0xc9, 0x5a, 0x92, 0x91, 0xf9, 0x9d, 0x70, 0x38, 0xf8, 0x49, 0xe6, 0x85, 0x48, 0xf1, 0x76, 0x8d,
|
||||||
0xdc, 0xb1, 0x84, 0x71, 0x5e, 0xa0, 0xd6, 0x74, 0x70, 0x3a, 0x38, 0x9b, 0xc6, 0x2d, 0x84, 0x84,
|
0xba, 0x26, 0xa7, 0x00, 0x2b, 0x96, 0x31, 0xce, 0x2b, 0xd4, 0x9a, 0x0e, 0xe6, 0x83, 0xb3, 0xfd,
|
||||||
0x10, 0x28, 0xa6, 0xf5, 0xbd, 0x2c, 0x38, 0x1d, 0xda, 0xd7, 0x8d, 0x4c, 0x28, 0x4c, 0x04, 0x96,
|
0x34, 0x20, 0x24, 0x86, 0x48, 0x31, 0xad, 0xef, 0x64, 0xc5, 0xe9, 0xd0, 0xee, 0x6e, 0xd7, 0x84,
|
||||||
0xf7, 0xb2, 0x58, 0xd2, 0x37, 0xf6, 0xa9, 0x16, 0xa3, 0xaf, 0x61, 0xee, 0xa3, 0x68, 0x25, 0x85,
|
0xc2, 0x44, 0x60, 0x7d, 0x27, 0xab, 0x25, 0x7d, 0x66, 0xb7, 0x9a, 0x65, 0xf2, 0x15, 0xcc, 0x7c,
|
||||||
0x46, 0x72, 0x0a, 0x33, 0x96, 0x24, 0xa8, 0x75, 0x29, 0x97, 0x28, 0x7c, 0x9c, 0x36, 0x14, 0xfd,
|
0x16, 0xad, 0xa4, 0xd0, 0x48, 0xe6, 0x30, 0x65, 0x59, 0x86, 0x5a, 0xd7, 0x72, 0x89, 0xc2, 0xe7,
|
||||||
0x33, 0x82, 0xd1, 0x07, 0xc9, 0x91, 0xec, 0xc1, 0x30, 0xe3, 0x5e, 0x63, 0x98, 0x71, 0x42, 0x60,
|
0x09, 0x51, 0xf2, 0xf7, 0x08, 0x46, 0x6f, 0x25, 0x47, 0x72, 0x08, 0xc3, 0x82, 0x7b, 0x8b, 0x61,
|
||||||
0x24, 0xd8, 0x1d, 0xfa, 0xe8, 0xf6, 0xb7, 0x89, 0x5c, 0xa7, 0xec, 0x23, 0xd7, 0xf9, 0x9e, 0x00,
|
0xc1, 0x09, 0x81, 0x91, 0x60, 0x2b, 0xf4, 0xd9, 0xed, 0x6f, 0x93, 0xb9, 0x39, 0xb2, 0xcf, 0xdc,
|
||||||
0xe4, 0x99, 0x2e, 0x51, 0x28, 0x59, 0x94, 0x74, 0x74, 0x3a, 0x38, 0x1b, 0xc7, 0x2d, 0x84, 0x1c,
|
0x9c, 0xf7, 0x14, 0xa0, 0x2c, 0x74, 0x8d, 0x42, 0xc9, 0xaa, 0xa6, 0xa3, 0xf9, 0xe0, 0x6c, 0x9c,
|
||||||
0xc3, 0x54, 0x55, 0x37, 0x79, 0x96, 0x2c, 0xf1, 0x81, 0x8e, 0xad, 0x6d, 0x03, 0x98, 0x6a, 0x51,
|
0x06, 0x84, 0x7c, 0x0a, 0xfb, 0x6a, 0x7d, 0x5d, 0x16, 0xd9, 0x12, 0xef, 0xe9, 0xd8, 0xfa, 0xb6,
|
||||||
0x70, 0x25, 0x33, 0x51, 0xd2, 0x1d, 0x57, 0x6d, 0x2d, 0xf7, 0x3a, 0x35, 0x79, 0xb2, 0x53, 0x41,
|
0xc0, 0x54, 0x8b, 0x82, 0x2b, 0x59, 0x88, 0x9a, 0xee, 0xb9, 0x6a, 0x9b, 0x75, 0xaf, 0x53, 0x93,
|
||||||
0xaf, 0x53, 0xc7, 0x30, 0x35, 0xdd, 0x4f, 0x0b, 0x59, 0x29, 0x3a, 0x75, 0x51, 0x37, 0x80, 0x79,
|
0x47, 0x3b, 0x15, 0xf5, 0x3a, 0x35, 0x87, 0xa9, 0xe9, 0x7e, 0xd3, 0xad, 0x7d, 0x57, 0x7e, 0x80,
|
||||||
0xcd, 0xb4, 0x42, 0xc1, 0x33, 0x91, 0x52, 0x38, 0x1d, 0x9c, 0x05, 0x71, 0x03, 0x90, 0xcf, 0x60,
|
0xcc, 0xb9, 0x0a, 0xad, 0x50, 0xf0, 0x42, 0xe4, 0x14, 0xe6, 0x83, 0xb3, 0x28, 0x6d, 0x01, 0xf9,
|
||||||
0x47, 0x49, 0x5d, 0x56, 0x8a, 0xce, 0xac, 0xa1, 0x97, 0xc8, 0x11, 0x8c, 0x55, 0x81, 0x95, 0xa2,
|
0x04, 0xf6, 0x94, 0xd4, 0xf5, 0x5a, 0xd1, 0xa9, 0x75, 0xf5, 0x2b, 0xf2, 0x02, 0xc6, 0xaa, 0xc2,
|
||||||
0xbb, 0x16, 0x76, 0x82, 0xf1, 0xb5, 0x44, 0x54, 0x2c, 0xcf, 0xd6, 0x48, 0xe7, 0xb6, 0xfc, 0x06,
|
0xb5, 0xa2, 0x07, 0x16, 0xbb, 0x85, 0x89, 0xb5, 0x44, 0x54, 0xac, 0x2c, 0x36, 0x48, 0x67, 0xb6,
|
||||||
0x30, 0x35, 0x68, 0xb6, 0xc6, 0x44, 0x8a, 0xdb, 0x2c, 0xa5, 0x7b, 0x36, 0x54, 0x0b, 0x31, 0xd6,
|
0x05, 0x2d, 0x30, 0x75, 0x68, 0xb6, 0xc1, 0x4c, 0x8a, 0x9b, 0x22, 0xa7, 0x87, 0x36, 0x55, 0x40,
|
||||||
0x6e, 0x26, 0xa6, 0x3b, 0xfb, 0x2e, 0xcf, 0x0d, 0x60, 0xf3, 0x14, 0x25, 0x16, 0xb7, 0x2c, 0x41,
|
0x8c, 0xb7, 0xbb, 0x17, 0xd3, 0xa1, 0x23, 0xd7, 0xa1, 0x2d, 0xb0, 0xe7, 0x14, 0x35, 0x56, 0x37,
|
||||||
0x7a, 0xe0, 0x5e, 0x37, 0x80, 0x19, 0x71, 0xce, 0x74, 0x99, 0x7c, 0xc4, 0x64, 0x99, 0x09, 0xfa,
|
0x2c, 0x43, 0x7a, 0xec, 0x76, 0xb7, 0xc0, 0xd4, 0x59, 0x32, 0x5d, 0x67, 0xef, 0x30, 0x5b, 0x16,
|
||||||
0xd6, 0x8d, 0xb8, 0x05, 0x91, 0x08, 0x76, 0x8d, 0x78, 0x27, 0x79, 0x76, 0x9b, 0x21, 0xa7, 0xc4,
|
0x82, 0x3e, 0x77, 0x75, 0x06, 0x88, 0x24, 0x70, 0x60, 0x96, 0x2b, 0xc9, 0x8b, 0x9b, 0x02, 0x39,
|
||||||
0xaa, 0x74, 0x30, 0x72, 0x06, 0xfb, 0x5e, 0xdd, 0x7a, 0x5e, 0xb3, 0x9c, 0x1e, 0xda, 0x2a, 0xfa,
|
0x25, 0xd6, 0xa4, 0xc3, 0xc8, 0x19, 0x1c, 0x79, 0x73, 0x1b, 0x79, 0xc3, 0x4a, 0x7a, 0x62, 0xab,
|
||||||
0xb0, 0xf5, 0x26, 0x13, 0x96, 0xd7, 0x13, 0x39, 0xf2, 0xde, 0x5a, 0x98, 0xc9, 0xc9, 0x74, 0x2b,
|
0xe8, 0x63, 0x1b, 0x4d, 0x66, 0xac, 0x6c, 0x6e, 0xe5, 0x85, 0x8f, 0x16, 0x30, 0x73, 0x26, 0xd3,
|
||||||
0xf9, 0xc8, 0x44, 0x8a, 0x9a, 0xbe, 0x73, 0x39, 0xb5, 0xa0, 0xe8, 0xaf, 0x21, 0xec, 0x5f, 0x1b,
|
0xad, 0xec, 0x1d, 0x13, 0x39, 0x6a, 0xfa, 0xd2, 0x9d, 0x29, 0x40, 0xc9, 0x9f, 0x43, 0x38, 0x7a,
|
||||||
0xcf, 0x3f, 0x37, 0x64, 0xa5, 0x30, 0xd1, 0x95, 0xad, 0xda, 0xd2, 0x30, 0x88, 0x6b, 0x91, 0x7c,
|
0x6d, 0x22, 0xff, 0xd8, 0x0a, 0x96, 0xc2, 0x44, 0xaf, 0x6d, 0xd5, 0x56, 0x8a, 0x51, 0xda, 0x2c,
|
||||||
0x01, 0x7b, 0x02, 0x91, 0x2b, 0xc4, 0xa2, 0x52, 0x9c, 0x95, 0x8e, 0x95, 0x41, 0xdc, 0x43, 0xc9,
|
0xc9, 0xe7, 0x70, 0x28, 0x10, 0xb9, 0x42, 0xac, 0xd6, 0x8a, 0xb3, 0xda, 0x29, 0x33, 0x4a, 0x7b,
|
||||||
0x97, 0x70, 0x60, 0x10, 0xd7, 0x55, 0xaf, 0xf9, 0xc6, 0x6a, 0x3e, 0xc2, 0x4d, 0x8e, 0x86, 0x0a,
|
0x94, 0x7c, 0x01, 0xc7, 0x86, 0xb8, 0xae, 0x7a, 0xcb, 0x67, 0xd6, 0xf2, 0x01, 0x6f, 0xf4, 0xb1,
|
||||||
0x77, 0xa8, 0x35, 0x4b, 0xd1, 0x52, 0x76, 0x1a, 0xb7, 0xa1, 0x2e, 0x3f, 0xc6, 0x7d, 0x7e, 0x7c,
|
0x42, 0xad, 0x59, 0x8e, 0x56, 0xb6, 0x5e, 0x1f, 0x1e, 0x75, 0xf5, 0x31, 0xee, 0xeb, 0xe3, 0x33,
|
||||||
0x0e, 0x73, 0xe3, 0x73, 0x89, 0x0f, 0x3e, 0xd0, 0x8e, 0xd5, 0xe8, 0x82, 0x66, 0xf2, 0x06, 0xe0,
|
0x98, 0x99, 0x98, 0x4b, 0xbc, 0xf7, 0x89, 0xf6, 0xac, 0x45, 0x17, 0x9a, 0x9b, 0x37, 0x80, 0x63,
|
||||||
0x98, 0x63, 0x89, 0x96, 0xbd, 0x41, 0xdc, 0x42, 0xa2, 0xbf, 0x07, 0x30, 0xff, 0x0d, 0xb1, 0xd0,
|
0x89, 0x35, 0x5a, 0x05, 0x47, 0x69, 0x40, 0x92, 0xbf, 0x06, 0x30, 0xfb, 0x05, 0xb1, 0xd2, 0xdb,
|
||||||
0x9b, 0x2e, 0xbc, 0x7e, 0x53, 0x5e, 0xbf, 0x9d, 0xfd, 0x99, 0x4e, 0xb6, 0xcc, 0xf4, 0x49, 0x86,
|
0x2e, 0x7c, 0xf8, 0x6b, 0xf9, 0xf0, 0x17, 0xda, 0xbf, 0xd3, 0xc9, 0x8e, 0x3b, 0x7d, 0x54, 0xe1,
|
||||||
0x47, 0x0b, 0x98, 0x5f, 0x17, 0xc8, 0x4a, 0x34, 0xb7, 0x24, 0xc6, 0x15, 0x39, 0x01, 0x7b, 0xf8,
|
0xc9, 0x02, 0x66, 0xaf, 0x2b, 0x64, 0x35, 0x9a, 0x79, 0x92, 0xe2, 0x2d, 0x39, 0x05, 0x3b, 0xfc,
|
||||||
0xec, 0x24, 0x67, 0x57, 0x70, 0x61, 0x2f, 0xa2, 0x7d, 0x74, 0x07, 0xb1, 0x67, 0xa0, 0x5f, 0x62,
|
0xec, 0x4d, 0x4e, 0xaf, 0xe0, 0xc2, 0x4e, 0x45, 0xbb, 0xe9, 0x86, 0x62, 0xcf, 0x41, 0xbf, 0x8f,
|
||||||
0xf0, 0x87, 0xed, 0xe9, 0x27, 0x44, 0x68, 0x1b, 0x3c, 0x1f, 0xe1, 0x1a, 0x66, 0x31, 0x32, 0xde,
|
0xc3, 0xef, 0xb6, 0xa7, 0xff, 0x23, 0x43, 0xe8, 0xf0, 0x74, 0x86, 0x37, 0x30, 0x4d, 0x91, 0xf1,
|
||||||
0xf8, 0x7f, 0xfa, 0x44, 0x1f, 0xc1, 0xd8, 0x1d, 0x16, 0x77, 0x21, 0x9d, 0x10, 0x9d, 0xb7, 0x9d,
|
0x36, 0xfe, 0xe3, 0x63, 0x3a, 0x18, 0xc5, 0xc3, 0xee, 0x28, 0x3e, 0x0f, 0x03, 0x3d, 0x9d, 0xf7,
|
||||||
0x3c, 0x1f, 0xf3, 0x57, 0x98, 0xff, 0x68, 0x99, 0xf0, 0xd2, 0xa8, 0xc7, 0x30, 0xb5, 0x81, 0x3e,
|
0x57, 0x98, 0xfd, 0x60, 0xd5, 0xf0, 0xbe, 0x99, 0x8d, 0x74, 0x5d, 0xaa, 0xb7, 0xed, 0x94, 0x0e,
|
||||||
0x34, 0xb7, 0xb9, 0x01, 0xa2, 0xf7, 0x5d, 0x77, 0xfa, 0xff, 0x77, 0xca, 0x54, 0xfb, 0x13, 0x96,
|
0x51, 0xf2, 0xaa, 0x1b, 0x52, 0xff, 0xf7, 0xdb, 0x32, 0x55, 0xbf, 0xc1, 0xda, 0x6b, 0xf0, 0x63,
|
||||||
0x9e, 0x7b, 0xaf, 0xad, 0xf6, 0xbb, 0xb6, 0x13, 0x4d, 0xde, 0xc3, 0xd8, 0x6c, 0xa3, 0xf6, 0xe5,
|
0xaa, 0xfe, 0x36, 0x0c, 0xa4, 0xc9, 0x2b, 0x18, 0x9b, 0x97, 0xa9, 0x7d, 0xd9, 0x27, 0xae, 0xec,
|
||||||
0x1e, 0xba, 0x72, 0x3b, 0xfc, 0x8e, 0x9d, 0x46, 0xf4, 0x15, 0xc0, 0x66, 0xff, 0x57, 0x2f, 0x68,
|
0x8e, 0xd6, 0x53, 0x67, 0x91, 0x7c, 0x09, 0xb0, 0x9d, 0x05, 0x4f, 0xdf, 0xeb, 0xcf, 0x81, 0xb5,
|
||||||
0x53, 0xa3, 0xad, 0xc9, 0xf7, 0x9b, 0x63, 0x55, 0x78, 0xaf, 0xde, 0xf0, 0x9d, 0x33, 0xec, 0x1d,
|
0x26, 0xdf, 0x6d, 0x07, 0x57, 0xe5, 0xa3, 0x7a, 0xc7, 0x97, 0xce, 0xb1, 0x37, 0x64, 0xd2, 0xbe,
|
||||||
0x96, 0xb8, 0xaf, 0x7d, 0xf5, 0xef, 0x10, 0x66, 0xc6, 0xfb, 0xef, 0x58, 0xac, 0xb3, 0x04, 0xc9,
|
0xf5, 0xd5, 0x3f, 0x43, 0x98, 0x9a, 0xe8, 0xbf, 0x61, 0xb5, 0x29, 0x32, 0x24, 0x97, 0x30, 0xb6,
|
||||||
0x25, 0x8c, 0xed, 0xff, 0x26, 0x21, 0xce, 0x41, 0xfb, 0xaf, 0x3a, 0x3c, 0xec, 0x60, 0x7e, 0x4b,
|
0xff, 0xa3, 0x84, 0xb8, 0x00, 0xe1, 0x5f, 0x77, 0x7c, 0xd2, 0x61, 0xfe, 0xc5, 0x7e, 0x03, 0xd0,
|
||||||
0xbf, 0x05, 0x68, 0xe8, 0x4b, 0xbc, 0x4a, 0x67, 0x03, 0xc2, 0x2d, 0xa0, 0x26, 0x97, 0x10, 0xd4,
|
0x4a, 0x99, 0x78, 0x93, 0xce, 0x6b, 0x88, 0x77, 0x40, 0x4d, 0x2e, 0x21, 0x6a, 0x64, 0x42, 0x9e,
|
||||||
0xf4, 0x20, 0x6f, 0x9d, 0x42, 0x8b, 0x73, 0xe1, 0x23, 0x48, 0x9b, 0x48, 0x0d, 0x8d, 0xeb, 0x48,
|
0x3b, 0x83, 0x40, 0x7f, 0xf1, 0x03, 0xa4, 0x4d, 0xa6, 0x56, 0xd2, 0x4d, 0xa6, 0xce, 0xab, 0x88,
|
||||||
0x9d, 0x4d, 0x08, 0xb7, 0x80, 0xd6, 0xae, 0xa1, 0x42, 0x6d, 0xd7, 0xe1, 0x5a, 0xb8, 0x05, 0xd4,
|
0x77, 0x40, 0xeb, 0xd7, 0xca, 0xa1, 0xf1, 0xeb, 0x68, 0x2e, 0xde, 0x01, 0x35, 0xb9, 0x82, 0xa8,
|
||||||
0xe4, 0x0a, 0x82, 0x7a, 0xa4, 0x75, 0x86, 0x2d, 0x9e, 0x84, 0x8f, 0x20, 0x7d, 0x39, 0x20, 0xe7,
|
0xb9, 0xd2, 0xe6, 0x84, 0x81, 0x56, 0xe2, 0x07, 0x48, 0x5f, 0x0e, 0xc8, 0x39, 0x4c, 0x7c, 0xcf,
|
||||||
0x30, 0xf1, 0x3d, 0x27, 0x07, 0xbd, 0x11, 0xac, 0xc2, 0x3e, 0xa2, 0x7f, 0x58, 0xfc, 0x79, 0x9e,
|
0xc9, 0x71, 0xef, 0x0a, 0x6e, 0xe3, 0x3e, 0xd1, 0xdf, 0x2f, 0xfe, 0x38, 0xcf, 0xa5, 0xcc, 0x4b,
|
||||||
0x4a, 0x99, 0xe6, 0x78, 0x91, 0xca, 0x9c, 0x89, 0xf4, 0x42, 0x16, 0xe9, 0xc2, 0x7e, 0x2d, 0xdd,
|
0xbc, 0xc8, 0x65, 0xc9, 0x44, 0x7e, 0x21, 0xab, 0x7c, 0x61, 0xbf, 0x9e, 0xae, 0xd7, 0x37, 0x8b,
|
||||||
0x54, 0xb7, 0x8b, 0xf2, 0x41, 0xa1, 0x5e, 0x2c, 0x85, 0xbc, 0x17, 0xf6, 0x3b, 0x4a, 0xdd, 0xdc,
|
0xfa, 0x5e, 0xa1, 0x5e, 0x2c, 0x85, 0xbc, 0x13, 0xf6, 0xbb, 0x4a, 0x5d, 0x5f, 0xef, 0xd9, 0xcd,
|
||||||
0xec, 0xd8, 0xc7, 0x6f, 0xfe, 0x0b, 0x00, 0x00, 0xff, 0xff, 0x28, 0x40, 0xb5, 0xd0, 0x5d, 0x09,
|
0xaf, 0xff, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x7d, 0x18, 0x12, 0x66, 0x6d, 0x09, 0x00, 0x00,
|
||||||
0x00, 0x00,
|
|
||||||
}
|
}
|
||||||
|
@@ -29,7 +29,7 @@ message Node {
|
|||||||
string endpoint = 6;
|
string endpoint = 6;
|
||||||
string macaddress = 7;
|
string macaddress = 7;
|
||||||
string password = 8;
|
string password = 8;
|
||||||
string nodegroup = 9;
|
string nodenetwork = 9;
|
||||||
bool ispending = 10;
|
bool ispending = 10;
|
||||||
string postup = 11;
|
string postup = 11;
|
||||||
string preup = 12;
|
string preup = 12;
|
||||||
@@ -81,7 +81,7 @@ message UpdateNodeRes {
|
|||||||
|
|
||||||
message ReadNodeReq {
|
message ReadNodeReq {
|
||||||
string macaddress = 1;
|
string macaddress = 1;
|
||||||
string group = 2;
|
string network = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
message ReadNodeRes {
|
message ReadNodeRes {
|
||||||
@@ -90,7 +90,7 @@ message ReadNodeRes {
|
|||||||
|
|
||||||
message DeleteNodeReq {
|
message DeleteNodeReq {
|
||||||
string macaddress = 1;
|
string macaddress = 1;
|
||||||
string groupName = 2;
|
string networkName = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
message DeleteNodeRes {
|
message DeleteNodeRes {
|
||||||
@@ -99,7 +99,7 @@ message DeleteNodeRes {
|
|||||||
|
|
||||||
message GetPeersReq {
|
message GetPeersReq {
|
||||||
string macaddress = 1;
|
string macaddress = 1;
|
||||||
string group = 2;
|
string network = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
message GetPeersRes {
|
message GetPeersRes {
|
||||||
|
79
main.go
79
main.go
@@ -5,6 +5,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
|
"flag"
|
||||||
"github.com/gravitl/netmaker/models"
|
"github.com/gravitl/netmaker/models"
|
||||||
"github.com/gravitl/netmaker/controllers"
|
"github.com/gravitl/netmaker/controllers"
|
||||||
"github.com/gravitl/netmaker/serverctl"
|
"github.com/gravitl/netmaker/serverctl"
|
||||||
@@ -18,8 +19,10 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"net"
|
"net"
|
||||||
"context"
|
"context"
|
||||||
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
service "github.com/gravitl/netmaker/controllers"
|
service "github.com/gravitl/netmaker/controllers"
|
||||||
@@ -32,34 +35,59 @@ var PortGRPC string
|
|||||||
|
|
||||||
//Start MongoDB Connection and start API Request Handler
|
//Start MongoDB Connection and start API Request Handler
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
|
var clientmode string
|
||||||
|
var defaultnet string
|
||||||
|
flag.StringVar(&clientmode, "clientmode", "on", "Have a client on the server")
|
||||||
|
flag.StringVar(&defaultnet, "defaultnet", "on", "Create a default network")
|
||||||
|
flag.Parse()
|
||||||
|
if clientmode == "on" {
|
||||||
|
|
||||||
|
cmd := exec.Command("id", "-u")
|
||||||
|
output, err := cmd.Output()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
i, err := strconv.Atoi(string(output[:len(output)-1]))
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if i != 0 {
|
||||||
|
log.Fatal("To run in client mode requires root privileges. Either turn off client mode with the --clientmode=off flag, or run with sudo.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
log.Println("Server starting...")
|
log.Println("Server starting...")
|
||||||
mongoconn.ConnectDatabase()
|
mongoconn.ConnectDatabase()
|
||||||
installserver := false
|
installserver := false
|
||||||
|
if !(defaultnet == "off") {
|
||||||
if config.Config.Server.CreateDefault {
|
if config.Config.Server.CreateDefault {
|
||||||
created, err := createDefaultNetwork()
|
created, err := createDefaultNetwork()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error creating default network: %v", err)
|
fmt.Printf("Error creating default network: %v", err)
|
||||||
}
|
}
|
||||||
if created {
|
if created && clientmode != "off" {
|
||||||
installserver = true
|
installserver = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
var waitgroup sync.WaitGroup
|
var waitnetwork sync.WaitGroup
|
||||||
|
|
||||||
if config.Config.Server.AgentBackend {
|
if config.Config.Server.AgentBackend {
|
||||||
waitgroup.Add(1)
|
waitnetwork.Add(1)
|
||||||
go runGRPC(&waitgroup, installserver)
|
go runGRPC(&waitnetwork, installserver)
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.Config.Server.RestBackend {
|
if config.Config.Server.RestBackend {
|
||||||
waitgroup.Add(1)
|
waitnetwork.Add(1)
|
||||||
controller.HandleRESTRequests(&waitgroup)
|
controller.HandleRESTRequests(&waitnetwork)
|
||||||
}
|
}
|
||||||
if !config.Config.Server.RestBackend && !config.Config.Server.AgentBackend {
|
if !config.Config.Server.RestBackend && !config.Config.Server.AgentBackend {
|
||||||
fmt.Println("Oops! No Server Mode selected. Nothing being served.")
|
fmt.Println("Oops! No Server Mode selected. Nothing being served.")
|
||||||
}
|
}
|
||||||
waitgroup.Wait()
|
waitnetwork.Wait()
|
||||||
fmt.Println("Exiting now.")
|
fmt.Println("Exiting now.")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,35 +221,38 @@ func setGlobalConfig(globalconf models.GlobalConfig) (error) {
|
|||||||
func createDefaultNetwork() (bool, error) {
|
func createDefaultNetwork() (bool, error) {
|
||||||
|
|
||||||
iscreated := false
|
iscreated := false
|
||||||
exists, err := functions.GroupExists(config.Config.Server.DefaultNetName)
|
exists, err := functions.NetworkExists(config.Config.Server.DefaultNetName)
|
||||||
|
|
||||||
if exists || err != nil {
|
if exists || err != nil {
|
||||||
fmt.Println("Default group already exists")
|
fmt.Println("Default network already exists")
|
||||||
fmt.Println("Skipping default group create")
|
fmt.Println("Skipping default network create")
|
||||||
return iscreated, err
|
return iscreated, err
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
var group models.Group
|
var network models.Network
|
||||||
|
|
||||||
group.NameID = config.Config.Server.DefaultNetName
|
network.NetID = config.Config.Server.DefaultNetName
|
||||||
group.AddressRange = config.Config.Server.DefaultNetRange
|
network.AddressRange = config.Config.Server.DefaultNetRange
|
||||||
group.DisplayName = config.Config.Server.DefaultNetName
|
network.DisplayName = config.Config.Server.DefaultNetName
|
||||||
group.SetDefaults()
|
network.SetDefaults()
|
||||||
group.SetNodesLastModified()
|
network.SetNodesLastModified()
|
||||||
group.SetGroupLastModified()
|
network.SetNetworkLastModified()
|
||||||
group.KeyUpdateTimeStamp = time.Now().Unix()
|
network.KeyUpdateTimeStamp = time.Now().Unix()
|
||||||
|
priv := false
|
||||||
|
network.IsPrivate = &priv
|
||||||
|
network.KeyUpdateTimeStamp = time.Now().Unix()
|
||||||
allow := true
|
allow := true
|
||||||
group.AllowManualSignUp = &allow
|
network.AllowManualSignUp = &allow
|
||||||
|
|
||||||
fmt.Println("Creating default group.")
|
fmt.Println("Creating default network.")
|
||||||
|
|
||||||
|
|
||||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
|
|
||||||
// insert our group into the group table
|
// insert our network into the network table
|
||||||
_, err = collection.InsertOne(ctx, group)
|
_, err = collection.InsertOne(ctx, network)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -6,15 +6,15 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
//Group Struct
|
//Network Struct
|
||||||
//At some point, need to replace all instances of Name with something else like Identifier
|
//At some point, need to replace all instances of Name with something else like Identifier
|
||||||
type Group struct {
|
type Network struct {
|
||||||
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
|
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
|
||||||
AddressRange string `json:"addressrange" bson:"addressrange" validate:"required,addressrange_valid"`
|
AddressRange string `json:"addressrange" bson:"addressrange" validate:"required,addressrange_valid"`
|
||||||
DisplayName string `json:"displayname,omitempty" bson:"displayname,omitempty" validate:"omitempty,displayname_unique,min=1,max=100"`
|
DisplayName string `json:"displayname,omitempty" bson:"displayname,omitempty" validate:"omitempty,displayname_unique,min=1,max=100"`
|
||||||
NameID string `json:"nameid" bson:"nameid" validate:"required,nameid_valid,min=1,max=12"`
|
NetID string `json:"netid" bson:"netid" validate:"required,netid_valid,min=1,max=12"`
|
||||||
NodesLastModified int64 `json:"nodeslastmodified" bson:"nodeslastmodified"`
|
NodesLastModified int64 `json:"nodeslastmodified" bson:"nodeslastmodified"`
|
||||||
GroupLastModified int64 `json:"grouplastmodified" bson:"grouplastmodified"`
|
NetworkLastModified int64 `json:"networklastmodified" bson:"networklastmodified"`
|
||||||
DefaultInterface string `json:"defaulinterface" bson:"defaultinterface"`
|
DefaultInterface string `json:"defaulinterface" bson:"defaultinterface"`
|
||||||
DefaultListenPort int32 `json:"defaultlistenport,omitempty" bson:"defaultlistenport,omitempty" validate:"omitempty,numeric,min=1024,max=65535"`
|
DefaultListenPort int32 `json:"defaultlistenport,omitempty" bson:"defaultlistenport,omitempty" validate:"omitempty,numeric,min=1024,max=65535"`
|
||||||
DefaultPostUp string `json:"defaultpostup" bson:"defaultpostup"`
|
DefaultPostUp string `json:"defaultpostup" bson:"defaultpostup"`
|
||||||
@@ -31,42 +31,42 @@ type Group struct {
|
|||||||
|
|
||||||
//TODO:
|
//TODO:
|
||||||
//Not sure if we need the below two functions. Got rid of one of the calls. May want to revisit
|
//Not sure if we need the below two functions. Got rid of one of the calls. May want to revisit
|
||||||
func(group *Group) SetNodesLastModified(){
|
func(network *Network) SetNodesLastModified(){
|
||||||
group.NodesLastModified = time.Now().Unix()
|
network.NodesLastModified = time.Now().Unix()
|
||||||
}
|
}
|
||||||
|
|
||||||
func(group *Group) SetGroupLastModified(){
|
func(network *Network) SetNetworkLastModified(){
|
||||||
group.GroupLastModified = time.Now().Unix()
|
network.NetworkLastModified = time.Now().Unix()
|
||||||
}
|
}
|
||||||
|
|
||||||
func(group *Group) SetDefaults(){
|
func(network *Network) SetDefaults(){
|
||||||
if group.DisplayName == "" {
|
if network.DisplayName == "" {
|
||||||
group.DisplayName = group.NameID
|
network.DisplayName = network.NetID
|
||||||
}
|
}
|
||||||
if group.DefaultInterface == "" {
|
if network.DefaultInterface == "" {
|
||||||
group.DefaultInterface = "nm-" + group.NameID
|
network.DefaultInterface = "nm-" + network.NetID
|
||||||
}
|
}
|
||||||
if group.DefaultListenPort == 0 {
|
if network.DefaultListenPort == 0 {
|
||||||
group.DefaultListenPort = 51821
|
network.DefaultListenPort = 51821
|
||||||
}
|
}
|
||||||
if group.DefaultPreUp == "" {
|
if network.DefaultPreUp == "" {
|
||||||
|
|
||||||
}
|
}
|
||||||
if group.DefaultSaveConfig == nil {
|
if network.DefaultSaveConfig == nil {
|
||||||
defaultsave := true
|
defaultsave := true
|
||||||
group.DefaultSaveConfig = &defaultsave
|
network.DefaultSaveConfig = &defaultsave
|
||||||
}
|
}
|
||||||
if group.DefaultKeepalive == 0 {
|
if network.DefaultKeepalive == 0 {
|
||||||
group.DefaultKeepalive = 20
|
network.DefaultKeepalive = 20
|
||||||
}
|
}
|
||||||
if group.DefaultPostUp == "" {
|
if network.DefaultPostUp == "" {
|
||||||
}
|
}
|
||||||
//Check-In Interval for Nodes, In Seconds
|
//Check-In Interval for Nodes, In Seconds
|
||||||
if group.DefaultCheckInInterval == 0 {
|
if network.DefaultCheckInInterval == 0 {
|
||||||
group.DefaultCheckInInterval = 30
|
network.DefaultCheckInInterval = 30
|
||||||
}
|
}
|
||||||
if group.AllowManualSignUp == nil {
|
if network.AllowManualSignUp == nil {
|
||||||
signup := false
|
signup := false
|
||||||
group.AllowManualSignUp = &signup
|
network.AllowManualSignUp = &signup
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -26,7 +26,7 @@ type Node struct {
|
|||||||
Endpoint string `json:"endpoint" bson:"endpoint" validate:"endpoint_check"`
|
Endpoint string `json:"endpoint" bson:"endpoint" validate:"endpoint_check"`
|
||||||
PostUp string `json:"postup" bson:"postup"`
|
PostUp string `json:"postup" bson:"postup"`
|
||||||
PreUp string `json:"preup" bson:"preup"`
|
PreUp string `json:"preup" bson:"preup"`
|
||||||
AllowedIPs string `json:"preup" bson:"preup"`
|
AllowedIPs string `json:"allowedips" bson:"allowedips"`
|
||||||
PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive" validate: "omitempty,numeric,max=1000"`
|
PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive" validate: "omitempty,numeric,max=1000"`
|
||||||
SaveConfig *bool `json:"saveconfig" bson:"saveconfig"`
|
SaveConfig *bool `json:"saveconfig" bson:"saveconfig"`
|
||||||
AccessKey string `json:"accesskey" bson:"accesskey"`
|
AccessKey string `json:"accesskey" bson:"accesskey"`
|
||||||
@@ -39,7 +39,7 @@ type Node struct {
|
|||||||
MacAddress string `json:"macaddress" bson:"macaddress" validate:"required,macaddress_valid,macaddress_unique"`
|
MacAddress string `json:"macaddress" bson:"macaddress" validate:"required,macaddress_valid,macaddress_unique"`
|
||||||
CheckInInterval int32 `json:"checkininterval" bson:"checkininterval"`
|
CheckInInterval int32 `json:"checkininterval" bson:"checkininterval"`
|
||||||
Password string `json:"password" bson:"password" validate:"password_check"`
|
Password string `json:"password" bson:"password" validate:"password_check"`
|
||||||
Group string `json:"group" bson:"group" validate:"group_exists"`
|
Network string `json:"network" bson:"network" validate:"network_exists"`
|
||||||
IsPending bool `json:"ispending" bson:"ispending"`
|
IsPending bool `json:"ispending" bson:"ispending"`
|
||||||
IsGateway bool `json:"isgateway" bson:"isgateway"`
|
IsGateway bool `json:"isgateway" bson:"isgateway"`
|
||||||
GatewayRange string `json:"gatewayrange" bson:"gatewayrange"`
|
GatewayRange string `json:"gatewayrange" bson:"gatewayrange"`
|
||||||
@@ -48,27 +48,27 @@ type Node struct {
|
|||||||
|
|
||||||
|
|
||||||
//TODO: Contains a fatal error return. Need to change
|
//TODO: Contains a fatal error return. Need to change
|
||||||
//Used in contexts where it's not the Parent group.
|
//Used in contexts where it's not the Parent network.
|
||||||
func(node *Node) GetGroup() (Group, error){
|
func(node *Node) GetNetwork() (Network, error){
|
||||||
|
|
||||||
var group Group
|
var network Network
|
||||||
|
|
||||||
collection := mongoconn.GroupDB
|
collection := mongoconn.NetworkDB
|
||||||
//collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
//collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
|
||||||
filter := bson.M{"nameid": node.Group}
|
filter := bson.M{"netid": node.Network}
|
||||||
err := collection.FindOne(ctx, filter).Decode(&group)
|
err := collection.FindOne(ctx, filter).Decode(&network)
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
//log.Fatal(err)
|
//log.Fatal(err)
|
||||||
return group, err
|
return network, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return group, err
|
return network, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -103,13 +103,13 @@ func(node *Node) SetDefaultName(){
|
|||||||
//This should exist on the node.go struct. I'm sure there was a reason?
|
//This should exist on the node.go struct. I'm sure there was a reason?
|
||||||
func(node *Node) SetDefaults() {
|
func(node *Node) SetDefaults() {
|
||||||
|
|
||||||
//TODO: Maybe I should make Group a part of the node struct. Then we can just query the Group object for stuff.
|
//TODO: Maybe I should make Network a part of the node struct. Then we can just query the Network object for stuff.
|
||||||
parentGroup, _ := node.GetGroup()
|
parentNetwork, _ := node.GetNetwork()
|
||||||
|
|
||||||
node.ExpirationDateTime = time.Unix(33174902665, 0).Unix()
|
node.ExpirationDateTime = time.Unix(33174902665, 0).Unix()
|
||||||
|
|
||||||
if node.ListenPort == 0 {
|
if node.ListenPort == 0 {
|
||||||
node.ListenPort = parentGroup.DefaultListenPort
|
node.ListenPort = parentNetwork.DefaultListenPort
|
||||||
}
|
}
|
||||||
if node.PreUp == "" {
|
if node.PreUp == "" {
|
||||||
//Empty because we dont set it
|
//Empty because we dont set it
|
||||||
@@ -118,20 +118,20 @@ func(node *Node) SetDefaults() {
|
|||||||
//TODO: This is dumb and doesn't work
|
//TODO: This is dumb and doesn't work
|
||||||
//Need to change
|
//Need to change
|
||||||
if node.SaveConfig == nil {
|
if node.SaveConfig == nil {
|
||||||
defaultsave := *parentGroup.DefaultSaveConfig
|
defaultsave := *parentNetwork.DefaultSaveConfig
|
||||||
node.SaveConfig = &defaultsave
|
node.SaveConfig = &defaultsave
|
||||||
}
|
}
|
||||||
if node.Interface == "" {
|
if node.Interface == "" {
|
||||||
node.Interface = parentGroup.DefaultInterface
|
node.Interface = parentNetwork.DefaultInterface
|
||||||
}
|
}
|
||||||
if node.PersistentKeepalive == 0 {
|
if node.PersistentKeepalive == 0 {
|
||||||
node.PersistentKeepalive = parentGroup.DefaultKeepalive
|
node.PersistentKeepalive = parentNetwork.DefaultKeepalive
|
||||||
}
|
}
|
||||||
if node.PostUp == "" {
|
if node.PostUp == "" {
|
||||||
postup := parentGroup.DefaultPostUp
|
postup := parentNetwork.DefaultPostUp
|
||||||
node.PostUp = postup
|
node.PostUp = postup
|
||||||
}
|
}
|
||||||
node.CheckInInterval = parentGroup.DefaultCheckInInterval
|
node.CheckInInterval = parentNetwork.DefaultCheckInInterval
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
//TODO: Either add a returnGroup and returnKey, or delete this
|
//TODO: Either add a returnNetwork and returnKey, or delete this
|
||||||
package models
|
package models
|
||||||
|
|
||||||
type ReturnNode struct {
|
type ReturnNode struct {
|
||||||
@@ -16,7 +16,7 @@ type ReturnNode struct {
|
|||||||
PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive"`
|
PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive"`
|
||||||
SaveConfig *bool `json:"saveconfig" bson:"saveconfig"`
|
SaveConfig *bool `json:"saveconfig" bson:"saveconfig"`
|
||||||
Interface string `json:"interface" bson:"interface"`
|
Interface string `json:"interface" bson:"interface"`
|
||||||
Group string `json:"group" bson:"group"`
|
Network string `json:"network" bson:"network"`
|
||||||
IsPending *bool `json:"ispending" bson:"ispending"`
|
IsPending *bool `json:"ispending" bson:"ispending"`
|
||||||
IsGateway *bool `json:"isgateway" bson:"ispending"`
|
IsGateway *bool `json:"isgateway" bson:"ispending"`
|
||||||
GatewayRange string `json:"gatewayrange" bson:"gatewayrange"`
|
GatewayRange string `json:"gatewayrange" bson:"gatewayrange"`
|
||||||
|
@@ -32,7 +32,7 @@ type SuccessfulUserLoginResponse struct {
|
|||||||
// Claims is a struct that will be encoded to a JWT.
|
// Claims is a struct that will be encoded to a JWT.
|
||||||
// jwt.StandardClaims is an embedded type to provide expiry time
|
// jwt.StandardClaims is an embedded type to provide expiry time
|
||||||
type Claims struct {
|
type Claims struct {
|
||||||
Group string
|
Network string
|
||||||
MacAddress string
|
MacAddress string
|
||||||
jwt.StandardClaims
|
jwt.StandardClaims
|
||||||
}
|
}
|
||||||
@@ -49,7 +49,7 @@ type ErrorResponse struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type NodeAuth struct {
|
type NodeAuth struct {
|
||||||
Group string
|
Network string
|
||||||
Password string
|
Password string
|
||||||
MacAddress string
|
MacAddress string
|
||||||
}
|
}
|
||||||
|
@@ -13,7 +13,7 @@ import (
|
|||||||
|
|
||||||
var Client *mongo.Client
|
var Client *mongo.Client
|
||||||
var NodeDB *mongo.Collection
|
var NodeDB *mongo.Collection
|
||||||
var GroupDB *mongo.Collection
|
var NetworkDB *mongo.Collection
|
||||||
var user string
|
var user string
|
||||||
var pass string
|
var pass string
|
||||||
var host string
|
var host string
|
||||||
@@ -94,7 +94,7 @@ func ConnectDatabase() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
NodeDB = Client.Database("netmaker").Collection("nodes")
|
NodeDB = Client.Database("netmaker").Collection("nodes")
|
||||||
GroupDB = Client.Database("netmaker").Collection("groups")
|
NetworkDB = Client.Database("netmaker").Collection("networks")
|
||||||
|
|
||||||
log.Println("Database Connected.")
|
log.Println("Database Connected.")
|
||||||
}
|
}
|
||||||
|
@@ -26,7 +26,7 @@ type ServerConfig struct {
|
|||||||
type NodeConfig struct {
|
type NodeConfig struct {
|
||||||
Name string `yaml:"name"`
|
Name string `yaml:"name"`
|
||||||
Interface string `yaml:"interface"`
|
Interface string `yaml:"interface"`
|
||||||
Group string `yaml:"group"`
|
Network string `yaml:"network"`
|
||||||
Password string `yaml:"password"`
|
Password string `yaml:"password"`
|
||||||
MacAddress string `yaml:"macaddress"`
|
MacAddress string `yaml:"macaddress"`
|
||||||
LocalAddress string `yaml:"localaddress"`
|
LocalAddress string `yaml:"localaddress"`
|
||||||
|
@@ -73,7 +73,7 @@ func GetFreePort(rangestart int32) (int32, error){
|
|||||||
return portno, err
|
return portno, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func Install(accesskey string, password string, server string, group string, noauto bool, accesstoken string, inputname string) error {
|
func Install(accesskey string, password string, server string, network string, noauto bool, accesstoken string, inputname string) error {
|
||||||
|
|
||||||
tserver := ""
|
tserver := ""
|
||||||
tnetwork := ""
|
tnetwork := ""
|
||||||
@@ -81,9 +81,9 @@ func Install(accesskey string, password string, server string, group string, noa
|
|||||||
trange := ""
|
trange := ""
|
||||||
var localrange *net.IPNet
|
var localrange *net.IPNet
|
||||||
islocal := false
|
islocal := false
|
||||||
if FileExists("/etc/systemd/system/netclient-"+group+".timer") ||
|
if FileExists("/etc/systemd/system/netclient-"+network+".timer") ||
|
||||||
FileExists("/etc/netclient/netconfig-"+group) {
|
FileExists("/etc/netclient/netconfig-"+network) {
|
||||||
err := errors.New("ALREADY_INSTALLED. Netclient appears to already be installed for network " + group + ". To re-install, please remove by executing 'sudo netclient -c remove -n " + group + "'. Then re-run the install command.")
|
err := errors.New("ALREADY_INSTALLED. Netclient appears to already be installed for network " + network + ". To re-install, please remove by executing 'sudo netclient -c remove -n " + network + "'. Then re-run the install command.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,29 +98,32 @@ func Install(accesskey string, password string, server string, group string, noa
|
|||||||
tnetwork = tokenvals[1]
|
tnetwork = tokenvals[1]
|
||||||
tkey = tokenvals[2]
|
tkey = tokenvals[2]
|
||||||
trange = tokenvals[3]
|
trange = tokenvals[3]
|
||||||
if server == "" {
|
printrange := ""
|
||||||
|
if server == "localhost:50051" {
|
||||||
server = tserver
|
server = tserver
|
||||||
}
|
}
|
||||||
if group == "" {
|
if network == "nonetwork" {
|
||||||
group = tnetwork
|
network = tnetwork
|
||||||
}
|
}
|
||||||
if accesskey == "" {
|
if accesskey == "badkey" {
|
||||||
accesskey = tkey
|
accesskey = tkey
|
||||||
}
|
}
|
||||||
if trange != "" {
|
if trange != "" {
|
||||||
islocal = true
|
islocal = true
|
||||||
_, localrange, err = net.ParseCIDR(trange)
|
_, localrange, err = net.ParseCIDR(trange)
|
||||||
|
printrange = localrange.String()
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
trange = "Not a local network. Will use public address for endpoint."
|
printrange = "Not a local network. Will use public address for endpoint."
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println("Decoded values from token:")
|
fmt.Println("Decoded values from token:")
|
||||||
fmt.Println(" Server: " + tserver)
|
fmt.Println(" Server: " + server)
|
||||||
fmt.Println(" Network: " + tnetwork)
|
fmt.Println(" Network: " + network)
|
||||||
fmt.Println(" Key: " + tkey)
|
fmt.Println(" Key: " + accesskey)
|
||||||
fmt.Println(" Local Range: " + localrange.String())
|
fmt.Println(" Local Range: " + printrange)
|
||||||
}
|
}
|
||||||
|
|
||||||
wgclient, err := wgctrl.New()
|
wgclient, err := wgctrl.New()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -128,7 +131,7 @@ func Install(accesskey string, password string, server string, group string, noa
|
|||||||
}
|
}
|
||||||
defer wgclient.Close()
|
defer wgclient.Close()
|
||||||
|
|
||||||
cfg, err := config.ReadConfig(group)
|
cfg, err := config.ReadConfig(network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("No Config Yet. Will Write: %v", err)
|
log.Printf("No Config Yet. Will Write: %v", err)
|
||||||
}
|
}
|
||||||
@@ -153,7 +156,7 @@ func Install(accesskey string, password string, server string, group string, noa
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Println(" AccessKey: " + accesskey)
|
fmt.Println(" AccessKey: " + accesskey)
|
||||||
err = config.WriteServer(server, accesskey, group)
|
err = config.WriteServer(server, accesskey, network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Error encountered while writing Server Config.")
|
fmt.Println("Error encountered while writing Server Config.")
|
||||||
return err
|
return err
|
||||||
@@ -171,15 +174,15 @@ func Install(accesskey string, password string, server string, group string, noa
|
|||||||
}
|
}
|
||||||
fmt.Println(" Password: " + password)
|
fmt.Println(" Password: " + password)
|
||||||
|
|
||||||
if group == "badgroup" {
|
if network == "badnetwork" {
|
||||||
if nodecfg.Group == "" && tnetwork == "" {
|
if nodecfg.Network == "" && tnetwork == "" {
|
||||||
//create error here
|
//create error here
|
||||||
log.Fatal("no group provided")
|
log.Fatal("no network provided")
|
||||||
} else {
|
} else {
|
||||||
group = nodecfg.Group
|
network = nodecfg.Network
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Println(" Group: " + group)
|
fmt.Println(" Network: " + network)
|
||||||
|
|
||||||
var macaddress string
|
var macaddress string
|
||||||
var localaddress string
|
var localaddress string
|
||||||
@@ -338,7 +341,7 @@ func Install(accesskey string, password string, server string, group string, noa
|
|||||||
Password: password,
|
Password: password,
|
||||||
Macaddress: macaddress,
|
Macaddress: macaddress,
|
||||||
Accesskey: accesskey,
|
Accesskey: accesskey,
|
||||||
Nodegroup: group,
|
Nodenetwork: network,
|
||||||
Listenport: listenport,
|
Listenport: listenport,
|
||||||
Keepalive: keepalive,
|
Keepalive: keepalive,
|
||||||
Localaddress: localaddress,
|
Localaddress: localaddress,
|
||||||
@@ -372,7 +375,7 @@ func Install(accesskey string, password string, server string, group string, noa
|
|||||||
fmt.Println("NODE RECIEVED SETTINGS: ")
|
fmt.Println("NODE RECIEVED SETTINGS: ")
|
||||||
fmt.Println(" Password: " + node.Password)
|
fmt.Println(" Password: " + node.Password)
|
||||||
fmt.Println(" WG Address: " + node.Address)
|
fmt.Println(" WG Address: " + node.Address)
|
||||||
fmt.Println(" Group: " + node.Nodegroup)
|
fmt.Println(" Network: " + node.Nodenetwork)
|
||||||
fmt.Println(" Public Endpoint: " + node.Endpoint)
|
fmt.Println(" Public Endpoint: " + node.Endpoint)
|
||||||
fmt.Println(" Local Address: " + node.Localaddress)
|
fmt.Println(" Local Address: " + node.Localaddress)
|
||||||
fmt.Println(" Name: " + node.Name)
|
fmt.Println(" Name: " + node.Name)
|
||||||
@@ -392,19 +395,19 @@ func Install(accesskey string, password string, server string, group string, noa
|
|||||||
fmt.Println("Awaiting approval from Admin before configuring WireGuard.")
|
fmt.Println("Awaiting approval from Admin before configuring WireGuard.")
|
||||||
if !noauto {
|
if !noauto {
|
||||||
fmt.Println("Configuring Netmaker Service.")
|
fmt.Println("Configuring Netmaker Service.")
|
||||||
err = ConfigureSystemD(group)
|
err = ConfigureSystemD(network)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
peers, err := getPeers(node.Macaddress, group, server)
|
peers, err := getPeers(node.Macaddress, network, server)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fmt.Println("retrived peers, setting wireguard config.")
|
fmt.Println("retrived peers, setting wireguard config.")
|
||||||
err = storePrivKey(privkeystring, group)
|
err = storePrivKey(privkeystring, network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -413,7 +416,7 @@ func Install(accesskey string, password string, server string, group string, noa
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !noauto {
|
if !noauto {
|
||||||
err = ConfigureSystemD(group)
|
err = ConfigureSystemD(network)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -450,12 +453,12 @@ func getPublicIP() (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func modConfig(node *nodepb.Node) error{
|
func modConfig(node *nodepb.Node) error{
|
||||||
group := node.Nodegroup
|
network := node.Nodenetwork
|
||||||
if group == "" {
|
if network == "" {
|
||||||
return errors.New("No Group Provided")
|
return errors.New("No Network Provided")
|
||||||
}
|
}
|
||||||
//modconfig := config.Config
|
//modconfig := config.Config
|
||||||
modconfig, err := config.ReadConfig(group)
|
modconfig, err := config.ReadConfig(network)
|
||||||
//modconfig.ReadConfig()
|
//modconfig.ReadConfig()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -467,8 +470,8 @@ func modConfig(node *nodepb.Node) error{
|
|||||||
if node.Interface != ""{
|
if node.Interface != ""{
|
||||||
nodecfg.Interface = node.Interface
|
nodecfg.Interface = node.Interface
|
||||||
}
|
}
|
||||||
if node.Nodegroup != ""{
|
if node.Nodenetwork != ""{
|
||||||
nodecfg.Group = node.Nodegroup
|
nodecfg.Network = node.Nodenetwork
|
||||||
}
|
}
|
||||||
if node.Macaddress != ""{
|
if node.Macaddress != ""{
|
||||||
nodecfg.MacAddress = node.Macaddress
|
nodecfg.MacAddress = node.Macaddress
|
||||||
@@ -498,7 +501,7 @@ func modConfig(node *nodepb.Node) error{
|
|||||||
nodecfg.PostChanges = node.Postchanges
|
nodecfg.PostChanges = node.Postchanges
|
||||||
}
|
}
|
||||||
modconfig.Node = nodecfg
|
modconfig.Node = nodecfg
|
||||||
err = config.Write(modconfig, group)
|
err = config.Write(modconfig, network)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -533,7 +536,7 @@ func initWireguard(node *nodepb.Node, privkey string, peers []wgtypes.PeerConfig
|
|||||||
wgclient, err := wgctrl.New()
|
wgclient, err := wgctrl.New()
|
||||||
//modcfg := config.Config
|
//modcfg := config.Config
|
||||||
//modcfg.ReadConfig()
|
//modcfg.ReadConfig()
|
||||||
modcfg, err := config.ReadConfig(node.Nodegroup)
|
modcfg, err := config.ReadConfig(node.Nodenetwork)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -730,7 +733,7 @@ func setWGConfig(network string) error {
|
|||||||
nodecfg := cfg.Node
|
nodecfg := cfg.Node
|
||||||
node := getNode(network)
|
node := getNode(network)
|
||||||
|
|
||||||
peers, err := getPeers(node.Macaddress, nodecfg.Group, servercfg.Address)
|
peers, err := getPeers(node.Macaddress, nodecfg.Network, servercfg.Address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -915,7 +918,7 @@ func CheckIn(network string) error {
|
|||||||
newinterface := getNode(network).Interface
|
newinterface := getNode(network).Interface
|
||||||
readreq := &nodepb.ReadNodeReq{
|
readreq := &nodepb.ReadNodeReq{
|
||||||
Macaddress: node.Macaddress,
|
Macaddress: node.Macaddress,
|
||||||
Group: node.Nodegroup,
|
Network: node.Nodenetwork,
|
||||||
}
|
}
|
||||||
readres, err := wcclient.ReadNode(ctx, readreq, grpc.Header(&header))
|
readres, err := wcclient.ReadNode(ctx, readreq, grpc.Header(&header))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -942,7 +945,7 @@ func CheckIn(network string) error {
|
|||||||
fmt.Println("Updating config from remote server.")
|
fmt.Println("Updating config from remote server.")
|
||||||
req := &nodepb.ReadNodeReq{
|
req := &nodepb.ReadNodeReq{
|
||||||
Macaddress: node.Macaddress,
|
Macaddress: node.Macaddress,
|
||||||
Group: node.Nodegroup,
|
Network: node.Nodenetwork,
|
||||||
}
|
}
|
||||||
readres, err := wcclient.ReadNode(ctx, req, grpc.Header(&header))
|
readres, err := wcclient.ReadNode(ctx, req, grpc.Header(&header))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1029,11 +1032,11 @@ func CheckIn(network string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func needInterfaceUpdate(ctx context.Context, mac string, group string, iface string) (bool, string, error) {
|
func needInterfaceUpdate(ctx context.Context, mac string, network string, iface string) (bool, string, error) {
|
||||||
var header metadata.MD
|
var header metadata.MD
|
||||||
req := &nodepb.ReadNodeReq{
|
req := &nodepb.ReadNodeReq{
|
||||||
Macaddress: mac,
|
Macaddress: mac,
|
||||||
Group: group,
|
Network: network,
|
||||||
}
|
}
|
||||||
readres, err := wcclient.ReadNode(ctx, req, grpc.Header(&header))
|
readres, err := wcclient.ReadNode(ctx, req, grpc.Header(&header))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1057,7 +1060,7 @@ func getNode(network string) nodepb.Node {
|
|||||||
|
|
||||||
node.Name = nodecfg.Name
|
node.Name = nodecfg.Name
|
||||||
node.Interface = nodecfg.Interface
|
node.Interface = nodecfg.Interface
|
||||||
node.Nodegroup = nodecfg.Group
|
node.Nodenetwork = nodecfg.Network
|
||||||
node.Localaddress = nodecfg.LocalAddress
|
node.Localaddress = nodecfg.LocalAddress
|
||||||
node.Address = nodecfg.WGAddress
|
node.Address = nodecfg.WGAddress
|
||||||
node.Listenport = nodecfg.Port
|
node.Listenport = nodecfg.Port
|
||||||
@@ -1112,7 +1115,7 @@ func Remove(network string) error {
|
|||||||
ctx,
|
ctx,
|
||||||
&nodepb.DeleteNodeReq{
|
&nodepb.DeleteNodeReq{
|
||||||
Macaddress: node.MacAddress,
|
Macaddress: node.MacAddress,
|
||||||
GroupName: node.Group,
|
NetworkName: node.Network,
|
||||||
},
|
},
|
||||||
grpc.Header(&header),
|
grpc.Header(&header),
|
||||||
)
|
)
|
||||||
@@ -1197,13 +1200,13 @@ func DeleteInterface(ifacename string) error{
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func getPeers(macaddress string, group string, server string) ([]wgtypes.PeerConfig, error) {
|
func getPeers(macaddress string, network string, server string) ([]wgtypes.PeerConfig, error) {
|
||||||
//need to implement checkin on server side
|
//need to implement checkin on server side
|
||||||
var peers []wgtypes.PeerConfig
|
var peers []wgtypes.PeerConfig
|
||||||
var wcclient nodepb.NodeServiceClient
|
var wcclient nodepb.NodeServiceClient
|
||||||
cfg, err := config.ReadConfig(group)
|
cfg, err := config.ReadConfig(network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Issue retrieving config for network: " + group + ". Please investigate: %v", err)
|
log.Fatalf("Issue retrieving config for network: " + network + ". Please investigate: %v", err)
|
||||||
}
|
}
|
||||||
nodecfg := cfg.Node
|
nodecfg := cfg.Node
|
||||||
keepalive := nodecfg.KeepAlive
|
keepalive := nodecfg.KeepAlive
|
||||||
@@ -1224,11 +1227,11 @@ func getPeers(macaddress string, group string, server string) ([]wgtypes.PeerCon
|
|||||||
|
|
||||||
req := &nodepb.GetPeersReq{
|
req := &nodepb.GetPeersReq{
|
||||||
Macaddress: macaddress,
|
Macaddress: macaddress,
|
||||||
Group: group,
|
Network: network,
|
||||||
}
|
}
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
fmt.Println("Authenticating with GRPC Server")
|
fmt.Println("Authenticating with GRPC Server")
|
||||||
ctx, err = SetJWT(wcclient, group)
|
ctx, err = SetJWT(wcclient, network)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Failed to authenticate.")
|
fmt.Println("Failed to authenticate.")
|
||||||
return peers, err
|
return peers, err
|
||||||
|
@@ -20,7 +20,7 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var password string
|
var password string
|
||||||
var group string
|
var network string
|
||||||
var server string
|
var server string
|
||||||
var accesskey string
|
var accesskey string
|
||||||
|
|
||||||
@@ -38,7 +38,7 @@ func main() {
|
|||||||
taccesstoken := flag.String("t", "badtoken", "an token generated by the server and used for one-time access (install only)")
|
taccesstoken := flag.String("t", "badtoken", "an token generated by the server and used for one-time access (install only)")
|
||||||
tname := flag.String("name", "noname", "give the node a name at runtime")
|
tname := flag.String("name", "noname", "give the node a name at runtime")
|
||||||
tserver := flag.String("s", "localhost:50051", "The location (including port) of the remote gRPC server.")
|
tserver := flag.String("s", "localhost:50051", "The location (including port) of the remote gRPC server.")
|
||||||
tnetwork := flag.String("n", "nonetwork", "The node group you are attempting to join.")
|
tnetwork := flag.String("n", "nonetwork", "The node network you are attempting to join.")
|
||||||
tnoauto := flag.Bool("na", false, "No auto mode. If true, netmclient will not be installed as a system service and you will have to retrieve updates manually via checkin command.")
|
tnoauto := flag.Bool("na", false, "No auto mode. If true, netmclient will not be installed as a system service and you will have to retrieve updates manually via checkin command.")
|
||||||
tnoforward := flag.Bool("nf", false, "No Forward mode. If true, netclient will not check for IP forwarding. This may break functionality")
|
tnoforward := flag.Bool("nf", false, "No Forward mode. If true, netclient will not check for IP forwarding. This may break functionality")
|
||||||
command := flag.String("c", "required", "The command to run")
|
command := flag.String("c", "required", "The command to run")
|
||||||
@@ -153,7 +153,7 @@ func main() {
|
|||||||
fmt.Println("Required, '-n'. No network provided. Exiting.")
|
fmt.Println("Required, '-n'. No network provided. Exiting.")
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
fmt.Println("Beginning node check in for group " + *tnetwork)
|
fmt.Println("Beginning node check in for network " + *tnetwork)
|
||||||
err := functions.CheckIn(*tnetwork)
|
err := functions.CheckIn(*tnetwork)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Error checking in: ", err)
|
fmt.Println("Error checking in: ", err)
|
||||||
|
@@ -44,9 +44,9 @@ type AuthorizeTestCase struct {
|
|||||||
|
|
||||||
func TestMain(m *testing.M) {
|
func TestMain(m *testing.M) {
|
||||||
mongoconn.ConnectDatabase()
|
mongoconn.ConnectDatabase()
|
||||||
var waitgroup sync.WaitGroup
|
var waitnetwork sync.Waitnetwork
|
||||||
waitgroup.Add(1)
|
waitnetwork.Add(1)
|
||||||
go controller.HandleRESTRequests(&waitgroup)
|
go controller.HandleRESTRequests(&waitnetwork)
|
||||||
//wait for http server to start
|
//wait for http server to start
|
||||||
time.Sleep(time.Second * 1)
|
time.Sleep(time.Second * 1)
|
||||||
os.Exit(m.Run())
|
os.Exit(m.Run())
|
||||||
@@ -117,11 +117,11 @@ func deleteAdmin(t *testing.T) {
|
|||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func createGroup(t *testing.T) {
|
func createnetwork(t *testing.T) {
|
||||||
group := models.Group{}
|
network := models.network{}
|
||||||
group.NameID = "skynet"
|
network.NetID = "skynet"
|
||||||
group.AddressRange = "10.71.0.0/16"
|
network.AddressRange = "10.71.0.0/16"
|
||||||
response, err := api(t, group, http.MethodPost, "http://localhost:8081/api/groups", "secretkey")
|
response, err := api(t, network, http.MethodPost, "http://localhost:8081/api/networks", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
}
|
}
|
||||||
@@ -130,7 +130,7 @@ func createKey(t *testing.T) {
|
|||||||
key := models.AccessKey{}
|
key := models.AccessKey{}
|
||||||
key.Name = "skynet"
|
key.Name = "skynet"
|
||||||
key.Uses = 10
|
key.Uses = 10
|
||||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -140,7 +140,7 @@ func createKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getKey(t *testing.T, name string) models.AccessKey {
|
func getKey(t *testing.T, name string) models.AccessKey {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -155,8 +155,8 @@ func getKey(t *testing.T, name string) models.AccessKey {
|
|||||||
return models.AccessKey{}
|
return models.AccessKey{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func deleteKey(t *testing.T, key, group string) {
|
func deleteKey(t *testing.T, key, network string) {
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/"+group+"/keys/"+key, "secretkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/"+network+"/keys/"+key, "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
//api does not return Deleted Count at this time
|
//api does not return Deleted Count at this time
|
||||||
//defer response.Body.Close()
|
//defer response.Body.Close()
|
||||||
@@ -167,31 +167,31 @@ func deleteKey(t *testing.T, key, group string) {
|
|||||||
//assert.Equal(t, int64(1), message.DeletedCount)
|
//assert.Equal(t, int64(1), message.DeletedCount)
|
||||||
}
|
}
|
||||||
|
|
||||||
func groupExists(t *testing.T) bool {
|
func networkExists(t *testing.T) bool {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
err = json.NewDecoder(response.Body).Decode(&Groups)
|
err = json.NewDecoder(response.Body).Decode(&networks)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
if Groups == nil {
|
if networks == nil {
|
||||||
return false
|
return false
|
||||||
} else {
|
} else {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func deleteGroups(t *testing.T) {
|
func deletenetworks(t *testing.T) {
|
||||||
|
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
err = json.NewDecoder(response.Body).Decode(&Groups)
|
err = json.NewDecoder(response.Body).Decode(&networks)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
for _, group := range Groups {
|
for _, network := range networks {
|
||||||
name := group.DisplayName
|
name := network.DisplayName
|
||||||
_, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/"+name, "secretkey")
|
_, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/"+name, "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -11,20 +11,20 @@ import (
|
|||||||
"go.mongodb.org/mongo-driver/mongo"
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Groups []models.Group
|
var networks []models.network
|
||||||
|
|
||||||
func TestCreateGroup(t *testing.T) {
|
func TestCreatenetwork(t *testing.T) {
|
||||||
group := models.Group{}
|
network := models.network{}
|
||||||
group.NameID = "skynet"
|
network.NetID = "skynet"
|
||||||
group.AddressRange = "10.71.0.0/16"
|
network.AddressRange = "10.71.0.0/16"
|
||||||
deleteGroups(t)
|
deletenetworks(t)
|
||||||
t.Run("CreateGroup", func(t *testing.T) {
|
t.Run("Createnetwork", func(t *testing.T) {
|
||||||
response, err := api(t, group, http.MethodPost, "http://localhost:8081/api/groups", "secretkey")
|
response, err := api(t, network, http.MethodPost, "http://localhost:8081/api/networks", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("InvalidToken", func(t *testing.T) {
|
t.Run("InvalidToken", func(t *testing.T) {
|
||||||
response, err := api(t, group, http.MethodPost, "http://localhost:8081/api/groups", "badkey")
|
response, err := api(t, network, http.MethodPost, "http://localhost:8081/api/networks", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -42,23 +42,23 @@ func TestCreateGroup(t *testing.T) {
|
|||||||
//issue #42
|
//issue #42
|
||||||
t.Skip()
|
t.Skip()
|
||||||
})
|
})
|
||||||
t.Run("DuplicateGroup", func(t *testing.T) {
|
t.Run("Duplicatenetwork", func(t *testing.T) {
|
||||||
//issue #42
|
//issue #42
|
||||||
t.Skip()
|
t.Skip()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetGroups(t *testing.T) {
|
func TestGetnetworks(t *testing.T) {
|
||||||
t.Run("ValidToken", func(t *testing.T) {
|
t.Run("ValidToken", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
err = json.NewDecoder(response.Body).Decode(&Groups)
|
err = json.NewDecoder(response.Body).Decode(&networks)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
})
|
})
|
||||||
t.Run("InvalidToken", func(t *testing.T) {
|
t.Run("InvalidToken", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "badkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
@@ -70,19 +70,19 @@ func TestGetGroups(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetGroup(t *testing.T) {
|
func TestGetnetwork(t *testing.T) {
|
||||||
t.Run("ValidToken", func(t *testing.T) {
|
t.Run("ValidToken", func(t *testing.T) {
|
||||||
var group models.Group
|
var network models.network
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
err = json.NewDecoder(response.Body).Decode(&group)
|
err = json.NewDecoder(response.Body).Decode(&network)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "skynet", group.DisplayName)
|
assert.Equal(t, "skynet", network.DisplayName)
|
||||||
})
|
})
|
||||||
t.Run("InvalidToken", func(t *testing.T) {
|
t.Run("InvalidToken", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet", "badkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
@@ -92,31 +92,31 @@ func TestGetGroup(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||||
})
|
})
|
||||||
t.Run("InvalidGroup", func(t *testing.T) {
|
t.Run("Invalidnetwork", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetGroupNodeNumber(t *testing.T) {
|
func TestGetnetworkNodeNumber(t *testing.T) {
|
||||||
t.Run("ValidKey", func(t *testing.T) {
|
t.Run("ValidKey", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/numnodes", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/numnodes", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message int
|
var message int
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
//assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
//assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("InvalidKey", func(t *testing.T) {
|
t.Run("InvalidKey", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/numnodes", "badkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/numnodes", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
@@ -126,21 +126,21 @@ func TestGetGroupNodeNumber(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||||
})
|
})
|
||||||
t.Run("BadGroup", func(t *testing.T) {
|
t.Run("Badnetwork", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup/numnodes", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork/numnodes", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDeleteGroup(t *testing.T) {
|
func TestDeletenetwork(t *testing.T) {
|
||||||
t.Run("InvalidKey", func(t *testing.T) {
|
t.Run("InvalidKey", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet", "badkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
@@ -151,7 +151,7 @@ func TestDeleteGroup(t *testing.T) {
|
|||||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||||
})
|
})
|
||||||
t.Run("ValidKey", func(t *testing.T) {
|
t.Run("ValidKey", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message mongo.DeleteResult
|
var message mongo.DeleteResult
|
||||||
@@ -161,21 +161,21 @@ func TestDeleteGroup(t *testing.T) {
|
|||||||
assert.Equal(t, int64(1), message.DeletedCount)
|
assert.Equal(t, int64(1), message.DeletedCount)
|
||||||
|
|
||||||
})
|
})
|
||||||
t.Run("BadGroup", func(t *testing.T) {
|
t.Run("Badnetwork", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("NodesExist", func(t *testing.T) {
|
t.Run("NodesExist", func(t *testing.T) {
|
||||||
t.Skip()
|
t.Skip()
|
||||||
})
|
})
|
||||||
//Create Group for follow-on tests
|
//Create network for follow-on tests
|
||||||
createGroup(t)
|
createnetwork(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCreateAccessKey(t *testing.T) {
|
func TestCreateAccessKey(t *testing.T) {
|
||||||
@@ -183,7 +183,7 @@ func TestCreateAccessKey(t *testing.T) {
|
|||||||
key.Name = "skynet"
|
key.Name = "skynet"
|
||||||
key.Uses = 10
|
key.Uses = 10
|
||||||
t.Run("MultiUse", func(t *testing.T) {
|
t.Run("MultiUse", func(t *testing.T) {
|
||||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -198,7 +198,7 @@ func TestCreateAccessKey(t *testing.T) {
|
|||||||
t.Run("ZeroUse", func(t *testing.T) {
|
t.Run("ZeroUse", func(t *testing.T) {
|
||||||
//t.Skip()
|
//t.Skip()
|
||||||
key.Uses = 0
|
key.Uses = 0
|
||||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -212,14 +212,14 @@ func TestCreateAccessKey(t *testing.T) {
|
|||||||
t.Run("DuplicateAccessKey", func(t *testing.T) {
|
t.Run("DuplicateAccessKey", func(t *testing.T) {
|
||||||
//t.Skip()
|
//t.Skip()
|
||||||
//this will fail
|
//this will fail
|
||||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
deleteKey(t, key.Name, "skynet")
|
deleteKey(t, key.Name, "skynet")
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("InvalidToken", func(t *testing.T) {
|
t.Run("InvalidToken", func(t *testing.T) {
|
||||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "badkey")
|
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -229,14 +229,14 @@ func TestCreateAccessKey(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||||
})
|
})
|
||||||
t.Run("BadGroup", func(t *testing.T) {
|
t.Run("Badnetwork", func(t *testing.T) {
|
||||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/badgroup/keys", "secretkey")
|
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/badnetwork/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -244,7 +244,7 @@ func TestCreateAccessKey(t *testing.T) {
|
|||||||
func TestDeleteKey(t *testing.T) {
|
func TestDeleteKey(t *testing.T) {
|
||||||
t.Run("KeyValid", func(t *testing.T) {
|
t.Run("KeyValid", func(t *testing.T) {
|
||||||
//fails -- deletecount not returned
|
//fails -- deletecount not returned
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/skynet", "secretkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message mongo.DeleteResult
|
var message mongo.DeleteResult
|
||||||
@@ -255,7 +255,7 @@ func TestDeleteKey(t *testing.T) {
|
|||||||
})
|
})
|
||||||
t.Run("InValidKey", func(t *testing.T) {
|
t.Run("InValidKey", func(t *testing.T) {
|
||||||
//fails -- status message not returned
|
//fails -- status message not returned
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/badkey", "secretkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/badkey", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
@@ -264,18 +264,18 @@ func TestDeleteKey(t *testing.T) {
|
|||||||
assert.Equal(t, "W1R3: This key does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This key does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("KeyInValidGroup", func(t *testing.T) {
|
t.Run("KeyInValidnetwork", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/badgroup/keys/skynet", "secretkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/badnetwork/keys/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("InvalidCredentials", func(t *testing.T) {
|
t.Run("InvalidCredentials", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/skynet", "badkey")
|
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/skynet", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -290,7 +290,7 @@ func TestDeleteKey(t *testing.T) {
|
|||||||
func TestGetKeys(t *testing.T) {
|
func TestGetKeys(t *testing.T) {
|
||||||
createKey(t)
|
createKey(t)
|
||||||
t.Run("Valid", func(t *testing.T) {
|
t.Run("Valid", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -299,18 +299,18 @@ func TestGetKeys(t *testing.T) {
|
|||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
})
|
})
|
||||||
//deletekeys
|
//deletekeys
|
||||||
t.Run("InvalidGroup", func(t *testing.T) {
|
t.Run("Invalidnetwork", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup/keys", "secretkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork/keys", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("InvalidCredentials", func(t *testing.T) {
|
t.Run("InvalidCredentials", func(t *testing.T) {
|
||||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/keys", "badkey")
|
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/keys", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
@@ -322,29 +322,29 @@ func TestGetKeys(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestUpdateGroup(t *testing.T) {
|
func TestUpdatenetwork(t *testing.T) {
|
||||||
var returnedGroup models.Group
|
var returnednetwork models.network
|
||||||
t.Run("UpdateNameID", func(t *testing.T) {
|
t.Run("UpdateNetID", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
NameID string
|
NetID string
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.NameID = "wirecat"
|
network.NetID = "wirecat"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.NameID, returnedGroup.NameID)
|
assert.Equal(t, network.NetID, returnednetwork.NetID)
|
||||||
})
|
})
|
||||||
t.Run("NameIDInvalidCredentials", func(t *testing.T) {
|
t.Run("NetIDInvalidCredentials", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
NameID string
|
NetID string
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.NameID = "wirecat"
|
network.NetID = "wirecat"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "badkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
@@ -353,83 +353,83 @@ func TestUpdateGroup(t *testing.T) {
|
|||||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("InvalidGroup", func(t *testing.T) {
|
t.Run("Invalidnetwork", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
NameID string
|
NetID string
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.NameID = "wirecat"
|
network.NetID = "wirecat"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusNotFound, message.Code)
|
assert.Equal(t, http.StatusNotFound, message.Code)
|
||||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("UpdateNameIDTooLong", func(t *testing.T) {
|
t.Run("UpdateNetIDTooLong", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
NameID string
|
NetID string
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.NameID = "wirecat-skynet"
|
network.NetID = "wirecat-skynet"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("UpdateAddress", func(t *testing.T) {
|
t.Run("UpdateAddress", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
AddressRange string
|
AddressRange string
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.AddressRange = "10.0.0.1/24"
|
network.AddressRange = "10.0.0.1/24"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.AddressRange, returnedGroup.AddressRange)
|
assert.Equal(t, network.AddressRange, returnednetwork.AddressRange)
|
||||||
})
|
})
|
||||||
t.Run("UpdateAddressInvalid", func(t *testing.T) {
|
t.Run("UpdateAddressInvalid", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
AddressRange string
|
AddressRange string
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.AddressRange = "10.0.0.1/36"
|
network.AddressRange = "10.0.0.1/36"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("UpdateDisplayName", func(t *testing.T) {
|
t.Run("UpdateDisplayName", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DisplayName string
|
DisplayName string
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.DisplayName = "wirecat"
|
network.DisplayName = "wirecat"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DisplayName, returnedGroup.DisplayName)
|
assert.Equal(t, network.DisplayName, returnednetwork.DisplayName)
|
||||||
|
|
||||||
})
|
})
|
||||||
t.Run("UpdateDisplayNameInvalidName", func(t *testing.T) {
|
t.Run("UpdateDisplayNameInvalidName", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DisplayName string
|
DisplayName string
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
//create name that is longer than 100 chars
|
//create name that is longer than 100 chars
|
||||||
name := ""
|
name := ""
|
||||||
for i := 0; i < 101; i++ {
|
for i := 0; i < 101; i++ {
|
||||||
name = name + "a"
|
name = name + "a"
|
||||||
}
|
}
|
||||||
group.DisplayName = name
|
network.DisplayName = name
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
@@ -439,41 +439,41 @@ func TestUpdateGroup(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("UpdateInterface", func(t *testing.T) {
|
t.Run("UpdateInterface", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DefaultInterface string
|
DefaultInterface string
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.DefaultInterface = "netmaker"
|
network.DefaultInterface = "netmaker"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultInterface, returnedGroup.DefaultInterface)
|
assert.Equal(t, network.DefaultInterface, returnednetwork.DefaultInterface)
|
||||||
|
|
||||||
})
|
})
|
||||||
t.Run("UpdateListenPort", func(t *testing.T) {
|
t.Run("UpdateListenPort", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DefaultListenPort int32
|
DefaultListenPort int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.DefaultListenPort = 6000
|
network.DefaultListenPort = 6000
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultListenPort, returnedGroup.DefaultListenPort)
|
assert.Equal(t, network.DefaultListenPort, returnednetwork.DefaultListenPort)
|
||||||
})
|
})
|
||||||
t.Run("UpdateListenPortInvalidPort", func(t *testing.T) {
|
t.Run("UpdateListenPortInvalidPort", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DefaultListenPort int32
|
DefaultListenPort int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.DefaultListenPort = 1023
|
network.DefaultListenPort = 1023
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
@@ -483,54 +483,54 @@ func TestUpdateGroup(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("UpdatePostUP", func(t *testing.T) {
|
t.Run("UpdatePostUP", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DefaultPostUp string
|
DefaultPostUp string
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.DefaultPostUp = "sudo wg add-conf wc-netmaker /etc/wireguard/peers/conf"
|
network.DefaultPostUp = "sudo wg add-conf wc-netmaker /etc/wireguard/peers/conf"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultPostUp, returnedGroup.DefaultPostUp)
|
assert.Equal(t, network.DefaultPostUp, returnednetwork.DefaultPostUp)
|
||||||
})
|
})
|
||||||
t.Run("UpdatePreUP", func(t *testing.T) {
|
t.Run("UpdatePreUP", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DefaultPreUp string
|
DefaultPreUp string
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.DefaultPreUp = "test string"
|
network.DefaultPreUp = "test string"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultPreUp, returnedGroup.DefaultPreUp)
|
assert.Equal(t, network.DefaultPreUp, returnednetwork.DefaultPreUp)
|
||||||
})
|
})
|
||||||
t.Run("UpdateKeepAlive", func(t *testing.T) {
|
t.Run("UpdateKeepAlive", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DefaultKeepalive int32
|
DefaultKeepalive int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.DefaultKeepalive = 60
|
network.DefaultKeepalive = 60
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultKeepalive, returnedGroup.DefaultKeepalive)
|
assert.Equal(t, network.DefaultKeepalive, returnednetwork.DefaultKeepalive)
|
||||||
})
|
})
|
||||||
t.Run("UpdateKeepAliveTooBig", func(t *testing.T) {
|
t.Run("UpdateKeepAliveTooBig", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DefaultKeepAlive int32
|
DefaultKeepAlive int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.DefaultKeepAlive = 1001
|
network.DefaultKeepAlive = 1001
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
@@ -542,57 +542,57 @@ func TestUpdateGroup(t *testing.T) {
|
|||||||
t.Run("UpdateSaveConfig", func(t *testing.T) {
|
t.Run("UpdateSaveConfig", func(t *testing.T) {
|
||||||
//causes panic
|
//causes panic
|
||||||
t.Skip()
|
t.Skip()
|
||||||
type Group struct {
|
type network struct {
|
||||||
DefaultSaveConfig *bool
|
DefaultSaveConfig *bool
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
value := false
|
value := false
|
||||||
group.DefaultSaveConfig = &value
|
network.DefaultSaveConfig = &value
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, *group.DefaultSaveConfig, *returnedGroup.DefaultSaveConfig)
|
assert.Equal(t, *network.DefaultSaveConfig, *returnednetwork.DefaultSaveConfig)
|
||||||
})
|
})
|
||||||
t.Run("UpdateManualSignUP", func(t *testing.T) {
|
t.Run("UpdateManualSignUP", func(t *testing.T) {
|
||||||
t.Skip()
|
t.Skip()
|
||||||
type Group struct {
|
type network struct {
|
||||||
AllowManualSignUp *bool
|
AllowManualSignUp *bool
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
value := true
|
value := true
|
||||||
group.AllowManualSignUp = &value
|
network.AllowManualSignUp = &value
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, *group.AllowManualSignUp, *returnedGroup.AllowManualSignUp)
|
assert.Equal(t, *network.AllowManualSignUp, *returnednetwork.AllowManualSignUp)
|
||||||
})
|
})
|
||||||
t.Run("DefaultCheckInterval", func(t *testing.T) {
|
t.Run("DefaultCheckInterval", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DefaultCheckInInterval int32
|
DefaultCheckInInterval int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.DefaultCheckInInterval = 6000
|
network.DefaultCheckInInterval = 6000
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DefaultCheckInInterval, returnedGroup.DefaultCheckInInterval)
|
assert.Equal(t, network.DefaultCheckInInterval, returnednetwork.DefaultCheckInInterval)
|
||||||
})
|
})
|
||||||
t.Run("DefaultCheckIntervalTooBig", func(t *testing.T) {
|
t.Run("DefaultCheckIntervalTooBig", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DefaultCheckInInterval int32
|
DefaultCheckInInterval int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.DefaultCheckInInterval = 100001
|
network.DefaultCheckInInterval = 100001
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
var message models.ErrorResponse
|
var message models.ErrorResponse
|
||||||
err = json.NewDecoder(response.Body).Decode(&message)
|
err = json.NewDecoder(response.Body).Decode(&message)
|
||||||
@@ -602,20 +602,20 @@ func TestUpdateGroup(t *testing.T) {
|
|||||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||||
})
|
})
|
||||||
t.Run("MultipleFields", func(t *testing.T) {
|
t.Run("MultipleFields", func(t *testing.T) {
|
||||||
type Group struct {
|
type network struct {
|
||||||
DisplayName string
|
DisplayName string
|
||||||
DefaultListenPort int32
|
DefaultListenPort int32
|
||||||
}
|
}
|
||||||
var group Group
|
var network network
|
||||||
group.DefaultListenPort = 7777
|
network.DefaultListenPort = 7777
|
||||||
group.DisplayName = "multi"
|
network.DisplayName = "multi"
|
||||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||||
defer response.Body.Close()
|
defer response.Body.Close()
|
||||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||||
assert.Nil(t, err, err)
|
assert.Nil(t, err, err)
|
||||||
assert.Equal(t, group.DisplayName, returnedGroup.DisplayName)
|
assert.Equal(t, network.DisplayName, returnednetwork.DisplayName)
|
||||||
assert.Equal(t, group.DefaultListenPort, returnedGroup.DefaultListenPort)
|
assert.Equal(t, network.DefaultListenPort, returnednetwork.DefaultListenPort)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@@ -7,7 +7,7 @@ generate_post_json ()
|
|||||||
{
|
{
|
||||||
cat <<EOF
|
cat <<EOF
|
||||||
{
|
{
|
||||||
"nameid": "$NAME",
|
"netid": "$NAME",
|
||||||
"addressrange": "$ADDRESSRANGE"
|
"addressrange": "$ADDRESSRANGE"
|
||||||
}
|
}
|
||||||
EOF
|
EOF
|
||||||
@@ -15,4 +15,4 @@ EOF
|
|||||||
|
|
||||||
POST_JSON=$(generate_post_json)
|
POST_JSON=$(generate_post_json)
|
||||||
|
|
||||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/groups
|
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/networks
|
||||||
|
@@ -7,7 +7,7 @@ generate_post_json ()
|
|||||||
{
|
{
|
||||||
cat <<EOF
|
cat <<EOF
|
||||||
{
|
{
|
||||||
"nameid": "$NAME",
|
"netid": "$NAME",
|
||||||
"addressrange": "$ADDRESSRANGE"
|
"addressrange": "$ADDRESSRANGE"
|
||||||
}
|
}
|
||||||
EOF
|
EOF
|
||||||
@@ -15,7 +15,7 @@ EOF
|
|||||||
|
|
||||||
POST_JSON=$(generate_post_json)
|
POST_JSON=$(generate_post_json)
|
||||||
|
|
||||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/groups
|
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/networks
|
||||||
|
|
||||||
NAME="skynet"
|
NAME="skynet"
|
||||||
ADDRESSRANGE="100.70.0.0/14"
|
ADDRESSRANGE="100.70.0.0/14"
|
||||||
@@ -23,4 +23,4 @@ ADDRESSRANGE="100.70.0.0/14"
|
|||||||
POST_JSON=$(generate_post_json)
|
POST_JSON=$(generate_post_json)
|
||||||
|
|
||||||
|
|
||||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/groups
|
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/networks
|
||||||
|
@@ -13,4 +13,4 @@ EOF
|
|||||||
|
|
||||||
POST_JSON=$(generate_post_json)
|
POST_JSON=$(generate_post_json)
|
||||||
|
|
||||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/groups/skynet/keys
|
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/networks/skynet/keys
|
||||||
|
Reference in New Issue
Block a user