12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- package controllers
- import (
- "net/http"
- "rate-it-api/models"
- "rate-it-api/utils"
- "time"
- "github.com/auth0/go-jwt-middleware"
- "github.com/dgrijalva/jwt-go"
- "golang.org/x/crypto/bcrypt"
- )
- // AuthToken return a JWT token
- func AuthToken(w http.ResponseWriter, r *http.Request) {
- r.ParseForm()
- user, err := models.UserGetByEmail(r.Form.Get("email"))
- if err != nil {
- utils.SendJSONErrorResponse(w, "This user doesn't exist", http.StatusBadRequest)
- return
- }
- if user.Verify != 1 {
- utils.SendJSONErrorResponse(w, "Email must be verify", http.StatusUnauthorized)
- return
- }
- password := r.Form.Get("password")
- err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
- if err != nil {
- utils.SendJSONErrorResponse(w, "Invalid password", http.StatusUnauthorized)
- return
- }
- /* Create the token */
- token := jwt.New(jwt.SigningMethodHS256)
- config := utils.GetConfig()
- /* Set token claims */
- claims := make(jwt.MapClaims)
- claims["email"] = user.Email
- claims["expiresAt "] = time.Now().Add(time.Duration(config.JWT.Expiration)).Unix()
- token.Claims = claims
- /* Sign the token with our secret */
- tokenString, _ := token.SignedString([]byte(config.JWT.Secret))
- tokenResponse := utils.TokenResponseStruct{
- Token: tokenString,
- Expiration: config.JWT.Expiration / (1000 * 1000 * 1000),
- }
- /* Finally, write the token to the browser window */
- utils.SendJSONTokenAcknowledgeResponse(w, tokenResponse, http.StatusOK)
- }
- func jwtErrorHandler(w http.ResponseWriter, r *http.Request, err string) {
- utils.SendJSONErrorResponse(w, err, http.StatusUnauthorized)
- }
- // JwtMiddleware check JWT signature
- var JwtMiddleware = jwtmiddleware.New(jwtmiddleware.Options{
- ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
- config := utils.GetConfig()
- return []byte(config.JWT.Secret), nil
- },
- // When set, the middleware verifies that tokens are signed with the specific signing algorithm
- // If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
- // Important to avoid security issues described here: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
- SigningMethod: jwt.SigningMethodHS256,
- ErrorHandler: jwtErrorHandler,
- })
|