Add handler auth
This commit is contained in:
@@ -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})
|
||||
}
|
||||
Reference in New Issue
Block a user