public async System.Threading.Tasks.Task <ActionResult> Register(string username, string password) { var userStore = new Microsoft.AspNet.Identity.EntityFramework.UserStore <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(); var manager = new Microsoft.AspNet.Identity.UserManager <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(userStore); var user = new Microsoft.AspNet.Identity.EntityFramework.IdentityUser() { UserName = username }; Microsoft.AspNet.Identity.IdentityResult result = await manager.CreateAsync(user, password); if (result.Succeeded) { //I have some options: log them in, or I can send them an email to "Confirm" their account details.' //I don't have email set up this week, so we'll come back to that. //This authentication manager will create a cookie for the current user, and that cookie will be exchanged on each request until the user logs out var authenticationManager = HttpContext.GetOwinContext().Authentication; var userIdentity = await manager.CreateIdentityAsync(user, Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties() { }, userIdentity); } else { ViewBag.Error = result.Errors; return(View()); } return(RedirectToAction("Index", "Home")); }
protected IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { // No ModelState errors are available to send, so just return an empty BadRequest. return BadRequest(); } return BadRequest(ModelState); } return null; }
public static void IsFailure(IdentityResult result, IdentityError error) { Assert.NotNull(result); Assert.False(result.Succeeded); Assert.Equal(error.Description, result.Errors.First().Description); Assert.Equal(error.Code, result.Errors.First().Code); }
private void HatalariEkle(IdentityResult sonuc) { foreach (var hata in sonuc.Errors) { ModelState.AddModelError("", hata); } }
public async Task<ActionResult> Create(UserRoles role) { if (ModelState.IsValid) { // Create a RoleStore object by using the ApplicationDbContext object. // The RoleStore is only allowed to contain IdentityRole objects. var roleStore = new RoleStore<IdentityRole>(context); // Create a RoleManager object that is only allowed to contain IdentityRole objects. // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object. var roleMgr = new RoleManager<IdentityRole>(roleStore); // Then, you create the "Administrator" role if it doesn't already exist. if (!roleMgr.RoleExists(role.RoleName)) { IdRoleResult = roleMgr.Create(new IdentityRole(role.RoleName)); if (IdRoleResult.Succeeded) { // Handle the error condition if there's a problem creating the RoleManager object. ViewBag.StatusMessage = "Role has been added Successfully"; } else { ViewBag.StatusMessage = "The Role Already Exists"; } } } // If we got this far, something failed, redisplay form return View(); }
private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } }
/// <summary> /// Método que realiza la validación de errores que se puedan presentar durante el proceso /// </summary> /// <param name="result"></param> /// <returns></returns> private IHttpActionResult ValidarErroresResultado(IdentityResult result) { if (result == null) { return InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { // Se retorna simplemente un bad request en caso de que no se encuentre un state valido return BadRequest(); } //Se retorna la información con el error return BadRequest(ModelState); } return null; }
//rolling up error message to return error result private IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return InternalServerError(); } if(!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { //no model state errors available to send, just send bad request return BadRequest(); } return BadRequest(ModelState); } return null; }
public static void AddErrors(this Controller controller, IdentityResult result) { foreach (var error in result.Errors) { controller.ModelState.AddModelError("", error); } }
private static void AddErrors(IdentityResult result, ModelMethodContext context) { foreach (var error in result.Errors) { context.ModelState.AddModelError("", error); } }
private void AddErrors(Microsoft.AspNet.Identity.IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } }
public static void Updatecustomers(List <Customer> customers) { using (var context = new WebsiteTTKEntities()) { foreach (Customer item in customers) { var userStore = new Microsoft.AspNet.Identity.EntityFramework.UserStore <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(); var manager = new Microsoft.AspNet.Identity.UserManager <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(userStore); var user = manager.FindByIdAsync(item.AspNetUser.Id).Result; if (user != null) { user.Email = item.AspNetUser.Email; user.PhoneNumber = item.AspNetUser.PhoneNumber; Microsoft.AspNet.Identity.IdentityResult result = manager.UpdateAsync(user).Result; } else { user = new Microsoft.AspNet.Identity.EntityFramework.IdentityUser() { UserName = item.AspNetUser.UserName, Email = item.AspNetUser.Email, PhoneNumber = item.AspNetUser.PhoneNumber }; Microsoft.AspNet.Identity.IdentityResult result = manager.CreateAsync(user, item.Password).Result; } } } }
public async Task<IdentityResult> RegisterCustomerAsync(UserModel userModel, AppRole appRole = AppRole.customer) { var addToRoleResult = new IdentityResult(); // Add generate username to the model IdentityUser user = new IdentityUser { UserName = userModel.UserName, Email = userModel.EmailAddress, EmailConfirmed = true, PhoneNumber = userModel.PhoneNumber, PhoneNumberConfirmed = true, }; var result = await _userManager.CreateAsync(user, userModel.Password); //Role-user combination is managed as Contact-Role combination in ContactRole table //Create Role Admin if it does not exist var _role = await _roleManager.FindByNameAsync(appRole.ToString()); if (_role == null) { _role = new IdentityRole(appRole.ToString()); var roleresult = await _roleManager.CreateAsync(_role); } var rolesForUser = await _userManager.GetRolesAsync(user.Id); if (!rolesForUser.Contains(_role.Name)) { addToRoleResult = await _userManager.AddToRoleAsync(user.Id, _role.Name); } return addToRoleResult; }
public ActionResult RegisterManager(RegisterModel model) { if (ModelState.IsValid) { string userRole = "manager"; ApplicationRole role = RoleManager.FindByName(userRole); ApplicationUser user = new ApplicationUser { Email = model.Email, UserName = model.UserName }; Microsoft.AspNet.Identity.IdentityResult result = UserManager.Create(user, model.Password); if (result.Succeeded) { UserManager.AddToRole(user.Id, role.Name); ManagerProfile profile = new ManagerProfile { Id = user.Id }; _managerProfileDataSource.AddManagerProfileAsync(profile); logger.Info("Был зарегистрирован новый менеджер"); return(RedirectToAction("Index", "Home")); } else { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } } return(View(model)); }
private IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("error", error); } } if (ModelState.IsValid) { // Ошибки ModelState для отправки отсутствуют, поэтому просто возвращается пустой BadRequest. return BadRequest(); } return BadRequest(ModelState); } return null; }
private void AddErrors(IdentityResult result) { foreach (string str in result.Errors) { base.ModelState.AddModelError("", str); } }
private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } }
private IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (var error in result.Errors) { ModelState.AddModelError("",error); } } if (ModelState.IsValid) { //No Modelstate errors are available to send so just return bad request return BadRequest(); } return BadRequest(ModelState); } return null; throw new NotImplementedException(); }
private IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { // No ModelState errors to send, so send a Bad Request return BadRequest(); } // Return the errors return BadRequest(ModelState); } return null; }
private void AddErrorsFromResult(IdentityResult result) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } }
private IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (String error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { //Ingen fejlkode, derfor sendes der bare en badrequest return BadRequest(); } } return null; }
public async Task <ActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { ApplicationUser user = new ApplicationUser { UserName = model.Email, Email = model.Email }; Microsoft.AspNet.Identity.IdentityResult result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { ClaimsIdentity claim = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignOut(); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claim); return(RedirectToAction("Main", "Home")); } else { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } } return(View(model)); }
protected IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return this.InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (var error in result.Errors) { this.ModelState.AddModelError(string.Empty, error); } } if (this.ModelState.IsValid) { return this.BadRequest(); } return this.BadRequest(this.ModelState); } return null; }
protected void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { this.ModelState.AddModelError(string.Empty, error); } }
public static Lazy<IApplicationUserManager> LazyMock(IdentityResult createAsyncResult = null, IdentityResult addToRoleAsyncResult = null) { var result = new Lazy<IApplicationUserManager>(() => Mock(createAsyncResult, addToRoleAsyncResult)); return result; }
private IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) return InternalServerError(); if (result.Succeeded) return null; if (result.Errors != null) foreach (string error in result.Errors) ModelState.AddModelError("", error); if (ModelState.IsValid) return BadRequest(); return BadRequest(ModelState); }
public void NullErrorsBecomeDefaultTest() { var result = new IdentityResult(null); Assert.NotNull(result.Errors); Assert.False(result.Succeeded); Assert.Equal(1, result.Errors.Count()); Assert.Equal("An unknown failure has occured.", result.Errors.First()); }
public ActionResult Register(RegisterModel model, HttpPostedFileBase file) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Home")); } else { if (ModelState.IsValid) { var path = Server.MapPath("~/Upload/Users"); //dosya yolu var filename = Path.ChangeExtension(model.Username + "", ".jpg"); if (file == null) { filename = "place.jpg"; } var fullpath = Path.Combine(path, filename); file.SaveAs(fullpath); model.UserImage = filename.ToString(); //Kayıt İşlemleri ApplicationUser user = new ApplicationUser(); user.Name = model.Name; user.Surname = model.Surname; user.Email = model.Email; user.UserName = model.Username; IdentityResult result = userManager.Create(user, model.Password); if (result.Succeeded) { //Kullanıcı oluştu ve rol atanabilir. if (roleManager.RoleExists("user")) { userManager.AddToRole(user.Id, "user"); } return(RedirectToAction("Login", "Account")); } else { ModelState.AddModelError("RegisterUserError", "Kullanıcı oluşturulamadı."); } } return(View(model)); } }
protected IHttpActionResult Error(IdentityResult result) { if (!result.Succeeded && result.Errors != null) { result.Errors.ForEach(err => ModelState.AddModelError("", err)); return BadRequest(ModelState); } return InternalServerError(); }
public override async Task<IdentityResult> ValidateAsync(string pass) { IdentityResult result = await base.ValidateAsync(pass); if (pass.Contains("12345")) { var errors = result.Errors.ToList(); errors.Add("passwords cannot contain numeric sequences"); result = new IdentityResult(errors); } return result; }
/// <summary> /// Failed helper method /// </summary> /// <param name="errors"></param> /// <returns></returns> public static IdentityResult Failed(params IdentityError[] errors) { var result = new IdentityResult { Succeeded = false }; if (errors != null) { result._errors.AddRange(errors); } return result; }
public override async Task<IdentityResult> ValidateAsync(string passwd) { var result = await base.ValidateAsync(passwd); if (passwd.Contains("123456")) { var errors = result.Errors.ToList(); errors.Add("密码不可包含连续的数字"); result = new IdentityResult(errors); } return result; }
public static IApplicationRoleManager Mock(IdentityResult createAsyncResult = null) { var result = new Mock<IApplicationRoleManager>(); if (createAsyncResult != null) { result.Setup(arm => arm.CreateAsync(It.IsAny<ApplicationRole>())).ReturnsAsync(createAsyncResult); } return result.Object; }
public override async Task<IdentityResult> ValidateAsync(string password) { IdentityResult result = await base.ValidateAsync(password); if (password.Contains("12345")) { List<string> errors = result.Errors.ToList(); errors.Add("密码不能包含连续数字"); result = new IdentityResult(errors); } return result; }
public static void AppendMessage(IdentityResult result, bool refresh = false) { if (refresh == true) sbMessage.Clear(); foreach (string error in result.Errors) { sbMessage.Append(error); sbMessage.Append(Environment.NewLine); } }
private void HandleError(IdentityResult result) { // todo better error handling if (result == null) { throw new Exception("Could not create user, response was null"); } if (result.Errors != null && result.Errors.Any()) { throw new Exception(string.Join(";", result.Errors)); } }
public override async Task<IdentityResult> ValidateAsync(string password) { IdentityResult result = await base.ValidateAsync(password); if (password.Contains("abcdef") || password.Contains("123456")) { var errors = result.Errors.ToList(); errors.Add("Password can not contain sequence of chars"); result = new IdentityResult(errors); } return result; }
public AspNet.IdentityResult CreateUser(ApplicationUser user) { AspNet.IdentityResult identityResult = null; SAPbobsCOM.BusinessPartners oDoc = null; SAPbobsCOM.Recordset oRecords = null; try { var password = Utilities.Encrypt(user.Password); oDoc = base.B1Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oBusinessPartners) as SAPbobsCOM.BusinessPartners; oRecords = base.B1Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset) as SAPbobsCOM.Recordset; oRecords.DoQuery($@"SELECT ""CardCode"" FROM OCRD WHERE ""U_UserName"" = '{user.UserName}' OR ""E_Mail"" = '{user.Email}'"); if (oRecords.RecordCount == 0) { oDoc.CardType = SAPbobsCOM.BoCardTypes.cCustomer; oDoc.Series = GetSeriesCode(); oDoc.UserFields.Fields.Item("U_Password").Value = password; oDoc.UserFields.Fields.Item("U_UserName").Value = user.UserName; oDoc.EmailAddress = user.Email; oDoc.CardName = $"{user.FirstName} {user.LastName}"; oDoc.EmailAddress = user.Email; if (oDoc.Add() != 0) { var err = base.B1Company.GetLastErrorDescription(); identityResult = new AspNet.IdentityResult(err); throw new Exception(err); } else { identityResult = AspNet.IdentityResult.Success; }; } else { identityResult = new AspNet.IdentityResult("Username or Email are already in use!"); } } catch (Exception ex) { Utilities.LogException(ex); identityResult = new AspNet.IdentityResult(ex.Message); } finally { oRecords.ReleaseObject(); oDoc.ReleaseObject(); } return(identityResult); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { /*Teacher t = new Teacher(); * t.TeacherName = model.UserName; * t.TeacherPassword = model.Password;*/ var user = new ApplicationUser { UserName = model.UserName, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var roleresult = new Microsoft.AspNet.Identity.IdentityResult(); var currentUser = UserManager.FindByName(user.UserName); if (model.UserRoles == "Teacher") { roleresult = UserManager.AddToRole(currentUser.Id, "Teacher"); } else { roleresult = UserManager.AddToRole(currentUser.Id, "Admin"); } await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // 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); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); /*//Assign user to role here * await this.UserManager.AddToRoleAsync(user.Id, model.UserRoles); * //Ends here*/ /*if (ModelState.IsValid) * { * db.Teachers.Add(t); * db.SaveChanges(); * }*/ return(RedirectToAction("Login", "Account")); } ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin")).ToList(), "Name", "Name"); AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
// only if you use unmanaged resources directly in AccountController //AccountController() //{ // Dispose(false); //} private IHttpActionResult GetErrorResult(Microsoft.AspNet.Identity.IdentityResult result) { if (result == null) { return(InternalServerError()); } if (!result.Succeeded) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } return(BadRequest(ModelState)); } return(null); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { Customer c = new Customer(); c.Customer_id = model.Email; c.Customer_name = model.Name; c.password = model.Password; var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var roleresult = new Microsoft.AspNet.Identity.IdentityResult(); var currentUser = UserManager.FindByName(user.UserName); if (model.Role == "Customer") { roleresult = UserManager.AddToRole(currentUser.Id, "Customer"); } else { roleresult = UserManager.AddToRole(currentUser.Id, "BranchManager"); } await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // 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); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); if (ModelState.IsValid) { db.Customers.Add(c); db.SaveChanges(); } return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async System.Threading.Tasks.Task <JsonResult> UserEdit(string value, string pk, string name) { try { var man = MembershipTools.NewUserManager(); var user = await man.FindByIdAsync(pk); PropertyInfo prop = null; foreach (PropertyInfo p in typeof(ApplicationUser).GetProperties()) { if (p.Name == name) { prop = p; p.SetValue(user, Convert.ChangeType(value, p.PropertyType)); } } Microsoft.AspNet.Identity.IdentityResult result = await man.UpdateAsync(user); if (result != Microsoft.AspNet.Identity.IdentityResult.Success) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(this.Json(new { message = result.Errors }, JsonRequestBehavior.AllowGet)); } } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(this.Json(new { message = ex }, JsonRequestBehavior.AllowGet)); } return(this.Json(new { success = true, }, JsonRequestBehavior.AllowGet)); }
// [ValidateAntiForgeryToken] public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; Microsoft.AspNet.Identity.IdentityResult result = null; try { var userTask = UserManager.CreateAsync(user, model.Password); result = await userTask; if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // 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); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } catch (Exception ex) { HttpContext.Trace.Write("UserManager.CreateAsync", ex.Message); AddErrors( IdentityResult.Failed(new string[] { "UserManager Error " + ex.Message })); } } // If we got this far, something failed, redisplay form return(View(model)); }