<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/system-index-block">[system-view:external]<xsl:comment>#START-ROOT-CODE
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
	string logInPage = "";
    string logInIncorrectPage = "";
	string url = "";
	
    protected void Page_Load(object sender, EventArgs e)
    {
     
 
/* Add [system-asset-page] tags around filename and give specific folder path. Do not add .aspx file extension after [/system-asset:page] */
        string configFileName = "[system-asset:page]/test/files/access-rights-config.xml[/system-asset:page]";
		
        string fullPathStart = Request.ServerVariables.Get("PATH_TRANSLATED");
        string currentPath = fullPathStart.Substring(0,fullPathStart.LastIndexOf('\\')+1);	                
        string extension = ".aspx";

/* Get the path the files and pages from the configuration file */
        XmlTextReader reader = new XmlTextReader(currentPath + configFileName);

        string permissionDeniedPage = "";
        string cmsAddress = "";
		
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    
                    if (reader.Name.Equals("logInPage"))
                    {
                        reader.ReadToDescendant("path");
                        logInPage = reader.ReadString();                        
                    }
                    else if (reader.Name.Equals("logInIncorrectPage"))
                    {
                        reader.ReadToDescendant("path");
                        logInIncorrectPage = reader.ReadString();                        
                    }
                    if (reader.Name.Equals("permissionDenied"))
                    {
                        reader.ReadToDescendant("path");
                        permissionDeniedPage = reader.ReadString();                        
                    }
                    if (reader.Name.Equals("cmsAddress"))
                        cmsAddress = reader.ReadString();
                    
                 break;
            }
        }
		logInPage = translateToVirtual(logInPage) + extension;
		logInIncorrectPage = translateToVirtual(logInIncorrectPage) + extension;
		permissionDeniedPage = translateToVirtual(permissionDeniedPage) + extension;
		
		string[] pageRights = new string[<xsl:value-of select="count(calling-page/system-page/dynamic-metadata[name='Audience Access Rights']/value)"/>];
		int i=0;
		<xsl:for-each select="calling-page/system-page/dynamic-metadata[name='Audience Access Rights']/value">
		pageRights[i] = "<xsl:value-of select="."/>";
		i++;
		</xsl:for-each>
        
		string username = "";
		string password = "";
		string givenPassword = "";
		bool gotIt = false;
		bool usernameExists = false;
		bool pageValidated = false;

/* if someone just logged in, check if the username and password are correct and add them to the session  */
		if (Request["_logInSubmit"]!=null)
		{
			username = Request["username"];
			password = Request["password"];
			Session["username"] = username;
			Session["password"] = password;
		}
		else
		{
			username = (string)Session["username"];
			password = (string)Session["password"];
		}
	
		if (Session["username"]==null)
			goToLogInPage();
		
/* 	validate the existing username and password */
		string rootAddress = cmsAddress;
		cmsAddress+="/ws/services/AssetOperationService?wsdl";
		url = cmsAddress;
	
		if (!validateUser(username, password))
			goToLogInPageIncorrect();
		
		Session["referer"]=null;
				
/* validate the page whether it can be viewed or not  */
		ArrayList groups = getUserGroups(username);		
        for(i = 0;i&lt;pageRights.Length;i++)
	        for(int j=0;j&lt;groups.Count;j++)
                if (pageRights[i].Equals(groups[j]))
                    pageValidated = true;
		if (!pageValidated)		
			Page.Server.Transfer(permissionDeniedPage);						
    }
	
	ArrayList getUserGroups(string usernameToGet)
    {        
        wsdl.AssetOperationHandlerService ser = new wsdl.AssetOperationHandlerService();
        ser.Url = url;

		wsdl.authentication auth = new wsdl.authentication();
        auth.username = "_system_all_groups";
        auth.password = "systemuser";

        wsdl.identifier id = new wsdl.identifier();
        id.id = usernameToGet;
        id.type = wsdl.entityTypeString.user;
        wsdl.readResult res = ser.read(auth, id);
        wsdl.user user = res.asset.user;
        string groupString = user.groups;
        ArrayList groups = new ArrayList();
        while(groupString.IndexOf(";")!=-1)
        {
            groups.Add(groupString.Substring(0,groupString.IndexOf(";")));
            groupString = groupString.Substring(groupString.IndexOf(";")+1);
        }
        groups.Add(groupString);
        return groups;
    }
	
	bool validateUser(string username, string password)
    {
        wsdl.AssetOperationHandlerService ser = new wsdl.AssetOperationHandlerService();
        ser.Url = url;

        wsdl.authentication auth = new wsdl.authentication();
        auth.username = username;
        auth.password = password;

        wsdl.identifier id = new wsdl.identifier();
        id.id = "_system_all_groups";
        id.type = wsdl.entityTypeString.user;
        wsdl.readResult res = ser.read(auth, id);
        return (res.message==null);
    }
	
	void goToLogInPageIncorrect()
	{
		Page.Server.Transfer(logInIncorrectPage);		
	}
	
	void goToLogInPage()
	{
		Session.Add("referer", "http://" + Request.ServerVariables.Get("HTTP_HOST") + Request.ServerVariables.Get("PATH_INFO"));
		Page.Server.Transfer(logInPage);		
	}
	
	string translateToVirtual(string path)
    {
        string applPath = Request.ServerVariables.Get("APPL_PHYSICAL_PATH");
        applPath = convertSlashes(applPath);
        string resultApplPath = convertSlashes(Request.PhysicalPath);
        int point = resultApplPath.IndexOf(Request.Path);
        string result = resultApplPath.Substring(0, point);
        string fullPath = applPath + path.Substring(1);
        return fullPath.Substring(result.Length);
    }

    string convertSlashes(string from)
    {
        string to = "";
        for (int i = 0; i &lt; from.Length; i++)
            if (from.Substring(i, 1).Equals("\\"))
                to += "/";
            else
                to += from.Substring(i, 1);
        return to;
    }
}

//#END-ROOT-CODE</xsl:comment>[/system-view:external]</xsl:template>
</xsl:stylesheet>