Добавил авторизацию в приложение, сделал регистарцию, добавил мидлы
This commit is contained in:
2026-05-07 17:57:49 +03:00
parent 7c3b588b26
commit 87ec792fd5
8 changed files with 275 additions and 64 deletions
+34
View File
@@ -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
View File
@@ -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")
}
+48
View File
@@ -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()
}
}