#include #include #include const std::string DB_PATH = "/root/.local/share/ddnet/ddnet-server.sqlite"; // Функция для выполнения SQL-запроса bool executeSQL(sqlite3* db, const std::string& sql) { char* errMsg = nullptr; int result = sqlite3_exec(db, sql.c_str(), nullptr, nullptr, &errMsg); if (result != SQLITE_OK) { std::cerr << "SQL error: " << errMsg << std::endl; sqlite3_free(errMsg); return false; } return true; } // Создание таблицы пользователей void createUsersTable(sqlite3* db) { const std::string sql = "CREATE TABLE IF NOT EXISTS users (" "login TEXT PRIMARY KEY, " "password TEXT NOT NULL);"; if (!executeSQL(db, sql)) { std::cerr << "Failed to create table." << std::endl; } } // Функция регистрации bool registerUser(sqlite3* db, const std::string& login, const std::string& password) { std::string sql = "INSERT INTO users (login, password) VALUES ('" + login + "', '" + password + "');"; if (executeSQL(db, sql)) { std::cout << "Registration successful." << std::endl; return true; } else { std::cerr << "User with this login already exists or registration failed." << std::endl; return false; } } // Функция авторизации bool loginUser(sqlite3* db, const std::string& login, const std::string& password) { std::string sql = "SELECT login FROM users WHERE login = '" + login + "' AND password = '" + password + "';"; sqlite3_stmt* stmt; bool success = false; if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, nullptr) == SQLITE_OK) { if (sqlite3_step(stmt) == SQLITE_ROW) { success = true; std::cout << "Login successful." << std::endl; } else { std::cerr << "Invalid login or password." << std::endl; } sqlite3_finalize(stmt); } else { std::cerr << "Failed to execute login query." << std::endl; } return success; } int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: ./program /register or /login " << std::endl; return 1; } sqlite3* db; if (sqlite3_open(DB_PATH.c_str(), &db) != SQLITE_OK) { std::cerr << "Failed to open database: " << sqlite3_errmsg(db) << std::endl; return 1; } // Создаем таблицу пользователей, если ее еще нет createUsersTable(db); std::string command = argv[1]; if (command == "/register" && argc == 5) { std::string login = argv[2]; std::string password = argv[3]; std::string password_confirm = argv[4]; if (password != password_confirm) { std::cerr << "Passwords do not match." << std::endl; } else { registerUser(db, login, password); } } else if (command == "/login" && argc == 4) { std::string login = argv[2]; std::string password = argv[3]; loginUser(db, login, password); } else { std::cerr << "Invalid command or arguments." << std::endl; } sqlite3_close(db); return 0; }