Пример #1
1
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {

            Session["Notification"] = "";
            if (ModelState.IsValid)
            {
                KIREIP.Core.Manager.UserManager CM = new KIREIP.Core.Manager.UserManager();
                KIREIP.Core.DAL.Login usr = CM.LoginUser(model.UserName, model.Password);
                if (usr != null)
                {
                    FormsAuthentication.Initialize();
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, usr.UserName.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe, FormsAuthentication.FormsCookiePath);
                    string hash = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
                    if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
                    Response.Cookies.Add(cookie);
                    if ((!String.IsNullOrEmpty(returnUrl)) && returnUrl.Length > 1)
                        return Redirect(returnUrl);
                    else
                    {
                        return RedirectToAction("Index", "Message");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Incorrect user name or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #2
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (System.Web.Security.FormsAuthentication.Authenticate(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #3
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    //Membership.DeleteUser(model.UserName, true);
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "CheatNotes");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Неправильный пароль или имя пользователя.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #4
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    UserSession = new UserSession(model.UserName, model.Password);
                    UserSession.Authenticate();
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    return RedirectToAction("Index", "Home");
                }
                catch (AuthenticationException)
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }

            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #5
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "El nombre de usuario o la contraseña especificados son incorrectos.");
                }
            }

            // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario
            return View(model);
        }
Пример #6
0
        public virtual ActionResult LogIn(LogOnModel model)
        {
            model.NavigationLocation = new string[] { "Home", "Login" };
            model.RememberMe = true;

            return View(model);
        }
Пример #7
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                UsuarioModel user = null;
                if (new Usuario().AutenticaUsuario(model.UserName, model.Password, ref user))
                {
                    Session["login"] = user;
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Senha e usuário incorretos ou você não possui permissão para acessar o sistema.");
                }
            }

            return View(model);
        }
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #9
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {            
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
 public FubuContinuation LogOnCommand(LogOnModel input)
 {
     if (_membershipService.UserExists(input.UserName, input.Password)) {
         _authenticationContext.ThisUserHasBeenAuthenticated(input.UserName, input.RememberMe);
         return FubuContinuation.RedirectTo<IndexInput>();
     }
     return FubuContinuation.TransferTo<LogOnInput>();
 }
Пример #11
0
        public ActionResult LogOn()
        {
            var viewModel = new LogOnModel
            {
                PageTitle = "Авторизация"
            };

            return View(viewModel);
        }
Пример #12
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            int logOnAttempt = Convert.ToInt32(Session["LogOnAttempt"]);

            const int logOnAttemptLock = 6;
            const int logOnAttemptCaptcha = 3;

            ViewBag.LOG_ON_ATTEMPT_LOCK = logOnAttemptLock;
            ViewBag.LOG_ON_ATTEMPT_CAPTCHA = logOnAttemptCaptcha;

            if (ModelState.IsValid)
            {
                if ((logOnAttempt >= logOnAttemptCaptcha) &&
                    (Session["Captcha"] == null || Session["Captcha"].ToString() != model.Captcha))
                {
                    ModelState.AddModelError("Captcha", @"Неверно указан результат вычисления");
                }

                if (ModelState.IsValid)
                {
                    if (_securityUserService.ValidateUser(model.Login, model.Password))
                    {
                        FormsAuthentication.SetAuthCookie(model.Login, model.RememberMe);

                        Session["LogOnAttempt"] = 0;

                        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                            && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                        {
                            return Redirect(returnUrl);
                        }
                        return RedirectToAction("Index", "Home");
                    }
                    ModelState.AddModelError("", @"Введено неправильное имя пользователя или пароль");
                }
            }
            else
            {
                ModelState.AddModelError("", @"Некорректный логин или пароль");
            }

            if (logOnAttempt >= logOnAttemptLock)
            {
                ModelState.AddModelError("",
                    String.Format(
                        "После {0} неудачных попыток войти, браузер должен быть закрыт. Пожалуйста, обратись к администратору за детальной информации о вашем входе.",
                        logOnAttemptLock));
            }


            Session["LogOnAttempt"] = logOnAttempt + 1;
            model.Captcha = "";
            ViewBag.ReturnUrl = returnUrl;

            return View(model);
        }
Пример #13
0
        public static bool ValidateLogOn(LogOnModel model)
        {
            if (Membership.ValidateUser(model.UserName, model.Password) && !profileDB.Users.Find(model.UserName).blocked)
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                printLog("User '" + model.UserName + "' logged in");
                return true;
            }

            return false;
        }
Пример #14
0
 public ActionResult AjaxLogin(LogOnModel model)
 {
     if (ModelState.IsValid)
     {
         if (LoginValidate(model))
         {
             return Content("succeed");
         }
         ModelState.AddModelError("", "用户名或密码不正确。");
     }
     return View(model);
 }
Пример #15
0
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            //Provided for simplicity with the sample
            var vm = new LogOnModel
                         {
                             UserName = "******", 
                             Password = "******", 
                             RememberMe = false
                         };

            return View(vm);
        }
Пример #16
0
        public ActionResult Index(LogOnModel model)
        {
            bool authSuc = AccountController.ValidateLogOn(model);
            if (!authSuc)
            {
                ModelState.AddModelError("", WJP_Resources.Lang.IncorrectLoginOrPass);
            }

            ViewBag.LoggedIn = authSuc;
            ViewBag.UserName = model.UserName;
            return View(model);
        }
Пример #17
0
        public ActionResult LogOn(LogOnModel viewModel)
        {
            if (!ModelState.IsValid) return View(viewModel);

            if (Membership.ValidateUser(viewModel.UserName, viewModel.Password))
            {
                FormsAuthentication.SetAuthCookie(viewModel.UserName, viewModel.RememberMe);
                return RedirectToAction("Index", "Home");
            }

            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(viewModel);
        }
Пример #18
0
 public static bool Auth(LogOnModel model)
 {
     MongoWorker _mongo = new MongoWorker();
     var doc = _mongo.GetDocument<User>(MongoCollections.UserCollection, Query.EQ("Email", model.Email));
     if (doc != null)
     {
         string hash = Encoding.UTF8.GetString(SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(doc.ID.ToString() + model.Password)));
         if (hash == doc.Password)
         {
             return true;
         }
     }
     return false;
 }
        public JsonResult LogOn(LogOnModel model)
        {
            var user = storeDB.Users.AsEnumerable()
                            .Where(w => w.UserName == model.UserName && w.Password == model.Password)
                            .Select(s => s.User_id).SingleOrDefault();
            if (user == 0)
            {
                Session["userId"] = null;
            }
            else
            {
                Session["userId"] = user;
            }

            return Json(user);
        }
Пример #20
0
        public JsonResult JsonLogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    return Json(new { success = true, redirect = returnUrl });
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed
            return Json(new { errors = GetErrorsFromModelState() });
        }
        //
        // GET: /Account/LogOn
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            ProjectPlannerContext ctx = new ProjectPlannerContext();

            if (ModelState.IsValid)
            {
                string passwordHash = model.Password.GetHash();
                if(ctx.Users.SingleOrDefault(p => (p.Username.Equals(model.Username) && p.PasswordHash.Equals(passwordHash))) != null)
                {
                    FormsAuthentication.SetAuthCookie(model.Username, model.RemindMe);

                    return Redirect(returnUrl);
                }

                ViewBag.Error = "Couldn't find the user or password did not match!";
            }

            return View();
        }
Пример #22
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid && model.IsValid())
            {
                if (_membershipTasks.ValidateUser(model.UserName, model.Password))
                {
                    _authTasks.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");
            }

            return View(model);
        }
Пример #23
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            if (!Membership.ValidateUser(model.UserName, model.Password))
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                return View(model);
            }

            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (!Url.IsLocalUrl(returnUrl) || returnUrl.Length <= 1 || !returnUrl.StartsWith("/") || returnUrl.StartsWith("//") || returnUrl.StartsWith("/\\"))
            {
                return RedirectToAction("Index", "Home");
            }

            return Redirect(returnUrl);
        }
        public void TestLogOnPostRedirectsWhenSuccessful1()
        {
            #region Arrange
            var model = new LogOnModel {UserName = "******", Password = "******"};
            MembershipService.Expect(a => a.ValidateUser(Arg<string>.Is.Anything, Arg<string>.Is.Anything))
                .Return(true).Repeat.Any();
            FormService.Expect(a => a.SignIn("*****@*****.**", false));
            #endregion Arrange

            #region Act
            var result = Controller.LogOn(model, "")
                .AssertActionRedirect()
                .ToAction<HomeController>(a => a.Index());
            #endregion Act

            #region Assert
            Assert.IsNotNull(result);
            MembershipService.AssertWasCalled(a => a.ValidateUser("*****@*****.**".ToLower(), "Password"));
            FormService.AssertWasCalled(a => a.SignIn("*****@*****.**", false));
            #endregion Assert
        }
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid) {
                if (Membership.ValidateUser(model.UserName, model.Password)) {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) {
                        return Redirect(returnUrl);
                    }
                    else {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else {
                    ModelState.AddModelError("", "제공한 사용자 이름 또는 암호가 잘못되었습니다.");
                }
            }

            // 이 경우 오류가 발생한 것이므로 폼을 다시 표시하십시오.
            return View(model);
        }
Пример #26
0
 public ActionResult Login(LogOnModel model, string returnUrl)
 {
     if (ModelState.IsValid)
     {
         if (Membership.ValidateUser(model.UserName, model.Password))
         {
             FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
             if (Url.IsLocalUrl(returnUrl))
             {
                 return Redirect(returnUrl);
             }
             else
             {
                 return RedirectToAction("Index", "catalog");
             }
         }
         else
         {
             ModelState.AddModelError("", "Неправильный пароль или логин");
         }
     }
     return View(model);
 }
Пример #27
0
        public ActionResult Index(LogOnModel model, string returnUrl, string password)
        {
            //if (ModelState.IsValid)
            //{
            //    if (Membership.ValidateUser(model.UserName, model.Password))
            //    {
            //        FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            //        if (Url.IsLocalUrl(returnUrl))
            //        {
            //            return Redirect(returnUrl);
            //        }
            //        else
            //        {
            //            return RedirectToAction("Index", "Home");
            //        }
            //    }
            //    else
            //    {
            //        ModelState.AddModelError("", "Неправильный пароль или логин");
            //    }
            //}

            if (ModelState.IsValid)
            {
                // поиск пользователя в бд
                Admin    admin    = null;
                Director director = null;
                Teacher  teacher  = null;
                Parent   parent   = null;
                Pupil    pupil    = null;
                using (DnevnikEntities db = new DnevnikEntities())
                {
                    admin    = db.Admins.FirstOrDefault(a => a.Email == model.UserName || a.UserName == model.UserName);
                    director = db.Directors.FirstOrDefault(d => d.Email == model.UserName || d.UserName == model.UserName);
                    teacher  = db.Teachers.FirstOrDefault(t => t.Email == model.UserName || t.UserName == model.UserName);
                    parent   = db.Parents.FirstOrDefault(p => p.Email == model.UserName || p.UserName == model.UserName);
                    pupil    = db.Pupils.FirstOrDefault(p => p.Username == model.UserName);
                }
                if (admin != null && Crypto.VerifyHashedPassword(admin.Password, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, true);
                    return(RedirectToAction("Index", "Admin"));
                }
                else
                {
                    ModelState.AddModelError("", "Пользователя с таким логином и паролем нет");
                }

                if (director != null && Crypto.VerifyHashedPassword(director.Password, model.Password))
                {
                    if (Crypto.VerifyHashedPassword(director.Password, "1111"))
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, true);
                        return(RedirectToAction("EditFirstTime", "ForDirector", new { id = director.Id }));
                    }
                    else
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, true);
                        return(RedirectToAction("Index", "ForDirector", new { id = director.Id }));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Пользователя с таким логином и паролем нет");
                }

                if (teacher != null && Crypto.VerifyHashedPassword(teacher.Password, model.Password))
                {
                    if (Crypto.VerifyHashedPassword(teacher.Password, "1111"))
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, true);
                        return(RedirectToAction("EditFirstTime", "Teacher", new { id = teacher.Id }));
                    }
                    else
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, true);
                        return(RedirectToAction("Index", "Teacher", new { id = teacher.Id }));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Пользователя с таким логином и паролем нет");
                }

                if (parent != null && Crypto.VerifyHashedPassword(parent.Password, model.Password))
                {
                    if (Crypto.VerifyHashedPassword(parent.Password, "1111"))
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, true);
                        return(RedirectToAction("EditFirstTime", "ForParent", new { id = parent.Id }));
                    }
                    else
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, true);
                        return(RedirectToAction("Index", "ForParent", new { id = parent.Id }));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Пользователя с таким логином и паролем нет");
                }
            }


            return(View(model));
        }
Пример #28
0
        public void AccountController_LogOn_Post_ReturnsViewIfModelStateIsInvalid()
        {
            // Arrange
            AccountController controller = GetAccountController();
            LogOnModel model = new LogOnModel()
            {
                UserName = "******",
                Password = "******",
                RememberMe = false
            };
            controller.ModelState.AddModelError("", "Dummy error message.");

            // Act
            ActionResult result = controller.LogOn(model, null);

            // Assert
            Assert.IsInstanceOfType(result, typeof(ViewResult));
            ViewResult viewResult = (ViewResult)result;
            Assert.AreEqual(model, viewResult.ViewData.Model);
        }
Пример #29
0
 //
 // GET: /Account/LogOn
 public ActionResult LogOn()
 {
     LogOnModel model = new LogOnModel();
     if (Request.Cookies["Name"] != null)
         model.UserName = Request.Cookies["Name"].Value;
     if (Request.Cookies["Password"] != null)
         model.Password = Request.Cookies["Password"].Value;
     if (Request.Cookies["Name"] != null && Request.Cookies["Password"] != null)
         model.RememberMe = true;
     return View(model);
 }
Пример #30
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            string result = "";


            if (string.IsNullOrEmpty(model.UserName))
            {
                result             = ("请输入用户名!");
                ViewData["Result"] = result;
                return(View());
            }

            if (string.IsNullOrEmpty(model.Password))
            {
                result             = ("请输入密码!");
                ViewData["Result"] = result;
                return(View());
            }

            if (model.ValidCode != (Session["ValidCode"] ?? string.Empty).ToString())
            {
                result             = ("验证码错误!");
                ViewData["Result"] = result;
                return(View());
            }

            var userInfoService =
                WebCrm.Framework.DependencyResolver.Resolver <IUserInfoService>();
            var userInfo = userInfoService.FindByUserName(model.UserName.ToUpper());

            if (userInfo == null)
            {
                result = "用户不存在!";
            }
            else
            {
                if (userInfo.UseFlag == 0)
                {
                    result = "用户已被停用!";
                }
                else
                {
                    if (userInfo.OperatorPass != model.Password.Md5())
                    {
                        result = "密码错误!";
                    }
                    else
                    {
                        userInfo.LastLoginTime = DateTime.Now;

                        userInfoService.Update(userInfo);
                        Session.Clear();
                        FormsAuthentication.SetAuthCookie(
                            string.Format("{0},{1}", userInfo.OperatorCode, userInfo.Id), false);

                        return(RedirectToAction("EvernoteList"));
                    }
                }
            }

            ViewData["Result"] = result;
            return(View());
        }
Пример #31
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                int icount = Uow.aspnet_Users.GetAll().Count();
                if (icount == 0)
                {
                    MembershipCreateStatus createStatus = MembershipService.CreateUser("admin", "123456", "系统管理员", Guid.Empty);
                    var user = Uow.aspnet_Users.GetAll().Where(w => w.UserName == "admin").FirstOrDefault();
                    DXInfo.Models.VouchAuthority va = Uow.VouchAuthority.GetById(g => g.UserId == user.UserId);
                    if (va == null)
                    {
                        va               = new VouchAuthority();
                        va.UserId        = user.UserId;
                        va.AuthorityType = 0;
                        Uow.VouchAuthority.Add(va);
                        Uow.Commit();
                    }
                    model.UserName = "******";
                    model.Password = "******";
                }
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    if (!string.IsNullOrEmpty(model.HardwareID))
                    {
                        //using (DXInfo.Models.FairiesMemberManage context = new DXInfo.Models.FairiesMemberManage())
                        //{
                        var key = Uow.ekey.GetAll().Where(w => w.HardwareID == model.HardwareID).FirstOrDefault();
                        var us  = Uow.aspnet_Users.GetAll().Where(w => w.UserName == model.UserName).FirstOrDefault();
                        if (key == null)
                        {
                            DXInfo.Models.ekey tk = new ekey();
                            tk.HardwareID = model.HardwareID;
                            tk.CardNo     = model.CardNo;
                            tk.CreateDate = DateTime.Now;
                            tk.IsUse      = true;
                            tk.UserId     = us != null ? us.UserId : Guid.Empty;
                            Uow.ekey.Add(tk);
                            Uow.Commit();
                        }
                        else
                        {
                            if (!key.IsUse)
                            {
                                ModelState.AddModelError("", "ekey失效。");
                                return(View(model));
                            }
                        }
                        //}
                    }
                    //if (System.Configuration.ConfigurationManager.AppSettings.AllKeys.Contains("AMSApp"))
                    //{
                    //    AMSLog clog = new AMSLog();
                    //    clog.WriteLine("LoginID:" + model.UserName + ";    Mac:" + model.MacAddress + ";");
                    //    Hashtable htapp = (Hashtable)this.HttpContext.Application["appconf"];
                    //    string strcons = (string)htapp["cons"];
                    //    DataTable dtMac = (DataTable)this.HttpContext.Application["MAC"];

                    //    if (dtMac == null || dtMac.Rows.Count == 0)
                    //    {
                    //        ModelState.AddModelError("", "请添加MAC地址。");
                    //        return View(model);
                    //    }
                    //    bool okflag = false;
                    //    if (model.UserName == "admin")
                    //    {
                    //        okflag = true;
                    //    }
                    //    else
                    //    {
                    //        for (int i = 0; i < dtMac.Rows.Count; i++)
                    //        {
                    //            if (dtMac.Rows[i][0].ToString() == model.MacAddress)
                    //            {
                    //                okflag = true;
                    //                break;
                    //            }
                    //        }
                    //    }
                    //    okflag = true;
                    //    if (!okflag)
                    //    {
                    //        ModelState.AddModelError("", "无访问权限" + model.MacAddress);
                    //        return View(model);
                    //    }
                    //    Manager m1 = new Manager(strcons);
                    //    CMSMStruct.LoginStruct ls1 = new CMSMStruct.LoginStruct();

                    //    CMSMStruct.OperStruct OperNew = new CMSMStruct.OperStruct();
                    //    OperNew.strMacAddress = model.MacAddress;
                    //    //using (AMSCM.Models.AMSCM context = new AMSCM.Models.AMSCM())
                    //    //{

                    //    var tbLogin = AmscmUow.tbLogin.GetById(g=>g.vcLoginID==model.UserName);
                    //    //var tbLogin = AmscmUow.tbLogin.GetAll().Where(w => w.vcLoginID == model.UserName).FirstOrDefault();

                    //    if (tbLogin == null)
                    //    {
                    //        ModelState.AddModelError("", "未配置AMSCM连接串");
                    //        return View(model);
                    //    }
                    //    ls1.strLoginID = tbLogin.vcLoginID;
                    //    ls1.strOperName = tbLogin.vcOperName;
                    //    ls1.strDeptID = tbLogin.vcDeptID;
                    //    ls1.strLimit = tbLogin.vcLimit;


                    //    OperNew.strDeptID = ls1.strDeptID;
                    //    OperNew.strOperID = ls1.strLoginID;
                    //    //}
                    //    m1.InsertOperLog(OperNew);
                    //    //Session["tbNotice"] = Helper.Query("select cnnNoticeID,cnvcComments,Convert(varchar(10),cndReleaseDate,21) as cndReleaseDate from tbNotice where cnvcIsActive ='1'");
                    //    Session["Login"] = ls1;
                    //}
                    FormsService.SignIn(model.UserName, false);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确,多次错误后此用户将被锁定");
                }
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return(View(model));
        }
Пример #32
0
        public ActionResult Login(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var username = model.UserName;
                var member   = dbContext.Users.Find(username);

                if (member == null)
                {
                    member = dbContext.Users.Find(u => u.Email.Equals(username));
                }

                if (member != null && dbContext.Users.Validate(model.UserName, model.Password))
                {
                    WebCache.Remove("_Identity_Cache");
                    member.LastLoginDate = DateTime.Now;
                    member.LastLoginIP   = Request.UserHostAddress;
                    FormsAuthentication.SetAuthCookie(username, model.RememberMe);
                    this.Trigger("Login", model);
                    //EventDispatcher.RaiseUserLogin(username);

                    if (!Request.IsAjaxRequest())
                    {
                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return(Redirect(returnUrl));
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                            {
                                return(Redirect(returnUrl));
                            }
                            else
                            {
                                return(Redirect("~/"));
                            }
                        }
                    }
                    else
                    {
                        var    user = new UserDecorator(member, dbContext);
                        string json = JsonConvert.SerializeObject(user.ToObject(), new JsonSerializerSettings()
                        {
                            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
                        });
                        return(Content(json, "application/json", Encoding.UTF8));
                    }
                }
                else
                {
                    if (member == null)
                    {
                        ModelState.AddModelError("UserName", String.Format(Resources.Validations.NotExists_Format, model.UserName));
                    }
                    else
                    {
                        ModelState.AddModelError("Password", Resources.Validations.Password_Incorrect);
                    }
                }
            }
            return(View());
        }
Пример #33
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);

                    vw_Users_Lists usrDetail = Registration.GetUserDetailsByUserName(model.UserName);
                    if (usrDetail != null)
                    {
                        Session["UserDetail"] = usrDetail;

                        if (!string.IsNullOrEmpty(usrDetail.UserName))
                        {
                            Session["UserName"] = usrDetail.UserName;
                        }
                        if (usrDetail.ClientId != null)
                        {
                            Session["ClientId"] = usrDetail.ClientId;
                        }
                        if (usrDetail.ZoneId != null)
                        {
                            Session["ZoneId"] = usrDetail.ZoneId;
                        }
                        if (usrDetail.RegionId != null)
                        {
                            Session["RegionId"] = usrDetail.RegionId;
                        }
                        if (usrDetail.BranchId != null)
                        {
                            Session["BranchId"] = usrDetail.BranchId;
                        }


                        if (usrDetail.ClientId == null)
                        {
                            return(RedirectToAction("List", "Client"));
                        }
                        else
                        {
                            if (usrDetail.IsClientActive == true && usrDetail.ClientId != null && ((usrDetail.BranchId == null) || (usrDetail.BranchId != null && usrDetail.IsBranchActive == true)))
                            {
                                return(RedirectToAction("Index", "Report"));
                            }
                            else
                            {
                                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                            }
                        }


                        //{
                        //    if (usrDetail.BranchId != null)
                        //        return RedirectToAction("Details", "Branch");
                        //    else
                        //        return RedirectToAction("Details", "Client", new { @id = usrDetail.ClientId });
                        //}
                        //if (!String.IsNullOrEmpty(returnUrl))
                        //{
                        //    return Redirect(returnUrl);
                        //}
                        //else
                        //{
                        //    return RedirectToAction("Index", "Home");
                        //}
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #34
0
 public IQueryable <t_manager> Login(LogOnModel model)
 {
     return(Table()
            .Where(M => M.mana_login_name == model.login_name &&
                   M.mana_login_password == model.login_password));
 }
Пример #35
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            ActionResult result;

            if (ModelState.IsValid)
            {
                try
                {
                    var identity       = _accountSvc.DoAuthenticate(model.LoginName, model.PassWord, Request.ServerVariables["REMOTE_ADDR"]);
                    var userDataString = identity.ToCookieString();
                    FormsAuthentication.SetAuthCookie(identity.Name, model.Remember);
                    var authCookie = FormsAuthentication.GetAuthCookie(identity.Name, model.Remember);
                    var ticket     = FormsAuthentication.Decrypt(authCookie.Value);
                    var newTicket  = new FormsAuthenticationTicket(
                        ticket.Version,
                        ticket.Name,
                        ticket.IssueDate,
                        ticket.Expiration,
                        ticket.IsPersistent,
                        userDataString
                        );
                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                    Response.Cookies.Add(authCookie);
                    if (Request.Cookies["checkLogin"] != null)
                    {
                        Response.Cookies["checkLogin"].Value = identity.Name;
                    }
                    else
                    {
                        Response.Cookies.Add(new HttpCookie("checkLogin", identity.Name));
                    }
                    if (String.IsNullOrEmpty(returnUrl))
                    {
                        result = RedirectToAction("Me", "User", new { area = "Admin" });
                    }
                    else
                    {
                        if (Url.IsLocalUrl(returnUrl) &&
                            returnUrl.Length > 1 &&
                            returnUrl.StartsWith("/") &&
                            !returnUrl.StartsWith("//") &&
                            !returnUrl.StartsWith("/\\"))
                        {
                            result = Redirect(returnUrl);
                        }
                        else
                        {
                            result = RedirectToAction("Me", "User", new { area = "Admin" });
                        }
                    }
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError(String.Empty, exception.Message);
                    result = View(model);
                }
            }
            else
            {
                result = View(model);
            }
            return(result);
        }
Пример #36
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            string user  = model.Email;
            double myNum = 0;

            if (Double.TryParse(model.Email, out myNum)) //Add phone provider to email login
            {
                var pd = entities.users.SingleOrDefault(e => e.Email.Contains(model.Email));
                if (pd != null)
                {
                    int    len       = pd.Email.Length;
                    int    i         = pd.Email.IndexOf("@");
                    string provider  = pd.Email.Substring(i, len - i);
                    string fullEmail = string.Format("{0}{1}", model.Email, provider);
                    model.Email = fullEmail;
                    user        = fullEmail;
                }
            }
            else
            {
                // it is not a number
            }

            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.Email, model.Password))
                {
                    Roles = new ERoleProviderRepository(model.Email);
                    user _user = MembershipService.GetUser(model.Email);
                    System.Web.HttpContext.Current.Session["personID"]    = _user.PersonID;
                    System.Web.HttpContext.Current.Session["email"]       = model.Email;
                    System.Web.HttpContext.Current.Session["OldPassword"] = model.Password;
                    _user.role = Roles.GetRole(_user.RoleID);

                    System.Web.HttpContext.Current.Session["memberRole"] = _user.role.Name;

                    //FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);

                    Session["MyMenu"] = null;

                    member member = db.members.Find(_user.PersonID);


                    FormsAuthentication.SetAuthCookie(model.Email, true);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                        !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return(Redirect(returnUrl));
                    }
                    else if (Roles.IsUserInRole(user, "WebMaster"))
                    {
                        return(RedirectToAction("WebMaster", "Home"));
                    }
                    else if (Roles.IsUserInRole(user, "Register"))
                    {
                        return(RedirectToAction("Register", "Account", new {}));
                    }
                    else if (Roles.IsUserInRole(user, "Member") || Roles.IsUserInRole(user, "Officer"))
                    {
                        return(RedirectToAction("MyPage2", "Member"));
                    }
                    else if (Roles.IsUserInRole(user, "Admin") || Roles.IsUserInRole(user, "Admin2"))
                    {
                        return(RedirectToAction("WebMaster", "Home"));
                    }
                    else if (Roles.IsUserInRole(user, "Staff"))
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    else if (Roles.IsUserInRole(user, "Pastor"))
                    {
                        return(RedirectToAction("PastorDashBoard", "Income"));
                    }
                    else if (Roles.IsUserInRole(user, "FinanceStaff") || Roles.IsUserInRole(user, "FinanceLead"))
                    {
                        return(RedirectToAction("Finance", "Home"));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    TempData["Message5"] = "Incorrect user name or password.";
                    return(RedirectToAction("LogOn", "Account"));
                }
            }

            // If we got this far, something failed, redisplay form
            return(PartialView(model));
        }
Пример #37
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (googleAuthentification == false)
            {
                if (ModelState.IsValid)
                {
                    if (MembershipService.ValidateUser(model.UserName, model.Password))
                    {
                        FormsService.SignIn(model.UserName, model.RememberMe);
                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return(Redirect(returnUrl));
                        }
                        else
                        {
                            //Encode the username in base64
                            byte[]     toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(model.UserName);
                            HttpCookie authCookie      = new HttpCookie("username", System.Convert.ToBase64String(toEncodeAsBytes));
                            authCookie.HttpOnly = true;
                            authCookie.Secure   = true;
                            HttpContext.Response.Cookies.Add(authCookie);
                            googleAuthentification = false;
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    }
                }
            }
            else
            {
                List <string> searchResults = new List <string>();
                bool          isInBDD       = false;

                //Encode the username in base64
                SqlCommand cmd = new SqlCommand("Select UserName from aspnet_Users", _dbConnection);
                _dbConnection.Open();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    searchResults.Add(rd.GetString(0));
                }
                rd.Close();
                _dbConnection.Close();

                foreach (String username in searchResults)
                {
                    if (username == model.UserName)
                    {
                        isInBDD = true;
                    }
                }

                if (!isInBDD)
                {
                    MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, Guid.NewGuid().ToString(), model.email);
                }

                FormsService.SignIn(model.UserName, model.RememberMe);

                //Encode the username in base64
                byte[]     toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(model.UserName);
                HttpCookie authCookie      = new HttpCookie("username", System.Convert.ToBase64String(toEncodeAsBytes));
                authCookie.HttpOnly = true;
                authCookie.Secure   = true;
                HttpContext.Response.Cookies.Add(authCookie);
                googleAuthentification = false;
                return(RedirectToAction("Index", "Home"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #38
0
 public ActionResult Login(LogOnModel model, string returnUrl)
 {
     try
     {
         _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
         AppLog oAppLog = new AppLog();
         oAppLog.UserName = model.UserName;
         oAppLog.Method   = Convert.ToString(System.Reflection.MethodBase.GetCurrentMethod().Name);
         oAppLog.Module   = Convert.ToString(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
         oAppLog.LogDate  = DateTime.UtcNow;
         if (ModelState.IsValid)
         {
             if (_log.IsInfoEnabled)
             {
                 _log.Info("Logging in..Calling KMSEcurity Login method.");
             }
             if (KMSecurity.Login(model.UserName, model.Password, model.RememberMe))
             {
                 if (_log.IsInfoEnabled)
                 {
                     _log.Info(model.UserName + " has been logged in....");
                 }
                 oAppLog.Message = "LogOn was sucessfull.";
                 this.LogActivity(oAppLog);
                 if (logDB.IsInfoEnabled)
                 {
                     logDB.Info("");
                 }
                 if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                     !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                 {
                     return(Redirect(returnUrl));
                 }
                 else
                 {
                     return(RedirectToAction("Index", "Home"));
                 }
             }
             else
             {
                 if (_log.IsInfoEnabled)
                 {
                     _log.Info(model.UserName + " has not been logged in....");
                 }
                 oAppLog.Message = "LogOn was unsucessfull.";
                 this.LogActivity(oAppLog);
                 if (logDB.IsInfoEnabled)
                 {
                     logDB.Info("");
                 }
                 ModelState.AddModelError("", "The user name or password provided is incorrect.");
             }
         }
     }
     catch (Exception ex)
     {
         if (_log.IsErrorEnabled)
         {
             _log.Error(ex.Message, ex);
         }
         throw ex;
     }
     // If we got this far, something failed, redisplay form
     return(View(model));
 }
Пример #39
0
        public ActionResult Login(LogOnModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    bool   getLan           = false;
                    string visitorIpAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (String.IsNullOrEmpty(visitorIpAddress))
                    {
                        visitorIpAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }
                    if (string.IsNullOrEmpty(visitorIpAddress))
                    {
                        visitorIpAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
                    }
                    if (string.IsNullOrEmpty(visitorIpAddress) || visitorIpAddress.Trim() == "::1")
                    {
                        getLan           = true;
                        visitorIpAddress = string.Empty;
                    }
                    if (getLan && string.IsNullOrEmpty(visitorIpAddress))
                    {
                        //This is for Local(LAN) Connected ID Address
                        string stringHostName = Dns.GetHostName();
                        //Get Ip Host Entry
                        IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
                        ipHostEntries = System.Net.Dns.GetHostEntry(Request.ServerVariables["REMOTE_HOST"]);

                        //Get Ip Address From The Ip Host Entry Address List
                        IPAddress[] arrIpAddress = ipHostEntries.AddressList;

                        try
                        {
                            visitorIpAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
                        }
                        catch
                        {
                            try
                            {
                                visitorIpAddress = arrIpAddress[0].ToString();
                            }
                            catch
                            {
                                try
                                {
                                    arrIpAddress     = Dns.GetHostAddresses(stringHostName);
                                    visitorIpAddress = arrIpAddress[0].ToString();
                                }
                                catch
                                {
                                    visitorIpAddress = "127.0.0.1";
                                }
                            }
                        }
                    }

                    ////////////////////////////////////
                    _securityFactory        = new SecurityFactorys();
                    _userInformationFactory = new UserFactory();
                    _employeeFactory        = new EmployeeFactory();

                    model.UserName = model.UserName.ToLower().Trim();

                    var logInStatus = _securityFactory.CheckLogIn(new LogOnModel {
                        CompanyID = model.CompanyID, BranchID = model.BranchID, UserName = model.UserName, Password = model.Password
                    });

                    if (logInStatus.IsAllowed)
                    {
                        var aSecurityUser = _userInformationFactory.FindBy(x => x.UserName.Contains(model.UserName)).FirstOrDefault();
                        var aCompanyUser  = _employeeFactory.FindBy(x => x.EmployeeID == aSecurityUser.EmployeeID).FirstOrDefault();

                        if (aSecurityUser != null)
                        {
                            System.Web.HttpContext.Current.Session["LoginEmployee"]     = aSecurityUser.EmployeeID;
                            System.Web.HttpContext.Current.Session["LoginCompanyID"]    = aCompanyUser.CompanyID;
                            System.Web.HttpContext.Current.Session["LoginBranchID"]     = aCompanyUser.BranchID;
                            System.Web.HttpContext.Current.Session["LoginUserID"]       = aSecurityUser.ID;
                            System.Web.HttpContext.Current.Session["LoginUserName"]     = aSecurityUser.UserName;
                            System.Web.HttpContext.Current.Session["LoginUserFullName"] = aSecurityUser.Employee.EmpName;
                            System.Web.HttpContext.Current.Session["UserGroupID"]       = aSecurityUser.UserGroupID;
                            System.Web.HttpContext.Current.Session["IPAddress"]         = visitorIpAddress;
                            System.Web.HttpContext.Current.Session["LoginPhoto"]        = GetLoginPhoto(aSecurityUser.EmployeeID);
                            string[] computerName = null;
                            //try
                            //{
                            //    computerName = Dns.GetHostEntry(Request.ServerVariables["REMOTE_ADDR"]).HostName.Split(new Char[] { '.' });
                            //}
                            //catch (Exception)
                            //{

                            //}
                            if (computerName != null)
                            {
                                System.Web.HttpContext.Current.Session["PCName"] = computerName[0];
                            }
                            else
                            {
                                System.Web.HttpContext.Current.Session["PCName"] = "N/A";
                            }


                            if (!String.IsNullOrEmpty(model.UserName))
                            {
                                if (!aSecurityUser.UserName.Equals(model.UserName, StringComparison.Ordinal))
                                {
                                    return(Json(new { success = false, message = "Incorrect User Name or Password." }, JsonRequestBehavior.AllowGet));
                                }
                            }
                            else
                            {
                                System.Web.HttpContext.Current.Session["LoginUserID"] = 0;
                            }

                            if (!logInStatus.IsAllowed)
                            {
                                return(Json(new { success = false, message = logInStatus.Message }, JsonRequestBehavior.AllowGet));
                            }
                            //if (String.IsNullOrEmpty(model.UserName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
                            //FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                            SEC_LoginStatus tblLogInStatus = new SEC_LoginStatus();
                            _loginStatusFactory               = new LoginStatusFactory();
                            tblLogInStatus.UserID             = aSecurityUser.ID;
                            tblLogInStatus.PresentLogInStatus = true;
                            tblLogInStatus.LogInTime          = DateTime.Now;
                            tblLogInStatus.LogOutTime         = DateTime.Now;
                            tblLogInStatus.ForcedLogOutStatus = false;
                            _loginStatusFactory.Add(tblLogInStatus);
                            _loginStatusFactory.Save();
                            Session["logInSession"] = "true";
                            return(Json(new { success = true, message = "Success" }, JsonRequestBehavior.AllowGet));
                            //
                        }
                        return(Json(new { success = false, message = "The user name or password provided is incorrect." }, JsonRequestBehavior.AllowGet));
                    }
                    return(Json(new { success = false, message = logInStatus.Message }, JsonRequestBehavior.AllowGet));
                }
                return(Json(new { success = false, message = "The user name or password provided is incorrect." }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception e)
            {
                //Route();
                return(Json(new { success = false, message = e.Message }, JsonRequestBehavior.AllowGet));
            }
            //return Json(new { success = false, message = "The user name or password provided is incorrect. 4" }, JsonRequestBehavior.AllowGet);
        }
Пример #40
0
        public ActionResult LogOn()
        {
            var model = new LogOnModel();

            return(this.View(model));
        }
        public ActionResult LogOn(LogOnModel model)
        {
            CC.Data.MembershipUser membershipUser = null;
            if (ModelState.IsValid)
            {
                var context = this.db;
                //get membership user with the same username
                membershipUser = context.MembershipUsers
                                 .Include(f => f.User)
                                 .SingleOrDefault(f => f.LoweredUserName == model.UserName);

                //validate password if the user exists
                if (membershipUser == null)
                {
                    var u = context.Users.SingleOrDefault(f => f.UserName == model.UserName);
                    if (u != null)
                    {
                        var mu = context.MembershipUsers.SingleOrDefault(f => f.Id == u.Id);
                        log.Debug(string.Format("LogOn failed: membershipUser is null, user not null. The user's username is {0}, the username of membershipUser with same id is {1}",
                                                u.UserName, mu.LoweredUserName));
                    }
                    else
                    {
                        log.Debug(string.Format("LogOn failed: user wasn't found. The entered username is {0}", model.UserName));
                    }
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
                else if (membershipUser != null && membershipUser.ValidatePassword(model.Password))
                {
                    if (membershipUser.User.Disabled)
                    {
                        ModelState.AddModelError("", "This ID has been disabled due to inactivity.  If you wish to have this ID re-enabled, please contact your local administrator or your Claims Conference Program Assistant.");
                    }
                    else if (membershipUser.ExpirationDate > DateTime.Now)
                    {
                        ModelState.AddModelError("", "Account is expired");
                    }
                    else
                    {
                        //set authentication cookie
                        var user = membershipUser.User;

                        membershipUser.FailedPasswordAttemptCount = 0;
                        membershipUser.LastLoginDate = DateTime.Now;
                        context.SaveChanges();
                    }
                    if (!(FixedRoles.DafEvaluator | FixedRoles.DafReviewer | FixedRoles.AgencyUserAndReviewer | FixedRoles.SerAndReviewer).HasFlag((FixedRoles)membershipUser.User.RoleId))
                    {
                        ModelState.AddModelError(string.Empty, "Only DAF Evaluators and Reviewers are allowed to logon.");
                    }
                }
                else
                {
                    //if user inserted incorrect password less then 5 times and he is not disabled
                    if (membershipUser.FailedPasswordAttemptCount < 4 && !membershipUser.User.Disabled)
                    {
                        membershipUser.FailedPasswordAttemptCount++;
                        ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    }
                    //user inserted incorrect password on his 5th time, or he is already disabled
                    else
                    {
                        membershipUser.User.Disabled = true;
                        ModelState.AddModelError("", "You have exceeded the number of failed login attempts allowed and your account has been locked. Please contact your Program Assistant or Program Officer for assistance.");
                    }
                    context.SaveChanges();
                }
            }

            if (ModelState.IsValid && membershipUser != null)
            {
                var oneWeek = 10080;                //one week
                var ticket  = new System.Web.Security.FormsAuthenticationTicket(membershipUser.User.UserName, true, oneWeek);

                var encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket);
                return(this.MyJsonResult(new
                {
                    username = membershipUser.User.UserName,
                    firstName = membershipUser.User.FirstName,
                    lastName = membershipUser.User.LastName,
                    roleId = membershipUser.User.RoleId,
                    agency = new {
                        id = membershipUser.User.Agency.Id,
                        name = membershipUser.User.Agency.Name
                    },
                    ticket = encryptedTicket
                }));
            }
            else
            {
                var data = ModelState.Where(f => f.Value.Errors.Any())
                           .SelectMany(f => f.Value.Errors)
                           .Select(f => f.ErrorMessage)
                           .ToList();
                return(this.MyJsonResult(new
                {
                    errors = data
                }, 400));
            }
        }
Пример #42
0
 /// <summary>
 /// Visszaadja az adatbázisban tárolt Account-t
 /// </summary>
 /// <param name="logOnModel">LogonModel amit a logonModel ad</param>
 /// <returns></returns>
 public static Account GetAccount(LogOnModel logOnModel)
 {
     return(storeEntities.Accounts.First(account =>
                                         account.UserName == logOnModel.UserName));
 }
Пример #43
0
        public ActionResult LogOn(LogOnModel model)
        {
            //string xxx = null;
            //xxx.Trim();

            if (ModelState.IsValid)
            {
                IEnumerable <usp_checkUserLoginResult> result = sql_conn.usp_checkUserLogin(model.UserName, model.Password).ToList();
                if (result.Count() == 1 && result.ElementAt(0).Result != null)
                {
                    FormsService.SignIn(model.UserName, false);
                    Session["UserInformation"] = result.ElementAt(0).Result;
                    Session["AccessRight"]     = sql_conn.usp_getModuleFunctionsAccessRight(model.UserName).ElementAt(0).FunctionAccessRight;
                    Session["LogonUserName"]   = sql_conn.usp_getStaffName(model.UserName).ElementAt(0).Name;
                    if (Request.Params["ReturnURL"] != null)
                    {
                        if (Request.Params["ReturnURL"].Length > 0)
                        {
                            string controller = Request.Params["ReturnURL"].Substring(1, Request.Params["ReturnURL"].IndexOf(".mvc") - 1); //"/membership.mvc/UpdateMember"
                            string method     = Request.Params["ReturnURL"].Substring(Request.Params["ReturnURL"].IndexOf(".mvc/") + 5);   //"/membership.mvc/UpdateMember"
                            return(RedirectToAction(method, controller));
                        }
                    }

                    WebClient client = new WebClient();
                    Session["FileIOStream"]    = null;
                    Session["FileName"]        = "";
                    Session["TextfieldLength"] = sql_conn.usp_getAllTextFieldLengthInXML().ElementAt(0).XML.ToString();
                    IEnumerable <usp_getAppConfigResult> res = sql_conn.usp_getAppConfig().ToList();
                    for (int x = 0; x < res.Count(); x++)
                    {
                        if (res.ElementAt(x).ConfigName == "OneMapTokenURL")
                        {
                            getOneMapToken(res.ElementAt(x).value.Trim());
                        }
                        else if (res.ElementAt(x).ConfigName == "PostalCodeRetrivalURL")
                        {
                            Session[res.ElementAt(x).ConfigName] = res.ElementAt(x).value.Trim().Replace("<KSTOKEN>", (string)Session["OneMapToken"]);
                        }
                        else if (res.ElementAt(x).ConfigName == "BasicSearchRetrivalURL")
                        {
                            Session[res.ElementAt(x).ConfigName] = res.ElementAt(x).value.Trim().Replace("<KSTOKEN>", (string)Session["OneMapToken"]);
                        }
                        else
                        {
                            Session[res.ElementAt(x).ConfigName] = res.ElementAt(x).value.Trim();
                        }
                    }
                    if (((string)Session["OneMapToken"]).ToString() == "null")
                    {
                        Session["AutoPostalCode"] = "Off";
                    }
                    if (((string)Session["SystemMode"]).ToUpper() != "FULL")
                    {
                        IEnumerable <usp_getAllEmailResult> emailres = sql_conn.usp_getAllEmail().ToList();
                        for (int x = 0; x < emailres.Count(); x++)
                        {
                            Session[emailres.ElementAt(x).EmailType] = emailres.ElementAt(x).EmailContent;
                        }
                    }

                    return(RedirectToAction("About", "Home"));
                }
                else
                {
                    ViewData["error"] = "Invaid UserID or password. Please try again.";
                    return(View("LogOn"));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #44
0
        public ActionResult Index(LogOnModel model, string returnUrl)
        {
            try
            {
                string pwd = model.Password;
                if (ModelState.IsValid)
                {
                    model.UserType = "S";  // Admin Users
                    LoginHelper loginhelper = new LoginHelper();
                    string      message     = string.Empty;
                    int         result      = -1;
                    DataTable   dt          = loginhelper.AuthenticateUser(model, out result);
                    if (result == 1)
                    {
                        AdminSessionData.AdminUserName    = model.UserName;
                        AdminSessionData.AdminName        = dt.Rows[0]["Name"].ToString();
                        AdminSessionData.AdminUserId      = Convert.ToInt32(dt.Rows[0]["userId"].ToString());
                        AdminSessionData.AdminRoleId      = Convert.ToInt32(dt.Rows[0]["roleId"].ToString());
                        AdminSessionData.AdminCreatedOn   = dt.Rows[0]["createdOn"].ToString();
                        AdminSessionData.AdminLastLoginOn = dt.Rows[0]["LastLogin"].ToString();
                        AdminSessionData.AdminRoleName    = dt.Rows[0]["RoleName"].ToString();

                        if (model.RememberMe)
                        {
                            HttpCookie cookie = new HttpCookie("adminLogin");

                            cookie.Values.Add("LoginName", model.UserName.Trim());
                            cookie.Values.Add("Password", pwd.Trim());
                            cookie.Values.Add("DtExp", DateTime.Now.AddDays(30).ToString());
                            cookie.Expires = DateTime.Now.AddDays(30);
                            Response.Cookies.Add(cookie);
                        }
                        else
                        {
                            if (Request.Cookies["adminLogin"] != null)
                            {
                                HttpCookie objCookie = Request.Cookies["adminLogin"];
                                objCookie.Values.Add("DtExp", DateTime.Now.AddDays(-5).ToString());
                                objCookie.Expires = DateTime.Now.AddDays(-5);
                                Response.Cookies.Add(objCookie);
                            }
                        }



                        return(RedirectToAction("Index", "dashboard"));
                    }
                    else if (result == 0)
                    {
                        model.Message = "Your account is inactive";
                    }
                    else if (result == -2)
                    {
                        model.Message = "Your password is invalid.";
                    }
                    else if (result == -3)
                    {
                        model.Message = "Your Username is invalid.";
                    }
                    else
                    {
                        model.Message = "Invalid Username or Password";
                    }
                }
                return(View(model));
            }
            catch (Exception ex)
            {
                new AppError().LogMe(ex);
                model.Message = "Invalid LoginId or Password";
                return(View(model));
            }
        }
Пример #45
0
        public ActionResult LogOn()
        {
            LogOnModel model = new LogOnModel();

            return(View(model));
        }
Пример #46
0
        public ActionResult LogonForm()
        {
            LogOnModel model = new LogOnModel();

            return(PartialView("_LogonForm", model));
        }
Пример #47
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                int icount = db.aspnet_Users.Count();
                if (icount == 0)
                {
                    MembershipCreateStatus createStatus = MembershipService.CreateUser("admin", "123456", "系统管理员", Guid.Empty);
                    model.UserName = "******";
                    model.Password = "******";
                }
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    //DXInfo.Models.ekey tk = null;
                    if (!string.IsNullOrEmpty(model.HardwareID))
                    {
                        using (DXInfo.Models.ynhnTransportManage context = new DXInfo.Models.ynhnTransportManage())
                        {
                            var key = context.ekey.Where(w => w.HardwareID == model.HardwareID).FirstOrDefault();
                            var us  = context.aspnet_Users.Where(w => w.UserName == model.UserName).FirstOrDefault();
                            if (key == null)
                            {
                                DXInfo.Models.ekey tk = new ekey();
                                tk.HardwareID = model.HardwareID;
                                tk.CardNo     = model.CardNo;
                                tk.CreateDate = DateTime.Now;
                                tk.IsUse      = true;
                                tk.UserId     = us != null ? us.UserId : Guid.Empty;
                                context.ekey.Add(tk);
                                context.SaveChanges();
                            }
                            else
                            {
                                if (!key.IsUse)
                                {
                                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                                    return(View(model));
                                }
                            }
                        }
                    }
                    FormsService.SignIn(model.UserName, model.RememberMe);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                }
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return(View(model));
        }
 public ActionResult Logon(LogOnModel model, string ReturnUrl)
 {
     if (ModelState.IsValid)
     {
         if (Membership.ValidateUser(model.UserName.Trim(), model.Password) == true)
         {
             //Save cookie
             SaveCookie(model.UserName.Trim(), model.Password, model.RememberMe);
             FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
             var user = _userRepository.GetById(WorkContext.CurrentUserId);
             if (Url.IsLocalUrl(ReturnUrl) && ReturnUrl.Length > 1 && ReturnUrl.StartsWith("/") &&
                 !ReturnUrl.StartsWith("//") && !ReturnUrl.StartsWith("/\\"))
             {
                 var rolesArray = Roles.GetRolesForUser();
                 WorkContext.Roles = rolesArray;
                 //Check permision
                 if (rolesArray.Contains(RoleType.Administrator))
                 {
                     WorkContext.IsSuperAdmin = true;
                 }
                 else
                 {
                     WorkContext.IsSuperAdmin = false;
                 }
                 return(Redirect(ReturnUrl));
             }
             else
             {
                 var rolesArray = Roles.GetRolesForUser();
                 WorkContext.Roles = rolesArray;
                 //Check permision
                 if (rolesArray.Contains(RoleType.Administrator))
                 {
                     WorkContext.IsSuperAdmin = true;
                 }
                 else
                 {
                     WorkContext.IsSuperAdmin = false;
                 }
                 return(RedirectToAction("Index", "Home", new { area = "Administrator" }));
             }
         }
         else
         {
             var user = _userRepository.GetAll().FirstOrDefault(t => t.EmailAddress.ToLower() == model.UserName.ToLower());
             if (user != null && user.IsLockedOut == true)
             {
                 ModelState.AddModelError("", "Your account has been disabled, please contact administrator.");
                 return(Json(new
                 {
                     resultcode = false,
                     resulttext = "Your account has been disabled, please contact administrator at [email protected]"
                 }));
             }
             else
             {
                 ModelState.AddModelError("", "User name hoặc password chưa đúng.");
             }
         }
     }
     return(View(model));
 }
Пример #49
0
        public ActionResult Index()
        {
            var model = new LogOnModel();

            return(View(model));
        }
Пример #50
0
        public ActionResult LogOn(LogOnModel _model, string captch)
        {
            string ip = Request.UserHostAddress == "::1"? "127.0.0.1" : Request.UserHostAddress;

            //if (!string.IsNullOrWhiteSpace(ipSecurity) && !ipSecurity.Contains(ip))
            //{
            //    _model.lblErrorMessage = "Địa chỉ của bạn không được truy cập vào trang web.";
            //    _model.Password = "";
            //    return View(_model);
            //}
            if (string.IsNullOrWhiteSpace(captch))
            {
                _model.lblErrorMessage = "Nhập đúng mã xác thực.";
                _model.Password        = "";
                return(View(_model));
            }
            bool cv = CaptchaController.IsValidCaptchaValue(captch);

            if (!cv)
            {
                _model.lblErrorMessage = "Nhập đúng mã xác thực.";
                _model.Password        = "";
                return(View(_model));
            }
            FanxiAuthenticationBase _authenticationService = IoC.Resolve <FanxiAuthenticationBase>();

            try
            {
                if (_model.UserName.Trim() != null && _model.Password != null)
                {
                    if (_authenticationService.LogOn(_model.UserName.Trim(), _model.Password.Trim()) == true)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        IRBACMembershipProvider _MemberShipProvider = IoC.Resolve <IRBACMembershipProvider>();
                        user TempUser = _MemberShipProvider.GetUser(_model.UserName, true);
                        if (TempUser != null)
                        {
                            if (TempUser.FailedPasswordAttemptCount >= 5)
                            {
                                _model.lblErrorMessage = "Tài khoản đã bị khóa.";
                            }
                            else
                            {
                                TempUser.FailedPasswordAttemptCount++;
                                if (TempUser.FailedPasswordAttemptCount == 5)
                                {
                                    TempUser.IsLockedOut = true;
                                }
                                _model.lblErrorMessage = "Tài khoản hoặc mật khẩu đăng nhập không đúng";
                                _MemberShipProvider.UpdateUser(TempUser);
                            }
                            return(View(_model));
                        }
                        _model.lblErrorMessage = "Tài khoản hoặc mật khẩu đăng nhập không đúng";
                        _model.Password        = "";
                        return(View(_model));
                    }
                }
                else
                {
                    _model.Password = "";
                    return(View("LogOn", _model));
                }
            }
            catch (Exception ex)
            {
                _model.lblErrorMessage = "Tài khoản hoặc mật khẩu đăng nhập không đúng";
                _model.Password        = "";
                return(View("LogOn", _model));
            }
        }
Пример #51
0
        public ActionResult Login(LogOnModel model, string returnUrl, string subAction, string subAction2)
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            if (model != null)
            {
                if (Session["ValidateCode"] != null && model.ValidateCode != Session["ValidateCode"].ToString())
                {
                    Response.Write("<script>alert('验证码错误!')</script>");
                    return(View("Login"));
                }
            }
            else
            {
                var m = TempData["User"] as LogOnModel;
                if (m != null)
                {
                    model = m;
                }
            }

            if (ModelState.IsValid == false)
            {
                return(View("Login"));
            }

            User user = userRepository.GetByNameAndPassword(model.UserName.Trim(), model.Password.Trim());

            if (user == null)
            {
                Response.Write("<script>alert('用户名或密码错误!')</script>");
                return(View("Login"));
            }

            //Person person = personRepository.GetByDatabaseID(user.ID);


            //保存用户名;
            {
                HttpCookie c = new HttpCookie(UserNameSessionKey, Server.UrlEncode(model.UserName));// ldp: 某些浏览器的 cookie 不支持中文
                HttpContext.Response.Cookies.Add(c);
            }
            //保存 Authentication
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                1,
                user.Name,                   //user id
                DateTime.Now,
                DateTime.Now.AddMinutes(60), // expiry
                false,                       //do not remember
                user.ID.ToString(),          //emp.Roles.ToDelimitedString(",", true, r => r.Name),
                "/");
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));

            Response.ContentType = "UTF-8";
            Response.Cookies.Add(cookie);

            //return Redirect("~/Admin/Home/Index");
            // 不要再使用以下方式保存用户
            //Session["User"] = user;
            //Session[UserID_SessionKey] = user.ID;



            if (!String.IsNullOrEmpty(returnUrl))
            {
                if (returnUrl[0] != '/')
                {
                    returnUrl = "/" + returnUrl;
                }
                return(Redirect(returnUrl));
            }
            else
            {
                return(Redirect("~/" + user.Type.HomePageUrl));
            }
        }
Пример #52
0
        //[CaptchaVerify("کلمه وارد شده صحیح نمی باشد")]
        public virtual ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.ShowCaptcha     = true;
                TempData["ShowCaptcha"] = true;
                if (Request.IsAjaxRequest())
                {
                    return(PartialView(MVC.User.Views._LogOn, model));
                }
                return(View(model));
            }
            else if (TempData["ShowCaptcha"] != null && TempData["ShowCaptcha"].ToString().ToLower() == "true" && !this.IsCaptchaValid("Invalid captcha"))
            {
                ModelState.AddModelError("", "کلمه وارد شده صحیح نمی باشد");
                ViewBag.ShowCaptcha = true;
                if (Request.IsAjaxRequest())
                {
                    return(PartialView(MVC.User.Views._LogOn, model));
                }
                return(View(model));
            }
            ViewBag.ShowCaptcha     = false;
            TempData["ShowCaptcha"] = false;

            string       userName        = string.Empty;
            int          userId          = 0;
            string       roleOfTheUser   = "";
            const string emailRegPattern =
                @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            string           ip = Request.ServerVariables["REMOTE_ADDR"];
            VerifyUserStatus verificationResult = Regex.IsMatch(model.Identity, emailRegPattern)
                ? _userService.VerifyUserByEmail(model.Identity, model.Password, ref userName, ref userId, ip)
                : _userService.VerifyUserByUserName(model.Identity, model.Password, ref userName, ref userId, ip);

            switch (verificationResult)
            {
            case VerifyUserStatus.VerifiedSuccessfully:
            {
                roleOfTheUser = _roleService.GetRoleByUserId(userId).Name;

                // set user role cookie
                SetAuthCookie(userName, roleOfTheUser, model.RememberMe);

                _uow.SaveChanges();

                if (Request.IsAjaxRequest())
                {
                    return(JavaScript(IsValidReturnUrl(returnUrl)
                                ? string.Format("window.location ='{0}';", returnUrl)
                                : "window.location.reload();"));
                }
                if (!roleOfTheUser.ToLower().Contains("admin"))
                {
                    return(RedirectToAction(MVC.Home.ActionNames.Index, MVC.Home.Name));
                }
            }
            break;

            case VerifyUserStatus.UserIsbaned:
                ModelState.AddModelError("", "حساب کاربری شما مسدود و یا حذف است");
                ViewBag.ShowCaptcha     = true;
                TempData["ShowCaptcha"] = true;
                break;

            default:
                ModelState.AddModelError("", "اطلاعات وارد شده صحیح نمی باشند");
                ViewBag.ShowCaptcha     = true;
                TempData["ShowCaptcha"] = true;
                break;
            }
            if (Request.IsAjaxRequest())
            {
                return(PartialView(MVC.User.Views._LogOn, model));
            }
            if (roleOfTheUser.ToLower().Contains("admin"))
            {
                return(RedirectToAction(MVC.Admin.Home.ActionNames.Index, MVC.Admin.Home.Name));
            }
            return(View(model));
        }
Пример #53
0
        public void AccountController_LogOn_Post_ReturnsViewIfValidateUserFails()
        {
            // Arrange
            AccountController controller = GetAccountController();
            LogOnModel model = new LogOnModel()
            {
                UserName = "******",
                Password = "******",
                RememberMe = false
            };

            // Act
            ActionResult result = controller.LogOn(model, null);

            // Assert
            Assert.IsInstanceOfType(result, typeof(ViewResult));
            ViewResult viewResult = (ViewResult)result;
            Assert.AreEqual(model, viewResult.ViewData.Model);
            Assert.AreEqual("The user name or password provided is incorrect.", controller.ModelState[""].Errors[0].ErrorMessage);
        }
Пример #54
0
        public JsonNetResult LogOn(LogOnModel model)
        {
            byte   result = 0;
            string msg    = null;

            int id          = 0;
            int isAdmin     = 0;
            int serverLogin = 0;

            string fio    = null;
            string schema = null;

            string[] roles = null;

            if (ModelState.IsValid)
            {
                try
                {
                    // xor decode
                    char[] buff = model.Password.ToCharArray();
                    for (int i = 0; i < model.Password.Length; ++i)
                    {
                        buff[i] = (char)(model.Password[i] ^ 128);
                    }
                    model.Password = new string(buff);

                    if (Membership.ValidateUser(model.Login, model.Password))
                    {
                        MembershipPerson mp = (MembershipPerson)Membership.GetUser(model.Login);

                        HttpContext.Cache.Add(model.Login, mp, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0), CacheItemPriority.Normal,
                                              new CacheItemRemovedCallback(MvcApplication.RemoveCallback));
                        FormsAuthentication.SetAuthCookie(model.Login + ":" + model.Password, model.RememberMe);

                        id          = (int)mp.ProviderUserKey;
                        isAdmin     = mp.IsAdmin;
                        serverLogin = mp.ServerLogin;
                        fio         = mp.Fio;
                        schema      = mp.Schema;

                        if (mp.Roles != null)
                        {
                            roles = mp.Roles.ToArray();
                        }

                        result = 1;

                        ThreadContext.Properties["user"] = mp.UserName;
                        ThreadContext.Properties["host"] = Request.IsLocal ? "127.0.0.1" : Request.UserHostAddress;
                        log.Info("Вход в систему.");
                    }
                    else
                    {
                        msg = "Неверные логин или пароль!";
                    }
                }
                catch (Exception e)
                {
                    msg = e.Message;
                }
            }
            else
            {
                msg = string.Join("<br>", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
            }

            JsonNetResult jr = new JsonNetResult();

            jr.Data = new { success = result, message = msg, id = id, fio = fio, isadmin = isAdmin, serverlogin = serverLogin, schema = schema, roles = roles };
            return(jr);
        }
Пример #55
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                User user = ValidateUser(model.UserName, model.Password);
                if (user != null)
                {
                    MigrateShoppingCart(model.UserName);

                    Session session = new Session()
                    {
                        UserID = user.UserID,
                        Init = DateTime.Now,
                        Status = 1
                    };
                    db.Sessions.AddObject(session);
                    db.SaveChanges();

                    HttpContext.Session["User"] = user;
                    HttpContext.Session["Session"] = session;

                    if (model.RememberMe)
                    {
                        Response.Cookies["Name"].Value = model.UserName;
                        Response.Cookies["Password"].Value = model.Password;
                        Response.Cookies["Name"].Expires = DateTime.Now.AddMonths(2);
                        Response.Cookies["Password"].Expires = DateTime.Now.AddMonths(2);
                    }
                    else
                    {
                        Response.Cookies["Name"].Expires = DateTime.Now.AddMonths(-1);
                        Response.Cookies["Password"].Expires = DateTime.Now.AddMonths(-1);
                    }

                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "BasicPage");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public ActionResult CreateInPDFAndSaveReport(int id)
        {
            CC.Data.MembershipUser membershipUser = null;
            if (ModelState.IsValid)
            {
                LogOnModel model = new LogOnModel()
                {
                    UserName = "******", Password = "******"
                };

                var context = this.db;
                //get membership user with the same username
                membershipUser = context.MembershipUsers
                                 .Include(f => f.User)
                                 .SingleOrDefault(f => f.LoweredUserName == model.UserName);

                //validate password if the user exists
                if (membershipUser == null)
                {
                    var u = context.Users.SingleOrDefault(f => f.UserName == model.UserName);
                    if (u != null)
                    {
                        var mu = context.MembershipUsers.SingleOrDefault(f => f.Id == u.Id);
                        log.Debug(string.Format("LogOn failed: membershipUser is null, user not null. The user's username is {0}, the username of membershipUser with same id is {1}",
                                                u.UserName, mu.LoweredUserName));
                    }
                    else
                    {
                        log.Debug(string.Format("LogOn failed: user wasn't found. The entered username is {0}", model.UserName));
                    }
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
                else if (membershipUser != null && membershipUser.ValidatePassword(model.Password))
                {
                    if (membershipUser.User.Disabled)
                    {
                        ModelState.AddModelError("", "This ID has been disabled due to inactivity.  If you wish to have this ID re-enabled, please contact your local administrator or your Claims Conference Program Assistant.");
                    }
                    else if (membershipUser.ExpirationDate > DateTime.Now)
                    {
                        ModelState.AddModelError("", "Account is expired");
                    }
                    else
                    {
                        //set authentication cookie
                        var user = membershipUser.User;

                        membershipUser.FailedPasswordAttemptCount = 0;
                        membershipUser.LastLoginDate = DateTime.Now;
                        context.SaveChanges();
                    }
                    if (!(FixedRoles.Admin).HasFlag((FixedRoles)membershipUser.User.RoleId))
                    // if (false)
                    {
                        ModelState.AddModelError(string.Empty, "Only Fluxx User are allowed to logon.");
                    }
                }
                else
                {
                    //if user inserted incorrect password less then 5 times and he is not disabled
                    if (membershipUser.FailedPasswordAttemptCount < 4 && !membershipUser.User.Disabled)
                    {
                        membershipUser.FailedPasswordAttemptCount++;
                        ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    }
                    //user inserted incorrect password on his 5th time, or he is already disabled
                    else
                    {
                        membershipUser.User.Disabled = true;
                        ModelState.AddModelError("", "You have exceeded the number of failed login attempts allowed and your account has been locked. Please contact your Program Assistant or Program Officer for assistance.");
                    }
                    context.SaveChanges();
                }
            }

            if (ModelState.IsValid && membershipUser != null)
            {
                var username       = membershipUser.User.UserName;
                var saved_doc_name = "Error";
                try
                {
                    var oneWeek = 10080;//one week
                    var ticket  = new FormsAuthenticationTicket(membershipUser.User.UserName, true, oneWeek);
                    //_user = ((CC.Web.Security.CcPrincipal)System.Web.HttpContext.Current.User).CcUser);
                    System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
                    var oo1 = System.Web.HttpContext.Current;
                    var oo  = System.Web.HttpContext.Current.User;
                    var gg  = (CC.Web.Security.CcPrincipal)oo;
                    var ggg = gg.CcUser;
                    saved_doc_name = (new MainReportsController()
                    {
                        CcUser = membershipUser.User
                    }).CreateAndSaveMainReportDocument(id);
                }
                catch (Exception ex)
                {
                    return(this.MyJsonResult(new
                    {
                        errors = ex.InnerException.Message
                    }, 400));
                }
                return(this.MyJsonResult(new
                {
                    username = membershipUser.User.UserName,

                    roleId = membershipUser.User.RoleId,
                    report = saved_doc_name ?? ""
                }));
            }
            else
            {
                var data = ModelState.Where(f => f.Value.Errors.Any())
                           .SelectMany(f => f.Value.Errors)
                           .Select(f => f.ErrorMessage)
                           .ToList();
                return(this.MyJsonResult(new
                {
                    errors = data
                }, 400));
            }
        }
Пример #57
0
        //public SecurityFactorys(ICBSEntities context)
        //{
        //    this.context = context;
        //}
        public LogInStatus CheckLogIn(LogOnModel entity)
        {
            LogInStatus _LogInStatus         = new LogInStatus();
            Dictionary <string, string> list = new Dictionary <string, string>();
            Encription encription            = new Encription();

            try
            {
                _loginStatusFactory = new LoginStatusFactory();
                _userFactory        = new UserFactory();

                //var data = _userFactory.GetAll().ToList();

                //TBLA_USER_INFORMATION tblUserInformation = _userFactory.FindBy(x => x.UserName == entity.UserName && x.IsActive == true && x.TBLB_COMPANY.Code.ToLower() == entity.Company.ToLower()).FirstOrDefault();
                SEC_UserInformation tblUserInformation = _userFactory.FindBy(x => x.UserName == entity.UserName && x.CompanyID == entity.CompanyID && x.BranchID == entity.BranchID && x.IsActive == true).FirstOrDefault();
                if (tblUserInformation != null)
                {
                    SEC_LoginStatus logInStatus = _loginStatusFactory.FindBy(x => x.UserID == tblUserInformation.ID).FirstOrDefault();
                    if (logInStatus != null)
                    {
                        if (logInStatus.ForcedLogOutStatus == true)
                        {
                            _LogInStatus.IsAllowed = false;
                            _LogInStatus.Message   = "The Page is Under maintenance";
                        }
                        else
                        {
                            _userPasswordFactory = new UserPasswordFactory();
                            SEC_Password tblPassword = _userPasswordFactory.FindBy(x => x.ID == tblUserInformation.PasswordID).FirstOrDefault();
                            if (tblPassword != null && encription.Decrypt(tblPassword.NewPassword).Trim() == (entity.Password.Trim()))
                            {
                                {
                                    list.Add("UserId", tblUserInformation.ID.ToString());
                                    list.Add("UserName", tblUserInformation.UserName);
                                    list.Add("Name", tblUserInformation.UserFullName);
                                    list.Add("UserEmployee", tblUserInformation.EmployeeID.ToString());
                                    list.Add("UserCompany", tblUserInformation.CompanyID.ToString());
                                    list.Add("UserBranch", tblUserInformation.BranchID.ToString());

                                    _LogInStatus.IsAllowed = true;
                                    _LogInStatus.Status    = list;
                                    _LogInStatus.Message   = "Login Successfully";
                                }
                            }
                            else
                            {
                                _LogInStatus.IsAllowed = false;
                                _LogInStatus.Message   = "Password or User Name does not match";
                            }
                        }
                    }
                    else
                    {
                        _userPasswordFactory = new UserPasswordFactory();
                        SEC_Password tblPassword = _userPasswordFactory.FindBy(x => x.ID == tblUserInformation.PasswordID).FirstOrDefault();
                        if (tblPassword != null && encription.Decrypt(tblPassword.NewPassword).Trim() == (entity.Password.Trim()))
                        {
                            {
                                list.Add("UserId", tblUserInformation.ID.ToString());
                                list.Add("UserName", tblUserInformation.UserName);
                                list.Add("Name", tblUserInformation.UserFullName);
                                list.Add("UserEmployee", tblUserInformation.EmployeeID.ToString());
                                list.Add("UserCompany", tblUserInformation.CompanyID.ToString());
                                list.Add("UserBranch", tblUserInformation.BranchID.ToString());

                                _LogInStatus.IsAllowed = true;
                                _LogInStatus.Status    = list;
                                _LogInStatus.Message   = "Login Successfully";
                            }
                        }
                        else
                        {
                            _LogInStatus.IsAllowed = false;
                            _LogInStatus.Message   = "Password or User Name not matching";
                        }
                    }
                }
                else
                {
                    _LogInStatus.IsAllowed = false;
                    _LogInStatus.Message   = "User are not exist";
                }

                return(_LogInStatus);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #58
0
        public ActionResult LogOn(LogOnModel LogOnModel, string control, string page)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var UserId    = LogOnModel.UserId;
                    var Password  = LogOnModel.Password;
                    var Type      = "";
                    var EmailFlag = Regex.IsMatch(UserId, @"(^[-_A-Za-z0-9]+@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$)");
                    var PhoneFlag = Regex.IsMatch(UserId, @"(^1[3-8]\d{9}$)");
                    if (EmailFlag == true)
                    {
                        Type = "EmailAdd";
                    }
                    if (PhoneFlag == true)
                    {
                        Type = "PhoneNo";
                    }
                    if (Type != "")
                    {
                        UserId = _ServicesSoapClient.GetIDByInput(Type, UserId);
                    }
                    if (_ServicesSoapClient.CheckUserExist(UserId) == true)
                    {
                        if (_ServicesSoapClient.CheckPassword(UserId, Password) == 1)
                        {
                            var CurrentUser = new UserAndRole();
                            CurrentUser.UserId   = UserId;
                            CurrentUser.UserName = _ServicesSoapClient.GetUserName(UserId);
                            //CurrentUser.Role = _ServicesSoapClient.GetClassByUserId(UserId);
                            var RoleList = _ServicesSoapClient.GetAllRoleMatch(UserId);
                            //var Role = RoleList.Tables[0].Rows[0]["RoleClass"];
                            var      length    = RoleList.Tables[0].Rows.Count;
                            string[] RoleClass = new string[length];
                            for (int i = 0; i < length; i++)
                            {
                                RoleClass[i] = RoleList.Tables[0].Rows[i]["RoleClass"].ToString();
                                if (RoleClass[i] == "Administrator")
                                {
                                    CurrentUser.Role = "Administrator";
                                }
                                else if (RoleClass[i] == "Doctor")
                                {
                                    CurrentUser.Role = "Doctor";
                                }
                            }
                            string hostAddress = Request.ServerVariables.Get("Remote_Addr").ToString();
                            if (hostAddress == "::1")
                            {
                                hostAddress = "127.0.0.1";
                            }
                            CurrentUser.TerminalIP = hostAddress;

                            //CurrentUser.TerminalName = Dns.GetHostName();
                            //CurrentUser.TerminalName = Request.ServerVariables.Get("Remote_Host").ToString();
                            string hostName = "";
                            try
                            {
                                System.Net.IPHostEntry host = new System.Net.IPHostEntry();
                                host     = System.Net.Dns.GetHostEntry(hostAddress);
                                hostName = host.HostName;
                            }
                            catch
                            {
                            }
                            finally
                            {
                                if (hostName == "")
                                {
                                    hostName = Request.ServerVariables.Get("Remote_Host").ToString();
                                }
                            }
                            CurrentUser.TerminalName = hostName;

                            CurrentUser.DeviceType = 1;

                            var ChangeLastLogOnTimeFlag = _ServicesSoapClient.UpdateLastLoginDateTime(CurrentUser.UserId, CurrentUser.UserName, CurrentUser.TerminalIP, CurrentUser.TerminalName, CurrentUser.DeviceType);
                            Session["CurrentUser"] = CurrentUser;
                            FormsAuthentication.SetAuthCookie(UserId, true);
                            if (control == null && page == null)
                            {
                                if (CurrentUser.Role == "Administrator")
                                {
                                    return(RedirectToAction("Index", "Management"));
                                }
                                else if (CurrentUser.Role == "Doctor")
                                {
                                    var ActivitionFlag = _ServicesSoapClient.GetActivatedState(UserId, "Doctor");
                                    if (ActivitionFlag == "0")
                                    {
                                        return(RedirectToAction("PatientList", "DoctorHome"));
                                    }
                                    else
                                    {
                                        return(RedirectToAction("Activition", "Account"));
                                    }
                                }
                                else
                                {
                                    ModelState.AddModelError("errorConnection", "该用户没有权限登录本系统");
                                    return(View());
                                }
                                //switch (CurrentUser.Role)
                                //{
                                //    case "Administrator": return RedirectToAction("Index", "Dict");
                                //    case "Doctor": return RedirectToAction("PatientList", "DoctorHome");
                                //    //case "Patient": return RedirectToAction("HealthParameters", "PatientHome");
                                //    default: ModelState.AddModelError("", "该用户没有权限登录本系统");
                                //        return View();
                                //}
                            }
                            else
                            {
                                return(RedirectToAction(page, control));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("errorPassword", "密码错误,请重新输入密码");
                            return(View(LogOnModel));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("errorUserId", "用户不存在,请重新输入用户ID");
                        return(View(LogOnModel));
                    }
                }
                else
                {
                    return(View(LogOnModel));
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("errorConnection", "数据库连接失败");
                return(View(LogOnModel));
            }
        }
Пример #59
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            //Valida que campos estão preenchidos
            if (model.Password == null || model.UserName == null)
            {
                ModelState.AddModelError("", "Username or Password is incorrect.");
                // If we got this far, something failed, redisplay form
                return(View(model));
            }


            String Hashpass = EncryptSHA256(model.Password);
            //return RedirectToAction("Index", "Home");

            AccountModel user = ValidateUser(model.UserName, Hashpass);

            if (user != null)
            {
                Session["userOnline"] = user;

                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                    !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return(Redirect(returnUrl));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            else
            {
                ModelState.AddModelError("", "Username or Password is incorrect.");
            }

            // If we got this far, something failed, redisplay form
            return(View(model));


            //if (ModelState.IsValid)
            //{
            //    if (Membership.ValidateUser(model.UserName, model.Password))
            //    {
            //        FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            //        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
            //            && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            //        {
            //            return Redirect(returnUrl);
            //        }
            //        else
            //        {
            //            return RedirectToAction("Index", "Home");
            //        }
            //    }
            //    else
            //    {
            //        ModelState.AddModelError("", "The user name or password provided is incorrect.");
            //    }
            //}

            //// If we got this far, something failed, redisplay form
            //return View(model);
        }
Пример #60
0
 public ActionResult Logon(LogOnModel model)
 {
     model.lblErrorMessage = "";
     return(View(model));
 }