/*
* This file is part of laurelin_api
* Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
*
* Licensed under GPL-3.0-only.
* See LICENSE for licensing information.
*/
package handlers
import (
"api/apierror"
"api/auth"
"api/db"
"api/models"
"net/http"
"github.com/gin-gonic/gin"
)
type TokenRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}
func GenerateToken(c *gin.Context) {
var req TokenRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": apierror.InvalidInput})
c.Abort()
return
}
var user models.User
record := db.DbConn.Where("email = ?", req.Email).First(&user)
if record.Error != nil {
c.JSON(http.StatusNotFound, gin.H{"error": apierror.UserNotFound})
c.Abort()
return
}
credErr := user.VerifyPwd(req.Password)
if credErr != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": apierror.InvalidCred})
c.Abort()
return
}
token, err := auth.NewJWTToken(user.Username, user.Email)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": apierror.NewJWTError})
c.Abort()
return
}
c.JSON(http.StatusOK, gin.H{"token": token, "id": user.ID})
}