auth-oauth.cpp 7.1 KB

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