// Code for check user login,session
        public ServiceResponse CheckLogin(LoginModel login, bool isRegenerateSession)
        {
            ServiceResponse response = new ServiceResponse { IsSuccess = false };
            String hostName = (Dns.GetHostEntry(HttpContext.Current.Request.ServerVariables["remote_addr"]).HostName);
            try
            {

                if (login != null)
                {

                   // String hostName = Environment.MachineName;// Dns.GetHostName();

                    List<SearchValueData> searchListValueData = new List<SearchValueData>();
                    searchListValueData.Add(new SearchValueData { Name = "Email", Value = login.Email, IsEqual = true });
                    //searchListValueData.Add(new SearchValueData { Name = "HostName", Value = login.Email, IsEqual = true });

                    User user = GetEntity<User>(searchListValueData);

                    if (user != null && (Common.PasswordsMatch(login.Password, user.PasswordSalt, user.Password) ||
                                         isRegenerateSession) && hostName.ToLower() == user.HostName.ToLower())
                    {

                        DateTime startDate = new DateTime(2050, 12, 1);
                        if (startDate.AddDays(Constants.BlockedUserAfterDay).Date <= DateTime.Now.Date)
                        {
                            response.Message = Common.MessageWithTitle(Resource.LicenceExpiredTitle, Resource.LicenceExpiredMessage);
                            return response;
                        }

                        if (!user.IsActive)
                            response.Message = Common.MessageWithTitle(Resource.LoginFailed, Resource.InactiveAccount);
                        else
                        {
                            SessionValueData sessionValueData = new SessionValueData();
                            sessionValueData.UserID = user.UserID;
                            sessionValueData.Name = string.Format("{0} {1}", user.FirstName, user.LastName);
                            sessionValueData.FirstName = user.FirstName;
                            sessionValueData.Roles = GetEntityList<LU_Role>();
                            sessionValueData.SelectedRole = sessionValueData.Roles.Single(c => c.RoleID == user.RoleID);
                            response.Data = sessionValueData;
                            response.IsSuccess = true;
                            response.Message = Common.MessageWithTitle(Resource.LoginSuccess, Resource.LoginSuccessMessage);
                        }
                    }
                    else
                    {
                        response.Message = Common.MessageWithTitle(string.Format("{0} for {1}",Resource.LoginFailed,hostName), Resource.UsernamePasswordIncorrect);
                    }
                }
                else
                    response.Message = Common.MessageWithTitle(string.Format("{0} for {1}", Resource.LoginFailed, hostName), Resource.ExceptionMessage);
            }
            catch (Exception)
            {
                response.IsSuccess = false;
                response.Message = Common.MessageWithTitle(string.Format("{0} for {1}", Resource.LoginFailed, hostName), Resource.ExceptionMessage);
            }

            return response;
        }
        public ActionResult Index()
        {
            if (SessionHelper.UserID == 0)
            {
                //Constants.

                LoginModel login = new LoginModel();
                return View(login);
            }
            return RedirectToAction("index", "home");
        }
        public JsonResult Login(LoginModel login)
        {
            _securityDataProvider = new SecurityDataProvider();
            ServiceResponse response = _securityDataProvider.CheckLogin(login, false);
            if (response.IsSuccess)
            {
                if (login.IsRemember)
                {
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                                                                     login.Email,
                                                                                     DateTime.Now,
                                                                                     DateTime.Now.AddMinutes(
                                                                                         ConfigSettings
                                                                                             .RememberMeDuration),
                                                                                     true,
                                                                                     login.Email,
                                                                                     FormsAuthentication.FormsCookiePath);

                    // Encrypt the ticket.
                    string encTicket = FormsAuthentication.Encrypt(ticket);
                    // Create the cookie.
                    HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                                                           encTicket)
                    {
                        Expires = ticket.Expiration
                    };
                    Response.Cookies.Add(httpCookie);
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(login.Email, false);
                }
                SessionValueData sessionValue = (SessionValueData)response.Data;

                SessionHelper.UserID = sessionValue.UserID;
                SessionHelper.Name = sessionValue.Name;
                SessionHelper.FirstName = sessionValue.FirstName;
                SessionHelper.Roles = sessionValue.Roles;
                SessionHelper.SelectedRole = sessionValue.SelectedRole;
            }
            return Json(response);
        }
        //public string Module { get; set; }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var isAjaxRequest = filterContext.HttpContext.Request.IsAjaxRequest();

            if (CheckAllowedActions())
                return;

            var strPermissions = string.IsNullOrEmpty(Permissions) ? new string[] { } : Permissions.Split(',');
            if (SessionHelper.UserID > 0)
            {
                bool isAuthoized =
                   strPermissions.Any(strPermission => SessionHelper.SelectedRole.RoleName.Contains(strPermission));

                if (!isAuthoized)
                    isAuthoized = strPermissions.Contains(Constants.AnonymousLoginPermission);

                if (!isAuthoized && !isAjaxRequest)
                    filterContext.Result = new RedirectResult(_accessDeniedUrl);
                else if (!isAuthoized)
                    RedirectToAction(filterContext, _accessDeniedUrl);
            }

            else
            {
                if (filterContext.HttpContext.Request.CurrentExecutionFilePath != Constants.LoginUrl)
                {
                    bool removeFormsAuthenticationTicket = true;
                    bool isTimeOut = false;
                    if (filterContext.HttpContext.Request.IsAuthenticated)
                    {
                        HttpCookie decryptedCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(decryptedCookie.Value);
                        if (ticket != null)
                        {
                            var identity = new GenericIdentity(ticket.Name);
                            if (identity.IsAuthenticated)
                            {
                                SecurityDataProvider securityDataProvider = new SecurityDataProvider();
                                LoginModel loginModel = new LoginModel { Email = ticket.Name };
                                ServiceResponse response = new ServiceResponse();
                                response = securityDataProvider.CheckLogin(loginModel, true);
                                if (response.IsSuccess)
                                {
                                    SessionValueData sessionValue = (SessionValueData)response.Data;

                                    SessionHelper.UserID = sessionValue.UserID;
                                    SessionHelper.Name = sessionValue.Name;
                                    SessionHelper.FirstName = sessionValue.FirstName;
                                    SessionHelper.Roles = sessionValue.Roles;
                                    SessionHelper.SelectedRole = sessionValue.SelectedRole;
                                    removeFormsAuthenticationTicket = false;
                                }
                                else
                                    isTimeOut = true;
                            }
                            else
                                isTimeOut = true;
                        }
                        else
                            isTimeOut = true;
                    }

                    string szCookieHeader = HttpContext.Current.Request.Headers["Cookie"];
                    if (isTimeOut || (SessionHelper.UserID == 0 && HttpContext.Current.Session.IsNewSession) && (null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") > 0))
                        SessionHelper.IsTimeOutHappened = true;

                    if (removeFormsAuthenticationTicket)
                    {
                        FormsAuthentication.SignOut();
                        string returnUrl = "?returnUrl=" +
                                             (isAjaxRequest
                                                  ? (filterContext.HttpContext.Request.UrlReferrer != null
                                                         ? filterContext.HttpContext.Request.UrlReferrer.LocalPath
                                                         : "")
                                                  : filterContext.HttpContext.Request.CurrentExecutionFilePath +
                                                    (filterContext.HttpContext.Request.QueryString.HasKeys()
                                                         ? "?" + filterContext.HttpContext.Request.QueryString
                                                         : ""));

                        string[] param = Regex.Split(filterContext.HttpContext.Request.CurrentExecutionFilePath, filterContext.ActionDescriptor.ActionName);

                        string additionParam = param.Length > 1 ? param[1] : "";
                        if (filterContext.HttpContext.Request.RequestType.ToLower() == "post")
                            additionParam = "";

                        RedirectToAction(filterContext, string.Format("{0}?returnUrl={1}{2}", _loginUrl, NgReturnUrl, additionParam));

                    }
                }
            }
        }