Remake
Добавил авторизацию в приложение, сделал регистарцию, добавил мидлы
This commit is contained in:
@@ -46,3 +46,37 @@ func Login(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"token": tokenString})
|
||||
}
|
||||
|
||||
func Register(c *gin.Context) {
|
||||
var input struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
// 1. Проверяем входящие данные
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid input"})
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Хешируем пароль (чтобы не хранить его в открытом виде)
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to hash password"})
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Создаем объект пользователя
|
||||
user := models.User{
|
||||
Username: input.Username,
|
||||
Password: string(hashedPassword),
|
||||
Role: "user", // по умолчанию
|
||||
}
|
||||
|
||||
// 4. Сохраняем в базу через GORM
|
||||
if err := database.DB.Create(&user).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not create user maybe username exists?"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Registration successful"})
|
||||
}
|
||||
|
||||
+17
-9
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"viplight-mrp/database"
|
||||
"viplight-mrp/handlers"
|
||||
"viplight-mrp/middleware"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -24,7 +25,7 @@ func main() {
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "https://mrp.kkhome.ru")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
@@ -32,14 +33,21 @@ func main() {
|
||||
c.Next()
|
||||
})
|
||||
|
||||
// Роуты теперь вызывают функции из handlers
|
||||
r.GET("/api/parts/:id", handlers.GetPart)
|
||||
r.GET("/api/parts", handlers.GetAllParts)
|
||||
r.GET("/api/orders", handlers.GetsOrders)
|
||||
r.POST("/api/parts", handlers.CreatePart)
|
||||
r.POST("/api/parts/bulk", handlers.ImportParts)
|
||||
r.PATCH("/api/parts/:id/status", handlers.UpdateStatus)
|
||||
r.DELETE("/api/parts/:id", handlers.DeletePart)
|
||||
r.POST("/register", handlers.Register)
|
||||
r.POST("/login", handlers.Login)
|
||||
|
||||
protected := r.Group("/api")
|
||||
protected.Use(middleware.AuthRequired())
|
||||
{
|
||||
protected.GET("/parts/:id", handlers.GetPart)
|
||||
protected.GET("/parts", handlers.GetAllParts)
|
||||
protected.GET("/orders", handlers.GetsOrders)
|
||||
protected.POST("/parts", handlers.CreatePart)
|
||||
protected.POST("/parts/bulk", handlers.ImportParts)
|
||||
protected.PATCH("/parts/:id/status", handlers.UpdateStatus)
|
||||
protected.DELETE("/parts/:id", handlers.DeletePart)
|
||||
|
||||
}
|
||||
|
||||
r.Run(":8090")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
)
|
||||
|
||||
func AuthRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
if tokenString == authHeader {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token format"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
jwtKey := []byte(os.Getenv("JWT_SECRET"))
|
||||
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
return jwtKey, nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired token"})
|
||||
c.Abort()
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok {
|
||||
c.Set("user_id", claims["user_id"])
|
||||
c.Set("role", claims["role"])
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user