fix(backend,frontend) remake update profile

This commit is contained in:
2026-05-09 11:42:41 +03:00
parent fe331026aa
commit 92e440deb0
14 changed files with 508 additions and 91 deletions
Binary file not shown.
-82
View File
@@ -1,82 +0,0 @@
package handlers
import (
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
"viplight-mrp/database"
"viplight-mrp/models"
)
func Login(c *gin.Context) {
jwtKey := []byte(os.Getenv("JWT_SECRET"))
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})
}
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"})
}
+122
View File
@@ -0,0 +1,122 @@
package handlers
import (
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
"viplight-mrp/database"
"viplight-mrp/models"
)
func Login(c *gin.Context) {
jwtKey := []byte(os.Getenv("JWT_SECRET"))
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, "user": gin.H{
"id": user.ID,
"first_name": user.FirstName,
"last_name": user.LastName,
"phone": user.Phone,
"department": user.Department,
"role": user.Role,
}})
}
func Register(c *gin.Context) {
var input struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required,min=8"`
FirstName string `json:"first_name" binding:"required"`
LastName string `json:"last_name" binding:"required"`
Phone string `json:"phone"`
Department string `json:"department" binding:"required"`
Role string `json:"role" binding:"required"`
}
// 1. Проверяем входящие данные
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Ошибка валидации ", "details": err.Error()})
return
}
// 2. Хешируем пароль (чтобы не хранить его в открытом виде)
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Ошибка при шифровании пароля"})
return
}
// 3. Создаем объект пользователя
user := models.User{
Username: input.Username,
Password: string(hashedPassword),
FirstName: input.FirstName,
LastName: input.LastName,
Phone: input.Phone,
Department: input.Department,
Role: input.Role, // по умолчанию
}
// 4. Сохраняем в базу через GORM
if err := database.DB.Create(&user).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Ошибка при регистрации пользователя", "details": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Пользователь успешно зарегистрирован"})
}
func UpdateProfile(c *gin.Context) {
var input models.UpdateUserInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
userID := c.MustGet("user_id")
if err := database.DB.Model(&models.User{}).Where("id = ?", userID).Updates(models.User{
FirstName: input.FirstName,
LastName: input.LastName,
Phone: input.Phone,
Department: input.Department,
Role: input.Role,
}).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Не удалось обновить данные", "details": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Данные успешно обновлены"})
}
+6 -2
View File
@@ -35,9 +35,7 @@ func main() {
api := r.Group("/api")
{
api.POST("/register", handlers.Register)
api.POST("/login", handlers.Login)
protected := api.Group("/")
protected.Use(middleware.AuthRequired())
{
@@ -47,8 +45,14 @@ func main() {
protected.POST("/parts", handlers.CreatePart)
protected.POST("/parts/bulk", handlers.ImportParts)
protected.PATCH("/parts/:id/status", handlers.UpdateStatus)
protected.PATCH("/user/update", handlers.UpdateProfile)
protected.DELETE("/parts/:id", handlers.DeletePart)
}
admin := protected.Group("/")
admin.Use(middleware.AdminOnly())
{
admin.POST("/register", handlers.Register)
}
}
+18 -3
View File
@@ -35,14 +35,29 @@ func AuthRequired() gin.HandlerFunc {
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"])
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
if id, ok := claims["user_id"].(float64); ok {
c.Set("user_id", uint(id))
}
c.Set("role", claims["role"])
}
c.Next()
}
}
func AdminOnly() gin.HandlerFunc {
return func(c *gin.Context) {
role, exists := c.Get("role")
if !exists || role != "Админ" {
c.JSON(http.StatusForbidden, gin.H{"error": "Доступ ограничен"})
c.Abort()
return
}
c.Next()
}
}
+9
View File
@@ -0,0 +1,9 @@
package models
type UpdateUserInput struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Phone string `json:"phone"`
Department string `json:"department"`
Role string `json:"role"`
}
+6 -2
View File
@@ -4,7 +4,11 @@ import "gorm.io/gorm"
type User struct {
gorm.Model `json:"-"`
Username string `gorm:"unique;not null"`
Password string `gorm:"not null" json:"-"`
Username string `gorm:"unique;not null" binding:"required"`
Password string `gorm:"not null" json:"-" binding:"required,min=8"`
Role string `gorm:"default:'Рабочий'" json:"role"`
FirstName string `json:"first_name" binding:"required"`
LastName string `gorm:"index" json:"last_name" binding:"required"`
Phone string `gorm:"index" json:"phone"`
Department string `json:"department" binding:"required"`
}