1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- #include "../include/UserManager.h"
- // TODO passwords are stored and checked in plain text
- // TODO read userStorage file location from config
- // initialize static filename to empty string
- std::string UserManager::filename = "";
- void UserManager::init(const std::string &file) {
- filename = file;
- std::ifstream ifile(filename);
- if (!ifile.is_open()) {
- // create new file if userStorage does not exist
- std::ofstream ofile;
- ofile.open(filename);
- ofile << "user;pass\n";
- ofile.close();
- std::cout << "Created \"" << filename << "\" and added the default user"
- << std::endl;
- }
- ifile.close();
- }
- bool UserManager::isAllowed(const std::string &name, const std::string &pw) {
- std::map<std::string, std::string> user_map;
- readFromFile(user_map);
- auto it = user_map.find(name);
- // check if user exists and pw is equal
- if (it != user_map.end() && (it->second.compare(pw) == 0)) {
- return true;
- }
- return false;
- }
- void UserManager::addUser(const std::string &name, const std::string &pw) {
- std::map<std::string, std::string> user_map;
- readFromFile(user_map);
- auto it = user_map.find(name);
- // if user exists, do nothing
- if (it != user_map.end()) {
- return;
- }
- user_map.insert(std::pair<std::string, std::string>(name, pw));
- writeToFile(user_map);
- }
- void UserManager::deleteUser(const std::string &name, const std::string &pw) {
- // TODO check pw before delete
- std::map<std::string, std::string> user_map;
- readFromFile(user_map);
- auto it = user_map.find(name);
- if (it == user_map.end()) {
- return;
- }
- user_map.erase(it);
- writeToFile(user_map);
- }
- // read content from file into given map
- void UserManager::readFromFile(std::map<std::string, std::string> &user_map) {
- std::ifstream ifile(filename);
- std::string line;
- while (getline(ifile, line)) {
- std::stringstream ss(line);
- std::string segment;
- std::vector<std::string> v;
- while (std::getline(ss, segment, ';')) {
- v.push_back(segment);
- }
- user_map.insert(std::pair<std::string, std::string>(v.at(0), v.at(1)));
- }
- ifile.close();
- }
- // write content from map to file
- void UserManager::writeToFile(std::map<std::string, std::string> &user_map) {
- std::ofstream file;
- file.open(filename);
- for (auto const &x : user_map) {
- file << x.first << ";" << x.second << std::endl;
- }
- file.close();
- }
|