{% extends 'layout.html'%}

{%block content%}

<br>
<div class="row">
    <div class="col-md-6">
        <h1>Request New PRT</h1>
        <form id="prt_form" class="row g-3">
            <div class="col-xl-6">
                <div class="input-group">
                    <label for="refresh_token_id" class="input-group-text">Refresh token id</label>
                    <input type="text" id="refresh_token_id" name="refresh_token_id" class="form-control" required>
                    <button class="btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#refresh_token_modal" onclick="$('#refresh_token_modal_table').DataTable().ajax.reload(null, false)">Select...</button>
                </div>
            </div>
            <div class="col-lg-6">
                <div class="input-group">
                    <label for="os_version" class="input-group-text">OS Version</label>
                    <input type="text" id="os_version" name="os_version" class="form-control" placeholder="10.0.26100">
                </div>
            </div>
            <div class="col-xl-8">
                <div class="input-group">
                    <label for="device_id" class="input-group-text">Device ID</label>
                    <input type="text" id="device_id" name="device_id" class="form-control" required>
                    <button class="btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#device_modal" onclick="$('#device_modal_table').DataTable().ajax.reload(null, false)">Select...</button>
                </div>
            </div>
            <div class="col-auto">
                <button type="button" class="btn btn-primary" onclick="requestPRT()">Request PRT</button>
            </div>
        </form>
        <br>
        <h1>Active PRT</h1>
        <form id="prt_form_active" class="row row-cols-auto">
            <div class="col-auto">
                <div class="input-group">
                    <label for="active_prt_id" class="input-group-text">Active PRT</label>
                    <input type="text" id="active_prt_id" name="active_prt_id" class="form-control">
                    <button type="Button" class="btn btn-primary" onclick="setActivePrt(active_prt_id.value)">Set active token</button>
                </div>
            </div>
        </form>
    </div>
    <div class="col-md-6">
        <h1>Import PRT</h1>
        <form id="import_prt_form" class="row g-3">
            <div class="col-12">
                <div class="input-group">
                    <label for="import_prt" class="input-group-text">PRT</label>
                    <input type="text" id="import_prt" name="prt" class="form-control" required>
                </div>
            </div>
            <div class="col-12">
                <div class="input-group">
                    <label for="import_session_key" class="input-group-text">Session Key (hex)</label>
                    <input type="text" id="import_session_key" name="session_key" class="form-control" required>
                </div>
            </div>
            <div class="col-xl-6">
                <div class="input-group">
                    <label for="import_issued_at" class="input-group-text">Issued At (epoch)</label>
                    <input type="text" id="import_issued_at" name="issued_at" class="form-control" placeholder="1735732800 (optional)">
                </div>
            </div>
            <div class="col-xl-6">
                <div class="input-group">
                    <label for="import_expires_at" class="input-group-text">Expires At (epoch)</label>
                    <input type="text" id="import_expires_at" name="expires_at" class="form-control" placeholder="1735732800 (optional)">
                </div>
            </div>
            <div class="col-xl-6">
                <div class="input-group">
                    <label for="import_user" class="input-group-text">User</label>
                    <input type="text" id="import_user" name="user" class="form-control" placeholder="john.doe@e-corp.local (optional)">
                </div>
            </div>
            <div class="col-xl-6">
                <div class="input-group">
                    <label for="import_description" class="input-group-text">Description</label>
                    <input type="text" id="import_description" name="description" class="form-control" placeholder="(optional)">
                </div>
            </div>
            <div class="col-xl-8">
                <div class="input-group">
                    <label for="import_device_id" class="input-group-text">Device ID</label>
                    <input type="text" id="import_device_id" name="import_device_id" class="form-control" placeholder="00000000-0000-0000-0000-000000000000 (optional)">
                    <button class="btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#device_modal" onclick="$('#device_modal_table').DataTable().ajax.reload(null, false)">Select...</button>
                </div>
            </div>
            <div class="col-auto">
                <button type="button" class="btn btn-primary" onclick="importPRT()">Import PRT</button>
            </div>
        </form>
    </div>
</div>
<script>
    getActiveRefreshToken(document.getElementById("refresh_token_id"));
    getActivePrt(document.getElementById("prt_form_active").active_prt_id);

    loadDeviceModalTable();

    function requestPRT() {
        let formData = {
            device_id: $('#device_id').val(),
            refresh_token_id: $('#refresh_token_id').val(),
            os_version: $('#os_version').val() || "10.0.26100"
        };

        $.ajax({
            url: '/api/request_prt_for_device',
            type: 'POST',
            data: formData,
            success: function(response) {
                bootstrapToast("Request PRT", response.message, "success");
                $('#primary_refresh_tokens').DataTable().ajax.reload(null, false);
            },
            error: function(xhr) {
                bootstrapToast("Request PRT", xhr.responseJSON.message, "danger");
            }
        });
    }

    function importPRT() {
        let formData = {
            prt: $('#import_prt').val(),
            session_key: $('#import_session_key').val(),
            device_id: $('#import_device_id').val() || "Unknown",
            user: $('#import_user').val() || "Unknown",
            description: $('#import_description').val() || null,
            issued_at: $('#import_issued_at').val() || null,
            expires_at: $('#import_expires_at').val() || null
        };

        $.ajax({
            url: '/api/import_prt',
            type: 'POST',
            data: formData,
            success: function(response) {
                bootstrapToast("Import PRT", response.message, "success");
                $('#primary_refresh_tokens').DataTable().ajax.reload(null, false);
                // Clear form
                $('#import_prt_form')[0].reset();
            },
            error: function(xhr) {
                bootstrapToast("Import PRT", xhr.responseJSON.message, "danger");
            }
        });
    }
</script>
<br>
<div>
    <h1>Primary Refresh Tokens</h1>
    <table id="primary_refresh_tokens" class="table nowrap" style="table-layout: fixed; width:100%">
    </table>
</div>
<script type="text/javascript" class="init">
    // Populate the primary_refresh_tokens table
    let myTable = new DataTable('#primary_refresh_tokens', {
        ajax: {
            url: '/api/list_primary_refresh_tokens', dataSrc: "data"
        },
        columns: [
            {
                className: 'dt-control table-control',
                orderable: false,
                data: null,
                defaultContent: '',
                'width': '40px'
            },
            {
                className: 'active-control table-control',
                orderable: false,
                data: null,
                defaultContent: '<i class="fi fi-br-check" title="Set as Active PRT" style="cursor: pointer"></i>',
                'width': '40px'
            },
            {
                className: 'copy-prt-control table-control',
                orderable: false,
                data: null,
                defaultContent: '<i class="fi fi-rr-copy-alt" title="Copy PRT to Clipboard" style="cursor: pointer"></i>',
                'width': '40px'
            },
            {
                className: 'copy-key-control table-control',
                orderable: false,
                data: null,
                defaultContent: '<i class="fi fi-rr-key" title="Copy Session Key to Clipboard" style="cursor: pointer"></i>',
                'width': '40px'
            },
            {
                className: 'cookie-control table-control',
                orderable: false,
                data: null,
                defaultContent: '<i class="fi fi-rr-cookie-alt" title="Generate a PRT Cookie" style="cursor: pointer"></i>',
                'width': '40px'
            },
            {
                className: 'delete-control table-control',
                orderable: false,
                data: null,
                defaultContent: '<i class="fi fi-rr-trash" title="Delete Primary Refresh Token" style="cursor: pointer"></i>',
                'width': '40px'
            },
            { data: 'id', title: 'ID', 'width': '60px' },
            { 
                data: 'issued_at', 
                title: 'Issued At', 
                'width': '170px',
                render: function(data) {
                    return data ? (new Date(data * 1000).toLocaleString()) : "Unknown";
                }
            },
            { 
                data: 'expires_at', 
                title: 'Expires At', 
                'width': '170px',
                render: function(data) {
                    return data ? (new Date(data * 1000).toLocaleString()) : "Unknown";
                }
            },
            { data: 'user', title: 'User', 'width': '370px' },
            { data: 'device_id', title: 'Device ID', 'width': '370px' },
            { data: 'description', title: 'Description', 'width': 'auto' }
        ],
        order: [[6, 'desc']],
        colReorder: {
            columns: ':gt(5)'
        },
        processing: true,
        createdRow: function (row, data, dataIndex) {
            if (!data.expires_at) {
                $(row).children().addClass('bg-warning-subtle').addClass('text-warning-emphasis');
            }
            else if (new Date(data.expires_at * 1000) > new Date()) {
                $(row).children().addClass('bg-success-subtle').addClass('text-success-emphasis');
            } else {
                $(row).children().addClass('bg-danger-subtle').addClass('text-danger-emphasis');
            }
        }
    })

    myTable.on('click', 'td.dt-control', function (e) {
        let tr = e.target.closest('tr');
        let row = myTable.row(tr);

        if (row.child.isShown()) {
            // This row is already open - close it
            row.child.hide();
        }
        else {
            // Open this row
            row.child(format(row.data())).show();
        }
    });

    myTable.on('click', 'td.active-control', function (e) {
        let tr = e.target.closest('tr');
        let row = myTable.row(tr);
        setActivePrt(row.data().id);
    });

    myTable.on('click', 'td.copy-prt-control', function (e) {
        let tr = e.target.closest('tr');
        let row = myTable.row(tr);
        copyToClipboard(row.data().prt);
    });

    myTable.on('click', 'td.copy-key-control', function (e) {
        let tr = e.target.closest('tr');
        let row = myTable.row(tr);
        copyToClipboard(row.data().session_key);
    });

    myTable.on('click', 'td.cookie-control', function (e) {
        let tr = e.target.closest('tr');
        let row = myTable.row(tr);
        generateAndCopyPrtCookie(row.data().id);
    });

    myTable.on('click', 'td.delete-control', function (e) {
        let tr = e.target.closest('tr');
        let row = myTable.row(tr);
        if (!confirm("Are you sure you want to delete primary refresh token with ID " + row.data().id + "?")) { return }
        deletePrimaryRefreshToken(row.data().id);
        $('#primary_refresh_tokens').DataTable().ajax.reload(null, false);
    });

    function format(d) {
        var formatWrapper = $('<dl style="word-break: break-all; white-space: pre-wrap"></dl>');
        formatWrapper.append($('<dt>Primary Refresh Token:</dt>'));
        formatWrapper.append($('<dd></dd>').append($('<code></code>').text(d.prt)));
        formatWrapper.append($('<dt>Session Key:</dt>'));
        formatWrapper.append($('<dd></dd>').append($('<code></code>').text(d.session_key)));
        return formatWrapper;
    }

    function deletePrimaryRefreshToken(id) {
        $.ajax({
            url: '/api/delete_primary_refresh_token',
            type: 'POST',
            data: {
                id: id
            },
            success: function(response) {
                bootstrapToast("Delete PRT", response.message, "success");
                $('#primary_refresh_tokens').DataTable().ajax.reload(null, false);
            },
            error: function(xhr) {
                bootstrapToast("Delete PRT", xhr.responseJSON.message, "danger");
            }
        });
    }

    function generateAndCopyPrtCookie(prtId) {
        $.ajax({
            url: '/api/generate_prt_cookie',
            type: 'POST',
            data: {
                prt_id: prtId
            },
            success: function(response) {
                bootstrapToast("PRT Cookie", response.message, "success");
                let prtCookie = response.data.prt_cookie;
                let cookieName = 'x-ms-RefreshTokenCredential';
                let domain = 'login.microsoftonline.com';

                createModal("prtCookieModal", "PRT Cookie Information", `
                    <div class="mb-3">
                        <b>Successfully generated a new PRT Cookie!</b><br>
                        This cookie is valid for about 5 minutes and allows signing in to any application using Entra ID SSO within this timeframe.
                    </div>
                    <ol class="mb-3">
                        <li>Go to <code>${domain}</code> in your browser <small class="text-muted">(Consider using a clean incognito Window to ensure you do not have any active sessions yet)</small></li>
                        <li>Open the developer tools (F12) and navigate to the <code>Cookies</code> section under the <code>Application</code> tab.</li>
                        <li>Clear any cookies for the <code>${domain}</code> domain, and insert a new cookie with the following details:</li>
                        <div class="my-3">
                            <div class="input-group">
                                <label for="cookieName" class="input-group-text">Cookie Name</label>
                                <input type="text" id="cookieName" class="form-control" value="${cookieName}" readonly style="max-width: 250px;">
                                <button class="btn btn-outline-secondary" type="button" onclick="copyToClipboard('${cookieName}')">
                                    <i class="fi fi-rr-copy"></i>
                                </button>
                                <label for="prtCookie" class="input-group-text">Cookie Value</label>
                                <input type="text" id="prtCookie" class="form-control" value="${prtCookie}" readonly>
                                <button class="btn btn-outline-secondary" type="button" onclick="copyToClipboard('${prtCookie}')">
                                    <i class="fi fi-rr-copy"></i>
                                </button>
                            </div>
                        </div>
                        <li>Reload the page, or go to <code>myapps.microsoft.com</code> to gain an overview of some of the applications supporting Entra ID SSO for the current user.</li>
                    </ol>
                `);

                let prtCookieModal = new bootstrap.Modal($('#prtCookieModal'));
                prtCookieModal.show();
            },
            error: function(xhr) {
                bootstrapToast("PRT Cookie", xhr.responseJSON.message, "danger");
            }
        });
    }
</script>
{%endblock content%} 