user.hpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. static string generateToken(string payload) {
  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() + conf::userJWTSecret);
  25. return oss.str();
  26. }
  27. static string tryLogin(string username, string password) {
  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 "loginFailed";
  37. }
  38. static string getTokenUserName(string token) {
  39. auto list = split(token, "/");
  40. if (list.size() != 3) {
  41. return "";
  42. }
  43. string username = list[0];
  44. string time = list[1];
  45. string hash = list[2];
  46. trim(username);
  47. trim(time);
  48. trim(hash);
  49. try {
  50. long timeSec = stol(time);
  51. ::time_t t;
  52. ::time(&t);
  53. if (t > timeSec) {
  54. return "";
  55. }
  56. }
  57. catch (...) {
  58. return "";
  59. }
  60. ostringstream oss;
  61. oss << username;
  62. oss << "/";
  63. oss << time;
  64. oss << "/";
  65. string rhash = sha256(oss.str() + conf::userJWTSecret);
  66. if (hash != rhash) {
  67. return "";
  68. }
  69. return username;
  70. }
  71. static bool isLogin(string token) {
  72. return !getTokenUserName(token).empty();
  73. }
  74. }