-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
96 lines (86 loc) · 2.28 KB
/
config.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
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"io/ioutil"
"log"
"net/http"
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
"github.com/xgfone/ngconf"
)
type ConfigController struct{}
const NGINX_PATH = "/usr/local/nginx/conf/nginx.conf"
var UNAUTHORIZED_RESPONSE = gin.H{
SUCCESS_KEY: false,
RESPONSE_MESSAGE_KEY: "Unauthorized",
}
type NginxConf struct {
Content string `json:"content"`
}
func (cc *ConfigController) GetConfiguration(c *gin.Context) {
claims := jwt.ExtractClaims(c)
if !(claims["isAdmin"].(bool)) {
c.JSON(http.StatusUnauthorized, gin.H{
SUCCESS_KEY: false,
RESPONSE_MESSAGE_KEY: "Unauthorized",
})
return
}
content, err := ioutil.ReadFile(NGINX_PATH)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
SUCCESS_KEY: false,
RESPONSE_MESSAGE_KEY: "Failed to read nginx conf for editing.",
"ioUtilError": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
SUCCESS_KEY: true,
RESPONSE_MESSAGE_KEY: "Succesfully fetched nginx conf for editing.",
"content": string(content),
})
}
func (cc *ConfigController) UpdateConfiguration(c *gin.Context) {
claims := jwt.ExtractClaims(c)
if !(claims["isAdmin"].(bool)) {
c.JSON(http.StatusUnauthorized, UNAUTHORIZED_RESPONSE)
return
}
var content NginxConf
c.BindJSON(&content)
log.Println(content.Content)
if content.Content == "" {
log.Fatal("I don't know jimbo...")
c.JSON(http.StatusBadRequest, gin.H{
SUCCESS_KEY: false,
RESPONSE_MESSAGE_KEY: "Content is empty, not saving file",
})
return
}
// TODO: verify valid nginx conf
confIsValid := testNginxConf(content.Content)
if !confIsValid {
c.JSON(http.StatusBadRequest, gin.H{
SUCCESS_KEY: false,
RESPONSE_MESSAGE_KEY: "Invalid config",
})
return
}
err := ioutil.WriteFile(NGINX_PATH, []byte(content.Content), 0644)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
SUCCESS_KEY: false,
RESPONSE_MESSAGE_KEY: "Cannot save content",
"ioUtilError": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
SUCCESS_KEY: true,
RESPONSE_MESSAGE_KEY: "Successfully saved modified nginx conf.",
})
}
func testNginxConf(content string) (b bool) {
_, err := ngconf.Decode(content)
return err == nil
}