Add user authorization

This commit is contained in:
gabdevele
2026-06-02 20:01:56 +02:00 Unverified
parent 795383a98c
commit 54aa4cb73e
13 changed files with 361 additions and 36 deletions
+95 -1
View File
@@ -137,5 +137,99 @@ Json::Value AdminService::overviewStats(const auth::UserContext &user)
"FROM reports WHERE status IN ('RESOLVED', 'CLOSED')"));
return response;
}
} // namespace visione::services
Json::Value AdminService::listUsers(const auth::UserContext &user)
{
if (!auth::isAdmin(user))
{
return failure("forbidden");
}
auto response = success();
response["users"] = repositories::resultToJson(
drogon::app().getDbClient()->execSqlSync(
"SELECT u.id, u.first_name, u.last_name, u.email, u.fiscal_code, "
"u.phone, u.points, u.banned, u.must_change_password, "
"GROUP_CONCAT(r.name ORDER BY r.name SEPARATOR ',') AS roles "
"FROM users u "
"LEFT JOIN user_roles ur ON ur.user_id = u.id "
"LEFT JOIN roles r ON r.id = ur.role_id "
"GROUP BY u.id, u.first_name, u.last_name, u.email, u.fiscal_code, "
"u.phone, u.points, u.banned, u.must_change_password "
"ORDER BY u.created_at DESC LIMIT 200"));
return response;
}
Json::Value AdminService::updateUserRoles(const auth::UserContext &user,
long long targetUserId,
const Json::Value &body)
{
if (!auth::isAdmin(user) || !body["roles"].isArray())
{
return failure("invalid_roles");
}
auto db = drogon::app().getDbClient();
const auto target =
db->execSqlSync("SELECT id FROM users WHERE id = ?", targetUserId);
if (target.empty())
{
return failure("user_not_found");
}
db->execSqlSync("DELETE FROM user_roles WHERE user_id = ?", targetUserId);
for (const auto &role : body["roles"])
{
if (!role.isString())
{
return failure("invalid_roles");
}
const auto roleRows =
db->execSqlSync("SELECT id FROM roles WHERE name = ?", role.asString());
if (roleRows.empty())
{
return failure("role_not_found");
}
db->execSqlSync(
"INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)",
targetUserId,
roleRows[0]["id"].as<long long>());
}
return success();
}
Json::Value AdminService::updateUserBan(const auth::UserContext &user,
long long targetUserId,
const Json::Value &body)
{
if (!auth::isAdmin(user) || !body["banned"].isBool())
{
return failure("invalid_ban_payload");
}
if (targetUserId == user.id)
{
return failure("cannot_ban_self");
}
auto db = drogon::app().getDbClient();
const auto target =
db->execSqlSync("SELECT id FROM users WHERE id = ?", targetUserId);
if (target.empty())
{
return failure("user_not_found");
}
db->execSqlSync("UPDATE users SET banned = ? WHERE id = ?",
body["banned"].asBool(),
targetUserId);
if (body["banned"].asBool())
{
db->execSqlSync(
"UPDATE api_tokens SET revoked_at = NOW() "
"WHERE user_id = ? AND revoked_at IS NULL",
targetUserId);
}
return success();
}
} // namespace visione::services