add change user data endpoint and in web

This commit is contained in:
wt
2024-05-27 11:41:13 +07:00
parent da7ccbd802
commit 4079d3a6fa
10 changed files with 176 additions and 2 deletions
+1
View File
@@ -19,5 +19,6 @@ add_executable(
src/users/add_user.cpp
src/users/get_all_users.cpp
src/users/get_user.cpp
src/users/change_user.cpp
)
target_link_libraries(auth_service jwt-cpp::jwt-cpp)
+1
View File
@@ -17,6 +17,7 @@ int main() {
srv.Post("/api/users/user/password/change", change_password);
srv.Post("/api/users/del", delete_user);
srv.Post("/api/access", user_access);
srv.Post("/api/users/user/change", change_user);
srv.set_mount_point("/admin", "../src/web");
srv.set_mount_point("/js", "../src/web/js");
+80
View File
@@ -0,0 +1,80 @@
#include "users.hpp"
void change_user(const httplib::Request& request, httplib::Response& response) {
if (request.body == "") {response.set_content(
"{\"required\":\"[token] or if you superuser [token,userid]\",\"optional\":\"[username,password,is_superuser,group]\"}",
"application/json"
);return;}
nlohmann::json json_body = nlohmann::json::parse(request.body);
if (json_body["token"] == nullptr) {response.set_content(
"{\"required\":\"[token] or if you superuser [token,userid]\",\"optional\":\"[username,password,is_superuser,group]\"}",
"application/json"
);return;}
if ((json_body["userid"] == nullptr) && (json_body["old_password"] == nullptr)) {
response.set_content("{\"required\":\"[token] or if you superuser [token,userid]\",\"optional\":\"[username,password,is_superuser,group]\"}", "application/json");
return;
}
// if (json_body["new_password"] == nullptr) {response.set_content("{\"required\":\"[token] or if you superuser [token,userid]\"}", "application/json");return;}
if (!verify_auth(json_body["token"])) {response.set_content("{\"status\":\"403\"}", "application/json");return;}
// std::string old_password = "";
// const std::string new_password = json_body["new_password"];
// if (json_body["userid"] == nullptr) {old_password = json_body["old_password"];}
jwt::decoded_jwt<jwt::traits::kazuho_picojson> decoded_token = jwt::decode(json_body["token"]);
std::string userid = "";
for (auto& e : decoded_token.get_payload_json()) {
if (e.first == "userId") {
userid = e.second.to_str();
break;
}
}
if (userid == "") {response.set_content("{\"status\":\"403\"}", "application/json");return;}
std::ifstream usersfile("users.json");
nlohmann::json all_users = nlohmann::json::parse(usersfile);
usersfile.close();
std::string changeusruserid = userid;
if (json_body["userid"] != nullptr) {
changeusruserid = json_body["userid"];
nlohmann::json response_user_data = nullptr;
for (nlohmann::json& user : all_users) {
if (user["id"] == userid) {
response_user_data = user;
}
}
if (response_user_data == nullptr) {response.set_content("{\"status\":\"403\"}", "application/json");return;}
if (response_user_data["is_superuser"] != "1") {response.set_content("{\"status\":\"403\"}", "application/json");return;}
}
bool found = false;
if (json_body["userid"] != nullptr) {
for (int i = 0; i < all_users.size(); i++) {
if ((all_users[i]["id"] == changeusruserid)) {
if (json_body["username"] != nullptr) {all_users[i]["username"] = json_body["username"];}
if (json_body["password"] != nullptr) {all_users[i]["password"] = json_body["password"];}
if (json_body["group"] != nullptr) {all_users[i]["group"] = json_body["group"];}
if (json_body["is_superuser"] != nullptr) {all_users[i]["is_superuser"] = json_body["is_superuser"];}
found = true;
break;
}
}
} else {
for (int i = 0; i < all_users.size(); i++) {
if ((all_users[i]["id"] == changeusruserid)) {
if (json_body["username"] != nullptr) {all_users[i]["username"] = json_body["username"];}
found = true;
break;
}
}
}
if (!found) {response.set_content("{\"status\":\"can't find this user\"}", "application/json");return;}
std::ofstream usersfilew("users.json");
usersfilew << all_users.dump(4);
usersfilew.close();
response.set_content("{\"status\":\"ok\"}", "application/json");
}
+2
View File
@@ -17,5 +17,7 @@ void add_user(const httplib::Request& request, httplib::Response& response);
void delete_user(const httplib::Request& request, httplib::Response& response);
// function for change password for user
void change_password(const httplib::Request& request, httplib::Response& response);
// function for change user data
void change_user(const httplib::Request& request, httplib::Response& response);
#endif // USERS_HPP
+1 -1
View File
@@ -27,7 +27,7 @@ th {
position: relative;
border-radius: 10px;
padding: 10px;
width: 16%;
width: 14%;
text-overflow: auto;
overflow-x: auto;
}
+28
View File
@@ -60,6 +60,32 @@
</form>
</div>
<div class="form changeuserform">
<form class="formbody changeuserformbody">
<h1 class="loginformheader">Change User Data</h1>
<div class="loginforminputbody">
<div class="loginformlabel">Username</div>
<input type="text" required id="changeuserformusername" class="loginforminput">
</div>
<div class="loginforminputbody">
<div class="loginformlabel">Password</div>
<input type="password" id="changeuserformpassword" class="loginforminput">
</div>
<div class="loginforminputbody">
<div class="loginformlabel">Group</div>
<input type="text" required id="changeuserformgroup" class="loginforminput">
</div>
<div class="loginforminputbody">
<div class="loginformlabel">Is Superuser</div>
<input type="checkbox" id="changeuserformissuperuser" class="loginforminput">
</div>
<div class="loginforminputbody">
<button class="loginformbutton">Change</button>
<button class="cancelchangeuser loginformbutton">Cancel</button>
</div>
</form>
</div>
<div class="form confirmform">
<div class="formbody confirmformbody">
<h1>Are you sure?</h1>
@@ -98,6 +124,7 @@
<th>is_superuser</th>
<th>delete</th>
<th>change password</th>
<th>change user data</th>
</tr>
</thead>
</table>
@@ -114,5 +141,6 @@
<script src="js/add_user.js"></script>
<script src="js/del_user.js"></script>
<script src="js/change_password.js"></script>
<script src="js/change_user.js"></script>
</body>
</html>
+57
View File
@@ -0,0 +1,57 @@
const changeuserform = document.querySelector('.changeuserform')
const changeuserformbody = document.querySelector('.changeuserformbody')
const changeuserformusername = document.querySelector('#changeuserformusername')
const changeuserformpassword = document.querySelector('#changeuserformpassword')
const changeuserformgroup = document.querySelector('#changeuserformgroup')
const changeuserformissuperuser = document.querySelector('#changeuserformissuperuser')
const cancelchangeuser = document.querySelector(".cancelchangeuser")
var changedatauserid = ""
var userdata = ""
const change_user_data = async (userid) => {
changeuserform.classList.add('active')
changedatauserid = userid
console.log(userid)
const all_users = await fetch(routes.all_users(), {
method: 'POST',
body: `{"token":"${localStorage.getItem('token')}"}`
}).then(data => data.json()).then(jsondata => jsondata).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
userdata = all_users.find(usr => usr.id === userid)
console.log(userdata)
changeuserformusername.value = userdata.username
changeuserformgroup.value = userdata.group
console.log(changeuserformissuperuser.checked)
changeuserformissuperuser.checked = userdata.is_superuser === "1"?true:false
}
cancelchangeuser.addEventListener('click', (e) => {
e.preventDefault()
changeuserform.classList.remove('active')
})
changeuserformbody.addEventListener('submit', async (e) => {
e.preventDefault()
var request = {
token: localStorage.getItem('token'),
userid: changedatauserid,
username: changeuserformusername.value,
is_superuser: changeuserformissuperuser.checked?"1":"0",
group: changeuserformgroup.value
}
if (changeuserformpassword.value !== "") {request = {...request, "password": changeuserformpassword.value}}
const status = await fetch(routes.change_user(), {
method: 'POST',
body: JSON.stringify(request)
}).then(data => data.json()).then(jsondata => jsondata).catch((error) => {
notification(`Ошибка на сервере: ${error}`, "error")
})
console.log(status)
if (status.status === "ok") {
notification("Данные пользователя успешно изменены", "success")
changeuserform.classList.remove('active')
get_all_users()
}
})
+3
View File
@@ -13,6 +13,9 @@ userstablebody.addEventListener('click', e => {
if (e.target.classList.contains('changepassword')) {
change_password(e.target.id)
}
if (e.target.classList.contains('changeuser')) {
change_user_data(e.target.id)
}
})
confirmformcancel.addEventListener('click', () => {
+1
View File
@@ -16,6 +16,7 @@ const get_all_users = async () => {
<th>${user.is_superuser}</th>
<th><button class="deleteuser thbutton" id="${user.id}">Delete</button></th>
<th><button class="changepassword thbutton" id="${user.id}">Change password</button></th>
<th><button class="changeuser thbutton" id="${user.id}">Change user data</button></th>
</tr>
`
}
+2 -1
View File
@@ -8,5 +8,6 @@ const routes = {
access: () => [host, prefix, 'access'].join('/'),
adduser: () => [host, prefix, 'users', 'add'].join('/'),
deluser: () => [host, prefix, 'users', 'del'].join('/'),
change_password_url: () => [host, prefix, 'users', 'user', 'password', 'change'].join('/')
change_password_url: () => [host, prefix, 'users', 'user', 'password', 'change'].join('/'),
change_user: () => [host, prefix, 'users', 'user', 'change'].join('/')
}