Security added on delete service and list all node + cleaning some code
This commit is contained in:
60
backend/repositories/login_repo.go
Normal file
60
backend/repositories/login_repo.go
Normal file
@ -0,0 +1,60 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"backend/models"
|
||||
"database/sql"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func (r *NodeRepository) LoginHandler(c *gin.Context) {
|
||||
var req models.LoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Format invalide"})
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("trying to login")
|
||||
|
||||
var user struct {
|
||||
ID int `db:"id"`
|
||||
PasswordHash string `db:"password_hash"`
|
||||
Role string `db:"role"`
|
||||
}
|
||||
|
||||
log.Printf("trying to login with %v pswd %v", req.Username, req.Password)
|
||||
|
||||
query := "SELECT id, password_hash, role FROM users WHERE username = $1"
|
||||
err := r.DB.Get(&user, query, req.Username)
|
||||
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Identifiants incorrects"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur serveur"})
|
||||
return
|
||||
}
|
||||
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Identifiants incorrects"})
|
||||
return
|
||||
} else {
|
||||
session := sessions.Default(c)
|
||||
session.Set("user_id", user.ID)
|
||||
session.Set("role", user.Role)
|
||||
|
||||
if err := session.Save(); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Impossible de créer la session"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Connexion réussie"})
|
||||
return
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user