-
Notifications
You must be signed in to change notification settings - Fork 0
/
ubus.go
85 lines (73 loc) · 2.05 KB
/
ubus.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* Copyright (C) 2023 Nethesis S.r.l.
* http://www.nethesis.it - info@nethesis.it
*
* SPDX-License-Identifier: GPL-2.0-only
*
* author: Edoardo Spadoni <edoardo.spadoni@nethesis.it>
*/
package methods
import (
"encoding/json"
"net/http"
"os/exec"
"github.com/NethServer/nethsecurity-api/models"
"github.com/NethServer/nethsecurity-api/response"
"github.com/Jeffail/gabs/v2"
"github.com/fatih/structs"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
func UBusCallAction(c *gin.Context) {
// parse request fields
var jsonUBusCall models.UBusCallJSON
if err := c.ShouldBindBodyWith(&jsonUBusCall, binding.JSON); err != nil {
c.JSON(http.StatusBadRequest, structs.Map(response.StatusBadRequest{
Code: 400,
Message: "request fields malformed",
Data: err.Error(),
}))
return
}
// convert payload to JSON
jsonPayload, _ := json.Marshal(jsonUBusCall.Payload)
// execute login command on ubus
out, err := exec.Command("/bin/ubus", "-S", "-t", "300", "call", jsonUBusCall.Path, jsonUBusCall.Method, string(jsonPayload[:])).Output()
// check errors
if err != nil {
c.JSON(http.StatusInternalServerError, structs.Map(response.StatusBadRequest{
Code: 500,
Message: "ubus call action failed",
Data: err.Error(),
}))
return
}
// parse output in a valid JSON
jsonParsed, _ := gabs.ParseJSON(out)
// check errors in response
errorMessage, errFound := jsonParsed.Path("error").Data().(string)
if errFound {
c.JSON(http.StatusInternalServerError, structs.Map(response.StatusBadRequest{
Code: 500,
Message: errorMessage,
Data: jsonParsed,
}))
return
}
// check validation error in response
validationFound := jsonParsed.Exists("validation")
if validationFound {
c.JSON(http.StatusBadRequest, structs.Map(response.StatusBadRequest{
Code: 400,
Message: "validation_failed",
Data: jsonParsed,
}))
return
}
// return 200 OK with data
c.JSON(http.StatusOK, structs.Map(response.StatusOK{
Code: 200,
Message: "ubus call action success",
Data: jsonParsed,
}))
}