2017-10-09 19:06:40 +00:00
|
|
|
package routes
|
|
|
|
|
|
|
|
import (
|
2017-11-07 15:35:10 +00:00
|
|
|
"git.mowie.cc/konrad/Library/models"
|
2017-10-09 19:06:40 +00:00
|
|
|
"github.com/dgrijalva/jwt-go"
|
2017-11-07 15:35:10 +00:00
|
|
|
"github.com/labstack/echo"
|
2017-10-09 19:06:40 +00:00
|
|
|
"net/http"
|
2017-11-07 15:35:10 +00:00
|
|
|
"time"
|
2017-10-09 19:06:40 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func Login(c echo.Context) error {
|
|
|
|
username := c.FormValue("username")
|
|
|
|
password := c.FormValue("password")
|
|
|
|
|
2017-10-10 09:09:26 +00:00
|
|
|
// Check user
|
|
|
|
user, err := models.CheckUserCredentials(username, password)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return c.JSON(http.StatusUnauthorized, models.Message{"Wrong username or password."})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create token
|
|
|
|
token := jwt.New(jwt.SigningMethodHS256)
|
|
|
|
|
|
|
|
// Set claims
|
|
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
|
|
claims["name"] = user.Name
|
|
|
|
claims["username"] = user.Username
|
|
|
|
claims["email"] = user.Email
|
|
|
|
claims["id"] = user.ID
|
|
|
|
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
|
|
|
|
|
|
|
|
// Generate encoded token and send it as response.
|
|
|
|
t, err := token.SignedString(models.Config.JWTLoginSecret)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2017-10-09 19:06:40 +00:00
|
|
|
}
|
|
|
|
|
2017-10-10 09:09:26 +00:00
|
|
|
return c.JSON(http.StatusOK, map[string]string{
|
|
|
|
"token": t,
|
|
|
|
})
|
|
|
|
}
|