From 9d373ae81def3e51688b2026898824a44662d507 Mon Sep 17 00:00:00 2001 From: kolaente Date: Sun, 1 Sep 2019 22:59:51 +0200 Subject: [PATCH] Refactored all the things --- add.go | 65 ---------------- admin.go | 37 --------- config.go | 25 ------ db.go | 23 ------ delete.go | 44 ----------- getList.go | 60 -------------- go.mod | 4 +- go.sum | 19 +++++ login.go | 31 -------- logout.go | 18 ----- main.go | 71 +++++++---------- pkg/config/config.go | 44 +++++++++++ pkg/models/community.go | 64 +++++++++++++++ pkg/models/db.go | 27 +++++++ pkg/models/errors.go | 11 +++ pkg/models/kofi.go | 44 +++++++++++ pkg/models/utils.go | 7 ++ .../router/TemplateRender.go | 4 +- pkg/router/add.go | 56 +++++++++++++ pkg/router/admin.go | 33 ++++++++ pkg/router/delete.go | 42 ++++++++++ pkg/router/getList.go | 35 +++++++++ pkg/router/login.go | 39 ++++++++++ pkg/router/logout.go | 19 +++++ pkg/router/router.go | 50 ++++++++++++ showList.go => pkg/router/showList.go | 7 +- pkg/router/update.go | 60 ++++++++++++++ ws.go => pkg/router/ws.go | 13 ++-- update.go | 78 ------------------- utils.go | 42 ---------- 30 files changed, 590 insertions(+), 482 deletions(-) delete mode 100644 add.go delete mode 100644 admin.go delete mode 100644 config.go delete mode 100644 db.go delete mode 100644 delete.go delete mode 100644 getList.go delete mode 100644 login.go delete mode 100644 logout.go create mode 100644 pkg/config/config.go create mode 100644 pkg/models/community.go create mode 100644 pkg/models/db.go create mode 100644 pkg/models/errors.go create mode 100644 pkg/models/kofi.go create mode 100644 pkg/models/utils.go rename TemplateRender.go => pkg/router/TemplateRender.go (83%) create mode 100644 pkg/router/add.go create mode 100644 pkg/router/admin.go create mode 100644 pkg/router/delete.go create mode 100644 pkg/router/getList.go create mode 100644 pkg/router/login.go create mode 100644 pkg/router/logout.go create mode 100644 pkg/router/router.go rename showList.go => pkg/router/showList.go (50%) create mode 100644 pkg/router/update.go rename ws.go => pkg/router/ws.go (80%) delete mode 100644 update.go delete mode 100644 utils.go diff --git a/add.go b/add.go deleted file mode 100644 index 4eaf337..0000000 --- a/add.go +++ /dev/null @@ -1,65 +0,0 @@ -package main - -import ( - "github.com/labstack/echo" - "net/http" - "strconv" -) - -func addKonfi(c echo.Context) error { - - //Config - SiteConf := initConfig() - - //Datenbankverbindung aufbauen - db := DBinit() - - rw := c.Response() - r := c.Request() - - //Session init - sess := GlobalSessions.SessionStart(rw, r) - logged := sess.Get("login") - - //Wenn eingeloggt - if logged != nil { - // Mode nach Kofis - if SiteConf.Mode == 0 { - kofi := new(Kofi) - kofi.Name = c.FormValue("name") - kofi.Gemeinde = c.FormValue("gemeinde") - - // Einfügen - _, err := db.Insert(kofi) - if err == nil { - return c.JSON(http.StatusOK, Message{"success"}) - } - - return c.JSON(http.StatusInternalServerError, Message{"Error."}) - - } else if SiteConf.Mode == 1 { // Mode nach Gemeinden - - var err error - gemeinde := new(Gemeinde) - gemeinde.Name = c.FormValue("name") - gemeinde.KonfiCount, err = strconv.Atoi(c.FormValue("konfis")) - - if err != nil { - return c.JSON(http.StatusInternalServerError, Message{"error. (konfiCount not int)"}) - } - - _, err = db.Insert(gemeinde) - if err == nil { - return c.JSON(http.StatusOK, Message{"success"}) - } - - return c.JSON(http.StatusInternalServerError, Message{"Error."}) - - } - - return c.JSON(http.StatusInternalServerError, Message{"Wrong Mode."}) - - } else { - return c.JSON(http.StatusOK, Message{"Login first."}) - } -} diff --git a/admin.go b/admin.go deleted file mode 100644 index dc2e520..0000000 --- a/admin.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "github.com/labstack/echo" - "net/http" - "strconv" -) - -type AdminInfos struct { - Loggedin bool - Mode int - Version string -} - -func adminHandler(c echo.Context) error { - //Config - SiteConf := initConfig() - - rw := c.Response() - r := c.Request() - - //Session init - sess := GlobalSessions.SessionStart(rw, r) - - //Loggedin - loggedin := sess.Get("login") - - // Admininfos - adminInfos := AdminInfos{true, SiteConf.Mode, Version} - - if loggedin != nil { - return c.Render(http.StatusOK, "admin_mode_" + strconv.Itoa(SiteConf.Mode), adminInfos) - } else { - adminInfos.Loggedin = false - return c.Render(http.StatusOK, "login", adminInfos) - } -} diff --git a/config.go b/config.go deleted file mode 100644 index c12e59f..0000000 --- a/config.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "github.com/go-ini/ini" - "log" -) - -//Configuration Struct -type Configuration struct { - AdminPassword string - Interface string - DBFile string - Mode int -} - -var SiteConf Configuration = Configuration{} - -func initConfig() *Configuration { - SiteConf := new(Configuration) - err := ini.MapTo(SiteConf, "config.ini") - if err != nil { - log.Fatal(err) - } - return SiteConf -} diff --git a/db.go b/db.go deleted file mode 100644 index 2cab681..0000000 --- a/db.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "github.com/go-xorm/xorm" - _ "github.com/mattn/go-sqlite3" - "xorm.io/core" -) - -var db *xorm.Engine - -func DBinit() *xorm.Engine { - SiteConf := initConfig() - db, err := xorm.NewEngine("sqlite3", SiteConf.DBFile) - if err != nil { - fmt.Println(err) - } - - db.SetMapper(core.SameMapper{}) - db.ShowSQL(false) - db.Logger().SetLevel(core.LOG_DEBUG) - return db -} diff --git a/delete.go b/delete.go deleted file mode 100644 index df9984a..0000000 --- a/delete.go +++ /dev/null @@ -1,44 +0,0 @@ -package main - -import ( - "github.com/labstack/echo" - "net/http" - "strconv" -) - -func deleteKonfi(c echo.Context) error { - - //Config - SiteConf := initConfig() - - //Datenbankverbindung aufbauen - db := DBinit() - - rw := c.Response() - r := c.Request() - - //Session init - sess := GlobalSessions.SessionStart(rw, r) - logged := sess.Get("login") - - //Wenn das password stimmt - if logged != nil { - id, _ := strconv.Atoi(c.FormValue("id")) - - //Löschen - if SiteConf.Mode == 0 { - _, err := db.Id(id).Delete(&Kofi{}) - if err == nil { - return c.JSON(http.StatusOK, Message{"success"}) - } - } else if SiteConf.Mode == 1{ - _, err := db.Id(id).Delete(&Gemeinde{}) - if err == nil { - return c.JSON(http.StatusOK, Message{"success"}) - } - } - return c.JSON(http.StatusInternalServerError, Message{"Error."}) - } else { - return c.JSON(http.StatusForbidden, Message{"Login first."}) - } -} diff --git a/getList.go b/getList.go deleted file mode 100644 index 774f02d..0000000 --- a/getList.go +++ /dev/null @@ -1,60 +0,0 @@ -package main - -import ( - "fmt" - "github.com/labstack/echo" - "net/http" -) - -func getList(c echo.Context) error { - //Datenbankverbindung aufbauen - db := DBinit() - - //Config - SiteConf := initConfig() - - if SiteConf.Mode == 0 { - //Daten holen und anzeigen - var kofi []Kofi - asc := c.QueryParam("asc") - if asc == "" { - err := db.OrderBy("KCoins DESC").Find(&kofi) - if err != nil { - fmt.Println(err) - } - } else { - err := db.OrderBy("Name ASC").Find(&kofi) - if err != nil { - fmt.Println(err) - } - } - - //Template - return c.JSON(http.StatusOK, kofi) - } else if SiteConf.Mode == 1 { - //Daten holen und anzeigen - var gemeinden []Gemeinde - asc := c.QueryParam("asc") - if asc == "" { - err := db.Select("Gemeinde.*, (cast(KCoins AS FLOAT) / cast(KonfiCount AS FLOAT)) as CoinsQuota").OrderBy("CoinsQuota DESC").Find(&gemeinden) - if err != nil { - fmt.Println(err) - } - } else { - err := db.Select("*, (cast(KCoins AS FLOAT) / cast(KonfiCount AS FLOAT)) AS CoinsQuota").OrderBy("Name ASC").Find(&gemeinden) - if err != nil { - fmt.Println(err) - } - } - - // Alles durchgehen und den Schnitt ausrechnen - for i, gem := range gemeinden{ - gemeinden[i].CoinsQuota = float64(gem.KCoins) / float64(gem.KonfiCount) - } - - //Template - return c.JSON(http.StatusOK, gemeinden) - } - - return c.HTML(http.StatusInternalServerError, "Error. (Wrong mode)") -} diff --git a/go.mod b/go.mod index 79c8b12..850e43a 100644 --- a/go.mod +++ b/go.mod @@ -7,10 +7,12 @@ require ( github.com/asticode/go-astilectron v0.8.0 github.com/asticode/go-astilog v1.0.0 github.com/asticode/go-astitools v1.1.0 // indirect - github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect github.com/go-ini/ini v1.46.0 github.com/go-xorm/xorm v0.7.6 + github.com/gorilla/sessions v1.2.0 github.com/labstack/echo v3.3.10+incompatible + github.com/labstack/echo-contrib v0.6.0 + github.com/labstack/echo/v4 v4.1.6 github.com/labstack/gommon v0.3.0 github.com/mattn/go-sqlite3 v1.11.0 github.com/pkg/errors v0.8.1 diff --git a/go.sum b/go.sum index 443b8f7..ae66f4b 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,7 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.37.4/go.mod h1:NHPJ89PdicEuT9hdPXMROBD91xc5uRDxsMtSB16k7hw= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= @@ -18,6 +19,7 @@ github.com/asticode/go-astitools v1.0.0/go.mod h1:E7f1P0KkBNgafRCD0dHqn41jNHyYHj github.com/asticode/go-astitools v1.1.0 h1:h5hVWUKB9eUZY7/mgu6Ic6Rke8ZiWHkiJO0rIGIb5j4= github.com/asticode/go-astitools v1.1.0/go.mod h1:EfgrhUJK6nM17TckqASIqR2W71uNUAoIonm6mNhUtaQ= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/casbin/casbin v1.8.2/go.mod h1:z8uPsfBJGUsnkagrt3G8QvjgTKFMBJ32UP8HpZllfog= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -51,8 +53,14 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/sessions v1.1.3/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w= +github.com/gorilla/sessions v1.2.0 h1:S7P+1Hm5V/AT9cjEcUD5uDaQSX0OE577aCXgoaKpYbQ= +github.com/gorilla/sessions v1.2.0/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= @@ -70,6 +78,11 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg= github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s= +github.com/labstack/echo-contrib v0.6.0 h1:WT+TwJkJXrK+9n+x5VcI8f17VkUsiY33H5Mw3Pe8OfI= +github.com/labstack/echo-contrib v0.6.0/go.mod h1:uQPocfnb5ZG2Nl0wsNaGEMTvGK16NF5vo/GHECCuJz4= +github.com/labstack/echo/v4 v4.1.6 h1:WOvLa4T1KzWCRpANwz0HGgWDelXSSGwIKtKBbFdHTv4= +github.com/labstack/echo/v4 v4.1.6/go.mod h1:kU/7PwzgNxZH4das4XNsSpBSOD09XIF5YEPzjpkGnGE= +github.com/labstack/gommon v0.2.9/go.mod h1:E8ZTmW9vw5az5/ZyHWCp0Lw4OH2ecsaBP1C/NKavGG4= github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0= github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= @@ -109,6 +122,7 @@ github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPx github.com/streadway/amqp v0.0.0-20181205114330-a314942b2fd9/go.mod h1:1WNBiOZtZQLpVAyu0iTduoJL9hEsMloAK5XWrtW0xdY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -140,6 +154,7 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190607181551-461777fb6f67/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297 h1:k7pJ2yAPLPgbskkFdhRCsA77k2fySZ1zf2zCjvQCiIM= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -159,6 +174,8 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190602015325-4c4f7f33c9ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190609082536-301114b31cce/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190610200419-93c9922d18ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= @@ -173,6 +190,8 @@ golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190606050223-4d9ae51c2468/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190608022120-eacb66d2a7c3/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190610214847-0945d3616f18/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= diff --git a/login.go b/login.go deleted file mode 100644 index d785723..0000000 --- a/login.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "github.com/labstack/echo" - "net/http" -) - -func login(c echo.Context) error { - rw := c.Response() - r := c.Request() - - //Session init - sess := GlobalSessions.SessionStart(rw, r) - - //Config - SiteConf := initConfig() - var pass string = c.FormValue("password") - - //Wenn das password stimmt, einloggen - if SiteConf.AdminPassword == pass { - sess.Set("login", true) - direct := c.QueryParam("direct") - if direct == "true" { - return c.Redirect(http.StatusSeeOther, "/admin") - } - return c.JSON(http.StatusOK, Message{"success"}) - } else { - return c.JSON(http.StatusOK, Message{"fail"}) - } - -} diff --git a/logout.go b/logout.go deleted file mode 100644 index 95b0387..0000000 --- a/logout.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "github.com/labstack/echo" - "net/http" -) - -func logout(c echo.Context) error { - rw := c.Response() - r := c.Request() - - //Session auf nil setzen zum ausloggen - sess := GlobalSessions.SessionStart(rw, r) - sess.Set("login", nil) - - //Auf die adminseite weiterleiten - return c.Redirect(http.StatusSeeOther, "/admin") -} diff --git a/main.go b/main.go index 465ce0b..f6982d0 100644 --- a/main.go +++ b/main.go @@ -1,12 +1,10 @@ package main import ( - "github.com/labstack/echo" - "github.com/labstack/echo/middleware" - "github.com/labstack/gommon/log" - "html/template" - "fmt" + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/config" + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/models" + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/router" "github.com/astaxie/session" _ "github.com/astaxie/session/providers/memory" "github.com/asticode/go-astilectron" @@ -46,50 +44,33 @@ func main() { # \_| \_/\__,_|___/_|_| |_|\___/ # # # # © 2017-2019 Konrad Langenberg (konradlangenberg.de) # -# Version: ` + Version + ` # +# Version: ` + models.Version + ` # ################################################################`) - //Echo init - e := echo.New() - e.HideBanner = true - - //Logger - e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ - Format: "${time_rfc3339}: ${remote_ip} ${method} ${status} ${uri} - ${user_agent}\n", - })) - - //Static ontent - e.Static("/assets", "assets") - - //Routes - e.GET("/", showList) - e.GET("/list", getList) - e.GET("/admin", adminHandler) - e.GET("/logout", logout) - e.GET("/ws", ws) - - e.POST("/login", login) - e.POST("/update", update) - e.POST("/delete", deleteKonfi) - e.POST("/add", addKonfi) - - //Template - t := &Template{ - templates: template.Must(template.ParseGlob("tpl/*.html")), - } - e.Renderer = t - //DB init - Create tables - db := DBinit() - db.Sync(&Kofi{}) - db.Sync(&Gemeinde{}) + models.DBinit() //Config - SiteConf := initConfig() + config.InitConfig() - //Start the server - e.Logger.SetLevel(log.ERROR) - go e.Start(SiteConf.Interface) + //Echo init + e := router.NewEcho() + router.RegisterRoutes(e) + // Start server + go func() { + if err := e.Start(config.GetInterface()); err != nil { + e.Logger.Info("shutting down...") + } + }() + + // TODO: Make sure everything still works + // TODO: Move all this window crap in its own package + // TODO: Distribute as single binary + // TODO: Switch to viper + // TODO: SSE + // TODO: Build a fancy thing with interfaces to avoid context switching code all over the place + // TODO: Build a middleware which checks the auth for admin routes + // TODO: Tests? //Windows // Create astilectron @@ -115,7 +96,7 @@ func main() { // Create Frontend window var wFrontend *astilectron.Window - wFrontend, err = a.NewWindow("http://"+SiteConf.Interface, &astilectron.WindowOptions{ + wFrontend, err = a.NewWindow("http://"+config.GetInterface(), &astilectron.WindowOptions{ Center: astilectron.PtrBool(true), Height: astilectron.PtrInt(800), Width: astilectron.PtrInt(1200), @@ -143,7 +124,7 @@ func main() { // Create Admin window var wAdmin *astilectron.Window - if wAdmin, err = a.NewWindow("http://"+SiteConf.Interface+"/admin", &astilectron.WindowOptions{ + if wAdmin, err = a.NewWindow("http://"+config.GetInterface()+"/admin", &astilectron.WindowOptions{ Center: astilectron.PtrBool(true), Height: astilectron.PtrInt(700), Width: astilectron.PtrInt(1200), diff --git a/pkg/config/config.go b/pkg/config/config.go new file mode 100644 index 0000000..c481aa5 --- /dev/null +++ b/pkg/config/config.go @@ -0,0 +1,44 @@ +package config + +import ( + "github.com/go-ini/ini" + "log" +) + +//Configuration Struct +type Configuration struct { + AdminPassword string + Interface string + DBFile string + Mode int +} + +var siteConf = &Configuration{} + +func InitConfig() { + siteConf := new(Configuration) + err := ini.MapTo(siteConf, "config.ini") + if err != nil { + log.Fatal(err) + } +} + +func GetConfig() *Configuration { + return siteConf +} + +func GetMode() int { + return siteConf.Mode +} + +func GetInterface() string { + return siteConf.Interface +} + +func GetAdminPassword() string { + return siteConf.AdminPassword +} + +func GetDBFile() string { + return siteConf.DBFile +} diff --git a/pkg/models/community.go b/pkg/models/community.go new file mode 100644 index 0000000..12e3264 --- /dev/null +++ b/pkg/models/community.go @@ -0,0 +1,64 @@ +package models + +type Community struct { + ID int64 `xorm:"pk autoincr"` + Name string + KCoins int64 + + KonfiCount int64 + CoinsQuota float64 `xorm:"-"` +} + +func (c *Community) Add() (err error) { + _, err = x.Insert(c) + return +} + +func (c *Community) Delete() (err error) { + _, err = x.Delete(c) + return +} + +func ReadAllCommunities(orderbyname bool) (communities []*Community, err error) { + + orderby := "CoinsQuota DESC" + if orderbyname { + orderby = "Name ASC" + } + + err = x.Select(".*, (cast(KCoins AS FLOAT) / cast(KonfiCount AS FLOAT)) as CoinsQuota"). + OrderBy(orderby). + Find(&communities) + if err != nil { + return + } + + for i, c := range communities { + communities[i].CoinsQuota = float64(c.KCoins) / float64(c.KonfiCount) + } + + return +} + +func (c *Community) Update(moreCoins int64) (err error) { + // Check if it exists + exists, err := x.Where("id = ?", c.ID).Get(c) + if err != nil { + return err + } + if !exists { + return ErrKofiDoesNotExist{ID: c.ID} + } + + c.KCoins += moreCoins + + // Update + _, err = x.Where("id = ?", c.ID).Update(c) + if err != nil { + return + } + + c.CoinsQuota = float64(c.KCoins) / float64(c.KonfiCount) + + return +} diff --git a/pkg/models/db.go b/pkg/models/db.go new file mode 100644 index 0000000..b6f9a30 --- /dev/null +++ b/pkg/models/db.go @@ -0,0 +1,27 @@ +package models + +import ( + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/config" + "github.com/go-xorm/xorm" + "github.com/labstack/gommon/log" + _ "github.com/mattn/go-sqlite3" + "xorm.io/core" +) + +var x *xorm.Engine + +func DBinit() { + var err error + x, err = xorm.NewEngine("sqlite3", config.GetDBFile()) + if err != nil { + log.Error(err) + } + + x.SetMapper(core.GonicMapper{}) + x.ShowSQL(false) + x.Logger().SetLevel(core.LOG_DEBUG) + + x.Sync(&Kofi{}, &Community{}) + + return +} diff --git a/pkg/models/errors.go b/pkg/models/errors.go new file mode 100644 index 0000000..011b9f0 --- /dev/null +++ b/pkg/models/errors.go @@ -0,0 +1,11 @@ +package models + +import "fmt" + +type ErrKofiDoesNotExist struct { + ID int64 +} + +func (err ErrKofiDoesNotExist) Error() string { + return fmt.Sprintf("This kofi does not exist [ID: %n]", err.ID) +} diff --git a/pkg/models/kofi.go b/pkg/models/kofi.go new file mode 100644 index 0000000..0212a79 --- /dev/null +++ b/pkg/models/kofi.go @@ -0,0 +1,44 @@ +package models + +type Kofi struct { + ID int64 `xorm:"pk autoincr"` + Name string + Gemeinde string + KCoins int64 +} + +func (k *Kofi) Add() (err error) { + _, err = x.Insert(k) + return +} + +func (k *Kofi) Delete() (err error) { + _, err = x.Delete(k) + return +} + +func (k *Kofi) Update(moreCoins int64) (err error) { + // Check if it exists + exists, err := x.Where("id = ?", k.ID).Get(k) + if err != nil { + return err + } + if !exists { + return ErrKofiDoesNotExist{ID: k.ID} + } + + k.KCoins += moreCoins + + // Update + _, err = x.Where("id = ?", k.ID).Update(k) + return +} + +func ReadAllKofis(orderbyNames bool) (kofis []*Kofi, err error) { + var orderby = "KCoins DESC" + if orderbyNames { + orderby = "Name ASC" + } + err = x.OrderBy(orderby).Find(&kofis) + return +} diff --git a/pkg/models/utils.go b/pkg/models/utils.go new file mode 100644 index 0000000..a779f2b --- /dev/null +++ b/pkg/models/utils.go @@ -0,0 +1,7 @@ +package models + +var Version = "+1.1-2-g353bf3b" + +type Message struct { + Message string +} diff --git a/TemplateRender.go b/pkg/router/TemplateRender.go similarity index 83% rename from TemplateRender.go rename to pkg/router/TemplateRender.go index 20a5a18..e2388ff 100644 --- a/TemplateRender.go +++ b/pkg/router/TemplateRender.go @@ -1,7 +1,7 @@ -package main +package router import ( - "github.com/labstack/echo" + "github.com/labstack/echo/v4" "html/template" "io" ) diff --git a/pkg/router/add.go b/pkg/router/add.go new file mode 100644 index 0000000..65a0b0c --- /dev/null +++ b/pkg/router/add.go @@ -0,0 +1,56 @@ +package router + +import ( + "net/http" + "strconv" + + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/config" + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/models" + "github.com/labstack/echo/v4" + "github.com/labstack/gommon/log" +) + +func addKonfi(c echo.Context) error { + + if !isLoggedIn(c) { + return echo.NewHTTPError(http.StatusForbidden, "Login first.") + } + + // Mode nach Kofis + if config.GetMode() == 0 { + kofi := &models.Kofi{} + kofi.Name = c.FormValue("name") + kofi.Gemeinde = c.FormValue("gemeinde") + + // Einfügen + err := kofi.Add() + if err != nil { + return echo.NewHTTPError(http.StatusInternalServerError, "Error.") + } + + return c.JSON(http.StatusOK, "success") + + } + + // Mode nach Gemeinden + if config.GetMode() == 1 { + + var err error + community := &models.Community{} + community.Name = c.FormValue("name") + community.KonfiCount, err = strconv.ParseInt(c.FormValue("konfis"), 10, 64) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, "konfiCount not int") + } + + err = community.Add() + if err != nil { + return echo.NewHTTPError(http.StatusInternalServerError, "Error.") + } + + return c.JSON(http.StatusOK, "success") + } + + log.Error("Invalid mode.") + return echo.ErrInternalServerError +} diff --git a/pkg/router/admin.go b/pkg/router/admin.go new file mode 100644 index 0000000..7760622 --- /dev/null +++ b/pkg/router/admin.go @@ -0,0 +1,33 @@ +package router + +import ( + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/models" + "github.com/labstack/echo-contrib/session" + "github.com/labstack/echo/v4" + "net/http" + "strconv" + + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/config" +) + +type AdminInfos struct { + Loggedin bool + Mode int + Version string +} + +func isLoggedIn(c echo.Context) bool { + sess, _ := session.Get(sessionName, c) + _, is := sess.Values[sessionKey] + return is +} + +func adminHandler(c echo.Context) error { + adminInfos := AdminInfos{true, config.GetMode(), models.Version} + if isLoggedIn(c) { + return c.Render(http.StatusOK, "admin_mode_"+strconv.Itoa(config.GetMode()), adminInfos) + } + + adminInfos.Loggedin = false + return c.Render(http.StatusOK, "login", adminInfos) +} diff --git a/pkg/router/delete.go b/pkg/router/delete.go new file mode 100644 index 0000000..5afcedc --- /dev/null +++ b/pkg/router/delete.go @@ -0,0 +1,42 @@ +package router + +import ( + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/config" + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/models" + "github.com/labstack/echo/v4" + "github.com/labstack/gommon/log" + "net/http" + "strconv" +) + +func deleteKonfi(c echo.Context) error { + + if !isLoggedIn(c) { + return echo.NewHTTPError(http.StatusForbidden, "Login first.") + } + + id, _ := strconv.ParseInt(c.FormValue("id"), 10, 64) + + if config.GetMode() == 0 { + k := &models.Kofi{ID: id} + err := k.Delete() + if err != nil { + return echo.NewHTTPError(http.StatusInternalServerError, "Error.") + } + + return c.JSON(http.StatusOK, "success") + } + + if config.GetMode() == 1 { + community := &models.Community{ID: id} + err := community.Delete() + if err != nil { + return echo.NewHTTPError(http.StatusInternalServerError, "Error.") + } + + return c.JSON(http.StatusOK, "success") + } + + log.Error("Invalid mode.") + return echo.ErrInternalServerError +} diff --git a/pkg/router/getList.go b/pkg/router/getList.go new file mode 100644 index 0000000..e933870 --- /dev/null +++ b/pkg/router/getList.go @@ -0,0 +1,35 @@ +package router + +import ( + "github.com/labstack/echo/v4" + "github.com/labstack/gommon/log" + "net/http" + + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/config" + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/models" +) + +func getList(c echo.Context) error { + if config.GetMode() == 0 { + asc := c.QueryParam("asc") + kofis, err := models.ReadAllKofis(asc != "") + if err != nil { + log.Error(err) + return echo.ErrInternalServerError + } + return c.JSON(http.StatusOK, kofis) + } + + if config.GetMode() == 1 { + asc := c.QueryParam("asc") + communities, err := models.ReadAllCommunities(asc != "") + if err != nil { + log.Error(err) + return echo.ErrInternalServerError + } + + return c.JSON(http.StatusOK, communities) + } + + return echo.NewHTTPError(http.StatusBadRequest, "Error. (Wrong mode)") +} diff --git a/pkg/router/login.go b/pkg/router/login.go new file mode 100644 index 0000000..825473b --- /dev/null +++ b/pkg/router/login.go @@ -0,0 +1,39 @@ +package router + +import ( + "github.com/gorilla/sessions" + "github.com/labstack/echo-contrib/session" + "github.com/labstack/echo/v4" + "net/http" + + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/config" +) + +const ( + sessionName = `session` + sessionKey = `login` +) + +func login(c echo.Context) error { + pass := c.FormValue("password") + + if config.GetAdminPassword() != pass { + return echo.NewHTTPError(http.StatusBadRequest, "Wrong password.") + } + + sess, _ := session.Get(sessionName, c) + sess.Options = &sessions.Options{ + MaxAge: 86400 * 7, + } + sess.Values[sessionKey] = true + err := sess.Save(c.Request(), c.Response()) + if err != nil { + return echo.ErrInternalServerError + } + + if c.QueryParam("direct") == "true" { + return c.Redirect(http.StatusSeeOther, "/admin") + } + + return c.NoContent(http.StatusOK) +} diff --git a/pkg/router/logout.go b/pkg/router/logout.go new file mode 100644 index 0000000..6480474 --- /dev/null +++ b/pkg/router/logout.go @@ -0,0 +1,19 @@ +package router + +import ( + "net/http" + + "github.com/labstack/echo-contrib/session" + "github.com/labstack/echo/v4" +) + +func logout(c echo.Context) error { + sess, _ := session.Get(sessionName, c) + sess.Values[sessionKey] = false + err := sess.Save(c.Request(), c.Response()) + if err != nil { + return echo.ErrInternalServerError + } + + return c.Redirect(http.StatusSeeOther, "/admin") +} diff --git a/pkg/router/router.go b/pkg/router/router.go new file mode 100644 index 0000000..e0a29e1 --- /dev/null +++ b/pkg/router/router.go @@ -0,0 +1,50 @@ +package router + +import ( + "github.com/gorilla/sessions" + "github.com/labstack/echo-contrib/session" + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" + "html/template" +) + +func NewEcho() *echo.Echo { + e := echo.New() + e.HideBanner = true + + //Template + t := &Template{ + templates: template.Must(template.ParseGlob("tpl/*.html")), + } + e.Renderer = t + + //Logger + e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ + Format: "${time_rfc3339}: ${remote_ip} ${method} ${status} ${uri} - ${user_agent}\n", + })) + + // Session middleware + e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret")))) + + return e +} + +func RegisterRoutes(e *echo.Echo) { + //Static ontent + e.Static("/assets", "assets") + + //Routes + e.GET("/admin", adminHandler) + e.GET("/", showList) + + e.GET("/list", getList) + e.GET("/ws", ws) + + e.POST("/login", login) + e.GET("/logout", logout) + + // Routes with auth -> TODO: build a middleware which checks this + e.POST("/update", update) + e.POST("/delete", deleteKonfi) + e.POST("/add", addKonfi) +} diff --git a/showList.go b/pkg/router/showList.go similarity index 50% rename from showList.go rename to pkg/router/showList.go index ca9d031..0ab7e49 100644 --- a/showList.go +++ b/pkg/router/showList.go @@ -1,14 +1,15 @@ -package main +package router import ( - "github.com/labstack/echo" + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/config" + "github.com/labstack/echo/v4" "net/http" ) func showList(c echo.Context) error { //Config - SiteConf := initConfig() + SiteConf := config.GetConfig() //Template return c.Render(http.StatusOK, "index", SiteConf) diff --git a/pkg/router/update.go b/pkg/router/update.go new file mode 100644 index 0000000..7506f74 --- /dev/null +++ b/pkg/router/update.go @@ -0,0 +1,60 @@ +package router + +import ( + "net/http" + "strconv" + + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/config" + "git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/models" + "github.com/labstack/echo/v4" + "github.com/labstack/gommon/log" +) + +type UpdatedMessageKofi struct { + Message string + Data *models.Kofi +} + +type UpdatedMessageCommunity struct { + Message string + Data *models.Community +} + +func update(c echo.Context) error { + + if !isLoggedIn(c) { + return echo.NewHTTPError(http.StatusForbidden, "Login first.") + } + + id, _ := strconv.ParseInt(c.FormValue("id"), 10, 64) + addcoins, _ := strconv.ParseInt(c.FormValue("addcoins"), 10, 64) + + if config.GetMode() == 0 { + kofi := &models.Kofi{ID: id} + err := kofi.Update(addcoins) + if err != nil { + log.Error(err) + return echo.NewHTTPError(http.StatusBadRequest, err) + } + return c.JSON(http.StatusOK, UpdatedMessageKofi{ + Message: "success", + Data: kofi, + }) + } + + if config.GetMode() == 1 { + community := &models.Community{ID: id} + err := community.Update(addcoins) + if err != nil { + log.Error(err) + return echo.NewHTTPError(http.StatusBadRequest, err) + } + return c.JSON(http.StatusOK, UpdatedMessageCommunity{ + Message: "success", + Data: community, + }) + } + + log.Error("Invalid mode.") + return echo.ErrInternalServerError +} diff --git a/ws.go b/pkg/router/ws.go similarity index 80% rename from ws.go rename to pkg/router/ws.go index 6154ddf..adc955d 100644 --- a/ws.go +++ b/pkg/router/ws.go @@ -1,15 +1,12 @@ -package main +package router import ( - "github.com/labstack/echo" - "golang.org/x/net/websocket" - "fmt" - "encoding/json" + "github.com/labstack/echo/v4" ) func ws(c echo.Context) error { //Datenbankverbindung aufbauen - db := DBinit() + /*db := DBinit() // Websocket websocket.Handler(func(ws *websocket.Conn) { @@ -36,6 +33,6 @@ func ws(c echo.Context) error { } } - }).ServeHTTP(c.Response(), c.Request()) + }).ServeHTTP(c.Response(), c.Request())*/ return nil -} \ No newline at end of file +} diff --git a/update.go b/update.go deleted file mode 100644 index bf3e309..0000000 --- a/update.go +++ /dev/null @@ -1,78 +0,0 @@ -package main - -import ( - "github.com/labstack/echo" - "net/http" - "strconv" -) - -func update(c echo.Context) error { - - //Config - SiteConf := initConfig() - - //Datenbankverbindung aufbauen - db := DBinit() - - rw := c.Response() - r := c.Request() - - //Session init - sess := GlobalSessions.SessionStart(rw, r) - logged := sess.Get("login") - - //Wenn das password stimmt - if logged != nil { - id, _ := strconv.Atoi(c.FormValue("id")) - addcoins, _ := strconv.Atoi(c.FormValue("addcoins")) - - if SiteConf.Mode == 0 { - //Aktuelle Coins holen - var kofi= Kofi{ID: id} - has, err := db.Get(&kofi) - checkErr(err) - if has { - newCoins := kofi.KCoins + addcoins - - //Updaten - kofi.KCoins = newCoins - _, err := db.Id(id).Update(kofi) - - if err == nil { - return c.JSON(http.StatusOK, UpdatedMessageKofi{"success", kofi}) - } - } - } else if SiteConf.Mode == 1{ - var gemeinde = Gemeinde{ID: id} - has, err := db.Get(&gemeinde) - checkErr(err) - - if has { - newCoins := gemeinde.KCoins + addcoins - - // Updaten - gemeinde.KCoins = newCoins - _, err := db.ID(id).Update(gemeinde) - - if err != nil { - return c.JSON(http.StatusInternalServerError, Message{"Error."}) - } - - _, err = db.ID(id).Get(&gemeinde) - - if err == nil { - - // Coins pP aausrechnen - gemeinde.CoinsQuota = float64(gemeinde.KCoins) / float64(gemeinde.KonfiCount) - - return c.JSON(http.StatusOK, UpdatedMessageGemeinde{"success", gemeinde}) - } - - } - - } - return c.JSON(http.StatusInternalServerError, Message{"Error."}) - } else { - return c.JSON(http.StatusForbidden, Message{"Login first."}) - } -} diff --git a/utils.go b/utils.go deleted file mode 100644 index 70ed34c..0000000 --- a/utils.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import "log" - -var Version string = "+1.1-2-g353bf3b" - -type Kofi struct { - ID int `xorm:"pk autoincr"` - Name string - Gemeinde string - KCoins int -} - -type Gemeinde struct { - ID int `xorm:"pk autoincr"` - Name string - KCoins int - - KonfiCount int - CoinsQuota float64 `xorm:"-"` -} - -type Message struct { - Message string -} - -type UpdatedMessageKofi struct { - Message string - Data Kofi -} - -type UpdatedMessageGemeinde struct { - Message string - Data Gemeinde -} - -//CheckError -func checkErr(err error) { - if err != nil { - log.Fatal(err) - } -}