Backend Integration of Email Magic Links

In Stytch’s B2B product there are two different versions of the EML authentication flow:

  1. Discovery Authentication: used for self-serve organization creation or login without Organization context
  2. Organization-specific Authentication: used when you already know the Organization that the end user is trying to log into

The guides below cover how to offer Email Magic Links for both scenarios, using a backend integration approach.

Discovery Sign-Up or Login

The discovery flow is designed for situations where your end users are signing up or logging in from a central landing page, and have not specified which organization they are trying to access or are attempting to create a new Organization.

The sequence for how this flow works when using a backend integration approach is as follows:

Backend integration of discovery Magic Links

1Complete config steps

If you haven't done so already complete the steps in the EML Quickstart Start Here

2Create login page with email input

You'll need some way for the user to input their email in order to trigger the magic link flow. Create a route that checks to will surface the discovery login or sign-up view to your end user.

You can create a super simple template for taking in the user input:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Dashboard</title>
    <link rel="stylesheet" href="/static/css/styles.css">
</head>
<body>
    <div class="card">
    <p>Sign-up or Login with Email Magic Links</p>
    <div class="divider">
        <hr class="line" />
    </div>
        <form action="/send-discovery-eml" method="post">
            <label for="email">Email Address:</label>
            <input type="email" id="email" name="email" required>
            <button type="submit">Submit</button>
        </form>
    </div>
</body>
</html>

which would be served by a basic route like the following:

@app.route("/", methods=["GET"])
def index(slug: str):

    # Next up: check for session, and if present redirect to logged in view

    return render_template("login.html")

3Handle submission of email

After the user submits the form with their email, you'll need a route for triggering the outbound call to Stytch to initiate the magic link discovery flow.

@app.route("/send-discovery-eml", methods=["POST"])
def send_discovery_eml() -> str:
    email = request.form.get("email", None)
    if email is None:
        return "Email is required", 400

    resp = stytch_client.magic_links.email.discovery.send(email_address=email)
    if resp.status_code != 200:
        return "Error sending EML", 500

    return "Success"

4Configure callback and surface UI for selecting an organization

Stytch will make a callback to the Discovery RedirectURL that you specified in the Stytch dashboard. Your application should handle checking the stytch_token_type for the callback, and call the appropriate authentication method to finish the login process.

If your RedirectURL was http://localhost:3000/discovery you would add the following route to your application:

@app.route("/discovery", methods=["GET"])
def discovery() -> str:
    token_type = request.args["stytch_token_type"]
    token = request.args["token"]
    if token_type != "discovery":
        # add handling for other discovery token types like discovery_oauth in the future
        return "Unsupported auth method", 400

    resp = stytch_client.magic_links.discovery.authenticate(discovery_magic_links_token=token)
    if resp.status_code != 200:
        return "Authentication error", 500

    # store IST as cookie or other mechanism for use in subsequent request to exchange
    session['ist'] = resp.intermediate_session_token
    orgs = []
    for discovered in resp.discovered_organizations:
        org = {
            "organization_id": discovered.organization.organization_id,
            "organization_name": discovered.organization.organization_name,
        }
        orgs.append(org)

    return render_template(
        'discoveredOrgs.html',
        discovered_organizations=orgs,
        email_address=resp.email_address
    )

Create a template that surfaces the available organizations to the end user as well as the option to create a new Organization.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Dashboard</title>
    <link rel="stylesheet" href="/static/css/styles.css">
</head>
<body>
    <div class="card">
    <div class="card-content">
        <h1>
            Discovered Organizations for {{ email_address }}
        </h1>
    </div>
    <p>Login to existing Organization or create a new one!</p>
    <div id="button-containers"></div>
    <div class="divider">
        <hr class="line" />
    </div>
        <button class="button" onclick="createOrg()"> Create New Organization </button>
    </div>
    <script>
        function selectOrg(organization_id) {
            window.location.href = `/login/${organization_id}`;
        }
        function createOrg() {
            window.location.href = `/create_org`;
        }
        const unparsedOrgs = "{{ discovered_organizations }}"
        const orgs = JSON.parse(unparsedOrgs.replaceAll("&#39;", "\""))
        function iterateOverOrgs() {
            document.getElementById('button-containers').innerHTML = orgs.map(org => (
            `<button class="button" onclick="selectOrg('${org.organization_id}')">
            ${org.organization_name}
            </button>`
            )).join('\n\n');
        }
        iterateOverOrgs();
    </script>
</body>
</html>

5Create routes for handling user selection

Create two routes to handle the options presented to the end user: logging into an existing Organization or creating a new Organization.

@app.route("/login/<string:organization_id>", methods=["GET"])
def login_to_org(organization_id):
    ist = session.get('ist', None)
    if ist is None:
        return "No IST found"

    resp = stytch_client.discovery.intermediate_sessions.exchange(
        intermediate_session_token=ist,
        organization_id=organization_id
    )
    if resp.status_code != 200:
        return "Error logging into org", 500

    # Clear IST and set stytch session
    session.pop('ist', None)
    session['stytch_session'] = resp.session_token
    return member.json()

@app.route("/create_org", methods=["GET"])
def create_org() -> str:
    ist = session.get('ist', None)
    if ist is None:
        return "No IST found"

    # Created org name and slug will be based on user's email
    # Can also prompt end user to provide these 
    resp = stytch_client.discovery.organizations.create(
        intermediate_session_token=ist,
        organization_slug='',
        organization_name=''
    )
    if resp.status_code != 200:
        return "Error creating org", 500

    # Clear IST and set stytch session
    session.pop('ist', None)
    session['stytch_session'] = resp.session_token
    return member.json()

6Test it out

Run your application, enter your email and test out the discovery flow!