public ActionResult SignIn(SignInUser signInUser) { try { ActionResult actionResult = ServiceHelper.IsAnyNullOrEmpty(signInUser); if (actionResult.Success) { actionResult.Success = false; return(actionResult); } ApplicationSignInManager signinManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationSignInManager>(); SignInStatus result = signinManager.PasswordSignIn(signInUser.Username, signInUser.Password, signInUser.RememberMe, false); switch (result) { case SignInStatus.Success: ApplicationUserManager userManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>(); ApplicationUser user = userManager.Find(signInUser.Username, signInUser.Password); if (!userManager.IsEmailConfirmed(user.Id)) { return(new ActionResult { Success = false, Message = "You need to confirm your email." }); } IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication; ClaimsIdentity userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = signInUser.RememberMe }, userIdentity); string token = Security.GenerateSecurityToken(user.Id, signInUser.Username, user.Email); return(new ActionResult { Success = true, Message = token }); case SignInStatus.LockedOut: userManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>(); user = userManager.FindByName(signInUser.Username); user.LockoutEnabled = true; userManager.Update(user); return(new ActionResult { Success = false, Message = "Your account has been locked out, please contact your system administrator." }); case SignInStatus.RequiresVerification: return(new ActionResult { Success = false, Message = "Your account has not yet been verified, please contact your system administrator." }); case SignInStatus.Failure: ApplicationUserManager manager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>(); ApplicationUser tryUser = manager.FindByName(signInUser.Username); if (tryUser != null) { manager.AccessFailed(tryUser.Id); } return(new ActionResult { Success = false, Message = "Invalid username/password combination." }); default: return(new ActionResult { Success = false, Message = "Could not login\r\n" + result }); } } catch (Exception exception) { Dictionary <string, string> dictionary = signInUser.ToDictionary(); ServiceHelper.LogException(exception, dictionary, ErrorSource.Authentication); return(new ActionResult { Success = false, Message = "Error, Failed to login." }); } }
public ActionResult Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { model.MostrarPopUpLoginFront = true; return(View(model)); } var usuario = new Repositorio <Persona>(db).TraerTodos().FirstOrDefault(x => x.Email.Contains(model.Email)); if (usuario == null) { model.MostrarPopUpLoginFront = true; ModelState.AddModelError("", "El usuario o la contraseña son incorrectos."); return(View(model)); } else { SignInStatus resultado; if (usuario.Email.Contains("@sapore-di-pane.com.ar")) { resultado = SignInManager.PasswordSignIn(usuario.Email, model.Password, model.RememberMe, shouldLockout: false); } else { resultado = SignInManager.PasswordSignIn(model.Email, model.Password, model.RememberMe, shouldLockout: false); } if (resultado != SignInStatus.Success) { model.MostrarPopUpLoginFront = true; ModelState.AddModelError("", "El usuario o la contraseña son incorrectos."); return(View(model)); } if (usuario.UsuarioApplicacion.Id.Substring(0, 4) == model.Password.Substring(0, 4)) { return(RedirectToAction("RecuperarPassword")); } if (usuario is Colaborador) { return(RedirectToAction("Index", "Home")); } else { return(RedirectToAction("Index", "Frontend")); } } }
public virtual ActionResult Login(LoginModel model, string returnUrl) { if (FeatureContext.IsEnabled <UseCaptcha>()) { var recaptchaHelper = this.GetRecaptchaVerificationHelper(); if (String.IsNullOrEmpty(recaptchaHelper.Response)) { ModelState.AddModelError("", "Captcha answer cannot be empty."); return(View(MVC.Account.Views.Login, model)); } var recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse(); if (recaptchaResult != RecaptchaVerificationResult.Success) { ModelState.AddModelError("", "Incorrect captcha answer."); } } if (ModelState.IsValid) { var result = signInManager.PasswordSignIn(model.UserName, model.Password, model.RememberMe, shouldLockout: false); if (result == SignInStatus.Success) { return(RedirectToLocal(returnUrl)); } ModelState.AddModelError("", result == SignInStatus.LockedOut ? $"Account disabled until {signInManager.UserManager.FindByName(model.UserName).LockoutEndDateUtc} UTC." : "Invalid username or password."); } // If we got this far, something failed, redisplay form return(View(MVC.Account.Views.Login, model)); }
public bool LoginProgramatically(string userName, string pwd, string returnUrl, ApplicationSignInManager SignInManager) { bool retVal = false; pwd = Encryptor.Encrypt(pwd); var result = SignInManager.PasswordSignIn(userName, pwd, false, shouldLockout: false); switch (result) { case SignInStatus.Success: retVal = true; break; case SignInStatus.LockedOut: retVal = false; break; case SignInStatus.RequiresVerification: retVal = false; break; case SignInStatus.Failure: retVal = false; break; } return(retVal); }
protected void LogIn(object sender, EventArgs e) { if (IsValid) { ApplicationUserManager manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>(); ApplicationSignInManager signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>(); SignInStatus result = signinManager.PasswordSignIn(Username.Text, Password.Text, RememberMe.Checked, shouldLockout: false); switch (result) { case SignInStatus.Success: IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); break; case SignInStatus.LockedOut: Response.Redirect("/Account/Lockout"); break; case SignInStatus.Failure: default: FailureText.Text = "Invalid login attempt"; ErrorMessage.Visible = true; break; } } }
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 = SignInManager.PasswordSignIn(model.Name, model.Password, isPersistent: false, 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)); } }
private void View_OnLogging(object sender, LoginEventArgs e) { ApplicationUserManager manager = e.HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>(); ApplicationSignInManager signinManager = e.HttpContext.GetOwinContext().GetUserManager <ApplicationSignInManager>(); // To enable password failures to trigger lockout, change to shouldLockout: true this.View.Model.SignInStatus = signinManager.PasswordSignIn(e.Username, e.Password, e.RememberMe, e.ShouldLockOut); }
public static bool Signin(string emailaddress, string password) { ApplicationSignInManager signinManager = GetSigninManager(); var status = signinManager.PasswordSignIn(emailaddress, password, true, false); return(status == SignInStatus.Success); }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var authHeader = request.Headers.Authorization; if (authHeader == null) { return(base.SendAsync(request, cancellationToken)); } if (authHeader.Scheme != "Basic") { return(base.SendAsync(request, cancellationToken)); } var encodedUserPass = authHeader.Parameter.Trim(); var userPass = Encoding.ASCII.GetString(Convert.FromBase64String(encodedUserPass)); var parts = userPass.Split(":".ToCharArray()); var username = parts[0]; var password = parts[1]; var appManager = new ApplicationUserManager(new UserStore <ApplicationUser>(new ApplicationDbContext())); using (var signInManager = new ApplicationSignInManager(appManager, HttpContext.Current.GetOwinContext().Authentication)) { var result = signInManager.PasswordSignIn(username, password, true, false); if (result != SignInStatus.Success) { // The SuppressFormsAuthenticationRedirect below has no effect currently; 302 is sent anyway HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true; // Send 401 code instead of 302 code on fail return(base.SendAsync(request, cancellationToken)); } } //if (username != "Brigade" || password != "brigade") //{ // return base.SendAsync(request, cancellationToken); //} var identity = new GenericIdentity(username, "Basic"); string[] roles = Roles.Provider.GetRolesForUser(username); //string[] roles = new string[1]; var principal = new GenericPrincipal(identity, roles); Thread.CurrentPrincipal = principal; if (HttpContext.Current != null) { HttpContext.Current.User = principal; } return(base.SendAsync(request, cancellationToken)); }
public virtual Foto UpoadDeFotoViaAplicativo(UploadFotoViewModel upl, string watermarkHorizontal, string watermarkVertical, string destination, int newSize) { var status = _sigMng.PasswordSignIn(upl.Login, upl.Senha, false, false); if (status != SignInStatus.Success) { throw new Exception("Usuário ou Senha inválidos"); } return(SavePhoto(upl, watermarkHorizontal, watermarkVertical, destination, newSize)); }
public StatusAccountViewModel Login(LoginViewModel login) { var result = signInManager.PasswordSignIn(login.Email, login.Password, login.IsRememberme, shouldLockout: false); if (result == SignInStatus.Success) { return(StatusAccountViewModel.Success); } return(StatusAccountViewModel.Error); }
public SignInStatus AuthenticateUser(string email, string password, ApplicationSignInManager SignInManager) { try { var result = SignInManager.PasswordSignIn(email, password, true, shouldLockout: false); return(result); } catch (Exception ex) { throw new Exception(ex.Message); } }
public JsonResult Login(LoginViewModel info) { ApplicationSignInManager signInManager = HttpContext.GetOwinContext().Get <ApplicationSignInManager>(); SignInStatus result = signInManager.PasswordSignIn(info.Email, info.Password, true, false); switch (result) { case SignInStatus.Success: return(Json(new { success = true })); case SignInStatus.Failure: return(Json(new { success = false })); } return(Json(new { success = false })); }
public ActionResult Login(string email, string password, string returnUrl) { LoginViewModel model = new LoginViewModel() { Email = email, Password = password, RememberMe = false }; if (!ModelState.IsValid) { return(View(model)); } SignInManager.PasswordSignIn(model.Email, model.Password, model.RememberMe, shouldLockout: false); return(RedirectToLocal(returnUrl)); }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { #if DEBUG // CHANGE TO YOUR USER MANAGER var userManger = filterContext.HttpContext.GetOwinContext().GetUserManager <ApplicationUser>(); var user = userManger.FindByName("***"); if (user == null) { this.Create(new ApplicationUser { /* ... */ }, "***"); } using (var signInManager = new ApplicationSignInManager(userManger, filterContext.HttpContext.GetOwinContext().Authentication)) signInManager.PasswordSignIn(user.UserName, "***", true, false); return; #endif return(base.OnAuthorization(filterContext)); }
public JsonResult _Login(LoginViewModel info) { //1 Signin manegare ulaş ApplicationSignInManager sigInManager = HttpContext.GetOwinContext().Get <ApplicationSignInManager>(); //2. Giriş yapmayı dene(result dene.) SignInStatus result = sigInManager.PasswordSignIn(info.Email, info.Password, true, false); //3. ilgili Durumlara göre sonucu döndür switch (result) { case SignInStatus.Success: return(Json(new { success = true, })); //giriş case SignInStatus.Failure: return(Json(new { success = false })); } return(Json(new { success = false })); }
public IHttpActionResult Post(LoginViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = _signInManager.PasswordSignIn(model.Email, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: return(Ok()); case SignInStatus.Failure: default: return(NotFound()); } }
public ActionResult Login(LoginViewModel model) { if (!ModelState.IsValid) { return(View(model)); } ApplicationSignInManager signInManager = Request.GetOwinContext().Get <ApplicationSignInManager>(); SignInStatus signInStatus = signInManager.PasswordSignIn(model.Email, model.Password, false, false); switch (signInStatus) { case SignInStatus.Success: return(Redirect("/")); default: ModelState.AddModelError("", "Invalid Login Attempt"); return(View(model)); } }
public JsonResult Login(LoginViewModel info) { //1.Sign in Managera ulaş ApplicationSignInManager signInManager = HttpContext.GetOwinContext().Get <ApplicationSignInManager>(); //2.Giriş yapmayı dene (result döner) SignInStatus result = signInManager.PasswordSignIn(info.Email, info.Password, true, false); //3.Sonucu döndür switch (result) { case SignInStatus.Success: return(Json(new { success = true })); case SignInStatus.Failure: return(Json(new { success = false }));; } return(Json(new { success = false })); }
public ActionResult Login(LoginViewModel vm) { ApplicationSignInManager asn = HttpContext.GetOwinContext().Get <ApplicationSignInManager>(); var input = asn.PasswordSignIn(vm.Username, vm.Password, true, false); switch (input) { case SignInStatus.Success: return(RedirectToAction("InitPage", "Home")); case SignInStatus.Failure: return(RedirectToAction("Login", "MyAccount")); default: break; } return(View()); }
public 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 = _signInManager.PasswordSignIn(model.Email, model.Password, model.RememberMe, false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); default: ModelState.AddModelError("", "Invalid login attempt."); break; } return(View(model)); }
/// <summary> /// Displays Partial view for Stock expiry /// </summary> /// <returns></returns> public PartialViewResult StockExpiry() { ASITPOSDBEntities db = new ASITPOSDBEntities(); // Repository<Stock> stockrep = new Repository<Stock>(); List<Stock> list = db.Stocks.SqlQuery("select * from Stock s where s.ExpiryDate - GETDATE() < 75").ToList(); return PartialView(list); } [AllowAnonymous] [HttpPost] public ActionResult Login(LoginViewModel lmodel, string returnUrl) { if (!ModelState.IsValid) { return View(lmodel); } ApplicationSignInManager signinManager = Request.GetOwinContext().Get<ApplicationSignInManager>(); // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true SignInStatus SigninStatus = signinManager.PasswordSignIn(lmodel.Email.Trim(), lmodel.Password, lmodel.RememberMe, shouldLockout: false); switch (SigninStatus) { case SignInStatus.Success: return Redirect("Home/Index"); default: ModelState.AddModelError("", "Invalid login attempt."); return View(lmodel); } } [Authorize] public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("Login"); } public ActionResult Product(string currentFilter,string searchString, int? page) { //ViewBag.CurrentSort = sortOrder; //ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; //ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date"; Repository<Item> rep = new Repository<Item>(); ASITPOSDBEntities db = new ASITPOSDBEntities(); var kkk = rep.GetAll(); var ttt = db.Items.ToList(); var lll = db.Catagories.ToList(); if (searchString != null) { page = 1; } else { searchString = currentFilter; } ViewBag.CurrentFilter = searchString; var param = _parm.GetProduct(); DataSet ds = _Data.GetDataSetResult(param); var list = ds.Tables[0].DataTableToList<Product>(); if (!String.IsNullOrEmpty(searchString)) { list = list.Where(s => s.ProductName.ToUpper().Contains(searchString.ToUpper())).ToList(); } int pageSize = 5; int pageNumber = (page ?? 1); return View(list.ToPagedList(pageNumber, pageSize)); } [HttpGet] public ActionResult AddProduct() { var pap = _parm.GetCatagory(); DataSet ds = _Data.GetDataSetResult(pap); var currencyList = ds.Tables[0].DataTableToList<BusinessEntity.Catagory>(); ViewBag.Catagory = currencyList.Select(x => new SelectListItem() { Value = x.catagoriid.ToString(), Text = x.catagoryname }).ToList(); return View(); } [HttpPost] public ActionResult AddProduct(Product pro) { var param = _parm.GetAddProduct(pro); DataSet ds = _Data.GetDataSetResult(param); return RedirectToAction("Product"); } public ActionResult DeletProduct(string id) { var param = _parm.DeleteProduct(id); DataSet ds = _Data.GetDataSetResult(param); return RedirectToAction("Product"); } public decimal TodaySales() { ASITPOSDBEntities db = new ASITPOSDBEntities(); var sales = db.Sales.Where(x => DbFunctions.DiffDays(x.Date, DateTime.Now) == 0).Sum(x => (decimal?)(x.GrandTotal)) ?? 0; return sales; } /// <summary> /// Calculates the Total Sales on Yesterday. /// </summary> /// <returns>returns total yesterday's sales</returns> public decimal YesterdaySales() { ASITPOSDBEntities db = new ASITPOSDBEntities(); decimal sales = db.Sales.Where(x => DbFunctions.DiffDays(x.Date, DateTime.Now) == 1).Sum(x => (decimal?)(x.GrandTotal)) ?? 0; return sales; } } }
// [ValidateAntiForgeryToken] public async Task <ActionResult> Register(RegisterViewModel model, string stateId) { LoadStatesAndCity(); ModelState.Remove("Email"); model.Email = model.Email; if (ModelState.IsValid) { DateTime dateOfBirth = new DateTime(1970, 1, 1); try { dateOfBirth = new DateTime(model.DateOfBirthYear.Value, model.DateOfBirthMonth.Value, model.DateOfBirthDay.Value); } catch { dateOfBirth = new DateTime(1971, 1, 1); } //var user = new ApplicationUser() { Email = model.UserName, UserName = model.UserName, FirstName = model.FirstName, LastName = model.LastName, DateofBirth = model.DateofBirth, Address = model.Address, State = model.StateId, City = model.CityId, Pincode = model.Pincode, EmailConfirmed = true }; var user = new ApplicationUser() { Email = model.UserName, UserName = model.UserName, FirstName = model.FirstName, LastName = model.LastName, DateofBirth = dateOfBirth, Address = model.Address, State = model.StateId, City = model.CityId, Pincode = model.Pincode, EmailConfirmed = true }; user.PhoneNumber = model.PhoneNumber; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //Add user to USERS Roles await UserManager.AddToRoleAsync(user.Id, "Users"); //SEnd Mail Code // Send an email with this link //string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); SignInManager.PasswordSignIn(user.UserName, model.Password, isPersistent: false, shouldLockout: false); //await UserManager.SendEmailAsync(user.Id, "Welcome- GreenPro", "Thanks For Registering with Green Pro"); // Customer Notification _workflowMessageService.SendWelcomeMailtoCustomer(user.FirstName + " " + user.LastName, user.UserName, user.Email); // New Customer Notification To Admin _workflowMessageService.SendNewUserRegisterMailtoAdmin(user.FirstName + " " + user.LastName, user.UserName, user.Email, user.PhoneNumber); var returnURL = GetCookie("returnURL"); string redirectReturnUr = string.Empty; if (returnURL != null) { if (!string.IsNullOrEmpty(returnURL.Value)) { redirectReturnUr = returnURL.Value; } } if (!string.IsNullOrEmpty(redirectReturnUr)) { return(RedirectToLocal(redirectReturnUr)); } else { return(RedirectToAction("Index", "CarUsers", null)); } } AddErrors(result); } return(View(model)); }
public static RBACStatus Login(this ControllerBase controller, LoginViewModel model, ApplicationUserManager userMngr, ApplicationSignInManager signInMngr, out List <string> _errors) { RBACStatus _retVal = RBACStatus.Failure; _errors = new List <string>(); try { var user = userMngr.FindByName(model.UserName); if (user != null) { var validCredentials = userMngr.Find(model.UserName, model.Password); if (userMngr.IsLockedOut(user.Id)) { _errors.Add(string.Format(c_AccountLockout, GetConfigSettingAsDouble(cKey_AccountLockoutTimeSpan))); return(RBACStatus.LockedOut); } else if (userMngr.GetLockoutEnabled(user.Id) && validCredentials == null) { userMngr.AccessFailed(user.Id); if (userMngr.IsLockedOut(user.Id)) { _errors.Add(string.Format(c_AccountLockout, GetConfigSettingAsDouble(cKey_AccountLockoutTimeSpan))); return(RBACStatus.LockedOut); } else { int _attemptsLeftB4Lockout = (GetConfigSettingAsInt(cKey_MaxFailedAccessAttemptsBeforeLockout) - userMngr.GetAccessFailedCount(user.Id)); _errors.Add(string.Format(c_InvalidCredentials, _attemptsLeftB4Lockout)); return(_retVal); } } else if (validCredentials == null) { _errors.Add(c_InvalidLogin); return(_retVal); } else { //Valid credentials entered, we need to check whether email verification is required... bool IsAccountVerificationRequired = GetConfigSettingAsBool(cKey_AccountVerificationRequired); bool Is2FAEnabled = GetConfigSettingAsBool(cKey_2FAEnabled); string DeviceType = GetConfigSetting(cKey_2FADeviceType); if ((IsAccountVerificationRequired && DeviceType == c_EmailCode) || (Is2FAEnabled && DeviceType == c_EmailCode)) { //Check if email verification has been confirmed! if (!userMngr.IsEmailConfirmed(user.Id)) { //Display error message on login page, take no further action... _errors.Add(c_AccountEmailUnconfirmed); return(RBACStatus.EmailUnconfirmed); } } //else if (Is2FAEnabled && DeviceType == c_PhoneCode) else if ((IsAccountVerificationRequired && DeviceType == c_PhoneCode) || (Is2FAEnabled && DeviceType == c_PhoneCode)) { if (!userMngr.IsPhoneNumberConfirmed(user.Id)) { _errors.Add(c_AccountPhoneNumberUnconfirmed); return(RBACStatus.PhoneNumberUnconfirmed); } } bool _userLockoutEnabled = GetConfigSettingAsBool(cKey_UserLockoutEnabled); //Before we signin, check that our 2FAEnabled config setting agrees with the database setting for this user... if (Is2FAEnabled != userMngr.GetTwoFactorEnabled(user.Id)) { userMngr.SetTwoFactorEnabled(user.Id, Is2FAEnabled); } _retVal = (RBACStatus)signInMngr.PasswordSignIn(model.UserName, model.Password, model.RememberMe, shouldLockout: _userLockoutEnabled); switch (_retVal) { case RBACStatus.Success: { userMngr.ResetAccessFailedCount(user.Id); break; } default: { _errors.Add(c_InvalidLogin); break; } } } } else { _errors.Add(c_InvalidUser); } } catch (Exception ex) { throw ex; } return(_retVal); }
public SignInStatus Create(UserDTO user) { _userManager.Create(_mapper.Map <UserDTO, User>(user), user.Password); _transaction.Commit(); return(_signInManager.PasswordSignIn(user.UserName, user.Password, true, false)); }