auth-oauth.cpp 6.6 KB

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