package routes

import (
	"github.com/labstack/echo"
	"github.com/dgrijalva/jwt-go"
	"time"
	"net/http"
	"git.mowie.cc/konrad/Library/models"
)

func Login(c echo.Context) error {
	username := c.FormValue("username")
	password := c.FormValue("password")

	// 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
	}

	return c.JSON(http.StatusOK, map[string]string{
		"token": t,
	})
}
