using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices.AccountManagement;

public partial class landing_wauth_auth : System.Web.UI.Page
{
    public string username = string.Empty;
    public string hash = string.Empty; 

    System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
    protected void Page_Load(object sender, EventArgs e)
    {
        string mode = (Request.Form["mode"] != null) ? Request.Form["mode"] : "GET";

        if (mode == "GET")
        {
            try
            {
                username = HttpContext.Current.User.Identity.Name;
                username = username.Replace("\\", "/");
                hash = DAL.getPasswordHash(username);
            }
            catch (Exception ex)
            {
                username = string.Empty;
                hash = string.Empty;
            }
            Response.Write(jss.Serialize(new { username = username, hash = hash }));
        }
        else if (mode == "TRYLOGIN")
        {
            try
            {
                string paramUser = Request.Form["username"];
                string paramPassword = Request.Form["password"];

                username = paramUser; 
                string[] splitUser = paramUser.Split('\\');
                paramUser = (splitUser.Length > 1) ? splitUser[1] : paramUser;

                bool valid = false;
                try
                {
                    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
                    {
                        valid = context.ValidateCredentials(paramUser, paramPassword);
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        using (PrincipalContext context = new PrincipalContext(ContextType.Machine))
                        {
                            valid = context.ValidateCredentials(paramUser, paramPassword);
                        }
                    }
                    catch (Exception ex1)
                    {
                        valid = false; 
                    }
                }

                if (valid)
                {
                    hash = DAL.getPasswordHash(username.Replace("\\", "/")); 
                }
            }
            catch (Exception ex)
            {
                username = string.Empty;
                hash = string.Empty;
            }
            Response.Write(jss.Serialize(new { username = username, hash = hash }));
        }
    }
}
