Complete rework using echo

This commit is contained in:
adro 2022-02-18 14:35:03 +01:00
parent 4b86aadae4
commit ecc004edba
10 changed files with 164 additions and 191 deletions

View File

@ -16,6 +16,7 @@ type Device struct {
type config struct {
Server string
PassHash string
SessionTTL float64
Device []Device
}
@ -26,6 +27,7 @@ var configPath string
func init() {
Config = config{
Server: ":8080",
SessionTTL: 1440,
}
// Locations to look for a config file for

12
go.mod
View File

@ -3,7 +3,19 @@ module miniwol
go 1.17
require (
github.com/labstack/echo/v4 v4.6.3
github.com/BurntSushi/toml v1.0.0
github.com/google/uuid v1.3.0
golang.org/x/crypto v0.0.0-20220214200702-86341886e292
)
require (
github.com/labstack/gommon v0.3.1 // indirect
github.com/mattn/go-colorable v0.1.12 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.1 // indirect
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect
golang.org/x/sys v0.0.0-20220209214540-3681064d5158 // indirect
golang.org/x/text v0.3.7 // indirect
)

51
go.sum
View File

@ -1,8 +1,55 @@
github.com/BurntSushi/toml v1.0.0 h1:dtDWrepsVPfW9H/4y7dDgFc2MBUSeJhlaDtK13CxFlU=
github.com/BurntSushi/toml v1.0.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/golang-migrate/migrate v3.5.4+incompatible h1:R7OzwvCJTCgwapPCiX6DyBiu2czIUMDCB118gFTKTUA=
github.com/golang-migrate/migrate v3.5.4+incompatible/go.mod h1:IsVUlFN5puWOmXrqjgGUfIRIbU7mr8oNBE2tyERd9Wk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/labstack/echo/v4 v4.6.3 h1:VhPuIZYxsbPmo4m9KAkMU/el2442eB7EBFFhNTTT9ac=
github.com/labstack/echo/v4 v4.6.3/go.mod h1:Hk5OiHj0kDqmFq7aHe7eDqI7CUhuCrfpupQtLGGLm7A=
github.com/labstack/gommon v0.3.1 h1:OomWaJXm7xR6L1HmEtGyQf26TEn7V6X88mktX9kee9o=
github.com/labstack/gommon v0.3.1/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM=
github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.1 h1:TVEnxayobAdVkhQfrfes2IzOB6o+z4roRkPF52WA1u4=
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220214200702-86341886e292 h1:f+lwQ+GtmgoY+A2YaQxlSOnDjXcQ7ZRLWOHbC6HtRqE=
golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210913180222-943fd674d43e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158 h1:rm+CHSpPEEW2IsXUib1ThaHIjuBVZjxNgSKmBLFfD4c=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -2,12 +2,10 @@ package web
import (
"errors"
"fmt"
"net/http"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"github.com/labstack/echo/v4"
)
var sessions map[string]time.Time
@ -16,52 +14,7 @@ func init() {
sessions = make(map[string]time.Time)
}
func auth(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
password := r.FormValue("password")
if bcrypt.CompareHashAndPassword([]byte("$2a$04$i4bdOiia2YFN7JXfXLgO4ONCffC67ECyzPEcTLzoP3Lzse/sZT5EC"), []byte(password)) != nil {
w.WriteHeader(401)
w.Write([]byte("Wrong Password"))
return
}
token := uuid.New().String()
sessions[token] = time.Now().Add(time.Hour * 24)
w.Header().Add("Set-Cookie", fmt.Sprintf("session=%s; Path=/; SameSite=Strict; HttpOnly; Secure", token))
http.Redirect(w, r, "/device", http.StatusTemporaryRedirect)
default:
w.WriteHeader(http.StatusMethodNotAllowed) // Method not Allowed
}
}
func deauth(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
cookie, err := r.Cookie("session")
if err != nil {
w.WriteHeader(400)
return
}
token := cookie.Value
if isAuthenticated(token) == nil {
delete(sessions, token)
}
default:
w.WriteHeader(405)
}
}
func checkAuthentication(w http.ResponseWriter, r *http.Request) error {
sCookie, err := r.Cookie("")
if err == nil && isAuthenticated(sCookie.Value) == nil {
return nil
}
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return errors.New("authentication error")
}
func isAuthenticated(token string) error {
func checkAuth(token string) error {
for sToken, expiree := range sessions {
// Expire old sessions
if time.Now().After(expiree) {
@ -76,3 +29,13 @@ func isAuthenticated(token string) error {
return errors.New("this token is not associated with a valid session")
}
func withAuth(handler echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
session, err := c.Cookie("session")
if err != nil || checkAuth(session.Value) != nil {
return c.Redirect(http.StatusSeeOther, "/")
}
return handler(c)
}
}

View File

@ -1,34 +0,0 @@
package web
import (
"bytes"
"html/template"
"miniwol/config"
"net/http"
)
func device(w http.ResponseWriter, r *http.Request) {
if checkAuthentication(w, r) != nil {
return
}
page := struct {
Title string
Content template.HTML
}{
Title: "Devices",
}
var contentBuffer bytes.Buffer
err := deviceTemplate.Execute(&contentBuffer, config.Config.Device)
if err != nil {
panic(err)
}
page.Content = template.HTML(contentBuffer.String())
err = pageTemplate.Execute(w, page)
if err != nil {
panic(err)
}
}

View File

@ -1,39 +0,0 @@
package web
import (
"bytes"
"html/template"
"net/http"
)
func index(w http.ResponseWriter, r *http.Request) {
// Serve static files
if r.URL.Path != "/" {
fileServer.ServeHTTP(w, r)
return
}
page := struct {
Title string
Content template.HTML
}{}
var contentBuffer bytes.Buffer
sCookie, err := r.Cookie("session")
if err == nil && isAuthenticated(sCookie.Value) == nil {
page.Title = "Miniwol"
contentBuffer.WriteString("<a href='/device'>Device</a>")
} else {
page.Title = "Login"
err = loginTemplate.Execute(&contentBuffer, struct{}{})
if err != nil {
panic(err)
}
}
page.Content = template.HTML(contentBuffer.String())
err = pageTemplate.Execute(w, page)
if err != nil {
panic(err)
}
}

View File

View File

@ -5,7 +5,7 @@
<th>IP/Broadcast</th>
<th>Actions</th>
</tr>
{{range $i, $d := .}}
{{range $i, $d := .Device}}
<tr>
<td>{{$d.Alias}}</td>
<td>{{$d.MAC}}</td>

View File

@ -1,30 +0,0 @@
package web
import (
"fmt"
"miniwol/config"
"miniwol/lib"
"net/http"
"strings"
)
func wake(w http.ResponseWriter, r *http.Request) {
if checkAuthentication(w, r) != nil {
return
}
for i, device := range config.Config.Device {
if r.FormValue("alias") == device.Alias && r.FormValue("index") == fmt.Sprint(i) {
if !strings.Contains(device.IP, ":") {
device.IP += ":9"
}
err := lib.SendPacket(":0", device.IP, device.MAC)
if err != nil {
panic(err)
}
w.Write([]byte("Successfuly woke up " + device.Alias))
return
}
}
}

View File

@ -1,55 +1,107 @@
package web
import (
"bytes"
"embed"
"errors"
"fmt"
"html/template"
"io/fs"
"log"
"miniwol/config"
"miniwol/lib"
"net/http"
"strings"
"time"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"golang.org/x/crypto/bcrypt"
)
//go:embed template/*
var templateFS embed.FS
var pageTemplate *template.Template
var loginTemplate *template.Template
var deviceTemplate *template.Template
//go:embed public
var publicFS embed.FS
var fileServer http.Handler
var templates *template.Template
func init() {
var err error
pageTemplate, err = template.ParseFS(templateFS, "template/page.html.tmpl")
templates, err = template.ParseFS(templateFS, "template/*.html.tmpl")
if err != nil {
panic(err)
}
loginTemplate, err = template.ParseFS(templateFS, "template/login.html.tmpl")
if err != nil {
panic(err)
}
deviceTemplate, err = template.ParseFS(templateFS, "template/device.html.tmpl")
if err != nil {
panic(err)
}
// Static file handler
staticContent, err := fs.Sub(publicFS, "public")
if err != nil {
panic(err)
}
fileServer = http.FileServer(http.FS(staticContent))
}
func Run() error {
http.HandleFunc("/auth", auth)
http.HandleFunc("/deauth", deauth)
http.HandleFunc("/device", device)
http.HandleFunc("/wake", wake)
http.HandleFunc("/", index)
e := echo.New()
log.Println("Starting Webserver on", config.Config.Server)
return http.ListenAndServe(config.Config.Server, nil)
e.GET("/", index)
e.POST("/auth", auth)
e.POST("/wake", withAuth(wake))
return e.Start(config.Config.Server)
}
func Page(c echo.Context, code int, title string, page string, data interface{}) error {
var contentBuffer bytes.Buffer
err := templates.ExecuteTemplate(&contentBuffer, page, data)
if err != nil {
return err
}
var pageBuffer bytes.Buffer
err = templates.ExecuteTemplate(&pageBuffer, "page.html.tmpl", struct {
Title string
Content template.HTML
}{
Title: title,
Content: template.HTML(contentBuffer.String()),
})
if err != nil {
return err
}
return c.HTML(code, pageBuffer.String())
}
// Handlers
func index(c echo.Context) error {
session, err := c.Cookie("session")
if err != nil || checkAuth(session.Value) != nil {
return Page(c, 401, "Login", "login.html.tmpl", nil)
} else {
return Page(c, 200, "Device", "device.html.tmpl", config.Config)
}
}
func auth(c echo.Context) error {
password := c.FormValue("password")
if bcrypt.CompareHashAndPassword([]byte(config.Config.PassHash), []byte(password)) != nil {
return c.String(401, "Wrong Password")
}
token := uuid.New().String()
sessions[token] = time.Now().Add(time.Second * time.Duration(config.Config.SessionTTL*60))
c.SetCookie(&http.Cookie{
Name: "session",
Value: token,
Path: "/",
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Expires: sessions[token],
})
return c.Redirect(http.StatusSeeOther, "/")
}
func wake(c echo.Context) error {
for i, device := range config.Config.Device {
if c.FormValue("alias") == device.Alias && c.FormValue("index") == fmt.Sprint(i) {
if !strings.Contains(device.IP, ":") {
device.IP += ":9"
}
err := lib.SendPacket(":0", device.IP, device.MAC)
if err != nil {
return err
}
return c.Redirect(http.StatusSeeOther, "/")
}
}
return errors.New("device not found")
}