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"})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user