auth-oauth.cpp 8.2 KB

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