auth-oauth.cpp 8.0 KB

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