<%@language = "javascript" %>
<% /*
     $Revision$
     $Id$

    File:           idp_self_register_save.asp
    Description:    Voor als je via een IdP zelfregistratie wilt aanbieden
    Parameters:     redirect_uri
                    return_to
                    aud
                    state
    Context:        vanuit idp_self_register.asp
    Note:           Wordt normaal gesproken twee keer aangeroepen.
                    De eerste keer zonder token, die wordt aangemaakt en gemaild
                    De tweede keer met token, dan wordt de user (via een JWT) teruggeleid/aangemaakt
*/
ANONYMOUS_Allowed = 1;
var JSON_Result = true;
%>
<!--#include file="../Shared/common.inc"-->
<% settings.overrule_setting("multi_language_option", 0); %>
<!-- #include file="../Shared/save2db.inc" -->
<!-- #include file="../Shared/send_mail.inc"-->
<!-- #include file="../aut/login.inc" -->
<%

if (S("self_register") != 1)
    shared.simpel_page(L("lcl_no_auth"));

var result = { rsuccess: 1, warning: "" };

var email      = getFParam("prs_email");
var naam       = getFParam("prs_naam");
var voornaam   = getFParam("prs_vrnaam", "");
var telefoon   = getFParam("prs_telnr");

var emailtoken = getFParam("mailtoken", "");



email = email.replace(/^\s+|\s+$/g,""); // trim spaces

// Uberhaupt syntactisch geldige e-mail?
if (!new RegExp(S("email_regexp_single"), "ig").test(email))
    abort_with_warning(L("lcl_invalid_email"));

// En valt het ook binnen onze eventuele white-list?
var sql = "SELECT aut_idp_saml_metaurl aut_idp_email_whitelist"
        + "     , aut_idp_audience"
        + "     , aut_idp_issuer"
        + "     , aut_idp_secret"
        + "  FROM aut_idp"
        + " WHERE aut_idp_type = 4" // JWT
        + "   AND aut_idp_saml_metaurl IS NOT NULL";
var oRs = Oracle.Execute(sql);
var aud = null;
while (!oRs.EOF)
{
    var email_whitelist = oRs("aut_idp_email_whitelist").Value;
    if (new RegExp(email_whitelist, "i").test(email))
    {
        aud = oRs("aut_idp_audience").Value;
        iss = oRs("aut_idp_issuer").Value;
        secret = oRs("aut_idp_secret").Value;
    }
    oRs.MoveNext();
}
if (!aud)
   abort_with_warning(L("lcl_self_register_email_wrong"));

oRs.Close()

if (emailtoken)
{
    var thetoken = emailtoken.toLowerCase(); // wij sturen lowercase base32
    thetoken = thetoken.replace(/0/i, 'o'); // 0 / 1 / 8 komen daar niet in voor
    thetoken = thetoken.replace(/1/i, 'l');
    thetoken = thetoken.replace(/8/i, 'b');
    var expire = Session("self_expire");
    if (expire < new Date())
    {
        abort_with_warning("Token is expired!");
    }
    if (thetoken != Session("self_token") || email != Session("self_email"))
    {
        abort_with_warning("Token Mismatch!");
    }

    var redirect_uri = getQParam("redirect_uri", rooturl + "/"); // TODO: verify?
    var return_to = getQParam("return_to", "");
    var state = getQParam("state", "");

    var claim =
    {
        jti: "#" + (email) + "#" + new Date().getTime(),
        iat: Math.round(new Date().getTime() / 1000),
        iss: iss,
        aud: aud,

        family_name: naam,
        given_name: voornaam,
        email: email,
        email_verified: true,
        phone_number: telefoon,
        password_reset: true
    }
    var jwt = jwt_encode(claim, secret);

    var url = redirect_uri + (redirect_uri.indexOf("?")>=0?"&":"?") + "jwt={0}";
    if (return_to)
        url = url + "&return_to=" + Server.URLencode(return_to);
    if (state)
        url = url + "&state=" + Server.URLencode(state);

    var result = { success: true, redirect_uri: url.format(jwt) };

    Session.Contents.Remove("self_token");
    Session.Contents.Remove("self_expire");
    Session.Contents.Remove("self_email");
}
else // nieuw token
{
    var emailtoken = shared.random(6, 'base32').toLowerCase(); // Effectief ? bits
    Session("self_email") = email;
    Session("self_token") = emailtoken;
    var expire = new Date();
    expire.setMinutes(expire.getMinutes + S("self_register_expire"));
    Session("self_expire") = expire;
    //Session("self_info_hash") = hex_sha1(alle info die je hebt gesubmit)

    fac_send_mail_html(email, "Facilitor aanmeld token", "Uw Facilitor aanmeld token is <span style='font-family:monospace'>{0}</span>".format(emailtoken),
                    { FromAddress: S("self_fromaddress"), ReplyAddress: S("self_replyaddress") })

    var result = { success: true, emailtokenprompt: true,
                   message: L("lcl_self_register_email_sent").format(email) + (Application("otap_environment") == "O"?"\n\nOTAP: Let op, je email adres is misschien overruled. Voor als je geen geduld hebt: " + emailtoken:"")};
}

Response.Write(JSON.stringify(result));
%>
<% ASPPAGE_END(); %>
