inteface.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/labstack/echo"
  5. "github.com/labstack/echo/middleware"
  6. "golang.org/x/crypto/bcrypt"
  7. "net/http"
  8. )
  9. func serveInterface(address string) {
  10. e := echo.New()
  11. e.GET("/", func(c echo.Context) error {
  12. return c.String(http.StatusOK, "ELEC0017 Project")
  13. //return c.JSON(http.StatusOK, &config)
  14. })
  15. e.GET("/new/admin", func(c echo.Context) error {
  16. name := c.QueryParam("username")
  17. pass := c.QueryParam("password")
  18. if len(name) == 0 {
  19. return c.String(400, "No username")
  20. }
  21. if len(pass) == 0 {
  22. return c.String(400, "No password")
  23. }
  24. hash, err := bcrypt.GenerateFromPassword([]byte(pass), 14)
  25. if err != nil {
  26. fmt.Printf("Failed hash password %s\n", err)
  27. return c.String(400, "Error")
  28. }
  29. cx := *config
  30. cx.Admins[name] = configAdmin{name, hash}
  31. saveConfig()
  32. return c.String(200, "OK")
  33. })
  34. //g := e.Group("/admin")
  35. e.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
  36. user, ok := config.Admins[username]
  37. if !ok {
  38. return false, nil
  39. }
  40. err := bcrypt.CompareHashAndPassword(user.Hash, []byte(password))
  41. return err == nil, nil
  42. }))
  43. e.GET("/admin/config", func(c echo.Context) error {
  44. return c.JSON(http.StatusOK, &config)
  45. })
  46. e.Logger.Fatal(e.Start(address))
  47. }