auth.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package controllers
  2. import (
  3. "net/http"
  4. "rate-it-api/models"
  5. "rate-it-api/utils"
  6. "time"
  7. "github.com/auth0/go-jwt-middleware"
  8. "github.com/dgrijalva/jwt-go"
  9. "golang.org/x/crypto/bcrypt"
  10. )
  11. // AuthToken return a JWT token
  12. func AuthToken(w http.ResponseWriter, r *http.Request) {
  13. r.ParseForm()
  14. user, err := models.UserGetByEmail(r.Form.Get("email"))
  15. if err != nil {
  16. utils.SendJSONErrorResponse(w, "This user doesn't exist", http.StatusBadRequest)
  17. return
  18. }
  19. if user.Verify != 1 {
  20. utils.SendJSONErrorResponse(w, "Email must be verify", http.StatusUnauthorized)
  21. return
  22. }
  23. password := r.Form.Get("password")
  24. err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
  25. if err != nil {
  26. utils.SendJSONErrorResponse(w, "Invalid password", http.StatusUnauthorized)
  27. return
  28. }
  29. /* Create the token */
  30. token := jwt.New(jwt.SigningMethodHS256)
  31. config := utils.GetConfig()
  32. /* Set token claims */
  33. claims := make(jwt.MapClaims)
  34. claims["email"] = user.Email
  35. claims["expiresAt "] = time.Now().Add(time.Duration(config.JWT.Expiration)).Unix()
  36. token.Claims = claims
  37. /* Sign the token with our secret */
  38. tokenString, _ := token.SignedString([]byte(config.JWT.Secret))
  39. tokenResponse := utils.TokenResponseStruct{
  40. Token: tokenString,
  41. Expiration: config.JWT.Expiration / (1000 * 1000 * 1000),
  42. }
  43. /* Finally, write the token to the browser window */
  44. utils.SendJSONTokenAcknowledgeResponse(w, tokenResponse, http.StatusOK)
  45. }
  46. func jwtErrorHandler(w http.ResponseWriter, r *http.Request, err string) {
  47. utils.SendJSONErrorResponse(w, err, http.StatusUnauthorized)
  48. }
  49. // JwtMiddleware check JWT signature
  50. var JwtMiddleware = jwtmiddleware.New(jwtmiddleware.Options{
  51. ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
  52. config := utils.GetConfig()
  53. return []byte(config.JWT.Secret), nil
  54. },
  55. // When set, the middleware verifies that tokens are signed with the specific signing algorithm
  56. // If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
  57. // Important to avoid security issues described here: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
  58. SigningMethod: jwt.SigningMethodHS256,
  59. ErrorHandler: jwtErrorHandler,
  60. })