Advertisement
Guest User

dank code

a guest
Oct 20th, 2017
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 25.45 KB | None | 0 0
  1. var phantom_checkpoint = phantom_checkpoint || function () { };
  2.  
  3. (function(console) {
  4. var url_root;
  5. window.localStorage.removeItem('url-root');
  6. var environment = window.environment || { };
  7. var oauth = environment.OAuth || null;
  8. if (oauth) {
  9. if (!oauth.TokenParam)
  10. oauth.TokenParam = "access_token";
  11. if (!oauth.ErrorParam)
  12. oauth.ErrorParam = "error_description";
  13. }
  14.  
  15. var fmt_re = /\$\{([^}]+)\}|\$([a-zA-Z0-9_]+)/g;
  16. function format(fmt /* ... */) {
  17. var args = Array.prototype.slice.call(arguments, 1);
  18. return fmt.replace(fmt_re, function(m, x, y) { return args[x || y] || ""; });
  19. }
  20.  
  21. function gettext(key) {
  22. if (window.cockpit_po) {
  23. var translated = window.cockpit_po[key];
  24. if (translated && translated[1])
  25. return translated[1];
  26. }
  27. return key;
  28. }
  29.  
  30. function translate() {
  31. if (!document.querySelectorAll)
  32. return;
  33. var list = document.querySelectorAll("[translate]");
  34. for (var i = 0; i < list.length; i++)
  35. list[i].textContent = gettext(list[i].textContent);
  36. }
  37.  
  38. var _ = gettext;
  39.  
  40. var login_path, application, org_login_path, org_application;
  41. var qs_re = /[?&]?([^=]+)=([^&]*)/g;
  42. var oauth_redirect_to = null;
  43.  
  44. function QueryParams(qs) {
  45. qs = qs.split('+').join(' ');
  46.  
  47. var params = {};
  48. var tokens;
  49.  
  50. for (;;) {
  51. tokens = qs_re.exec(qs);
  52. if (!tokens)
  53. break;
  54. params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
  55. }
  56. return params;
  57. }
  58.  
  59. function unquote(str) {
  60. str = str.trim();
  61. if (str[0] == '"')
  62. str = str.substr(1, str.length - 2);
  63. return str;
  64. }
  65.  
  66. if (!console)
  67. console = function() { };
  68.  
  69. /* Determine if we are nested or not, and switch styles */
  70. if (window.location.pathname.indexOf("/cockpit/") === 0 ||
  71. window.location.pathname.indexOf("/cockpit+") === 0)
  72. document.documentElement.setAttribute("class", "inline");
  73.  
  74. function id(name) {
  75. return document.getElementById(name);
  76. }
  77.  
  78. function fatal(msg) {
  79. if (window.console)
  80. console.warn("fatal:", msg);
  81.  
  82. id("login-again").style.display = "none";
  83. id("login-wait-validating").style.display = "none";
  84.  
  85. if (oauth_redirect_to) {
  86. id("login-again").href = oauth_redirect_to;
  87. id("login-again").style.display = "block";
  88. }
  89.  
  90. id("login").style.display = 'none';
  91. id("login-details").style.display = 'none';
  92. id("login-fatal").style.display = 'block';
  93.  
  94. var el = id("login-fatal-message");
  95. el.textContent = "";
  96. el.appendChild(document.createTextNode(msg));
  97. }
  98.  
  99. function brand(_id, def) {
  100. var style, elt = id(_id);
  101. if (elt)
  102. style = window.getComputedStyle(elt);
  103. if (!style)
  104. return;
  105.  
  106. var len, content = style.content;
  107. if (content && content != "none" && content != "normal") {
  108. len = content.length;
  109. if ((content[0] === '"' || content[0] === '\'') &&
  110. len > 2 && content[len - 1] === content[0])
  111. content = content.substr(1, len - 2);
  112. elt.innerHTML = content || def;
  113. }
  114. }
  115.  
  116. function requisites() {
  117. function req(name, obj) {
  118. var ret;
  119. try {
  120. ret = (obj[name]);
  121. } catch(ex) {
  122. fatal(format(_("The web browser configuration prevents Cockpit from running (inaccessible $0)"),
  123. name));
  124. throw ex;
  125. }
  126. if (ret === undefined) {
  127. fatal(format(_("This web browser is too old to run Cockpit (missing $0)"), name));
  128. return false;
  129. }
  130. return true;
  131. }
  132. return ("MozWebSocket" in window || req("WebSocket", window)) &&
  133. req("XMLHttpRequest", window) &&
  134. req("localStorage", window) &&
  135. req("sessionStorage", window) &&
  136. req("JSON", window) &&
  137. req("defineProperty", Object) &&
  138. req("console", window) &&
  139. req("pushState", window.history) &&
  140. req("textContent", document);
  141. }
  142.  
  143. function trim(s) {
  144. return s.replace(/^\s+|\s+$/g, '');
  145. }
  146.  
  147. /* Sets values for application, url_root and login_path */
  148. function setup_path_globals (path) {
  149. var parser = document.createElement('a');
  150. var base = document.baseURI;
  151. var base_tags;
  152. /* Some IEs don't support baseURI */
  153. if (!base) {
  154. base_tags = document.getElementsByTagName ("base");
  155. if (base_tags.length > 0)
  156. base = base_tags[0].href;
  157. else
  158. base = "/";
  159. }
  160.  
  161. path = path || "/";
  162. parser.href = base;
  163. if (parser.pathname != "/") {
  164. url_root = parser.pathname.replace(/^\/+|\/+$/g, '');
  165. window.localStorage.setItem('url-root', url_root);
  166. if (url_root && path.indexOf('/' + url_root) === 0)
  167. path = path.replace('/' + url_root, '') || '/';
  168. }
  169.  
  170. if (path.indexOf("/=") === 0) {
  171. environment.hostname = path.substring(2);
  172. path = "/cockpit+" + path.split("/")[1];
  173. } else if (path.indexOf("/cockpit/") !== 0 && path.indexOf("/cockpit+") !== 0) {
  174. path = "/cockpit";
  175. }
  176.  
  177. application = path.split("/")[1];
  178. login_path = "/" + application + "/login";
  179. if (url_root)
  180. login_path = "/" + url_root + login_path;
  181.  
  182. org_application = application;
  183. org_login_path = login_path;
  184. }
  185.  
  186. function toggle_options(ev, show) {
  187. if (show === undefined)
  188. show = id("server-group").style.display === "none";
  189.  
  190. id("option-group").setAttribute("data-state", show);
  191. if (show) {
  192. id("server-group").style.display = 'block';
  193. id("option-caret").setAttribute("class", "caret caret-down");
  194. id("option-caret").setAttribute("className", "caret caret-down");
  195. } else {
  196. id("server-group").style.display = 'none';
  197. id("option-caret").setAttribute("class", "caret caret-right");
  198. id("option-caret").setAttribute("className", "caret caret-right");
  199. }
  200. }
  201.  
  202. function boot() {
  203. window.onload = null;
  204.  
  205. translate();
  206.  
  207. setup_path_globals (window.location.pathname);
  208.  
  209. // Setup title
  210. var title = environment.page.title;
  211. if (!title)
  212. title = environment.hostname;
  213. document.title = title;
  214.  
  215. if (application.indexOf("cockpit+=") === 0) {
  216. id("brand").style.display = "none";
  217. id("badge").style.visibility = "hidden";
  218. } else {
  219. brand("badge", "");
  220. brand("brand", "Cockpit");
  221. }
  222.  
  223. id("option-group").addEventListener("click", toggle_options);
  224. id("server-clear").addEventListener("click", function () {
  225. var el = id("server-field");
  226. el.value = "";
  227. el.focus();
  228. });
  229.  
  230. if (!requisites())
  231. return;
  232.  
  233. /* Setup the user's last choice about the authorized button */
  234. var authorized = window.localStorage.getItem('authorized-default') || "";
  235. if (authorized.indexOf("password") !== -1)
  236. id("authorized-input").checked = true;
  237.  
  238. var os_release = JSON.stringify(environment["os-release"]);
  239. var logout_intent = window.sessionStorage.getItem("logout-intent") == "explicit";
  240. if (logout_intent)
  241. window.sessionStorage.removeItem("logout-intent");
  242. window.localStorage.setItem('os-release', os_release);
  243.  
  244. /* Try automatic/kerberos authentication? */
  245. if (oauth) {
  246. id("login-details").style.display = 'none';
  247. id("login").style.display = 'none';
  248. if (logout_intent) {
  249. build_oauth_redirect_to();
  250. id("login-again").textContent = _("Login Again");
  251. fatal(_("Logout Successful"));
  252. } else {
  253. oauth_auto_login();
  254. }
  255. } else if (logout_intent) {
  256. show_login();
  257. } else {
  258. standard_auto_login();
  259. }
  260. }
  261.  
  262. function standard_auto_login() {
  263. var xhr = new XMLHttpRequest();
  264. xhr.open("GET", login_path, true);
  265. xhr.onreadystatechange = function () {
  266. if (xhr.readyState != 4) {
  267. return;
  268. } else if (xhr.status == 200) {
  269. run(JSON.parse(xhr.responseText));
  270. } else if (xhr.status == 401) {
  271. show_login();
  272. } else if (xhr.statusText) {
  273. fatal(decodeURIComponent(xhr.statusText));
  274. } else if (xhr.status === 0) {
  275. show_login();
  276. } else {
  277. fatal(format(_("$0 error"), xhr.status));
  278. }
  279. };
  280. xhr.send();
  281. }
  282.  
  283. function build_oauth_redirect_to() {
  284. var url_parts = window.location.href.split('#', 2);
  285. oauth_redirect_to = oauth.URL;
  286. if (oauth.URL.indexOf("?") > -1)
  287. oauth_redirect_to += "&";
  288. else
  289. oauth_redirect_to += "?";
  290. oauth_redirect_to += "redirect_uri=" + encodeURIComponent(url_parts[0]);
  291. }
  292.  
  293. function oauth_auto_login() {
  294. var parser = document.createElement('a');
  295. if (!oauth.URL)
  296. return fatal(_("Cockpit authentication is configured incorrectly."));
  297.  
  298. var query = QueryParams(window.location.search);
  299. if (!window.location.search && window.location.hash)
  300. query = QueryParams(window.location.hash.slice(1));
  301.  
  302. /* Not all providers allow hashes in redirect urls */
  303.  
  304. var token_val, prompt_data, xhr;
  305. build_oauth_redirect_to();
  306.  
  307. if (query[oauth.TokenParam]) {
  308. if (window.sessionStorage.getItem('login-wanted')) {
  309. parser.href = window.sessionStorage.getItem('login-wanted');
  310. setup_path_globals (parser.pathname);
  311. }
  312.  
  313. token_val = query[oauth.TokenParam];
  314. id("login-wait-validating").style.display = "block";
  315. xhr = new XMLHttpRequest();
  316. xhr.open("GET", login_path, true);
  317. xhr.setRequestHeader("Authorization", "Bearer " + token_val);
  318. xhr.onreadystatechange = function () {
  319. if (xhr.readyState != 4) {
  320. return;
  321. } else if (xhr.status == 200) {
  322. run(JSON.parse(xhr.responseText));
  323. } else {
  324. prompt_data = get_prompt_from_challenge(xhr.getResponseHeader("WWW-Authenticate"),
  325. xhr.responseText);
  326. if (prompt_data)
  327. show_converse(prompt_data);
  328. else
  329. fatal(xhr.statusText);
  330. }
  331. };
  332. xhr.send();
  333. } else if (query[oauth.ErrorParam]) {
  334. fatal(query[oauth.ErrorParam]);
  335. } else {
  336. /* Store url we originally wanted in case we
  337. * had to strip a hash or query params
  338. */
  339. window.sessionStorage.setItem('login-wanted',
  340. window.location.href);
  341. window.location = oauth_redirect_to;
  342. }
  343. }
  344.  
  345. function clear_errors() {
  346. id("error-group").style.display = "none";
  347. id("login-error-message").textContent = "";
  348. }
  349.  
  350. function login_failure(msg, in_conversation) {
  351. clear_errors();
  352. if (msg) {
  353. /* OAuth failures are always fatal */
  354. if (oauth) {
  355. fatal(msg);
  356. } else {
  357. show_form(in_conversation);
  358. id("login-error-message").textContent = msg;
  359. id("error-group").style.display = "block";
  360. }
  361. }
  362. }
  363.  
  364. function host_failure(msg) {
  365. var host = id("server-field").value;
  366. if (!host) {
  367. login_failure(msg, false);
  368. } else {
  369. clear_errors();
  370. id("login-error-message").textContent = msg;
  371. id("error-group").style.display = "block";
  372. toggle_options(null, true);
  373. show_form();
  374. }
  375. }
  376.  
  377. function login_note(msg) {
  378. var el = id("login-note");
  379. if (msg) {
  380. el.style.display = 'block';
  381. el.textContent = msg;
  382. } else {
  383. el.innerHTML = '&nbsp;';
  384. }
  385. }
  386.  
  387. function call_login() {
  388. login_failure(null);
  389. var machine, user = trim(id("login-user-input").value);
  390. if (user === "") {
  391. login_failure(_("User name cannot be empty"));
  392. } else {
  393. machine = id("server-field").value;
  394. if (machine) {
  395. application = "cockpit+=" + machine;
  396. login_path = org_login_path.replace("/" + org_application + "/", "/" + application + "/");
  397. } else {
  398. application = org_application;
  399. login_path = org_login_path;
  400. }
  401.  
  402. id("server-name").textContent = machine || environment.hostname;
  403. id("login-button").removeEventListener("click", call_login);
  404.  
  405.  
  406. /* When checked we tell the server to keep authentication */
  407. var authorized = id("authorized-input").checked ? "password" : "";
  408. var password = id("login-password-input").value;
  409. window.localStorage.setItem('authorized-default', authorized);
  410.  
  411. var headers = {
  412. "Authorization": "Basic " + window.btoa(utf8(user + ":" + password)),
  413. "X-Authorize": authorized,
  414. };
  415.  
  416. send_login_request("GET", headers, false);
  417. }
  418. }
  419.  
  420. function show_form(in_conversation) {
  421. var connectable = environment.page.connect;
  422. var expanded = id("option-group").getAttribute("data-state");
  423. id("login-wait-validating").style.display = "none";
  424. id("login").style.visibility = 'visible';
  425. id("login").style.display = "block";
  426. id("user-group").style.display = in_conversation ? "none" : "block";
  427. id("password-group").style.display = in_conversation ? "none" : "block";
  428. id("option-group").style.display = !connectable || in_conversation ? "none" : "block";
  429. id("conversation-group").style.display = in_conversation ? "block" : "none";
  430. id("login-button-text").textContent = "Log In";
  431. id("login-password-input").value = '';
  432.  
  433. if (!connectable || in_conversation) {
  434. id("server-group").style.display = "none";
  435. } else {
  436. id("server-group").style.display = expanded ? "block" : "none";
  437. }
  438.  
  439.  
  440. id("login-button").removeAttribute('disabled');
  441.  
  442. if (!in_conversation)
  443. id("login-button").addEventListener("click", call_login);
  444. }
  445.  
  446. function show_login() {
  447. /* Show the login screen */
  448. id("server-name").textContent = document.title;
  449. login_note("Log in with your server user account.");
  450. id("login-user-input").addEventListener("keydown", function(e) {
  451. login_failure(null);
  452. if (e.which == 13)
  453. id("login-password-input").focus();
  454. }, false);
  455.  
  456. id("login-password-input").addEventListener("keydown", function(e) {
  457. login_failure(null);
  458. if (e.which == 13)
  459. call_login();
  460. });
  461. show_form();
  462. id("login-user-input").focus();
  463. phantom_checkpoint();
  464. }
  465.  
  466. function show_converse(prompt_data) {
  467. var type = prompt_data.echo ? "text" : "password";
  468. id("conversation-prompt").textContent = prompt_data.prompt;
  469.  
  470. var em = id("conversation-message");
  471. var msg = prompt_data.error || prompt_data.message;
  472. if (msg) {
  473. em.textContent = msg;
  474. em.style.display = "block";
  475. } else {
  476. em.style.display = "none";
  477. }
  478.  
  479. var ei = id("conversation-input");
  480. ei.value = "";
  481. if (prompt_data.default)
  482. ei.value = prompt_data.default;
  483. ei.setAttribute('type', type);
  484. ei.focus();
  485.  
  486. login_failure("");
  487.  
  488. function call_converse() {
  489. id("conversation-input").removeEventListener("keydown", key_down);
  490. id("login-button").removeEventListener("click", call_converse);
  491. login_failure(null, true);
  492. converse(prompt_data.id, id("conversation-input").value);
  493. }
  494.  
  495. function key_down(e) {
  496. login_failure(null, true);
  497. if (e.which == 13) {
  498. call_converse();
  499. }
  500. }
  501.  
  502. id("conversation-input").addEventListener("keydown", key_down);
  503. id("login-button").addEventListener("click", call_converse);
  504. show_form(true);
  505. phantom_checkpoint();
  506. }
  507.  
  508. function utf8(str) {
  509. return window.unescape(encodeURIComponent(str));
  510. }
  511.  
  512. function get_prompt_from_challenge (header, body) {
  513. var parts;
  514. var prompt;
  515. var resp;
  516. var id;
  517.  
  518. if (!header)
  519. return null;
  520.  
  521. parts = header.split(' ');
  522. if (parts[0].toLowerCase() !== 'x-conversation' && parts.length != 3)
  523. return null;
  524.  
  525. id = parts[1];
  526. try {
  527. prompt = window.atob(parts[2]);
  528. } catch (err) {
  529. if (window.console)
  530. console.error("Invalid prompt data", err);
  531. return null;
  532. }
  533.  
  534. try {
  535. resp = JSON.parse(body);
  536. } catch (err) {
  537. if (window.console)
  538. console.log("Got invalid JSON response for prompt data", err);
  539. resp = {};
  540. }
  541.  
  542. resp.id = id;
  543. resp.prompt = prompt;
  544. return resp;
  545. }
  546.  
  547. function send_login_request(method, headers, is_conversation) {
  548. id("login-button").setAttribute('disabled', "true");
  549. var xhr = new XMLHttpRequest();
  550. xhr.open("GET", login_path, true);
  551. var prompt_data;
  552. var challenge;
  553.  
  554. var k;
  555. for (k in headers)
  556. xhr.setRequestHeader(k, headers[k]);
  557.  
  558. xhr.onreadystatechange = function () {
  559. if (xhr.readyState != 4) {
  560. return;
  561. } else if (xhr.status == 200) {
  562. var resp = JSON.parse(xhr.responseText);
  563. run(resp);
  564. } else if (xhr.status == 401) {
  565. challenge = xhr.getResponseHeader("WWW-Authenticate");
  566. if (challenge && challenge.toLowerCase().indexOf("x-conversation") === 0) {
  567. prompt_data = get_prompt_from_challenge(challenge, xhr.responseText);
  568. if (prompt_data)
  569. show_converse(prompt_data);
  570. else
  571. fatal(_("Internal Error: Invalid challenge header"));
  572. } else {
  573. if (window.console)
  574. console.log(xhr.statusText);
  575. if (xhr.statusText.indexOf("authentication-not-supported") > -1) {
  576. var user = trim(id("login-user-input").value);
  577. fatal(format(_("The server refused to authenticate '$0' using password authentication, and no other supported authentication methods are available."), user));
  578. } else if (xhr.statusText.indexOf("terminated") > -1) {
  579. login_failure(_("Authentication Failed: Server closed connection"));
  580. } else if (xhr.statusText.indexOf("no-host") > -1) {
  581. host_failure(_("Unable to connect to that address"));
  582. } else if (xhr.statusText.indexOf("unknown-hostkey") > -1) {
  583. host_failure(_("Refusing to connect. Hostkey is unknown"));
  584. } else if (xhr.statusText.indexOf("unknown-host") > -1) {
  585. host_failure(_("Refusing to connect. Host is unknown"));
  586. } else if (xhr.statusText.indexOf("invalid-hostkey") > -1) {
  587. host_failure(_("Refusing to connect. Hostkey does not match"));
  588. } else if (is_conversation) {
  589. login_failure(_("Authentication failed"));
  590. } else {
  591. login_failure(_("Wrong user name or password"));
  592. }
  593. }
  594. } else if (xhr.status == 403) {
  595. login_failure(decodeURIComponent(xhr.statusText) || _("Permission denied"));
  596. } else if (xhr.statusText) {
  597. fatal(decodeURIComponent(xhr.statusText));
  598. } else {
  599. fatal(format(_("$0 error"), xhr.status));
  600. }
  601. id("login-button").removeAttribute('disabled');
  602. phantom_checkpoint();
  603. };
  604. xhr.send();
  605. }
  606.  
  607. function converse(id, msg) {
  608. var headers = {
  609. "Authorization": "X-Conversation " + id + " " + window.btoa(utf8(msg))
  610. };
  611. send_login_request("GET", headers, true);
  612. }
  613.  
  614. function login_reload (wanted) {
  615. if (wanted && wanted != window.location.href)
  616. window.location = wanted;
  617.  
  618. // Force a reload if the above didn't trigger it
  619. window.setTimeout(function() {
  620. window.location.reload(true);
  621. }, 100);
  622. }
  623.  
  624. function machine_application_login_reload (wanted) {
  625. var base = '/' + application + '/@localhost/';
  626. if (url_root)
  627. base = '/' + url_root + base;
  628. var embeded_url = base + 'shell/index.html';
  629. var xhr = new XMLHttpRequest();
  630. xhr.open("GET", base + 'manifests.json', true);
  631. xhr.onreadystatechange = function () {
  632. if (xhr.readyState != 4) {
  633. return;
  634. } else if (xhr.status == 200) {
  635. var resp = JSON.parse(xhr.responseText);
  636. var base1 = resp ? resp['base1'] : {};
  637. if (!base1['version'] || base1['version'] < "119.x") {
  638. login_reload (embeded_url);
  639. } else
  640. login_reload (wanted);
  641. } else {
  642. login_reload (embeded_url);
  643. }
  644. phantom_checkpoint();
  645. };
  646. xhr.send();
  647. }
  648.  
  649. function clear_storage (storage, prefix, full) {
  650. var i = 0;
  651. while (i < storage.length) {
  652. var k = storage.key(i);
  653. if (full && k.indexOf("cockpit") !== 0)
  654. storage.removeItem(k);
  655. else if (k.indexOf(prefix) === 0)
  656. storage.removeItem(k);
  657. else
  658. i++;
  659. }
  660. }
  661.  
  662. function setup_localstorage (response) {
  663. /* Clear anything not prefixed with
  664. * different application from sessionStorage
  665. */
  666. clear_storage (window.sessionStorage, application, true);
  667.  
  668. /* Clear anything prefixed with our application
  669. * and login-data, but not other non-application values.
  670. */
  671. window.localStorage.removeItem('login-data');
  672. clear_storage (window.localStorage, application, false);
  673.  
  674. var str;
  675. if (response && response["login-data"]) {
  676. str = JSON.stringify(response["login-data"]);
  677. try {
  678. /* login-data is tied to the auth cookie, since
  679. * cookies are available after the page
  680. * session ends login-data should be too.
  681. */
  682. window.localStorage.setItem(application + 'login-data', str);
  683. /* Backwards compatbility for packages that aren't application prefixed */
  684. window.localStorage.setItem('login-data', str);
  685. } catch(ex) {
  686. console.warn("Error storing login-data:", ex);
  687. }
  688. }
  689.  
  690. /* URL Root is set by cockpit ws and shouldn't be prefixed
  691. * by application
  692. */
  693. if (url_root)
  694. window.localStorage.setItem('url-root', url_root);
  695. }
  696.  
  697. function run(response) {
  698. var wanted = window.sessionStorage.getItem('login-wanted');
  699. var machine = id("server-field").value;
  700. var str;
  701.  
  702. if (machine && application != org_application) {
  703. wanted = "/=" + machine;
  704. if (url_root)
  705. wanted = "/" + url_root + wanted;
  706. }
  707.  
  708. /* clean up sessionStorage. clear anything that isn't prefixed
  709. * with an application and anything prefixed with our application.
  710. */
  711. clear_storage(window.sessionStorage, application, false);
  712.  
  713. setup_localstorage(response);
  714.  
  715. /* Make sure that the base1 version is new enough to handle
  716. * urls that reference machines.
  717. */
  718. if (application.indexOf("cockpit+=") === 0) {
  719. machine_application_login_reload (wanted);
  720. } else {
  721. login_reload (wanted);
  722. }
  723. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement