<html>
    <body>
    Waiting for responses from identity server and validate response and forward to requested URI.
        <%
(function () {
    include("jagg.jag");
    var site = require("/site/conf/site.json");
    var log = new Log();
    var samlResponse = request.getParameter("SAMLResponse");
    var sessionId = session.getId();
    var samlRequest = request.getParameter("SAMLRequest");
    // create a sso relying party js object
    var security = require("sso");
    var ssoRelyingParty = new security.SSORelyingParty(site.ssoConfiguration.issuer);
    var isLogoutResponse = false;
    var isLogoutRequest = false;

    // if saml response is not a log out response
    if (samlResponse != null) {
        isLogoutResponse = ssoRelyingParty.isLogoutResponse(samlResponse);
        if (!Boolean(isLogoutResponse)) {
            // relay state value should be a valid value, this value is mapped with request uri.
            var relayState = request.getParameter("RelayState");
            var requestedURI = ssoRelyingParty.getRelayStateProperty(relayState);
            if (requestedURI == null) {
                log.error("Relaystate value is invalid.");
                response.sendRedirect("../error.jag");
                return;
            }

            // validating the signature
            if(site.ssoConfiguration.responseSigningEnabled === 'true'){
		var fullUserName = ssoRelyingParty.getSAMLResponseNameId(samlResponse);			
			if(fullUserName != null && fullUserName.indexOf("@")!=-1){
				var domainName = fullUserName.split("@")[1];
				jagg.module("manager").loadTenantRegistry(domainName);	
		}
                var isSignatureValid = ssoRelyingParty.validateSignature(samlResponse);
                if (!Boolean(isSignatureValid)) {
                    log.error("SAML response signature is verification failed.");
                    response.sendRedirect("../error.jag");
                    return;
                }
            }
            ssoRelyingParty.setSessionAuthenticated(sessionId, samlResponse);
            session.put("showLogin", "false");
            var api = jagg.module("api");
            var isUserCreatePermitted = api.hasUserPermissions(ssoRelyingParty.getLoggedInUser(sessionId));
            //First check whether user is having sufficent permissions [create/publish]
            if (isUserCreatePermitted.permitted) {
                jagg.setUser({username: ssoRelyingParty.getLoggedInUser(sessionId), cookie: null});
                session.put("LOGGED_IN_USER", ssoRelyingParty.getLoggedInUser(sessionId));
            }
            var isCreatePermitted = api.hasCreatePermission();
            var isPublishPermitted = api.hasPublishPermission();
	    var hasTierPermission = api.hasManageTierPermission();
            jagg.setCreatePermitted(isCreatePermitted);
            jagg.setPublishPermitted(isPublishPermitted);
            jagg.setManageTierPermitted(hasTierPermission);
            response.sendRedirect(requestedURI);
        } else {
            // if the saml response is log out request from IDP, we log out from web app.
            ssoRelyingParty.invalidateSessionBySessionId(sessionId);
            session.invalidate();
            response.sendRedirect("../");
            return;
        }

    }

    // if saml request is a log out request, then invalidate session.
    if (samlRequest != null) {
        isLogoutRequest = ssoRelyingParty.isLogoutRequest(samlRequest);
        if (Boolean(isLogoutRequest)) {
            ssoRelyingParty.invalidateSessionBySAMLResponse(samlRequest);
            session.invalidate();
        }
    }

}());
%>
</body>
</html>
