user.hpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. //
  2. // Created by xcbosa on 2023/1/30.
  3. //
  4. #pragma once
  5. #include <sys/stat.h>
  6. #include <string>
  7. #include <time.h>
  8. #include "utils/utils.h"
  9. #include "webuiconf.h"
  10. #include "fs.hpp"
  11. #include "thirdparty/sha256.hpp"
  12. using namespace std;
  13. using namespace xc;
  14. using namespace xc::utils;
  15. namespace user {
  16. inline string generateToken(string payload) __attribute__((weak)) {
  17. ostringstream oss;
  18. oss << payload;
  19. oss << "/";
  20. ::time_t t;
  21. ::time(&t);
  22. oss << (t + conf::userTokenExpireSeconds);
  23. oss << "/";
  24. oss << sha256(oss.str());
  25. return oss.str();
  26. }
  27. inline string tryLogin(string username, string password) __attribute__((weak)) {
  28. string userInfoFile = conf::getUserDataDir() + "/" + username;
  29. if (fs::existsFile(userInfoFile)) {
  30. INIFile ini(userInfoFile);
  31. string iniPwd = ini.getMust("info")->get("password");
  32. if (iniPwd == password) {
  33. return generateToken(username);
  34. }
  35. }
  36. return "";
  37. }
  38. static vector<string> split(const string& str, const string& delim) {
  39. vector<string> res;
  40. if ("" == str) return res;
  41. char * strs = new char[str.length() + 1];
  42. strcpy(strs, str.c_str());
  43. char * d = new char[delim.length() + 1];
  44. strcpy(d, delim.c_str());
  45. char *p = strtok(strs, d);
  46. while(p) {
  47. string s = p;
  48. res.push_back(s);
  49. p = strtok(NULL, d);
  50. }
  51. return res;
  52. }
  53. static std::string& trim(std::string &s) {
  54. if (s.empty()) { return s; }
  55. s.erase(0,s.find_first_not_of(" "));
  56. s.erase(s.find_last_not_of(" ") + 1);
  57. return s;
  58. }
  59. inline string getTokenUserName(string token) __attribute__((weak)) {
  60. auto list = split(token, "/");
  61. if (list.size() != 3) {
  62. return "";
  63. }
  64. string username = list[0];
  65. string time = list[1];
  66. string hash = list[2];
  67. trim(username);
  68. trim(time);
  69. trim(hash);
  70. try {
  71. long timeSec = stol(time);
  72. ::time_t t;
  73. ::time(&t);
  74. if (t > timeSec) {
  75. return "";
  76. }
  77. }
  78. catch (...) {
  79. return "";
  80. }
  81. ostringstream oss;
  82. oss << username;
  83. oss << "/";
  84. oss << time;
  85. oss << "/";
  86. string rhash = sha256(oss.str());
  87. if (hash != rhash) {
  88. return "";
  89. }
  90. return username;
  91. }
  92. inline bool isLogin(string token) __attribute__((weak)) {
  93. return !getTokenUserName(token).empty();
  94. }
  95. }