UserManager.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "../include/UserManager.h"
  2. // TODO passwords are stored and checked in plain text
  3. // TODO read userStorage file location from config
  4. // initialize static filename to empty string
  5. std::string UserManager::filename = "";
  6. void UserManager::init(const std::string &file) {
  7. filename = file;
  8. std::ifstream ifile(filename);
  9. if (!ifile.is_open()) {
  10. // create new file if userStorage does not exist
  11. std::ofstream ofile;
  12. ofile.open(filename);
  13. ofile << "user;pass\n";
  14. ofile.close();
  15. std::cout << "Created \"" << filename << "\" and added the default user" << std::endl;
  16. }
  17. ifile.close();
  18. }
  19. bool UserManager::isAllowed(const std::string &name, const std::string &pw) {
  20. std::map<std::string, std::string> user_map;
  21. readFromFile(user_map);
  22. auto it = user_map.find(name);
  23. // check if user exists and pw is equal
  24. if (it != user_map.end() && (it->second.compare(pw) == 0)) {
  25. return true;
  26. }
  27. return false;
  28. }
  29. bool UserManager::addUser(const std::string &name, const std::string &pw) {
  30. std::map<std::string, std::string> user_map;
  31. readFromFile(user_map);
  32. auto it = user_map.find(name);
  33. // if user exists, do nothing
  34. if (it != user_map.end()) {
  35. return false;
  36. }
  37. user_map.insert(std::pair<std::string, std::string>(name, pw));
  38. writeToFile(user_map);
  39. return true;
  40. }
  41. bool UserManager::deleteUser(const std::string &name, const std::string &pw) {
  42. // TODO check pw before delete
  43. std::map<std::string, std::string> user_map;
  44. readFromFile(user_map);
  45. auto it = user_map.find(name);
  46. if (it == user_map.end()) {
  47. return false;
  48. }
  49. if (it->second.compare(pw) != 0) {
  50. return false;
  51. }
  52. user_map.erase(it);
  53. writeToFile(user_map);
  54. return true;
  55. }
  56. // read content from file into given map
  57. void UserManager::readFromFile(std::map<std::string, std::string> &user_map) {
  58. std::ifstream ifile(filename);
  59. std::string line;
  60. while (getline(ifile, line)) {
  61. std::stringstream ss(line);
  62. std::string segment;
  63. std::vector<std::string> v;
  64. while (std::getline(ss, segment, ';')) {
  65. v.push_back(segment);
  66. }
  67. user_map.insert(std::pair<std::string, std::string>(v.at(0), v.at(1)));
  68. }
  69. ifile.close();
  70. }
  71. // write content from map to file
  72. void UserManager::writeToFile(std::map<std::string, std::string> &user_map) {
  73. std::ofstream file;
  74. file.open(filename);
  75. for (auto const &x : user_map) {
  76. file << x.first << ";" << x.second << std::endl;
  77. }
  78. file.close();
  79. }