auth-oauth.cpp 6.8 KB

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