auth-oauth.cpp 8.0 KB

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