1
0

auth-oauth.cpp 8.2 KB

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