handler.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  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. tokens, err := generateTokenPair()
  17. if err != nil {
  18. return err
  19. }
  20. return c.JSON(http.StatusOK, tokens)
  21. }
  22. return echo.ErrUnauthorized
  23. }
  24. // This is the api to refresh tokens
  25. // Most of the code is taken from the jwt-go package's sample codes
  26. // https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac
  27. func (h *handler) token(c echo.Context) error {
  28. type tokenReqBody struct {
  29. RefreshToken string `json:"refresh_token"`
  30. }
  31. tokenReq := tokenReqBody{}
  32. c.Bind(&tokenReq)
  33. // Parse takes the token string and a function for looking up the key.
  34. // The latter is especially useful if you use multiple keys for your application.
  35. // The standard is to use 'kid' in the head of the token to identify
  36. // which key to use, but the parsed token (head and claims) is provided
  37. // to the callback, providing flexibility.
  38. token, err := jwt.Parse(tokenReq.RefreshToken, func(token *jwt.Token) (interface{}, error) {
  39. // Don't forget to validate the alg is what you expect:
  40. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  41. return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
  42. }
  43. // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
  44. return []byte("secret"), nil
  45. })
  46. if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
  47. // Get the user record from database or
  48. // run through your business logic to verify if the user can log in
  49. if int(claims["sub"].(float64)) == 1 {
  50. newTokenPair, err := generateTokenPair()
  51. if err != nil {
  52. return err
  53. }
  54. return c.JSON(http.StatusOK, newTokenPair)
  55. }
  56. return echo.ErrUnauthorized
  57. }
  58. return err
  59. }
  60. // Most of the code is taken from the echo guide
  61. // https://echo.labstack.com/cookbook/jwt
  62. func (h *handler) private(c echo.Context) error {
  63. user := c.Get("user").(*jwt.Token)
  64. claims := user.Claims.(jwt.MapClaims)
  65. name := claims["name"].(string)
  66. return c.String(http.StatusOK, "Welcome "+name+"!")
  67. }