Implement user login with password hash verification and username lookup

This commit is contained in:
2025-05-15 12:24:48 +03:30
parent b3fae6b80c
commit d646515776
5 changed files with 39 additions and 8 deletions

View File

@@ -7,4 +7,9 @@ import (
func HashPassword(password string) (string, error) { func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes), err return string(bytes), err
}
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
} }

View File

@@ -0,0 +1,6 @@
package requestmodels
type LoginInput struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}

View File

@@ -1 +0,0 @@
package repositories

View File

@@ -15,4 +15,10 @@ func NewUserService(db *gorm.DB) *UserService {
func (us *UserService) CreateUser(user models.ComUser) int { func (us *UserService) CreateUser(user models.ComUser) int {
return int(us.db.Create(&user).RowsAffected) return int(us.db.Create(&user).RowsAffected)
}
func (us *UserService) GetUserByUsername(username string) models.ComUser {
var user models.ComUser
us.db.Where("username = ?", username).First(&user)
return user
} }

View File

@@ -61,15 +61,30 @@ func (appContext *AdminDashboardHandler) Register(c *gin.Context) {
"success": false, "success": false,
"error": "failed to create user", "error": "failed to create user",
}) })
} else {
c.JSON(200, gin.H{
"success": true,
})
} }
c.JSON(200, gin.H{
"success": true,
})
} }
func (appContext *AdminDashboardHandler) Login(c *gin.Context) { func (appContext *AdminDashboardHandler) Login(c *gin.Context) {
c.JSON(200, gin.H{
"YouAreOn": "Login", var input requestmodels.LoginInput
})
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var user = appContext.AppContext.UserService.GetUserByUsername(input.Username)
if auth.CheckPasswordHash(input.Password, user.Password) && user.IsVerified { // TODO: Add verification process
c.JSON(200, gin.H{
"success": true,
})
} else {
c.JSON(200, gin.H{
"success": false,
})
}
} }