Exemplo n.º 1
0
        public virtual async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // Require the user to have a confirmed email before they can log on.
            var user = await UserManager.FindByNameAsync(model.Email);
            if (user != null)
            {
                if (!await UserManager.IsEmailConfirmedAsync(user.Id))
                {
                    ViewBag.errorMessage = "You must have a confirmed email to log on. Please check your email.";
                    return View("Error");
                }
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }


            List<Tenant> tenants = new List<Tenant>();
            tenants.Add(new Tenant() { Id = 1, Name = "K Force", DbContext = "KforceDB", Email = "*****@*****.**" });
            tenants.Add(new Tenant() { Id = 2, Name = "Sudeep Company", DbContext = "SudeepDB", Email = "*****@*****.**" });

            string dbContext = tenants.First(x => x.Id == model.TenantId).DbContext;

            ApplicationDbContext _db= new ApplicationDbContext(dbContext);
            UserManager<ApplicationUser> _myUserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_db));

            var user = await _myUserManager.FindAsync("tcadmin", model.Password);
            if (user != null)
            {
                var claim = await _myUserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = model.RememberMe }, claim);
                return RedirectToAction("Index", "Admin");
            }


            //_myUserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            //    case SignInStatus.Failure:
            //    default:
            //        ModelState.AddModelError("", "Invalid login attempt.");
            //        return View(model);
            //}
            ViewData["Tenants"] = (from t in tenants
                                   select new SelectListItem()
                                   {
                                       Text = t.Name,
                                       Value = t.Id.ToString()
                                   }).ToList();
            return View(model);
        }
Exemplo n.º 3
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.Email, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Недопустимое имя пользователя или пароль.");
                }
            }

            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return View(model);
        }
Exemplo n.º 4
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.Email, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Ungültiger Benutzername oder ungültiges Kennwort.");
                }
            }

            // Wurde dieser Punkt erreicht, ist ein Fehler aufgetreten; Formular erneut anzeigen.
            return View(model);
        }
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
            return View(model);
        }
Exemplo n.º 6
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.Email, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Exemplo n.º 7
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // Se chegamos até aqui e houver alguma falha, exiba novamente o formulário
            return View(model);
        }
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                // Validate the password
                IdentityResult result = await IdentityManager.Authentication.CheckPasswordAndSignInAsync(AuthenticationManager, model.UserName, model.Password, model.RememberMe);
                if (result.Success)
                {
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Exemplo n.º 9
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return View(model);
        }
Exemplo n.º 10
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            string[] email_split = model.Email.Split('@');
            switch (result)
            {                
                case SignInStatus.Success:
                    TempData["userid"] = email_split[0];

                    if(model.Password == "Piit@123")
                    {
                        return RedirectToAction("ChangePassword", "Manage");
                    }

                    db.Database.ExecuteSqlCommand("INSERT INTO Login_details(idlogin,invalid_attempt,ip_address,browser) VALUES({0},0,{1},{2})", email_split[0], Request.UserHostAddress, Request.UserAgent);
                    if (String.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToLocal("/ams/FacultyHome");
                    }
                    else
                    {
                        return RedirectToLocal(returnUrl);
                    }
                    
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    db.Database.ExecuteSqlCommand("INSERT INTO Login_details(idlogin,invalid_attempt,ip_address,browser) VALUES({0},1,{1},{2})", email_split[0], Request.UserHostAddress, Request.UserAgent);
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }
Exemplo n.º 11
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            Trace.TraceInformation("Beginning login for {0}, returnUrl {1}", model.UsernameOrEmail, returnUrl);
            return await Data.PerformAsync(async () =>
            {
                if (ModelState.IsValid)
                {
                    var user = await UserManager.FindAsync(model.UsernameOrEmail, model.Password);
                    if (user != null)
                    {
                        Trace.TraceInformation("Found user by name {0}, completing login", model.UsernameOrEmail);
                        await SignInAsync(user, model.RememberMe);
                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        Trace.TraceInformation("Failed to find user by name {0}, trying email", model.UsernameOrEmail);
                        user = await UserManager.FindByEmailAsync(model.UsernameOrEmail);
                        if (user != null)
                        {
                            Trace.TraceInformation("Found user by email {0}, completing login", model.UsernameOrEmail);
                            user = await UserManager.FindAsync(user.UserName, model.Password);
                            if (user != null)
                            {
                                await SignInAsync(user, model.RememberMe);
                                return RedirectToLocal(returnUrl);
                            }
                        }
                        Trace.TraceEvent(TraceEventType.Error, 0, "Failed to find user {0}, username or password was incorrect", model.UsernameOrEmail);
                        ModelState.AddModelError("", "Invalid username or password.");
                    }
                }

                Trace.TraceEvent(TraceEventType.Error, 0, "Model state was not valid for user {0}'s login attempt.  {1}", model.UsernameOrEmail, String.Join(", ", ModelState));

                // If we got this far, something failed, redisplay form
                return View(model);
            });
        }
        public async Task<ActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {

                using (var context = new AssessmentEntities())
                {
                    var userExist = context.spLOGIN(model.UserName, model.Password).ToList();
                    if (userExist.Count == 1)
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, false);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Log in credentials invalid");
                    }
                }
            }
           
            // If we got this far, something failed, redisplay form
            return View(model);
        }
Exemplo n.º 13
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }
Exemplo n.º 14
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var comprobarUsuario = _Entities.Usuario.ToList();
                foreach (var itera in comprobarUsuario)
                {
                    if (model.UserName.Equals(itera.Nombre))
                    {

                        IdUsuarioDeLaBaseDeDatos = itera.Id;
                        //si existe entonces hay que cambiar a la vista de las fotos de este usuario
                        return RedirectToAction("MostrarGaleria", "Account");
                    }

                }

                return RedirectToAction("Index", "Home");

            }

            // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario
            return View(model);
        }
Exemplo n.º 15
0
        public async Task<string> ajax_Login(LoginViewModel model)
        {
            var userManager = UserManager;

            LoginResult getLoginResult = new LoginResult();

            //if (!ModelState.IsValid)
            //{
            //    getLoginResult.result = false;
            //    getLoginResult.message = "資訊不完整";
            //    return defJSON(getLoginResult);
            //}

            #region 驗證碼檢查程序

#if DEBUG
            getLoginResult.vildate = true;
#else
            if (string.IsNullOrEmpty(Session["CheckCode"].ToString()))
            {
                Session["CheckCode"] = Guid.NewGuid();
                getLoginResult.result = false;
                getLoginResult.message = Resources.Res.Log_Err_ImgValideNotEquel;
                return defJSON(getLoginResult);
            }

            getLoginResult.vildate = Session["CheckCode"].Equals(model.validate) ? true : false;
#endif
            if (!getLoginResult.vildate)
            {
                Session["CheckCode"] = Guid.NewGuid(); //只要有錯先隨意產生唯一碼 以防暴力破解,新的CheckCode會在Validate產生。
                getLoginResult.result = false;
                getLoginResult.message = Resources.Res.Log_Err_ImgValideNotEquel;
                return defJSON(getLoginResult);
            }
            #endregion

            #region 帳密碼檢查

            var result = await SignInManager.PasswordSignInAsync(model.account, model.password, model.rememberme, shouldLockout: false);

            if (result == SignInStatus.Failure)
            {
                getLoginResult.result = false;
                getLoginResult.message = Resources.Res.Login_Err_Password;
                return defJSON(getLoginResult);
            }

            getLoginResult.result = true;
            var item = await userManager.FindByNameAsync(model.account);

            if (isTablet)
            {
                getLoginResult.url = Url.Content(CommWebSetup.ManageDefCTR);  //是行動裝置
            }
            else
            {
                //不是行動裝置
                var get_user_roles_id = item.Roles.Select(x => x.RoleId);

                ApplicationDbContext context = ApplicationDbContext.Create();
                var roleManage = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
                var get_user_roles_name = roleManage.Roles.Where(x => get_user_roles_id.Contains(x.Id)).Select(x => x.Name);

                if (get_user_roles_name.Contains("Admins") || get_user_roles_name.Contains("Managers"))
                {
                    getLoginResult.url = Url.Content(CommWebSetup.ManageDefCTR);
                }
                else
                {
                    getLoginResult.url = Url.Content("~/Active/Sales/PersonalInfo");
                }
            }

            Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_UserName, item.UserName));
            Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_LastLogin, DateTime.Now.ToString("yyyy-MM-dd")));
            #endregion

            //語系使用
            HttpCookie WebLang = Request.Cookies[CommWebSetup.WebCookiesId + ".Lang"];
            WebLang.Value = model.lang;
            Response.Cookies.Add(WebLang);

            try
            {
                var db = getDB0();

                var item_department = await db.Department.FindAsync(item.department_id);

                Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_DepartmentId, item.department_id.ToString()));
                //Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_DepartmentName, item_department.department_name));
                Response.Cookies.Add(new HttpCookie("user_login", Server.UrlEncode(EncryptString.desEncryptBase64("N"))));
                var item_lang = db.i_Lang
                    .Where(x => x.lang == WebLang.Value)
                    .Select(x => new { x.area })
                    .Single();

                ViewData["lang"] = item_lang.area;
                db.Dispose();
            }
            catch (Exception ex)
            {
                getLoginResult.result = false;
                getLoginResult.message = ex.Message;
                return defJSON(getLoginResult);
            }

            return defJSON(getLoginResult);
        }
Exemplo n.º 16
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                //Invalid username/password combination - make model invalid.
                ModelState.AddModelError("", "");
            }

            // Process model errors.
            return View(model);
        }
Exemplo n.º 17
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!this.ModelState.IsValid)
            {
                return this.View(model);
            }

            var user = await this.UserManager.FindAsync(model.Email, model.Password);
            if (user != null)
            {
                if (user.IsEmailVerified)
                {
                    await this.SignInAsync(user, model.RememberMe);
                    return this.RedirectToLocal(returnUrl);
                }

                this.ModelState.AddModelError(string.Empty, "Votre compte n'est pas validé, veuillez vérifier vos emails.");
            }
            else
            {
                this.ModelState.AddModelError(string.Empty, "Email ou mot de passe invalide.");
            }

            // Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
            return this.View(model);
        }
Exemplo n.º 18
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var repository = RepositoryFactory.GetInstance(Session);
                var logException = default(Exception);
                var userManager = new MyMentorUserManager(repository, Session);

                try
                {
                    var user = await userManager.Login(model.UserName, model.Password, Session);
                    var adminData = user.GetPointerObject<UserAdminData>("adminData");
                    user.GetPointerObject<BL.Models.SugNirut>("sugNirut");
                    var userStatusObj = adminData.GetPointerObject<ParseObject>("userStatus");
                    var userStatus = userStatusObj.GetString("status");
                    var userStatusTitle = userStatusObj.GetLocalizedField("statusTitle");

                    var prohibitedStatuses = new[] {"blocked", "hold"};

                    if (prohibitedStatuses.Contains(userStatus))
                    {
                        ParseUser.LogOut();
                        Session["user"] = null;
                        ModelState.AddModelError("",
                            string.Format(MyMentorResources.userNotAllowedToLogin, userStatusTitle));
                        return View(model);
                    }
                    if (userStatus == UserStatusStrings.AppUser)
                    {
                        return RedirectToAction("UpdateStudent");
                    }

                    var prefferences = new UserPrefferences
                    {
                        SelectedLanguage = user.GetPointerObjectId("interfaceLanguage"),
                        SelectedContentType = user.GetPointerObjectId("contentType"),
                        SelectedCurrency = user.GetPointerObjectId("currency")
                    };
                    var prefferencesManager = new UserPrefferencesManager(repository, HttpContext);
                    prefferencesManager.SetUserPrefferences(prefferences, Session.GetLoggedInUser() == null);

                    SetPurchases(repository, user);
                    if (model.RememberMe)
                    {
                        var ticket = new FormsAuthenticationTicket(1,
                            model.UserName,
                            DateTime.Now,
                            DateTime.Now.AddMinutes(30),
                            true,
                            model.Password,
                            FormsAuthentication.FormsCookiePath);

                        string encTicket = FormsAuthentication.Encrypt(ticket);

                        // Create the cookie.
                        var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                        authCookie.Expires = DateTime.Now.AddYears(1);
                        Response.Cookies.Add(authCookie);
                    }
                    var webCacheProvider = new WebCacheProvider(System.Web.HttpContext.Current);
                    var currencyRatesService = new CurrencyRatesService(repository, webCacheProvider,System.Configuration.ConfigurationManager.AppSettings["bankServiceUrl"]);
                    currencyRatesService.UpdateRates();
                    
                }
                catch (Exception ex)
                {
                    logException = ex;
                    mLogger.Log(LogLevel.Error, ex);
                    ModelState.AddModelError("", MyMentorResources.passwordIncorrect);
                }
                finally
                {
                    repository.Dispose();
                }

                if (logException != null)
                {
                    await ParseLogger.Log("login", logException);
                }

                if (Session.GetLoggedInUser() != null)
                {
                    return RedirectToLocal(returnUrl);
                }
            }

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