<% jagg.template("sso/filter", function(inputs, outputs, jagg) { %>
<%
    var site = require("/site/conf/site.json");
    var security =require("sso");

	var ssoRelyingParty = new security.SSORelyingParty(site.ssoConfiguration.issuer);
	var sessionId = session.getId();
	var isAuthenticated = ssoRelyingParty.isSessionAuthenticated(sessionId);

    var encode = require('encode');
    encode = new encode.Encode();

	var requestURI;
	var requestedPage = encode.forUriComponent(request.getParameter("requestedPage"));
	if(requestedPage!=null && requestedPage != 'null'){
	requestURI = requestedPage;
	}else{
	  requestURI = request.getRequestURI();
	  if(request.getQueryString()!=null && request.getQueryString() != 'null'){
	    requestURI =requestURI+'?'+request.getQueryString();
	  }
	}
	var checkSSO = true;

	if(requestURI.indexOf("register.jag") != -1) {
		checkSSO = false;
	}else if(requestURI.indexOf("confirmemail.jag") != -1) {
		checkSSO = false;
	}
	if (checkSSO && !Boolean(isAuthenticated)) {

	    ssoRelyingParty.setProperty("identityProviderURL", site.ssoConfiguration.identityProviderURL);
	    ssoRelyingParty.setProperty("keyStorePassword", site.ssoConfiguration.keyStorePassword);
	    ssoRelyingParty.setProperty("identityAlias",site.ssoConfiguration.identityAlias);
	    ssoRelyingParty.setProperty("keyStoreName",site.ssoConfiguration.keyStoreName);

	    var samlAuthRequest = ssoRelyingParty.getSAMLAuthRequest();
	    var encodedRequest = ssoRelyingParty.encode(samlAuthRequest);
	    var relayState = ssoRelyingParty.getUUID();
	    ssoRelyingParty.setRelayStateProperty(relayState, requestURI);
	    var idpURL = ssoRelyingParty.getProperty("identityProviderURL");
%>
<div>

	        <p>You are now redirected to Identity. If the

	        redirection fails, please click the post button.</p>

	        <form method="post" action="<%=idpURL%>">

	            <p>

	                <input type="hidden" name="SAMLRequest"

	                value="<%= encodedRequest %>"/>

	                <input type="hidden" name="RelayState" value="<%= relayState %>"/>

	                <input type="hidden" name="SSOAuthSessionID" value="<%= sessionId %>"/>

	                <button type="submit">POST</button>

	            </p>

	        </form>

	    </div>

	    <script type = "text/javascript" >

	           document.forms[0].submit();

	    </script>

<%  }  %>
<% }); %>


