UserManager.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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"
  16. << std::endl;
  17. }
  18. ifile.close();
  19. }
  20. bool UserManager::isAllowed(const std::string &name, const std::string &pw) {
  21. std::map<std::string, std::string> user_map;
  22. readFromFile(user_map);
  23. auto it = user_map.find(name);
  24. // check if user exists and pw is equal
  25. if (it != user_map.end() && (it->second.compare(pw) == 0)) {
  26. return true;
  27. }
  28. return false;
  29. }
  30. void UserManager::addUser(const std::string &name, const std::string &pw) {
  31. std::map<std::string, std::string> user_map;
  32. readFromFile(user_map);
  33. auto it = user_map.find(name);
  34. // if user exists, do nothing
  35. if (it != user_map.end()) {
  36. return;
  37. }
  38. user_map.insert(std::pair<std::string, std::string>(name, pw));
  39. writeToFile(user_map);
  40. }
  41. void 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;
  48. }
  49. user_map.erase(it);
  50. writeToFile(user_map);
  51. }
  52. // read content from file into given map
  53. void UserManager::readFromFile(std::map<std::string, std::string> &user_map) {
  54. std::ifstream ifile(filename);
  55. std::string line;
  56. while (getline(ifile, line)) {
  57. std::stringstream ss(line);
  58. std::string segment;
  59. std::vector<std::string> v;
  60. while (std::getline(ss, segment, ';')) {
  61. v.push_back(segment);
  62. }
  63. user_map.insert(std::pair<std::string, std::string>(v.at(0), v.at(1)));
  64. }
  65. ifile.close();
  66. }
  67. // write content from map to file
  68. void UserManager::writeToFile(std::map<std::string, std::string> &user_map) {
  69. std::ofstream file;
  70. file.open(filename);
  71. for (auto const &x : user_map) {
  72. file << x.first << ";" << x.second << std::endl;
  73. }
  74. file.close();
  75. }