Check if user exists before processing PUT/DELETE

This commit is contained in:
raul 2024-12-12 12:56:01 +01:00
parent 6014213036
commit f6c6bf28e7
Signed by: raul
GPG Key ID: C1AA797073F17129
1 changed files with 22 additions and 1 deletions

View File

@ -50,6 +50,16 @@ func server() {
r.Run(":" + ListenPort)
}
func checkUserExists(id string) bool {
dynStmt := `SELECT id_usuario FROM usuarios WHERE id_usuario = $1`
err := db.QueryRow(dynStmt, id).Scan()
if err == sql.ErrNoRows {
return false
} else {
return true
}
}
func modifyUser(c *gin.Context) {
id := c.Param("userid")
dynStmt := `UPDATE usuarios SET email=$1,nombre=$2,apellido1=$3,apellido2=$4,password=$5 WHERE id_usuario = $6`
@ -60,6 +70,12 @@ func modifyUser(c *gin.Context) {
c.IndentedJSON(http.StatusNotFound, setResponse(e, false))
return
}
if exists := checkUserExists(id); exists != true {
c.IndentedJSON(http.StatusNotFound, setResponse("User not found", false))
return
}
user := user{}
if err := c.BindJSON(&user); err != nil {
e := fmt.Sprintf("Something went wrong updating the user: %v", err)
@ -71,7 +87,7 @@ func modifyUser(c *gin.Context) {
_, err = db.Exec(dynStmt, user.Email, user.Name, user.Surname1, user.Surname2, hashPW(user.Password), id)
if err != nil {
e := fmt.Sprintf("Something went wrong trying to modify the user: %v", err)
log.Println(e, user.Email, user.Name, user.Surname1, user.Surname2, hashPW(user.Password), id)
log.Println(e)
c.IndentedJSON(http.StatusInternalServerError, setResponse(e, false))
return
}
@ -90,6 +106,11 @@ func deleteUser(c *gin.Context) {
return
}
if exists := checkUserExists(id); exists != true {
c.IndentedJSON(http.StatusNotFound, setResponse("User not found", false))
return
}
_, err = db.Exec(dynStmt, id)
if err != nil {
e := fmt.Sprintf("Something went wrong trying to delete the user: %v", err)