58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
package controllers
|
|
|
|
import (
|
|
"gitea.zjmud.xyz/phyer/rbac/models"
|
|
"gitea.zjmud.xyz/phyer/rbac/services"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func Login(c *gin.Context) {
|
|
var loginData struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
if err := c.ShouldBindJSON(&loginData); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
user, err := services.Authenticate(loginData.Username, loginData.Password)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
|
|
return
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
|
"sub": user.ID,
|
|
"exp": time.Now().Add(time.Hour * 24).Unix(),
|
|
})
|
|
|
|
tokenString, err := token.SignedString([]byte("your-256-bit-secret"))
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"token": tokenString})
|
|
}
|
|
|
|
func Register(c *gin.Context) {
|
|
var user models.User
|
|
if err := c.ShouldBindJSON(&user); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
if err := services.CreateUser(&user); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusCreated, user)
|
|
}
|