Add handler auth

This commit is contained in:
2026-05-07 11:39:41 +03:00
parent e4d356b92e
commit 1c67d06c50
6 changed files with 78 additions and 1 deletions
+50
View File
@@ -0,0 +1,50 @@
package handlers
import (
"net/http"
"time"
"os"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
"viplight-mrp/database"
"viplight-mrp/models"
)
jwtSecret := os.Getenv("JWT_SECRET")
jwtKey := []byte(jwtSecret)
func Login(c *gin.Context) {
var input struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"})
return
}
var user models.User
err := database.DB.Where("username = ?", input.Username).First(&user).Error
passErr := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(input.Password))
if err != nil || passErr != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid login or password"})
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": user.ID,
"role": user.Role,
"exp": time.Now().Add(time.Hour * 24).Unix(),
})
tokenString, _ := token.SignedString(jwtKey)
c.JSON(http.StatusOK, gin.H{"token": tokenString})
}