Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

2.1 KB
Raw Blame
(ns metabase-enterprise.sso.integrations.saml-utils
  "Functions for handling SAML authentication with the SDK side, including HTML popups"
  (:require
   [java-time.api :as t]
   [metabase.server.middleware.security :as mw.security]
   [metabase.util.json :as json])
  (:import
   (java.time Instant)))

(set! *warn-on-reflection* true)

(defn- generate-saml-html-popup
  [key ^Instant exp ^Instant iat origin continue-url nonce]
  (str "<!DOCTYPE html>
<html>
<head>
  <title>Authentication Complete</title>
  <script nonce=\"" nonce "\">
    const authData = {
      id: " (json/encode key) ",
      exp: " (.getEpochSecond exp) ",
      iat: " (.getEpochSecond iat) ",
      status: \"ok\"
    };
    if (window.opener) {
      try {
        window.opener.postMessage({
          type: 'SAML_AUTH_COMPLETE',
          authData: authData
        }, " (json/encode origin) ");

        setTimeout(function() {
          window.close();
        }, 500);
      } catch(e) {
        console.error('Error sending message:', e);
        document.body.innerHTML += '<p>Error: ' + e.message + '</p>';
      }
    } else {
      window.location.href = " (json/encode continue-url) ";
    }
  </script>
</head>
<body style=\"background-color: white; margin: 20px; padding: 20px;\">
  <h3>Authentication complete</h3>
  <p>This window should close automatically.</p>
  <p>If it doesn't close, please click the button below:</p>
  <button onclick=\"window.close()\">Close Window</button>
</body>
</html>"))

(defn create-token-response
  "Create a token response with HTML and JavaScript to post the auth message. The inline script carries the
  session key and timestamps, so it varies per request and no build-time hash can cover it. The response
  opts into a `script-src` nonce for that reason."
  [session origin continue-url nonce]
  (let [current-time (t/instant)
        expiration-time (t/plus current-time (t/seconds 86400))]
    {:status 200
     :headers {"Content-Type" "text/html"}
     mw.security/script-nonce-response-key true
     :body (generate-saml-html-popup (:key session) expiration-time current-time origin continue-url nonce)}))