Implement user login with password hash verification and username lookup
This commit is contained in:
@@ -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
|
||||||
}
|
}
|
6
internal/models/requestModels/login.go
Normal file
6
internal/models/requestModels/login.go
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
package requestmodels
|
||||||
|
|
||||||
|
type LoginInput struct {
|
||||||
|
Username string `json:"username" binding:"required"`
|
||||||
|
Password string `json:"password" binding:"required"`
|
||||||
|
}
|
@@ -1 +0,0 @@
|
|||||||
package repositories
|
|
@@ -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
|
||||||
}
|
}
|
@@ -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,
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user