Skip to content

Commit

Permalink
add JWT to addCounseling
Browse files Browse the repository at this point in the history
  • Loading branch information
Brendon committed Nov 17, 2024
1 parent 2763968 commit b426b57
Showing 1 changed file with 57 additions and 23 deletions.
80 changes: 57 additions & 23 deletions src/RouteController.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -250,33 +250,67 @@ void RouteController::getCounseling(const crow::request& req,
*/
void RouteController::addCounseling(const crow::request& req,
crow::response& res) {
if (!authenticatePermissionsToPost(req)) {
res.code = 403;
res.write("Unauthorized.");
res.end();
return;
}
// Check for JWT token authentication
auto authHeader = req.get_header_value("Authorization");
if (authHeader.empty()) {
res.code = 401;
res.write("Authentication required. Please provide a valid token.");
res.end();
return;
}

try {
auto resource = bsoncxx::from_json(req.body);
std::string counselorName =
resource["counselorName"].get_utf8().value.to_string();
std::string specialty = resource["specialty"].get_utf8().value.to_string();
std::string token = extractToken(authHeader);
if (token.empty()) {
res.code = 401;
res.write("Invalid authorization header format.");
res.end();
return;
}

std::string result =
counselingManager.addCounselor(counselorName, specialty);
// Verify token and check role authorization
AuthService& authService = AuthService::getInstance();
if (!authService.verifyJWT(token)) {
res.code = 401;
res.write("Invalid or expired token.");
res.end();
return;
}

if (result == "Success") {
res.code = 201;
res.write("Counseling resource added successfully.");
} else {
res.code = 400;
res.write(result);
// // Optional: Check for specific role authorization
// if (!authService.hasRole(token, "NGO")) { // Or any other appropriate role
// res.code = 403;
// res.write("Insufficient permissions to perform this action.");
// res.end();
// return;
// }

try {
auto resource = bsoncxx::from_json(req.body);

// Validate required fields
if (!resource["counselorName"] || !resource["specialty"]) {
res.code = 400;
res.write("Missing required fields: counselorName and specialty");
res.end();
return;
}

std::string counselorName = resource["counselorName"].get_utf8().value.to_string();
std::string specialty = resource["specialty"].get_utf8().value.to_string();

std::string result = counselingManager.addCounselor(counselorName, specialty);

if (result == "Success") {
res.code = 201;
res.write("Counseling resource added successfully.");
} else {
res.code = 400;
res.write(result);
}
res.end();
} catch (const std::exception& e) {
res = handleException(e);
}
res.end();
} catch (const std::exception& e) {
res = handleException(e);
}
}

/**
Expand Down

0 comments on commit b426b57

Please sign in to comment.