Example #1
0
        public void RegisterLoginAttempt(string ip)
        {
            using (var context = new DataContext())
            {
                var search = (from s in context.LoginAttempt where s.IP == ip select s).FirstOrDefault();

                if (search != null)
                {
                    search.attemptAmmounts++;
                    context.SaveChanges();
                    return;
                }
                if (search == null)
                {
                    var attempt = new LoginAttempts
                    {
                        IP = ip,
                        attemptAmmounts = 1
                    };
                    context.LoginAttempt.Add(attempt);
                    context.SaveChanges();
                    return;
                }
            }
        }
Example #2
0
        public bool Delete(LoginAttempts item, Session session = null)
        {
            //LoggerFactory.CreateLog().Start();
            var committed = 0;

            try
            {
                //if (session != null)
                //    _repositoryLoginAttempts.UnitOfWork.SetConnectionDb(session.ConnectionString);

                if (item == null)
                {
                    throw new ArgumentNullException("item");
                }

                // Domain Services?
                //_repositoryLoginAttempts.Delete(Mapper.Map<Dominio.Entidades.LoginAttempts>(item));
                _repositoryLoginAttempts.Delete(item);
                committed = _unitOfWorkAsync.SaveChanges();
            }
            catch (Exception ex)
            {
                //LoggerFactory.CreateLog().Error(ex);
            }

            //LoggerFactory.CreateLog().Stop();
            return(committed > 0);
        }
Example #3
0
        public static string GetLoginAttempt(RestCommand command, int loginAttemptID)
        {
            LoginAttempt loginAttempt = LoginAttempts.GetLoginAttempt(command.LoginUser, loginAttemptID);

            if (loginAttempt.OrganizationID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            return(loginAttempt.GetXml("LoginAttempt", true));
        }
Example #4
0
 //Задаёт информацию для записи в бд
 public void SetLoginAttempt(string password)
 {
     using (DataBaseContext context = new DataBaseContext())
     {
         LoginAttempts attempt = new LoginAttempts();
         attempt.Passwords  = GetPasswordHash(password);
         attempt.MacAddress = GetMACAddress();
         context.attempts.Add(attempt);
         context.SaveChanges();
     }
 }
Example #5
0
        public static string GetLoginAttempts(RestCommand command)
        {
            LoginAttempts loginAttempts = new LoginAttempts(command.LoginUser);

            loginAttempts.LoadByOrganizationID(command.Organization.OrganizationID);

            if (command.Format == RestFormat.XML)
            {
                return(loginAttempts.GetXml("LoginAttempts", "LoginAttempt", true, command.Filters));
            }
            else
            {
                throw new RestException(HttpStatusCode.BadRequest, "Invalid data format");
            }
        }
Example #6
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void grdLockedUsers_RowCommand(object sender, GridViewCommandEventArgs e)
 {
     try
     {
         if (e.CommandName == "Locked")
         {
             ImageButton lnkBtn        = (ImageButton)e.CommandSource;
             GridViewRow grdCurrentRow = (GridViewRow)lnkBtn.Parent.Parent;
             GridView    myGrid        = (GridView)sender;
             int         ID            = Convert.ToInt32(myGrid.DataKeys[grdCurrentRow.RowIndex].Value.ToString());
             if (Convert.ToBoolean(e.CommandArgument))
             {
                 Int32.TryParse(Convert.ToString(Session["UserId"]), out userId);
                 User objUser = objUserBLL.GetUserDetailsById(userId);
                 objUserLogin.AccountLocked         = false;
                 objUserLogin.PasswordWrongAttempts = 0;
                 objUserLogin.UpdatedBy             = objUser.Id;
                 objUserLogin.UpdatedOn             = DateTime.Now;
                 objUserLogin.LastPasswordWrong     = null;
                 objUserLogin.UserId = ID;
                 objUserBLL.UpdatePasswordWorngAttemptDetails(objUserLogin);
             }
             else
             {
                 objLoginAttempts = objUserBLL.GetLoginAttempts();
                 if (objLoginAttempts != null && objLoginAttempts.Id > 0)
                 {
                     Int32.TryParse(Convert.ToString(Session["UserId"]), out userId);
                     User objUser = objUserBLL.GetUserDetailsById(userId);
                     objUserLogin.AccountLocked         = true;
                     objUserLogin.PasswordWrongAttempts = objLoginAttempts.LoginAttempt;
                     objUserLogin.UpdatedBy             = objUser.Id;
                     objUserLogin.UpdatedOn             = DateTime.Now;
                     objUserLogin.LastPasswordWrong     = DateTime.Now;
                     objUserLogin.UserId = ID;
                     objUserBLL.UpdatePasswordWorngAttemptDetails(objUserLogin);
                 }
             }
             BindUsers(txtUserName.Text.Trim());
         }
     }
     catch (Exception ex)
     {
         log.Error("gvLockedUsers_RowCommand \n Message: " + ex.Message + "\n Source: " + ex.Source + "\n StackTrace: " + ex.StackTrace);
         ExceptionLog.WriteLog(PageName + " @ gvLockedUsers_RowCommand ", ex.Message + " \n " + ex.StackTrace);
     }
 }
Example #7
0
        public static LoginAttempts getUserRequestInfo()
        {
            LoginAttempts la = new LoginAttempts()
            {
                UserIpAddress = System.Web.HttpContext.Current.Request.UserHostAddress,
                CreateDate    = DateTime.Now,
                IP4Address    = GetIPAddress(),
                MacAddress    = GetMACAddress(),
                GeoLocation   = null,
                HostName      = Environment.MachineName,
                UserAgent     = System.Web.HttpContext.Current.Request.UserAgent,
                CalledURL     = System.Web.HttpContext.Current.Request.Url.OriginalString,
                Browser       = System.Web.HttpContext.Current.Request.Browser.Browser + "/" + System.Web.HttpContext.Current.Request.Browser.Version,
                OpSystem      = GetUserPlatform(),
#pragma warning disable CS0618 // Type or member is obsolete
                BrowserJavascript = System.Web.HttpContext.Current.Request.Browser.JavaScript
#pragma warning restore CS0618 // Type or member is obsolete
            };

            return(la);
        }
Example #8
0
        public ActionResult Login(UserModel model)
        {
            using (SE2Entities context = new SE2Entities())
            {
                //check whether attempted login is valid
                bool IsValidUser = context.Users.Any(user => user.UserName.ToLower() == model.UserName.ToLower() &&
                                                     user.UserPassword == model.Password);
                LoginAttempts la = new LoginAttempts();

                if (IsValidUser)
                {
                    la.UserName   = model.UserName;
                    la.Successful = true;

                    //log this login attempt as successful
                    using (var client = new HttpClient())
                    {
                        client.BaseAddress = new Uri("https://dahkm.azurewebsites.net/api/loginattempts");
                        var postTask = client.PostAsJsonAsync <LoginAttempts>("loginattempts", la);
                        postTask.Wait();
                    }

                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    return(RedirectToAction("Index", "Home"));
                }
                la.UserName   = model.UserName;
                la.Successful = false;
                //log this login attempt as failed
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://dahkm.azurewebsites.net/api/loginattempts");
                    var postTask = client.PostAsJsonAsync <LoginAttempts>("loginattempts", la);
                    postTask.Wait();
                }
                ModelState.AddModelError("", "Invalid Username or Password");
                return(View());
            }
        }
 /// <summary>
 /// Page Load
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         if (!Page.IsPostBack)
         {
             objLoginAttempts      = objUserBLL.GetLoginAttempts();
             txtLoginAttempts.Text = "0";
             if (objLoginAttempts != null)
             {
                 if (objLoginAttempts.Id > 0)
                 {
                     txtLoginAttempts.Text = Convert.ToString(objLoginAttempts.LoginAttempt);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         log.Error("Page_Load \n Message: " + ex.Message + "\n Source: " + ex.Source + "\n StackTrace: " + ex.StackTrace);
         ExceptionLog.WriteLog(PageName + " @ Page_Load ", ex.Message + " \n " + ex.StackTrace);
     }
 }
Example #10
0
        public bool Update(LoginAttempts item, Session session = null)
        {
            //LoggerFactory.CreateLog().Start();
            var committed = 0;

            try
            {
                //if (session != null)
                //    _repositoryLoginAttempts.UnitOfWork.SetConnectionDb(session.ConnectionString);

                if (item == null)
                {
                    throw new ArgumentNullException("item");
                }

                var validator = EntityValidatorFactory.CreateValidator();
                if (validator.IsValid(item))
                {
                    // Domain Services?
                    //_repositoryLoginAttempts.Update(Mapper.Map<Dominio.Entidades.LoginAttempts>(item));
                    _repositoryLoginAttempts.Update(item);
                    committed = _unitOfWorkAsync.SaveChanges();
                }
                else
                {
                    throw new ApplicationValidationErrorsException(validator.GetInvalidMessages(item));
                }
            }
            catch (Exception ex)
            {
                //LoggerFactory.CreateLog().Error(ex);
            }

            //LoggerFactory.CreateLog().Stop();
            //_repositoryLoginAttempts.Update(entity);
            return(committed > 0);
        }
Example #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                // Active Directory selected
                if (rdolstAuthenticationType.SelectedValue == "0")
                {
                    Dns.GetHostName();
                    ExceptionLog.WriteLog(PageName + " @ HttpContext.Current.User.Identity.Name ", HttpContext.Current.User.Identity.Name + " \n ");
                    ExceptionLog.WriteLog(PageName + " @  Dns.GetHostName()", Dns.GetHostName() + " \n ");
                    ExceptionLog.WriteLog(PageName + " @  Dns.GetHostEntry(Request.ServerVariables[]).HostName", Dns.GetHostEntry(Dns.GetHostName()).HostName + " \n ");
                    ExceptionLog.WriteLog(PageName + " @  System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName", System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName + " \n ");
                    if (DoesUserExist(System.Security.Principal.WindowsIdentity.GetCurrent().Name))
                    {
                        objLoginHistory.UserId    = Convert.ToInt32(Session["UserId"]);
                        objLoginHistory.LoginTime = DateTime.Now;
                        objLoginHistory.CreatedBy = Convert.ToInt32(Session["UserId"]);
                        objLoginHistory.CreatedOn = DateTime.Now;
                        objLoginHistory.CreatedIp = CommonUtils.GetIPAddresses();
                        objLoginHistory.UserName  = Environment.UserName;
                        objUserBLL.LogLoginTime(objLoginHistory);

                        Session["UserName"] = Environment.UserName;
                        Response.Redirect("LoginLogoutHistory.aspx");
                    }
                    else
                    {
                        lblError.Text = "No account found with that username.";
                        lblError.Attributes.Add("display", "block");
                        txtUserName.Text = string.Empty;
                        txtPassword.Text = string.Empty;
                    }
                }
                else if (rdolstAuthenticationType.SelectedValue == "1")
                {
                    if (!string.IsNullOrEmpty(txtUserName.Text.Trim()) && !string.IsNullOrEmpty(txtPassword.Text.Trim()))
                    {
                        //SQL Server Validation
                        objUser = objUserBLL.GetUserDetailsByUserName(txtUserName.Text.Trim());
                        if (objUser != null)
                        {
                            if (objUser.Id != 0 && objUser.UserLogin.IsActive == true)
                            {
                                if (objUser.UserLogin.AccountLocked == true)
                                {
                                    lblError.Text = "The account is locked please contact administrator.";
                                    lblError.Attributes.Add("display", "block");
                                    txtUserName.Text = string.Empty;
                                    txtPassword.Text = string.Empty;
                                }
                                else
                                {
                                    if (objUser.UserLogin.Password.Equals(CommonUtils.Encrypt(txtPassword.Text.Trim())))
                                    {
                                        Session["RoleId"]         = Convert.ToString(objUser.UserLogin.RoleId);
                                        Session["UserId"]         = Convert.ToString(objUser.Id);
                                        objLoginHistory.UserId    = objUser.Id;
                                        objLoginHistory.LoginTime = DateTime.Now;
                                        objLoginHistory.CreatedBy = Convert.ToInt32(Session["UserId"]);
                                        objLoginHistory.CreatedOn = DateTime.Now;
                                        objLoginHistory.CreatedIp = CommonUtils.GetIPAddresses();
                                        objLoginHistory.UserName  = objUser.UserLogin.UserName;
                                        objUserBLL.LogLoginTime(objLoginHistory);
                                        objUserBLL.ClearLoginAttempts(objUser.Id);

                                        if (chkRememberPassword.Checked == true)
                                        {
                                            Response.Cookies["UserName"].Value   = txtUserName.Text;
                                            Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(10);
                                            Response.Cookies["Password"].Value   = txtPassword.Text;
                                            Response.Cookies["Password"].Expires = DateTime.Now.AddDays(10);
                                        }
                                        else
                                        {
                                            Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
                                            Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-1);
                                        }
                                        Response.Redirect("LoginLogoutHistory.aspx");
                                    }
                                    else
                                    {
                                        objLoginAttempts = objUserBLL.GetLoginAttempts();
                                        if (objLoginAttempts != null && objLoginAttempts.Id > 0)
                                        {
                                            if (objLoginAttempts.LoginAttempt > objUser.UserLogin.PasswordWrongAttempts)
                                            {
                                                if (objLoginAttempts.LoginAttempt == objUser.UserLogin.PasswordWrongAttempts + 1)
                                                {
                                                    objUserLogin.AccountLocked         = true;
                                                    objUserLogin.PasswordWrongAttempts = objUser.UserLogin.PasswordWrongAttempts + 1;
                                                    objUserLogin.UpdatedBy             = Convert.ToInt32(Session["UserId"]);
                                                    objUserLogin.UpdatedOn             = DateTime.Now;
                                                    objUserLogin.LastPasswordWrong     = DateTime.Now;
                                                    objUserLogin.UserId = objUser.Id;
                                                    objUserBLL.LockUserDetails(objUserLogin);
                                                }
                                                else
                                                {
                                                    objUserLogin.AccountLocked         = false;
                                                    objUserLogin.PasswordWrongAttempts = objUser.UserLogin.PasswordWrongAttempts + 1;
                                                    objUserLogin.UpdatedBy             = Convert.ToInt32(Session["UserId"]);
                                                    objUserLogin.UpdatedOn             = DateTime.Now;
                                                    objUserLogin.LastPasswordWrong     = DateTime.Now;
                                                    objUserLogin.UserId = objUser.Id;
                                                    objUserBLL.UpdatePasswordWorngAttemptDetails(objUserLogin);

                                                    lblError.Text = "Please enter correct User name and password Your access will be locked after " + (objLoginAttempts.LoginAttempt - (objUser.UserLogin.PasswordWrongAttempts + 1)) + " consecutive wrong attempts.";
                                                    lblError.Attributes.Add("display", "block");
                                                    txtUserName.Text = string.Empty;
                                                    txtPassword.Text = string.Empty;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            lblError.Text = "The username or password you entered is incorrect.";
                                            lblError.Attributes.Add("display", "block");
                                            txtUserName.Text = string.Empty;
                                            txtPassword.Text = string.Empty;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                lblError.Text = "No account found with that username.";
                                lblError.Attributes.Add("display", "block");
                                txtUserName.Text = string.Empty;
                                txtPassword.Text = string.Empty;
                            }
                        }
                        else
                        {
                            lblError.Text = "No account found with that username.";
                            lblError.Attributes.Add("display", "block");
                            txtUserName.Text = string.Empty;
                            txtPassword.Text = string.Empty;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("btnLogin_Click \n Message: " + ex.Message + "\n Source: " + ex.Source + "\n StackTrace: " + ex.StackTrace);
                ExceptionLog.WriteLog(PageName + " @ btnLogin_Click ", ex.Message + " \n " + ex.StackTrace);
            }
        }
        private static string AuthenticateUser(int userId, int organizationId, bool storeInfo, bool isBackDoor = false)
        {
            string    result    = string.Empty;
            LoginUser loginUser = new LoginUser(UserSession.ConnectionString, userId, organizationId, null);
            User      user      = Users.GetUser(loginUser, userId);
            string    deviceID  = GetDeviceID();

            TSAuthentication.Authenticate(user, isBackDoor, deviceID);
            if (!isBackDoor)
            {
                LoginAttempts.AddAttempt(loginUser, userId, true, HttpContext.Current.Request.UserHostAddress, HttpContext.Current.Request.Browser, HttpContext.Current.Request.UserAgent, deviceID);
                System.Web.HttpBrowserCapabilities browser = HttpContext.Current.Request.Browser;
                ActionLogs.AddActionLog(loginUser, ActionLogType.Insert, ReferenceType.Users, userId, "Logged in (" + browser.Browser + " " + browser.Version + ")");

                ConfirmBaseData(loginUser);

                if (storeInfo)
                {
                    HttpContext.Current.Response.Cookies["rm"]["a"]    = user.Email;
                    HttpContext.Current.Response.Cookies["rm"]["b"]    = user.OrganizationID.ToString();
                    HttpContext.Current.Response.Cookies["rm"].Expires = DateTime.UtcNow.AddDays(7);
                }
                else
                {
                    HttpContext.Current.Response.Cookies["rm"].Value = "";
                }
            }

            if (user.IsPasswordExpired && !isBackDoor)
            {
                result = string.Format("vcr/1/LoginNewPassword.html?UserID={0}&Token={1}", user.UserID, user.CryptedPassword);
            }
            else
            {
                string rawQueryString = null;

                try
                {
                    rawQueryString = HttpContext.Current.Request.UrlReferrer.Query;
                }
                catch (Exception)
                {
                    //vv
                }

                if (!string.IsNullOrEmpty(rawQueryString))
                {
                    string urlRedirect = GetQueryStringValue(rawQueryString, "ReturnUrl");

                    if (!string.IsNullOrEmpty(urlRedirect) && urlRedirect.Trim().Length > 0)
                    {
                        result = urlRedirect;
                    }
                    else
                    {
                        result = ".";
                    }
                }
                else
                {
                    result = ".";
                }
            }

            return(result);
        }
        private static SignInResult IsValid(LoginUser loginUser, string email, string password, int organizationId, ref User user, ref Organization organization)
        {
            SignInResult validation = new SignInResult();

            organization = Organizations.GetOrganization(loginUser, organizationId);
            bool isNewSignUp = DateTime.UtcNow.Subtract(organization.DateCreatedUtc).TotalMinutes < 10;


            if (!organization.IsActive)
            {
                if (string.IsNullOrEmpty(organization.InActiveReason))
                {
                    validation.Error  = "Your account is no longer active.  Please contact TeamSupport.com.";
                    validation.Result = LoginResult.Fail;
                }
                else
                {
                    validation.Error  = "Your company account is no longer active.<br />" + organization.InActiveReason;
                    validation.Result = LoginResult.Fail;
                }
                TSEventLog.WriteEvent(TSEventLogEventType.FailedLoginAttempt, HttpContext.Current.Request, null, organization, new string[] { "Email: " + email });
                return(validation);
            }


            Users users = new Users(loginUser);

            users.LoadByEmail(1, email);

            if (users.Count == 1)
            {
                user = users[0];
            }
            else
            {
                foreach (User u in users)
                {
                    if (u.OrganizationID == organizationId)
                    {
                        user = u;
                        break;
                    }
                }
            }

            int attempts = LoginAttempts.GetAttemptCount(loginUser, user.UserID, 15);

            validation.LoginFailedAttempts = attempts;

            if (user != null && attempts <= MAXLOGINATTEMPTS)
            {
                validation.UserId         = user.UserID;
                validation.OrganizationId = user.OrganizationID;

                if (IsSupportImpersonation(password))
                {
                    _skipVerification = true;
                    validation.Result = LoginResult.Success;
                    validation.Error  = string.Empty;
                    //vv Log this information!
                }
                else
                {
                    if (user.CryptedPassword != EncryptPassword(password) && user.CryptedPassword != password && !isNewSignUp)
                    {
                        validation.Error  = "Invalid email or password.";
                        validation.Result = LoginResult.Fail;
                    }

                    if (!organization.IsActive)
                    {
                        if (string.IsNullOrEmpty(organization.InActiveReason))
                        {
                            validation.Error  = "Your account is no longer active.  Please contact TeamSupport.com.";
                            validation.Result = LoginResult.Fail;
                        }
                        else
                        {
                            validation.Error  = "Your company account is no longer active.<br />" + organization.InActiveReason;
                            validation.Result = LoginResult.Fail;
                        }
                    }

                    if (!user.IsActive)
                    {
                        validation.Error  = "Your account is no longer active.&nbsp&nbsp Please contact your administrator.";
                        validation.Result = LoginResult.Fail;
                    }

                    DateTime passwordCreatedDate = user.PasswordCreatedUtc != null ? (DateTime)user.PasswordCreatedUtc : user.DateCreated;

                    if (validation.Result != LoginResult.Fail && user.IsPasswordExpired || (organization.DaysBeforePasswordExpire > 0 && DateTime.UtcNow > passwordCreatedDate.AddDays(organization.DaysBeforePasswordExpire)))
                    {
                        validation.Error  = "Your password has expired.";
                        validation.Result = LoginResult.PasswordExpired;
                    }
                }
            }
            else if (user == null)
            {
                validation.Error  = "Invalid email or password.";
                validation.Result = LoginResult.Fail;
            }
            else
            {
                validation.Error  = string.Format("Your account is temporarily locked, because of too many failed login attempts.{0}Try again in 15 minutes or use the forgot password link above to reset your password. ", Environment.NewLine);
                validation.Result = LoginResult.Fail;
                if (attempts == MAXLOGINATTEMPTS + 1)
                {
                    TSEventLog.WriteEvent(TSEventLogEventType.AccountLocked, HttpContext.Current.Request, user, organization);
                    EmailPosts.SendTooManyAttempts(loginUser, user.UserID);
                }
            }

            if (validation.Result != LoginResult.Success && validation.Result != LoginResult.Unknown && !string.IsNullOrEmpty(validation.Error))
            {
                TSEventLog.WriteEvent(TSEventLogEventType.FailedLoginAttempt, HttpContext.Current.Request, user, organization, new string[] { "Attempted Email: " + email });
                LoginAttempts.AddAttempt(loginUser, user.UserID, false, HttpContext.Current.Request.UserHostAddress, HttpContext.Current.Request.Browser, HttpContext.Current.Request.UserAgent, GetDeviceID());
            }
            else
            {
                TSEventLog.WriteEvent(TSEventLogEventType.LoginSuccess, HttpContext.Current.Request, user, organization);
                validation.Result = LoginResult.Success;
            }

            return(validation);
        }
Example #14
0
 public LoginAttemptsCrudViewModel()
 {
     LoginAttempts = new LoginAttempts();
 }
Example #15
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!Request.IsAuthenticated)
            {
                // filterContext.Result = new RedirectResult("~/Account/Login");
                var values = new RouteValueDictionary(new
                {
                    action     = "Login",
                    controller = "Account",
                    returnUrl  = HttpContext.Request.Url.PathAndQuery
                });
                var result = new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Bad Request");
                if (Request.IsAjaxRequest())
                {
                    filterContext.Result = result;
                }
                else
                {
                    filterContext.Result = new RedirectToRouteResult(values);
                }
                return;
            }
            if (Request.UrlReferrer != null && Request.UrlReferrer.AbsolutePath.EndsWith("/Account/Login"))
            {
                ApplicationDbContext usercontext = new ApplicationDbContext();
                var           userid             = usercontext.Users.FirstOrDefault(p => p.UserName == User.Name).Id;
                LoginAttempts history            = new LoginAttempts();
                history.UserId        = userid;
                history.Date          = DateTime.UtcNow;
                history.IsSuccessfull = true;
                history.IPAddress     = Request.UserHostAddress;
                usercontext.LoginAttempts.Add(history);
                usercontext.SaveChanges();

                string applySecurityPolicy = db.AppSettings.Where(p => p.Key == "ApplySecurityPolicy").FirstOrDefault().Value;
                int    duration            = Convert.ToInt32(db.AppSettings.Where(p => p.Key == "PasswordExpirationInDays").FirstOrDefault().Value);
                if ((applySecurityPolicy.ToLower() == "yes") && !(((CustomPrincipal)User).Identity is System.Security.Principal.WindowsIdentity))
                {
                    if (IsPasswordExpired(duration, userid))
                    {
                        filterContext.Result = new RedirectResult("~/Account/Manage");
                    }
                }
            }
            if (Request.Url.PathAndQuery.ToUpper().Contains("/HOME?ISTHIRDPARTY=TRUE") || (Request.UrlReferrer != null && Request.UrlReferrer.AbsolutePath.EndsWith("/Account/Login") && !Request.Url.PathAndQuery.Contains("/Home?RegistrationEntity")))
            {
                ApplicationDbContext usercontext = new ApplicationDbContext();
                var userid = usercontext.Users.FirstOrDefault(p => p.UserName == User.Name).Id;
                if (IsAutoRegistration(userid))
                {
                    filterContext.Result = Redirect(Url.Action("Index", "Home", new { RegistrationEntity = string.Join(",", User.permissions.Where(p => p.SelfRegistration.Value).Select(p => p.EntityName)), TokenId = userid }));
                }
                if (Request.Url.PathAndQuery.ToUpper().Contains("/BULKUPDATE"))
                {
                    filterContext.Result = Redirect(Url.Action("Index", "Home"));
                }
            }

            objFavorite = db.FavoriteItems.Where(p => p.LastUpdatedByUser == User.Name && HttpContext.Request.Url.PathAndQuery.EndsWith(p.LinkAddress)).FirstOrDefault();
            string entity = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

            if (User.CanView(entity))
            {
                base.OnActionExecuting(filterContext);
            }
            else
            {
                filterContext.Result = new RedirectResult("~/Error");
            }
            base.OnActionExecuting(filterContext);
        }
Example #16
0
        public void DoLogLoginUser(LoginAttempts log)
        {
            LoginAttemptsRepository lRepo = new LoginAttemptsRepository();

            lRepo.Insert(log);
        }
Example #17
0
 public void ApplyChanges(LoginAttempts entity)
 {
     _repositoryLoginAttempts.ApplyChanges(entity);
 }
Example #18
0
 /// <summary>
 /// Method for updating login attempts
 /// </summary>
 /// <param name="objLoginAttempts"></param>
 /// <returns></returns>
 public bool UpdateLoginAttempts(LoginAttempts objLoginAttempts)
 {
     return(objUserDAL.UpdateLoginAttempts(objLoginAttempts));
 }