Library/routes/login.go

52 lines
1.2 KiB
Go
Raw Normal View History

package routes
import (
2017-11-21 10:40:07 +00:00
"crypto/md5"
"encoding/hex"
2018-03-05 11:53:12 +00:00
"git.kolaente.de/konrad/Library/models"
"github.com/dgrijalva/jwt-go"
2017-11-07 15:35:10 +00:00
"github.com/labstack/echo"
"net/http"
2017-11-07 15:35:10 +00:00
"time"
)
2017-11-08 09:55:17 +00:00
// Login is the login handler
func Login(c echo.Context) error {
2017-11-08 16:12:05 +00:00
u := new(models.UserLogin)
if err := c.Bind(u); err != nil {
return c.JSON(http.StatusBadRequest, models.Message{"Please provide a username and password."})
}
// Check user
user, err := models.CheckUserCredentials(u)
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
2018-01-23 11:37:13 +00:00
claims["admin"] = user.IsAdmin
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
2017-11-20 14:42:36 +00:00
avatar := md5.Sum([]byte(user.Email))
claims["avatar"] = hex.EncodeToString(avatar[:])
// Generate encoded token and send it as response.
t, err := token.SignedString(models.Config.JWTLoginSecret)
if err != nil {
return err
}
return c.JSON(http.StatusOK, map[string]string{
"token": t,
})
}