Skip to content

Commit

Permalink
Fix cpplint
Browse files Browse the repository at this point in the history
  • Loading branch information
suranimaria committed Nov 28, 2024
1 parent 18ef06f commit 1a37fdb
Show file tree
Hide file tree
Showing 17 changed files with 438 additions and 379 deletions.
7 changes: 7 additions & 0 deletions docs/cpplint_output.txt
Original file line number Diff line number Diff line change
@@ -1,23 +1,30 @@
[100%] Running cpplint for Google C++ Style Guide compliance
Done processing include/Auth.h
Done processing include/Counseling.h
Done processing include/DatabaseManager.h
Done processing include/Food.h
Done processing include/Healthcare.h
Done processing include/Outreach.h
Done processing include/RouteController.h
Done processing include/Shelter.h
Done processing src/Auth.cpp
Done processing src/DatabaseManager.cpp
Done processing src/RouteController.cpp
Done processing src/SubscriptionManager.cpp
Done processing src/main.cpp
Done processing src/services/Counseling.cpp
Done processing src/services/Food.cpp
Done processing src/services/Healthcare.cpp
Done processing src/services/Outreach.cpp
Done processing src/services/Shelter.cpp
Done processing test/AuthUnitTests.cpp
Done processing test/CounselingUnitTests.cpp
Done processing test/DataBaseTest.cpp
Done processing test/FoodUnitTests.cpp
Done processing test/HealthcareUnitTests.cpp
Done processing test/IntegrationTests.cpp
Done processing test/OutreachUnitTests.cpp
Done processing test/RouteControllerUnitTests.cpp
Done processing test/ShelterUnitTests.cpp
Done processing test/SubscriptionManagerUnitTests.cpp
[100%] Built target cpplint
176 changes: 87 additions & 89 deletions include/Auth.h
Original file line number Diff line number Diff line change
@@ -1,120 +1,118 @@
#ifndef AUTH_H
#define AUTH_H

#include <string>
#include <memory>
#include <stdexcept>
#include <optional>
#include "DatabaseManager.h"
#include <stdexcept>
#include <string>

#include "../external_libraries/Crow/include/crow.h"
#include "DatabaseManager.h"

// Custom exceptions for authentication
class AuthException : public std::runtime_error {
public:
explicit AuthException(const std::string& message) : std::runtime_error(message) {}
public:
explicit AuthException(const std::string& message)
: std::runtime_error(message) {}
};

class InvalidCredentialsException : public AuthException {
public:
InvalidCredentialsException() : AuthException("Invalid email or password") {}
public:
InvalidCredentialsException() : AuthException("Invalid email or password") {}
};

class UserAlreadyExistsException : public AuthException {
public:
UserAlreadyExistsException() : AuthException("User with this email already exists") {}
public:
UserAlreadyExistsException()
: AuthException("User with this email already exists") {}
};

// User model
struct User {
std::string id;
std::string email;
std::string passwordHash;
std::string role;
std::string createdAt;

// Updated constructor
User(const std::string& email,
const std::string& passwordHash,
const std::string& role = "user")
: email(email)
, passwordHash(passwordHash)
, role(role) {}

// Default constructor
User() = default;
std::string id;
std::string email;
std::string passwordHash;
std::string role;
std::string createdAt;

// Updated constructor
User(const std::string& email, const std::string& passwordHash,
const std::string& role = "user")
: email(email), passwordHash(passwordHash), role(role) {}

// Default constructor
User() = default;
};

// JWT payload structure
struct JWTPayload {
std::string userId;
std::string email;
std::string role;
int64_t exp; // Expiration time
std::string userId;
std::string email;
std::string role;
int64_t exp; // Expiration time
};

class AuthService {
private:
// Private constructor for singleton pattern
AuthService();
// Delete copy constructor and assignment operator
AuthService(const AuthService&) = delete;
AuthService& operator=(const AuthService&) = delete;

public:
// Static method to get the singleton instance
static AuthService& getInstance() {
static AuthService instance;
return instance;
}
explicit AuthService(DatabaseManager& dbManager);
~AuthService() = default;

// User registration and login
std::string registerUser(const std::string& email,
private:
// Private constructor for singleton pattern
AuthService();

// Delete copy constructor and assignment operator
AuthService(const AuthService&) = delete;
AuthService& operator=(const AuthService&) = delete;

public:
// Static method to get the singleton instance
static AuthService& getInstance() {
static AuthService instance;
return instance;
}

explicit AuthService(DatabaseManager& dbManager);
~AuthService() = default;

// User registration and login
std::string registerUser(const std::string& email,
const std::string& password,
const std::string& role = "user");

std::string loginUser(const std::string& email,
const std::string& password);

// JWT operations
std::string generateJWT(const User& user);
bool verifyJWT(const std::string& token);
std::optional<JWTPayload> decodeJWT(const std::string& token);

// User operations
std::optional<User> findUserByEmail(const std::string& email);
bool updateUserPassword(const std::string& userId, const std::string& newPassword);
bool deleteUser(const std::string& userId);

// Role-based authorization
bool hasRole(const std::string& token, const std::string& requiredRole);

// Password hashing
std::string hashPassword(const std::string& password);
bool verifyPassword(const std::string& password, const std::string& hash);
// User validation
bool isValidEmail(const std::string& email);
bool isValidPassword(const std::string& password);
// JWT utilities
int64_t getCurrentTimestamp();
int64_t getExpirationTimestamp();

// Database operations
std::vector<std::pair<std::string, std::string>> createUserDocument(
const std::string& email,
const std::string& passwordHash,
const std::string& role = "user"
);
private:
DatabaseManager& dbManager;
const std::string collection_name = "Users";
const int JWT_EXPIRATION_HOURS = 240000;
const std::string JWT_SECRET = "your-secret-key"; // In production, load from env variables


std::string loginUser(const std::string& email, const std::string& password);

// JWT operations
std::string generateJWT(const User& user);
bool verifyJWT(const std::string& token);
std::optional<JWTPayload> decodeJWT(const std::string& token);

// User operations
std::optional<User> findUserByEmail(const std::string& email);
bool updateUserPassword(const std::string& userId,
const std::string& newPassword);
bool deleteUser(const std::string& userId);

// Role-based authorization
bool hasRole(const std::string& token, const std::string& requiredRole);

// Password hashing
std::string hashPassword(const std::string& password);
bool verifyPassword(const std::string& password, const std::string& hash);
// User validation
bool isValidEmail(const std::string& email);
bool isValidPassword(const std::string& password);
// JWT utilities
int64_t getCurrentTimestamp();
int64_t getExpirationTimestamp();

// Database operations
std::vector<std::pair<std::string, std::string>> createUserDocument(
const std::string& email, const std::string& passwordHash,
const std::string& role = "user");

private:
DatabaseManager& dbManager;
const std::string collection_name = "Users";
const int JWT_EXPIRATION_HOURS = 240000;
const std::string JWT_SECRET =
"your-secret-key"; // In production, load from env variables
};

// Middleware function for token verification
Expand All @@ -126,4 +124,4 @@ bool authorizeRole(const crow::request& req, const std::string& requiredRole);
// Helper function to extract token from Authorization header
std::string extractToken(const std::string& authHeader);

#endif // AUTH_H
#endif // AUTH_H
104 changes: 57 additions & 47 deletions include/Logger.h
Original file line number Diff line number Diff line change
@@ -1,74 +1,84 @@
#pragma once

#include <stdexcept>
#include <string>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <memory>
#include <spdlog/spdlog.h>

#include <chrono>
#include <iomanip>
#include <filesystem>
#include <iomanip>
#include <memory>
#include <stdexcept>
#include <string>

class TradingError : public std::runtime_error {
public:
explicit TradingError(const std::string& message) : std::runtime_error(message) {}
public:
explicit TradingError(const std::string& message)
: std::runtime_error(message) {}
};

class NetworkError : public TradingError {
public:
explicit NetworkError(const std::string& message) : TradingError("Network error: " + message) {}
public:
explicit NetworkError(const std::string& message)
: TradingError("Network error: " + message) {}
};

class APIError : public TradingError {
public:
explicit APIError(const std::string& message) : TradingError("API error: " + message) {}
public:
explicit APIError(const std::string& message)
: TradingError("API error: " + message) {}
};

class JSONParseError : public TradingError {
public:
explicit JSONParseError(const std::string& message) : TradingError("JSON parse error: " + message) {}
public:
explicit JSONParseError(const std::string& message)
: TradingError("JSON parse error: " + message) {}
};

class Logger {
private:
std::unordered_map<std::string, std::shared_ptr<spdlog::logger>> loggers;
private:
std::unordered_map<std::string, std::shared_ptr<spdlog::logger>> loggers;

Logger() = default; // Private constructor

public:
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
Logger() = default; // Private constructor

static Logger& getInstance() {
static Logger instance;
return instance;
}
public:
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;

std::shared_ptr<spdlog::logger> getLogger(const std::string& log_name) {
auto it = loggers.find(log_name);
if (it == loggers.end()) {
std::string log_path = "logs/" + log_name + ".log";
auto logger = spdlog::basic_logger_mt(log_name, log_path, true);
loggers[log_name] = logger;
return logger;
}
return it->second;
}
static Logger& getInstance() {
static Logger instance;
return instance;
}

template<typename... Args>
void log(const std::string& logger_name, spdlog::level::level_enum level, spdlog::format_string_t<Args...> fmt, Args&&... args) {
auto logger = getLogger(logger_name);
logger->log(level, fmt, std::forward<Args>(args)...);
logger->flush();
std::shared_ptr<spdlog::logger> getLogger(const std::string& log_name) {
auto it = loggers.find(log_name);
if (it == loggers.end()) {
std::string log_path = "logs/" + log_name + ".log";
auto logger = spdlog::basic_logger_mt(log_name, log_path, true);
loggers[log_name] = logger;
return logger;
}
return it->second;
}

void flush(const std::string& logger_name) {
auto logger = getLogger(logger_name);
logger->flush();
}
template <typename... Args>
void log(const std::string& logger_name, spdlog::level::level_enum level,
spdlog::format_string_t<Args...> fmt, Args&&... args) {
auto logger = getLogger(logger_name);
logger->log(level, fmt, std::forward<Args>(args)...);
logger->flush();
}

void flush(const std::string& logger_name) {
auto logger = getLogger(logger_name);
logger->flush();
}
};

#define LOG_INFO(logger_name, ...) Logger::getInstance().log(logger_name, spdlog::level::info, __VA_ARGS__)
#define LOG_WARNING(logger_name, ...) Logger::getInstance().log(logger_name, spdlog::level::warn, __VA_ARGS__)
#define LOG_ERROR(logger_name, ...) Logger::getInstance().log(logger_name, spdlog::level::err, __VA_ARGS__)
#define LOG_CRITICAL(logger_name, ...) Logger::getInstance().log(logger_name, spdlog::level::critical, __VA_ARGS__)
#define LOG_INFO(logger_name, ...) \
Logger::getInstance().log(logger_name, spdlog::level::info, __VA_ARGS__)
#define LOG_WARNING(logger_name, ...) \
Logger::getInstance().log(logger_name, spdlog::level::warn, __VA_ARGS__)
#define LOG_ERROR(logger_name, ...) \
Logger::getInstance().log(logger_name, spdlog::level::err, __VA_ARGS__)
#define LOG_CRITICAL(logger_name, ...) \
Logger::getInstance().log(logger_name, spdlog::level::critical, __VA_ARGS__)
Loading

0 comments on commit 1a37fdb

Please sign in to comment.