Skip to content

Commit

Permalink
Fix thread safe config object
Browse files Browse the repository at this point in the history
  • Loading branch information
sarjsheff committed Feb 23, 2021
1 parent 587bf60 commit fa7143b
Show file tree
Hide file tree
Showing 8 changed files with 347 additions and 217 deletions.
72 changes: 36 additions & 36 deletions bindata.go

Large diffs are not rendered by default.

354 changes: 256 additions & 98 deletions datautils.go

Large diffs are not rendered by default.

111 changes: 41 additions & 70 deletions http.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"fmt"
"log"
"net/http"
"reflect"
)

func httpserver() {
Expand Down Expand Up @@ -49,65 +48,43 @@ func httpserver() {
mux.HandleFunc("/setvalue", checkAuth(HTTPSetValue))

mux.HandleFunc("/config/", checkAuth(func(w http.ResponseWriter, req *http.Request) {
res1, err := json.Marshal(config)
if err != nil {
log.Println(err)
fmt.Fprintf(w, `{"error":"true"}`)
} else {
w.Write(res1)
}
res1 := sconfig.Json() //json.Marshal(config)
w.Write(res1)
}))

mux.HandleFunc("/rejects/", checkAuth(func(w http.ResponseWriter, req *http.Request) {
HTTPCRUDArray(w, req, "rejects", &config.RejectNames)
HTTPCRUDArrayObject(w, req, "rejects", "RejectNames")
}))
mux.HandleFunc("/relaydns/", checkAuth(func(w http.ResponseWriter, req *http.Request) {
HTTPCRUDArray(w, req, "relaydns", &config.RelayDNS)
HTTPCRUDArrayObject(w, req, "relaydns", "RelayDNS")
}))
mux.HandleFunc("/rules/", checkAuth(func(w http.ResponseWriter, req *http.Request) {
HTTPCRUDArrayObject(w, req, "rules", &config.Rules)
HTTPCRUDArrayObject(w, req, "rules", "Rules")
}))

mux.HandleFunc("/users/", checkAuth(func(w http.ResponseWriter, req *http.Request) {
HTTPCRUD(w, req, "users", func(res map[string]interface{}) {

log.Printf("%T\n", res["name"].(map[string]interface{})["Username"])
item := res["name"].(map[string]interface{})
if _, ok := config.Users[item["Username"].(string)]; ok {
if sconfig.GetUser(item["Username"].(string)) != nil {
fmt.Fprintf(w, `{"ok":false,"error":"User exist."}`)
} else {
if config.Users == nil {
config.Users = map[string]interface{}{}
}
config.Users[item["Username"].(string)] = map[string]interface{}{
"PasswordHash": fmt.Sprintf("%x", sha256.Sum256([]byte(item["Password"].(string)))),
"IsAdmin": item["IsAdmin"] != nil,
}
configwriter <- config
sconfig.AddUser(item["Username"].(string), fmt.Sprintf("%x", sha256.Sum256([]byte(item["Password"].(string)))), item["IsAdmin"] != nil)
fmt.Fprintf(w, `{"ok":true}`)
}

}, func(res map[string]interface{}) {
delete(config.Users, res["id"].(string))
configwriter <- config
sconfig.DelUser(res["id"].(string))
fmt.Fprintf(w, `{"ok":true}`)
}, func(res map[string]interface{}) {
//ArrSaveObject(arr, int(res["id"].(float64)), res["name"])

item := res["name"].(map[string]interface{})
log.Println(item["IsAdmin"])
if _, ok := config.Users[res["id"].(string)]; ok {
config.Users[res["id"].(string)] = map[string]interface{}{
"PasswordHash": config.Users[res["id"].(string)].(map[string]interface{})["PasswordHash"],
"IsAdmin": item["IsAdmin"].(bool) == true,
}
configwriter <- config
if sconfig.GetUser(res["id"].(string)) != nil {
sconfig.SetUser(res["id"].(string), item["IsAdmin"].(bool) == true)
fmt.Fprintf(w, `{"ok":true}`)
} else {
fmt.Fprintf(w, `{"ok":false,"error":"User not found."}`)
}
}, func(res map[string]interface{}) {
res1, err := json.Marshal(config.Users)
res1, err := json.Marshal(sconfig.Get("Users"))
if err != nil {
log.Println(err)
fmt.Fprintf(w, `{"error":true}`)
Expand All @@ -121,7 +98,7 @@ func httpserver() {

mux.HandleFunc("/ws", WSHandler)

http.ListenAndServe(config.HTTPListen, mux)
http.ListenAndServe(sconfig.Get("HTTPListen").(string), mux)

}

Expand Down Expand Up @@ -162,18 +139,10 @@ func HTTPSetValue(w http.ResponseWriter, req *http.Request) {
dec := json.NewDecoder(req.Body)
err := dec.Decode(&params)

postconfig := config

if err == nil {
rr := reflect.ValueOf(&postconfig).Elem()
for key, value := range params {
v := rr.FieldByName(key)
if v.IsValid() {
v.Set(reflect.ValueOf(value))
}
sconfig.Set(key, value)
}

configwriter <- postconfig
fmt.Fprintf(w, `{"ok":"true"}`)
} else {
fmt.Fprintf(w, `{"error":"true"}`)
Expand All @@ -193,7 +162,7 @@ func HTTPCRUD(w http.ResponseWriter, req *http.Request, ctxname string, add CRUD

err := dec.Decode(&res)

log.Println(res)
//log.Println(res)

if err != nil {
def(nil)
Expand Down Expand Up @@ -224,18 +193,20 @@ func HTTPCRUD(w http.ResponseWriter, req *http.Request, ctxname string, add CRUD
}

// HTTPCRUDArrayObject - Universal HTTP handler for add, delete and set element of configuration array of objects.
func HTTPCRUDArrayObject(w http.ResponseWriter, req *http.Request, name string, arr *[]interface{}) {
func HTTPCRUDArrayObject(w http.ResponseWriter, req *http.Request, name string, arr string) {
HTTPCRUD(w, req, name, func(res map[string]interface{}) {
ArrAddObject(arr, res["name"])
sconfig.AddObject(arr, res["name"])
fmt.Fprintf(w, `{"ok":"true"}`)
}, func(res map[string]interface{}) {
ArrDelObject(arr, int(res["id"].(float64)))
//ArrDelObject(arr, int(res["id"].(float64)))
sconfig.DelObject(arr, int(res["id"].(float64)))
fmt.Fprintf(w, `{"ok":"true"}`)
}, func(res map[string]interface{}) {
ArrSaveObject(arr, int(res["id"].(float64)), res["name"])
//ArrSaveObject(arr, int(res["id"].(float64)), res["name"])
sconfig.SetObject(arr, int(res["id"].(float64)), res["name"])
fmt.Fprintf(w, `{"ok":"true"}`)
}, func(res map[string]interface{}) {
res1, err := json.Marshal(arr)
res1, err := json.Marshal(sconfig.Get(arr))
if err != nil {
log.Println(err)
fmt.Fprintf(w, `{"error":"true"}`)
Expand All @@ -246,23 +217,23 @@ func HTTPCRUDArrayObject(w http.ResponseWriter, req *http.Request, name string,
}

// HTTPCRUDArray - Universal HTTP handler for add, delete and set element of configuration array of string.
func HTTPCRUDArray(w http.ResponseWriter, req *http.Request, name string, arr *[]string) {
HTTPCRUD(w, req, name, func(res map[string]interface{}) {
ArrAdd(arr, res["name"].(string))
fmt.Fprintf(w, `{"ok":"true"}`)
}, func(res map[string]interface{}) {
ArrDel(arr, int(res["id"].(float64)))
fmt.Fprintf(w, `{"ok":"true"}`)
}, func(res map[string]interface{}) {
ArrSave(arr, int(res["id"].(float64)), res["name"].(string))
fmt.Fprintf(w, `{"ok":"true"}`)
}, func(res map[string]interface{}) {
res1, err := json.Marshal(*arr)
if err != nil {
log.Println(err)
fmt.Fprintf(w, `{"error":"true"}`)
} else {
w.Write(res1)
}
})
}
// func HTTPCRUDArray(w http.ResponseWriter, req *http.Request, name string, arr *[]string) {
// HTTPCRUD(w, req, name, func(res map[string]interface{}) {
// ArrAdd(arr, res["name"].(string))
// fmt.Fprintf(w, `{"ok":"true"}`)
// }, func(res map[string]interface{}) {
// ArrDel(arr, int(res["id"].(float64)))
// fmt.Fprintf(w, `{"ok":"true"}`)
// }, func(res map[string]interface{}) {
// ArrSave(arr, int(res["id"].(float64)), res["name"].(string))
// fmt.Fprintf(w, `{"ok":"true"}`)
// }, func(res map[string]interface{}) {
// res1, err := json.Marshal(*arr)
// if err != nil {
// log.Println(err)
// fmt.Fprintf(w, `{"error":"true"}`)
// } else {
// w.Write(res1)
// }
// })
// }
6 changes: 3 additions & 3 deletions httpauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ func HTTPLogin(w http.ResponseWriter, req *http.Request) {
if err != nil {
fmt.Fprintf(w, `{"ok":false}`)
} else {
u := config.Users[res["username"]]
if u != nil && u.(map[string]interface{})["PasswordHash"].(string) == res["password"] {
u := sconfig.GetUser(res["username"]) //config.Users[res["username"]]
if u != nil && u["PasswordHash"].(string) == res["password"] {
session, _ := store.Get(req, "owndns")
user := HTTPUser{res["username"], u.(map[string]interface{})["IsAdmin"].(bool)}
user := HTTPUser{res["username"], u["IsAdmin"].(bool)}

ret, _ := json.Marshal(map[string]interface{}{
"ok": true,
Expand Down
12 changes: 6 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ func parseQuery(m *dns.Msg, w dns.ResponseWriter) {
Log(i)
// log.Println("found in cache")
} else {
relays := GetRelaydns()
relays := sconfig.GetRelaydns()
for _, dnsserver := range relays {
in, _, err := cli.Exchange(m1, dnsserver)
in, _, err := cli.Exchange(m1, dnsserver.(string))

if err == nil {
m.Answer = in.Answer
Expand Down Expand Up @@ -133,13 +133,13 @@ func main() {

// start server

server := &dns.Server{Addr: config.DNSListen, Net: "udp"}
server := &dns.Server{Addr: sconfig.Get("DNSListen").(string), Net: "udp"}

if config.HTTPListen != "" {
log.Printf("Starting HTTP at port %v\n", config.HTTPListen)
if sconfig.Get("HTTPListen").(string) != "" {
log.Printf("Starting HTTP at port %v\n", sconfig.Get("HTTPListen"))
go httpserver()
}
log.Printf("Starting DNS at port %v\n", config.DNSListen)
log.Printf("Starting DNS at port %v\n", sconfig.Get("DNSListen"))
err := server.ListenAndServe()
defer server.Shutdown()
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion ui/src/components/OwnLogin.vue
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export default {
.then((data) => data.json())
.then((json) => {
if (json.ok) {
this.$store.commit("setuser", json.user);
this.$store.dispatch("setuser", json.user);
this.loading = false;
} else {
this.loading = false;
Expand Down
3 changes: 2 additions & 1 deletion ui/src/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ export default new Vuex.Store({
fetch("/logout").then(() => context.commit("setuser", undefined)).catch(() => context.commit("setuser", undefined))
},
setuser(context, user) {
console.log("Must REFRESH");
context.dispatch("getversion");
context.dispatch("getconfig");
context.commit("setuser", user);
Expand Down Expand Up @@ -203,7 +204,7 @@ export default new Vuex.Store({
});
},
getversion(context) {
fetch(`/version.json`)
fetch(`/version.json`, { cache: "no-cache" })
.then(authCheck(context))
.then((json) => {
context.commit("setversion", json ? json.version || "" : "");
Expand Down
4 changes: 2 additions & 2 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package main

import "strings"

func stringInSlice(a string, list []string) bool {
func stringInSlice(a string, list []interface{}) bool {
for _, b := range list {
if strings.Contains(a, b) {
if strings.Contains(a, b.(string)) {
return true
}
}
Expand Down

0 comments on commit fa7143b

Please sign in to comment.