105 lines
2.5 KiB
Go
105 lines
2.5 KiB
Go
package controllers
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"gitea.zjmud.com/phyer/rbac/models"
|
|
"gitea.zjmud.com/phyer/rbac/repositories"
|
|
"gitea.zjmud.com/phyer/rbac/utils"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/go-redis/redis/v8"
|
|
"github.com/go-redis/redis/v8"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type AuthController struct {
|
|
DB *gorm.DB
|
|
Redis *redis.Client
|
|
}
|
|
|
|
func NewAuthController(db *gorm.DB, redis *redis.Client) *AuthController {
|
|
return &AuthController{DB: db, Redis: redis}
|
|
}
|
|
|
|
func (ac *AuthController) Login(c *gin.Context) {
|
|
type LoginRequest struct {
|
|
Username string `json:"username" binding:"required"`
|
|
Password string `json:"password" binding:"required"`
|
|
}
|
|
|
|
var req LoginRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
utils.Error(c, http.StatusBadRequest, "Invalid request format")
|
|
return
|
|
}
|
|
|
|
userRepo := repositories.NewUserRepository(ac.DB)
|
|
user, err := userRepo.FindByUsername(req.Username)
|
|
if err != nil {
|
|
utils.Error(c, http.StatusUnauthorized, "Invalid credentials")
|
|
return
|
|
}
|
|
|
|
|
|
hashedPassword, err := models.HashPassword(req.Password)
|
|
if err != nil {
|
|
utils.Error(c, http.StatusUnauthorized, "Invalid credentials")
|
|
return
|
|
}
|
|
hashedHex := fmt.Sprintf("%x", hashedPassword)
|
|
if hashedHex != user.Password {
|
|
if err != nil {
|
|
utils.Error(c, http.StatusUnauthorized, "Invalid credentials")
|
|
return
|
|
}
|
|
|
|
hashedHex := fmt.Sprintf("%x", hashedPassword)
|
|
if hashedHex != user.Password {
|
|
utils.Error(c, http.StatusUnauthorized, "Invalid credentials")
|
|
return
|
|
}
|
|
|
|
token, err := utils.GenerateToken(user.ID)
|
|
if err != nil {
|
|
utils.Error(c, http.StatusInternalServerError, "Failed to generate token")
|
|
return
|
|
}
|
|
|
|
utils.Success(c, gin.H{"token": token})
|
|
}
|
|
|
|
func (ac *AuthController) Register(c *gin.Context) {
|
|
type RegisterRequest struct {
|
|
Username string `json:"username" binding:"required"`
|
|
Password string `json:"password" binding:"required"`
|
|
Email string `json:"email" binding:"required,email"`
|
|
}
|
|
|
|
var req RegisterRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
utils.Error(c, http.StatusBadRequest, "Invalid request format")
|
|
return
|
|
}
|
|
|
|
hashedPassword, err := models.HashPassword(req.Password)
|
|
if err != nil {
|
|
utils.Error(c, http.StatusInternalServerError, "Failed to hash password")
|
|
return
|
|
}
|
|
|
|
newUser := &models.User{
|
|
Username: req.Username,
|
|
Password: string(hashedPassword),
|
|
Email: req.Email,
|
|
}
|
|
|
|
userRepo := repositories.NewUserRepository(ac.DB)
|
|
if err := userRepo.Create(newUser); err != nil {
|
|
utils.Error(c, http.StatusConflict, "User already exists")
|
|
return
|
|
}
|
|
|
|
utils.Success(c, newUser)
|
|
}
|