1
0

OAuth.cpp 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #include "OAuth.hpp"
  2. #include <utility/RemoteTextThread.hpp>
  3. #include <widgets/OBSBasic.hpp>
  4. #include <qt-wrappers.hpp>
  5. #include <QMessageBox>
  6. #include <json11.hpp>
  7. #include "moc_OAuth.cpp"
  8. using namespace json11;
  9. struct OAuthInfo {
  10. Auth::Def def;
  11. OAuth::login_cb login;
  12. OAuth::delete_cookies_cb delete_cookies;
  13. };
  14. static std::vector<OAuthInfo> loginCBs;
  15. void OAuth::RegisterOAuth(const Def &d, create_cb create, login_cb login, delete_cookies_cb delete_cookies)
  16. {
  17. OAuthInfo info = {d, login, delete_cookies};
  18. loginCBs.push_back(info);
  19. RegisterAuth(d, create);
  20. }
  21. std::shared_ptr<Auth> OAuth::Login(QWidget *parent, const std::string &service)
  22. {
  23. for (auto &a : loginCBs) {
  24. if (service.find(a.def.service) != std::string::npos) {
  25. return a.login(parent, service);
  26. }
  27. }
  28. return nullptr;
  29. }
  30. void OAuth::DeleteCookies(const std::string &service)
  31. {
  32. for (auto &a : loginCBs) {
  33. if (service.find(a.def.service) != std::string::npos) {
  34. a.delete_cookies();
  35. }
  36. }
  37. }
  38. void OAuth::SaveInternal()
  39. {
  40. OBSBasic *main = OBSBasic::Get();
  41. config_set_string(main->Config(), service(), "RefreshToken", refresh_token.c_str());
  42. config_set_string(main->Config(), service(), "Token", token.c_str());
  43. config_set_uint(main->Config(), service(), "ExpireTime", expire_time);
  44. config_set_int(main->Config(), service(), "ScopeVer", currentScopeVer);
  45. }
  46. static inline std::string get_config_str(OBSBasic *main, const char *section, const char *name)
  47. {
  48. const char *val = config_get_string(main->Config(), section, name);
  49. return val ? val : "";
  50. }
  51. bool OAuth::LoadInternal()
  52. {
  53. OBSBasic *main = OBSBasic::Get();
  54. refresh_token = get_config_str(main, service(), "RefreshToken");
  55. token = get_config_str(main, service(), "Token");
  56. expire_time = config_get_uint(main->Config(), service(), "ExpireTime");
  57. currentScopeVer = (int)config_get_int(main->Config(), service(), "ScopeVer");
  58. return implicit ? !token.empty() : !refresh_token.empty();
  59. }
  60. bool OAuth::TokenExpired()
  61. {
  62. if (token.empty())
  63. return true;
  64. if ((uint64_t)time(nullptr) > expire_time - 5)
  65. return true;
  66. return false;
  67. }
  68. bool OAuth::GetToken(const char *url, const std::string &client_id, const std::string &secret,
  69. const std::string &redirect_uri, int scope_ver, const std::string &auth_code, bool retry)
  70. {
  71. return GetTokenInternal(url, client_id, secret, redirect_uri, scope_ver, auth_code, retry);
  72. }
  73. bool OAuth::GetToken(const char *url, const std::string &client_id, int scope_ver, const std::string &auth_code,
  74. bool retry)
  75. {
  76. return GetTokenInternal(url, client_id, {}, {}, scope_ver, auth_code, retry);
  77. }
  78. bool OAuth::GetTokenInternal(const char *url, const std::string &client_id, const std::string &secret,
  79. const std::string &redirect_uri, int scope_ver, const std::string &auth_code, bool retry)
  80. try {
  81. std::string output;
  82. std::string error;
  83. std::string desc;
  84. if (currentScopeVer > 0 && currentScopeVer < scope_ver) {
  85. if (RetryLogin()) {
  86. return true;
  87. } else {
  88. QString title = QTStr("Auth.InvalidScope.Title");
  89. QString text = QTStr("Auth.InvalidScope.Text").arg(service());
  90. QMessageBox::warning(OBSBasic::Get(), title, text);
  91. }
  92. }
  93. if (auth_code.empty() && !TokenExpired()) {
  94. return true;
  95. }
  96. std::string post_data;
  97. post_data += "action=redirect&client_id=";
  98. post_data += client_id;
  99. if (!secret.empty()) {
  100. post_data += "&client_secret=";
  101. post_data += secret;
  102. }
  103. if (!redirect_uri.empty()) {
  104. post_data += "&redirect_uri=";
  105. post_data += redirect_uri;
  106. }
  107. if (!auth_code.empty()) {
  108. post_data += "&grant_type=authorization_code&code=";
  109. post_data += auth_code;
  110. } else {
  111. post_data += "&grant_type=refresh_token&refresh_token=";
  112. post_data += refresh_token;
  113. }
  114. bool success = false;
  115. auto func = [&]() {
  116. success = GetRemoteFile(url, output, error, nullptr, "application/x-www-form-urlencoded", "",
  117. post_data.c_str(), std::vector<std::string>(), nullptr, 5);
  118. };
  119. ExecThreadedWithoutBlocking(func, QTStr("Auth.Authing.Title"), QTStr("Auth.Authing.Text").arg(service()));
  120. if (!success || output.empty())
  121. throw ErrorInfo("Failed to get token from remote", error);
  122. Json json = Json::parse(output, error);
  123. if (!error.empty())
  124. throw ErrorInfo("Failed to parse json", error);
  125. /* -------------------------- */
  126. /* error handling */
  127. error = json["error"].string_value();
  128. if (!retry && error == "invalid_grant") {
  129. if (RetryLogin()) {
  130. return true;
  131. }
  132. }
  133. if (!error.empty())
  134. throw ErrorInfo(error, json["error_description"].string_value());
  135. /* -------------------------- */
  136. /* success! */
  137. expire_time = (uint64_t)time(nullptr) + json["expires_in"].int_value();
  138. token = json["access_token"].string_value();
  139. if (token.empty())
  140. throw ErrorInfo("Failed to get token from remote", error);
  141. if (!auth_code.empty()) {
  142. refresh_token = json["refresh_token"].string_value();
  143. if (refresh_token.empty())
  144. throw ErrorInfo("Failed to get refresh token from "
  145. "remote",
  146. error);
  147. currentScopeVer = scope_ver;
  148. }
  149. return true;
  150. } catch (ErrorInfo &info) {
  151. if (!retry) {
  152. QString title = QTStr("Auth.AuthFailure.Title");
  153. QString text = QTStr("Auth.AuthFailure.Text").arg(service(), info.message.c_str(), info.error.c_str());
  154. QMessageBox::warning(OBSBasic::Get(), title, text);
  155. }
  156. blog(LOG_WARNING, "%s: %s: %s", __FUNCTION__, info.message.c_str(), info.error.c_str());
  157. return false;
  158. }
  159. void OAuthStreamKey::OnStreamConfig()
  160. {
  161. if (key_.empty())
  162. return;
  163. OBSBasic *main = OBSBasic::Get();
  164. obs_service_t *service = main->GetService();
  165. OBSDataAutoRelease settings = obs_service_get_settings(service);
  166. bool bwtest = obs_data_get_bool(settings, "bwtest");
  167. if (bwtest && strcmp(this->service(), "Twitch") == 0)
  168. obs_data_set_string(settings, "key", (key_ + "?bandwidthtest=true").c_str());
  169. else
  170. obs_data_set_string(settings, "key", key_.c_str());
  171. obs_service_update(service, settings);
  172. }