delete users

This commit is contained in:
vinchent 2024-08-26 14:10:18 +02:00
parent bced6d7036
commit 3f0ddf7138
5 changed files with 67 additions and 2 deletions

View File

@ -779,3 +779,17 @@ func (app *application) EditUser(w http.ResponseWriter, r *http.Request) {
resp.OK = true
app.writeJSON(w, http.StatusOK, resp)
}
func (app *application) DeleteUser(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
userID, _ := strconv.Atoi(id)
err := app.DB.DeleteUser(userID)
if err != nil {
app.errorLog.Println(err)
app.badRequest(w, r, err)
return
}
var resp jsonResponse
resp.OK = true
app.writeJSON(w, http.StatusOK, resp)
}

View File

@ -40,6 +40,7 @@ func (app *application) routes() http.Handler {
mux.Post("/all-users", app.AllUsers)
mux.Post("/all-users/{id}", app.OneUser)
mux.Post("/all-users/edit/{id}", app.EditUser)
mux.Post("/all-users/delete/{id}", app.DeleteUser)
})
mux.Post("/api/forgot-password", app.SendPasswordResetEmail)
mux.Post("/api/reset-password", app.ResetPassword)

View File

@ -69,10 +69,13 @@ Admin User
{{ define "js" }}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script type="module">
import {showUser, saveUser} from "/static/js/users.js"
import {showUser, saveUser, deleteUser} from "/static/js/users.js"
showUser({{.API}}, {{.UserID}});
document.getElementById("saveBtn").addEventListener("click", (evt) => {
saveUser({{.API}}, evt);
});
document.getElementById("deleteBtn").addEventListener("click", () => {
deleteUser({{.API}});
});
</script>
{{ end }}

View File

@ -629,5 +629,15 @@ func (m *DBModel) DeleteUser(id int) error {
if err != nil {
return err
}
stmt = `
DELETE FROM tokens
WHERE id = ?;
`
_, err = m.DB.ExecContext(ctx, stmt, id)
if err != nil {
return err
}
return nil
}

View File

@ -121,7 +121,7 @@ export function saveUser(api, event) {
.then(response => response.json())
.then(function (data) {
console.log(data);
if (data.ok === false) {
if (!data.ok) {
Swal.fire("Error" + data.message)
} else {
location.href = "/admin/all-users"
@ -129,3 +129,40 @@ export function saveUser(api, event) {
});
}
export function deleteUser(api) {
const token = localStorage.getItem("token");
let id = window.location.pathname.split("/").pop();
Swal.fire({
title: "Are you sure?",
text: "You won't be able to undo this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Delete user"
}).then((result) => {
if (result.isConfirmed) {
const requestOptions = {
method: 'post',
headers: {
'Accept': `application/json`,
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
},
};
fetch(api + `/api/admin/all-users/delete/${id}`, requestOptions)
.then(response => response.json())
.then(function (data) {
console.log(data);
if (!data.ok) {
Swal.fire("Error" + data.message)
} else {
location.href = "/admin/all-users"
}
});
}
});
}