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

    File:           idp_get_bearer.asp
    Description:    Maak een bearer token geschikt voor Azure SCIM
    Parameters:     username  e.g. _SCIMKOPPELING
                    idp_code  e.g. SCIM moet 'Maximale geldigheid' op 31536000 voor 1 jaar
    Context:        Handmatige url appl/aut/idp_get_bearer.asp?username=_SCIMKOPPELING&idp_code=SCIM
    Note:           TODO: * Nettere interface
                          * We zetten nu altijd 'username' in de claim maar eigenlijk
                            moeten we het identifying attribute zoeken

*/
%>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../api2/api2.inc" -->
<!-- #include file="../api2/model_aut_idp.inc" -->
<!-- #include file="./login.inc" -->
<%

user.checkAutorisation("WEB_FACFAC"); // Heel streng (nog)

var username = getQParam("username");
var idp_code = getQParam("idp_code");

var filter = {
               type: 4, // IDP
               code: idp_code
             }

var idp_data_arr = new model_aut_idp({ internal: true }).REST_GET({ filter: filter, include: [ "idpmappings" ]});
if (!idp_data_arr.length)
    shared.internal_error("Unknown SSO code {0}".format(filter.code));
var idp_data = idp_data_arr[0];

var oCrypto = new ActiveXObject("SLNKDWF.Crypto");

var header =
{
  "typ":"JWT",
  "alg":"HS256"
};

var iat = Math.round(new Date().getTime() / 1000);
var exp = iat + idp_data.duration;

var claim =
{
    iat: iat,
    exp: exp,
    jti: "#" + username + "#" + String(new Date().getTime()),
    aud: idp_data.audience,
    iss: idp_data.issuer,
    username: username,
    ver: "1.0"
}

var jwt = jwt_encode(claim, idp_data.secret)

shared.simpel_page("Duration is set to {0} so expect expiration at {1}".format(idp_data.duration, toDateTimeString(new Date(exp * 1000)))
                   + "<br>Bearer token for <pre>{0}</pre><pre>{1}</pre>".format(JSON.stringify(claim, null, "  "), jwt));
ASPPAGE_END();
%>
