handler.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package main
  2. import (
  3. "net/http"
  4. "time"
  5. "github.com/dgrijalva/jwt-go"
  6. "github.com/labstack/echo"
  7. )
  8. type handler struct{}
  9. // Most of the code is taken from the echo guide
  10. // https://echo.labstack.com/cookbook/jwt
  11. func (h *handler) login(c echo.Context) error {
  12. username := c.FormValue("username")
  13. password := c.FormValue("password")
  14. // Check in your db if the user exists or not
  15. if username == "jon" && password == "password" {
  16. // Create token
  17. token := jwt.New(jwt.SigningMethodHS256)
  18. // Set claims
  19. // This is the information which frontend can use
  20. // The backend can also decode the token and get admin etc.
  21. claims := token.Claims.(jwt.MapClaims)
  22. claims["name"] = "Jon Doe"
  23. claims["admin"] = true
  24. claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
  25. // Generate encoded token and send it as response.
  26. // The signing string should be secret (a generated UUID works too)
  27. t, err := token.SignedString([]byte("secret"))
  28. if err != nil {
  29. return err
  30. }
  31. return c.JSON(http.StatusOK, map[string]string{
  32. "token": t,
  33. })
  34. }
  35. return echo.ErrUnauthorized
  36. }
  37. // Most of the code is taken from the echo guide
  38. // https://echo.labstack.com/cookbook/jwt
  39. func (h *handler) private(c echo.Context) error {
  40. user := c.Get("user").(*jwt.Token)
  41. claims := user.Claims.(jwt.MapClaims)
  42. name := claims["name"].(string)
  43. return c.String(http.StatusOK, "Welcome "+name+"!")
  44. }