Refactored all the things
continuous-integration/drone/push Build is passing Details

This commit is contained in:
kolaente 2019-09-01 22:59:51 +02:00
parent 0e220b7a9c
commit 9d373ae81d
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
30 changed files with 590 additions and 482 deletions

65
add.go
View File

@ -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."})
}
}

View File

@ -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)
}
}

View File

@ -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
}

23
db.go
View File

@ -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
}

View File

@ -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."})
}
}

View File

@ -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)")
}

4
go.mod
View File

@ -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

19
go.sum
View File

@ -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=

View File

@ -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"})
}
}

View File

@ -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")
}

71
main.go
View File

@ -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),

44
pkg/config/config.go Normal file
View File

@ -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
}

64
pkg/models/community.go Normal file
View File

@ -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
}

27
pkg/models/db.go Normal file
View File

@ -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
}

11
pkg/models/errors.go Normal file
View File

@ -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)
}

44
pkg/models/kofi.go Normal file
View File

@ -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
}

7
pkg/models/utils.go Normal file
View File

@ -0,0 +1,7 @@
package models
var Version = "+1.1-2-g353bf3b"
type Message struct {
Message string
}

View File

@ -1,7 +1,7 @@
package main
package router
import (
"github.com/labstack/echo"
"github.com/labstack/echo/v4"
"html/template"
"io"
)

56
pkg/router/add.go Normal file
View File

@ -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
}

33
pkg/router/admin.go Normal file
View File

@ -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)
}

42
pkg/router/delete.go Normal file
View File

@ -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
}

35
pkg/router/getList.go Normal file
View File

@ -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)")
}

39
pkg/router/login.go Normal file
View File

@ -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)
}

19
pkg/router/logout.go Normal file
View File

@ -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")
}

50
pkg/router/router.go Normal file
View File

@ -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)
}

View File

@ -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)

60
pkg/router/update.go Normal file
View File

@ -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
}

View File

@ -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
}
}

View File

@ -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."})
}
}

View File

@ -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)
}
}