auth-oauth.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #include "auth-oauth.hpp"
  2. #include <QPushButton>
  3. #include <QHBoxLayout>
  4. #include <QVBoxLayout>
  5. #include <qt-wrappers.hpp>
  6. #include <obs-app.hpp>
  7. #include "window-basic-main.hpp"
  8. #include "remote-text.hpp"
  9. #include <unordered_map>
  10. #include <json11.hpp>
  11. using namespace json11;
  12. #include <browser-panel.hpp>
  13. extern QCef *cef;
  14. extern QCefCookieManager *panel_cookies;
  15. /* ------------------------------------------------------------------------- */
  16. OAuthLogin::OAuthLogin(QWidget *parent, const std::string &url, bool token)
  17. : QDialog (parent),
  18. get_token (token)
  19. {
  20. setWindowTitle("Auth");
  21. resize(700, 700);
  22. OBSBasic::InitBrowserPanelSafeBlock(true);
  23. cefWidget = cef->create_widget(nullptr, url, panel_cookies);
  24. if (!cefWidget) {
  25. fail = true;
  26. return;
  27. }
  28. connect(cefWidget, SIGNAL(titleChanged(const QString &)),
  29. this, SLOT(setWindowTitle(const QString &)));
  30. connect(cefWidget, SIGNAL(urlChanged(const QString &)),
  31. this, SLOT(urlChanged(const QString &)));
  32. QPushButton *close = new QPushButton(QTStr("Cancel"));
  33. connect(close, &QAbstractButton::clicked,
  34. this, &QDialog::reject);
  35. QHBoxLayout *bottomLayout = new QHBoxLayout();
  36. bottomLayout->addStretch();
  37. bottomLayout->addWidget(close);
  38. bottomLayout->addStretch();
  39. QVBoxLayout *topLayout = new QVBoxLayout(this);
  40. topLayout->addWidget(cefWidget);
  41. topLayout->addLayout(bottomLayout);
  42. }
  43. OAuthLogin::~OAuthLogin()
  44. {
  45. delete cefWidget;
  46. }
  47. void OAuthLogin::urlChanged(const QString &url)
  48. {
  49. std::string uri = get_token ? "access_token=" : "code=";
  50. int code_idx = url.indexOf(uri.c_str());
  51. if (code_idx == -1)
  52. return;
  53. if (url.left(22) != "https://obsproject.com")
  54. return;
  55. code_idx += (int)uri.size();
  56. int next_idx = url.indexOf("&", code_idx);
  57. if (next_idx != -1)
  58. code = url.mid(code_idx, next_idx - code_idx);
  59. else
  60. code = url.right(url.size() - code_idx);
  61. accept();
  62. }
  63. /* ------------------------------------------------------------------------- */
  64. struct OAuthInfo {
  65. Auth::Def def;
  66. OAuth::login_cb login;
  67. OAuth::delete_cookies_cb delete_cookies;
  68. };
  69. static std::vector<OAuthInfo> loginCBs;
  70. void OAuth::RegisterOAuth(const Def &d, create_cb create, login_cb login,
  71. delete_cookies_cb delete_cookies)
  72. {
  73. OAuthInfo info = {d, login, delete_cookies};
  74. loginCBs.push_back(info);
  75. RegisterAuth(d, create);
  76. }
  77. std::shared_ptr<Auth> OAuth::Login(QWidget *parent, const std::string &service)
  78. {
  79. for (auto &a : loginCBs) {
  80. if (service.find(a.def.service) != std::string::npos) {
  81. return a.login(parent);
  82. }
  83. }
  84. return nullptr;
  85. }
  86. void OAuth::DeleteCookies(const std::string &service)
  87. {
  88. for (auto &a : loginCBs) {
  89. if (service.find(a.def.service) != std::string::npos) {
  90. a.delete_cookies();
  91. }
  92. }
  93. }
  94. void OAuth::SaveInternal()
  95. {
  96. OBSBasic *main = OBSBasic::Get();
  97. config_set_string(main->Config(), service(), "RefreshToken",
  98. refresh_token.c_str());
  99. config_set_string(main->Config(), service(), "Token", token.c_str());
  100. config_set_uint(main->Config(), service(), "ExpireTime", expire_time);
  101. config_set_int(main->Config(), service(), "ScopeVer", currentScopeVer);
  102. }
  103. static inline std::string get_config_str(
  104. OBSBasic *main,
  105. const char *section,
  106. const char *name)
  107. {
  108. const char *val = config_get_string(main->Config(), section, name);
  109. return val ? val : "";
  110. }
  111. bool OAuth::LoadInternal()
  112. {
  113. OBSBasic *main = OBSBasic::Get();
  114. refresh_token = get_config_str(main, service(), "RefreshToken");
  115. token = get_config_str(main, service(), "Token");
  116. expire_time = config_get_uint(main->Config(), service(), "ExpireTime");
  117. currentScopeVer = (int)config_get_int(main->Config(), service(),
  118. "ScopeVer");
  119. return implicit
  120. ? !token.empty()
  121. : !refresh_token.empty();
  122. }
  123. bool OAuth::TokenExpired()
  124. {
  125. if (token.empty())
  126. return true;
  127. if ((uint64_t)time(nullptr) > expire_time - 5)
  128. return true;
  129. return false;
  130. }
  131. bool OAuth::GetToken(const char *url, const std::string &client_id,
  132. int scope_ver, const std::string &auth_code, bool retry)
  133. try {
  134. std::string output;
  135. std::string error;
  136. std::string desc;
  137. if (currentScopeVer > 0 && currentScopeVer < scope_ver) {
  138. if (RetryLogin()) {
  139. return true;
  140. } else {
  141. QString title = QTStr("Auth.InvalidScope.Title");
  142. QString text = QTStr("Auth.InvalidScope.Text")
  143. .arg(service());
  144. QMessageBox::warning(OBSBasic::Get(), title, text);
  145. }
  146. }
  147. if (auth_code.empty() && !TokenExpired()) {
  148. return true;
  149. }
  150. std::string post_data;
  151. post_data += "action=redirect&client_id=";
  152. post_data += client_id;
  153. if (!auth_code.empty()) {
  154. post_data += "&grant_type=authorization_code&code=";
  155. post_data += auth_code;
  156. } else {
  157. post_data += "&grant_type=refresh_token&refresh_token=";
  158. post_data += refresh_token;
  159. }
  160. bool success = false;
  161. auto func = [&] () {
  162. success = GetRemoteFile(
  163. url,
  164. output,
  165. error,
  166. nullptr,
  167. "application/x-www-form-urlencoded",
  168. post_data.c_str(),
  169. std::vector<std::string>(),
  170. nullptr,
  171. 5);
  172. };
  173. ExecuteFuncSafeBlockMsgBox(
  174. func,
  175. QTStr("Auth.Authing.Title"),
  176. QTStr("Auth.Authing.Text").arg(service()));
  177. if (!success || output.empty())
  178. throw ErrorInfo("Failed to get token from remote", error);
  179. Json json = Json::parse(output, error);
  180. if (!error.empty())
  181. throw ErrorInfo("Failed to parse json", error);
  182. /* -------------------------- */
  183. /* error handling */
  184. error = json["error"].string_value();
  185. if (!retry && error == "invalid_grant") {
  186. if (RetryLogin()) {
  187. return true;
  188. }
  189. }
  190. if (!error.empty())
  191. throw ErrorInfo(error, json["error_description"].string_value());
  192. /* -------------------------- */
  193. /* success! */
  194. expire_time = (uint64_t)time(nullptr) + json["expires_in"].int_value();
  195. token = json["access_token"].string_value();
  196. if (token.empty())
  197. throw ErrorInfo("Failed to get token from remote", error);
  198. if (!auth_code.empty()) {
  199. refresh_token = json["refresh_token"].string_value();
  200. if (refresh_token.empty())
  201. throw ErrorInfo("Failed to get refresh token from "
  202. "remote", error);
  203. currentScopeVer = scope_ver;
  204. }
  205. return true;
  206. } catch (ErrorInfo info) {
  207. if (!retry) {
  208. QString title = QTStr("Auth.AuthFailure.Title");
  209. QString text = QTStr("Auth.AuthFailure.Text")
  210. .arg(service(), info.message.c_str(), info.error.c_str());
  211. QMessageBox::warning(OBSBasic::Get(), title, text);
  212. }
  213. blog(LOG_WARNING, "%s: %s: %s",
  214. __FUNCTION__,
  215. info.message.c_str(),
  216. info.error.c_str());
  217. return false;
  218. }
  219. void OAuthStreamKey::OnStreamConfig()
  220. {
  221. OBSBasic *main = OBSBasic::Get();
  222. obs_service_t *service = main->GetService();
  223. obs_data_t *settings = obs_service_get_settings(service);
  224. obs_data_set_string(settings, "key", key_.c_str());
  225. obs_service_update(service, settings);
  226. obs_data_release(settings);
  227. }