public virtual async Task <ActionResult> Register(RegisterViewModel_ userViewModel) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = userViewModel.Email, Email = userViewModel.Email, EmailConfirmed = true, RegisterDate = DateTime.Now.Date, DateDisableUser = DateTime.Parse("2001/1/1") }; var publicresult = await _userManager.CreateAsync(user, userViewModel.Password); var result = await _userManager.AddToRoleAsync(user.Id, "public"); if (publicresult.Succeeded && result.Succeeded) { return(PartialView(viewName: MVC.admin.Shared.Views._alert, model: new AlertViewModel { Alert = AlertOperation.SurveyOperation(StatusOperation.SuccessCreateUser), Status = AlertMode.success })); } else { return(PartialView(viewName: MVC.admin.Shared.Views._alert, model: new AlertViewModel { Alert = AlertOperation.SurveyOperation(StatusOperation.FailCreateUser), Status = AlertMode.warning })); } } else { return(PartialView(viewName: MVC.admin.Shared.Views._alert, model: new AlertViewModel { Alert = AlertOperation.SurveyOperation(StatusOperation.InValidCreateUser), Status = AlertMode.warning })); } }
public async Task <ActionResult> Create() { //Create Role Admin if it does not exist var role = await _roleManager.FindByNameAsync(roleName); if (role == null) { role = new ApplicationRole { Name = roleName }; await _roleManager.CreateAsync(role); } var user = await _userManager.FindByNameAsync(name); if (user == null) { user = new AppUser { UserName = name, Email = name }; var createResult = await _userManager.CreateWithPasswordAsync(user, password); } else { await _userManager.SetLockoutEnabledAsync(user.Id, false); } // Add user admin to Role Admin if not already added var rolesForUser = await _userManager.GetRolesAsync(user.Id); if (!rolesForUser.Contains(role.Name)) { await _userManager.AddToRoleAsync(user.Id, role.Name); } return(Content("test")); }
public async Task <IActionResult> Register(RegisterViewModel viewModel) { if (ModelState.IsValid) { var user = new User { UserName = viewModel.UserName, Email = viewModel.Email, RegisterDateTime = DateTime.Now, IsActive = true, FirstName = "", LastName = "" }; IdentityResult result = await _userManager.CreateAsync(user, viewModel.Password); if (result.Succeeded) { var role = await _roleManager.FindByNameAsync("کاربر"); if (role == null) { await _roleManager.CreateAsync(new Role("کاربر")); } result = await _userManager.AddToRoleAsync(user, "کاربر"); if (result.Succeeded) { var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action("ConfirmEmail", "Account", values: new { userId = user.Id, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(viewModel.Email, "تایید حساب کاربری - سایت میزفا", $"<div dir='rtl' style='font-family:tahoma;font-size:14px'>لطفا با کلیک روی لینک رویه رو حساب کاربری خود را فعال کنید. <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>کلیک کنید</a></div>"); TempData["notification"] = $" ایمیل فعال سازی حساب کاربری به {viewModel.Email} ارسال شد. "; } } ModelState.AddErrorsFromResult(result); } return(PartialView("_Register")); }
public virtual async Task <ActionResult> Register(RegisterViewModel userViewModel, params string[] SelectedRoles) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = userViewModel.Email, Email = userViewModel.Email, RegisterDate = DateTime.Now, EmailConfirmed = true, DateDisableUser = DateTime.Parse("1/1/1") }; var adminresult = await _userManager.CreateAsync(user, userViewModel.Password); //Add User to the selected Roles if (adminresult.Succeeded) { if (SelectedRoles != null) { var result = await _userManager.AddToRolesAsync(user.Id, SelectedRoles); if (!result.Succeeded) { return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel { Alert = AlertOperation.SurveyOperation(StatusOperation.FailCreateUser), Status = AlertMode.warning })); } else { return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel { Alert = AlertOperation.SurveyOperation(StatusOperation.SuccessCreateUser), Status = AlertMode.success })); } } else { var result = await _userManager.AddToRoleAsync(user.Id, "public"); if (!result.Succeeded) { return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel { Alert = AlertOperation.SurveyOperation(StatusOperation.FailCreateUser), Status = AlertMode.warning })); } else { return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel { Alert = AlertOperation.SurveyOperation(StatusOperation.SuccessCreateUser), Status = AlertMode.success })); } } } else { // ViewBag.RoleId = new SelectList(_roleManager.Roles, "Name", "Name"); return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel { Alert = AlertOperation.SurveyOperation(StatusOperation.FailCreateUser), Status = AlertMode.warning })); } } else { //ViewBag.RoleId = new SelectList(_roleManager.Roles, "Name", "Name"); return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel { Alert = AlertOperation.SurveyOperation(StatusOperation.Invalid), Status = AlertMode.warning })); } }
public async Task <IdentityResult> SeedDatabaseWithAdminUserAsync() { var adminUserSeed = _adminUserSeedOptions.Value.AdminUserSeed; var name = adminUserSeed.Username; var password = adminUserSeed.Password; var email = adminUserSeed.Email; var roleName = adminUserSeed.RoleName; var thisMethodName = nameof(SeedDatabaseWithAdminUserAsync); var adminUser = await _applicationUserManager.FindByNameAsync(name); if (adminUser != null) { _logger.LogInformation($"{thisMethodName}: adminUser already exists."); return(IdentityResult.Success); } //Create the `Admin` Role if it does not exist var adminRole = await _roleManager.FindByNameAsync(roleName); if (adminRole == null) { adminRole = new ApplicationRole(roleName); var adminRoleResult = await _roleManager.CreateAsync(adminRole); if (adminRoleResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminRole CreateAsync failed. {adminRoleResult.DumpErrors()}"); return(IdentityResult.Failed()); } } else { _logger.LogInformation($"{thisMethodName}: adminRole already exists."); } adminUser = new ApplicationUser { UserName = name, Email = email, EmailConfirmed = true, LockoutEnabled = true, IsActive = true }; var adminUserResult = await _applicationUserManager.CreateAsync(adminUser, password); if (adminUserResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminUser CreateAsync failed. {adminUserResult.DumpErrors()}"); return(IdentityResult.Failed()); } var setLockoutResult = await _applicationUserManager.SetLockoutEnabledAsync(adminUser, enabled : false); if (setLockoutResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminUser SetLockoutEnabledAsync failed."); return(IdentityResult.Failed()); } var addToRoleResult = await _applicationUserManager.AddToRoleAsync(adminUser, adminRole.Name); if (addToRoleResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminUser AddToRoleAsync failed. {addToRoleResult.DumpErrors()}"); return(IdentityResult.Failed()); } return(IdentityResult.Success); }
public async Task <IActionResult> Index(RegisterViewModel model) { if (ModelState.IsValid) { var random = new Random(); var code = random.Next(1000, 9999); var user = new User { UserName = model.Username, Email = model.Username + "@mousigha.com", FirstName = model.FirstName, LastName = model.FirstName, PhoneNumber = model.PhoneNumber, PhoneNumberConfirmed = false, IsActive = false, EmailConfirmed = false, ActivationCode = code.ToString() }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "site-user"); _logger.LogInformation(3, $"{user.UserName} created a new account with password."); if (_siteOptions.Value.EnableEmailConfirmation) { var code1 = await _userManager.GenerateEmailConfirmationTokenAsync(user); //ControllerExtensions.ShortControllerName<RegisterController>(), //todo: use everywhere ................. await _emailSender.SendEmailAsync( email : user.Email, subject : "لطفا اکانت خود را تائید کنید", viewNameOrPath : "~/Areas/Identity/Views/EmailTemplates/_RegisterEmailConfirmation.cshtml", model : new RegisterEmailConfirmationViewModel { User = user, EmailConfirmationToken = code1, EmailSignature = _siteOptions.Value.Smtp.FromName, MessageDateTime = DateTime.UtcNow.ToLongPersianDateTimeString() }); return(RedirectToAction(nameof(ConfirmYourEmail))); } if (_siteOptions.Value.EnableMobileConfirmation) { var api = new Kavenegar.KavenegarApi("7768417353496E56316A5A6464754E516149704C753251465473515177587458"); var res = api.VerifyLookup(model.PhoneNumber, code.ToString(), "activation"); return(Json(new { id = user.Id, result = true, phone = user.PhoneNumber, username = user.UserName })); // return RedirectToAction(nameof(ConfirmYourMobile), new { id = user.Id }); } return(RedirectToAction(nameof(ConfirmedRegisteration))); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return(Content("Captcha")); }
public async Task <ApiResult <string> > CreateUser([FromBody] UserViewModelApi viewModel) { try { if (ModelState.IsValid) { IdentityResult result; AppUser user = new AppUser(); if (!string.IsNullOrWhiteSpace(viewModel.PersianBirthDate)) { viewModel.BirthDate = viewModel.PersianBirthDate.ConvertPersianToGeorgian(); } user.EmailConfirmed = true; user.UserName = viewModel.UserName; user.FirstName = viewModel.FirstName; user.LastName = viewModel.LastName; user.PasswordHash = viewModel.Password; user.Email = viewModel.Email; user.BirthDate = viewModel.BirthDate; user.PhoneNumber = viewModel.PhoneNumber; user.IsActive = true; //user.Image = viewModel.File != null ? viewModel.File.FileName : ""; if (viewModel.Gender != null) { user.Gender = viewModel.Gender.Value; } result = await _userManager.CreateAsync(user, viewModel.Password); if (result.Succeeded) { var role = await _roleManager.FindByIdAsync(viewModel.RoleId.ToString()); if (role != null) { await _userManager.AddToRoleAsync(user, role.Name); } } //if (result.Succeeded) //{ // logicResult.MessageType = MessageType.Success; // logicResult.Message.Add(NotificationMessages.CreateSuccess); //} //else //{ // logicResult.MessageType = MessageType.Error; // logicResult.Message.Add(result.DumpErrors()); //} } else { throw new AppException(ModelState.GetErrorsModelState()); } } catch (Exception e) { throw new AppException(e.Message); } return(Ok(NotificationMessages.CreateSuccess)); }
public async Task <IdentityResult> SeedDatabaseWithAdminUserAsync() { var name = "admin"; var password = "******"; var email = "*****@*****.**"; var roleName = "admin"; var thisMethodName = nameof(SeedDatabaseWithAdminUserAsync); var adminUser = await _applicationUserManager.FindByNameAsync(name); if (adminUser != null) { _logger.LogInformation($"{thisMethodName}: adminUser already exists."); var role = _roleManager.GetRoleByUserGuid(adminUser.Id); if (_env.IsDevelopment() && role != null) { await _roleManager.AddOrUpdateRoleClaims(role.Id, GlobalEnum.DynamicRole, _mvcActionsDiscoveryService.GetAllAdminActionRoute()); } await _uow.SaveChangesAsync(); return(IdentityResult.Success); } //Create the `Admin` Role if it does not exist var adminRole = await _roleManager.FindByNameAsync(roleName); if (adminRole == null) { adminRole = new Role(roleName); adminRole.Id = new Guid(); var adminRoleResult = await _roleManager.CreateAsync(adminRole); if (adminRoleResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminRole CreateAsync failed. {adminRoleResult.DumpErrors()}"); return(IdentityResult.Failed()); } else { // await _roleManager.AddOrUpdateRoleClaims(adminRole.Id, GlobalEnum.DynamicRole, _mvcControllerDiscovery.GetAllAdminActionRoute()); } } else { _logger.LogInformation($"{thisMethodName}: adminRole already exists."); } adminUser = new User { UserName = name, Email = email, EmailConfirmed = true, IsEmailPublic = true, LockoutEnabled = true }; var adminUserResult = await _applicationUserManager.CreateAsync(adminUser, password); if (adminUserResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminUser CreateAsync failed. {adminUserResult.DumpErrors()}"); return(IdentityResult.Failed()); } var setLockoutResult = await _applicationUserManager.SetLockoutEnabledAsync(adminUser, enabled : false); if (setLockoutResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminUser SetLockoutEnabledAsync failed. {setLockoutResult.DumpErrors()}"); return(IdentityResult.Failed()); } var addToRoleResult = await _applicationUserManager.AddToRoleAsync(adminUser, adminRole.Name); if (addToRoleResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminUser AddToRoleAsync failed. {addToRoleResult.DumpErrors()}"); return(IdentityResult.Failed()); } return(IdentityResult.Success); }
public async Task <IdentityResult> SeedDatabaseWithAdminUserAsync() { var adminUserSeed = _adminUserSeedOptions.Value.AdminUserSeed; var name = adminUserSeed.Username; var password = adminUserSeed.Password; var email = adminUserSeed.Email; var roleName = adminUserSeed.RoleName; var firstName = adminUserSeed.FirstName; var lastName = adminUserSeed.LastName; var thisMethodName = nameof(SeedDatabaseWithAdminUserAsync); var adminUser = await _applicationUserManager.FindByNameAsync(name); if (adminUser != null) { _logger.LogInformation($"{thisMethodName}: adminUser already exists."); return(IdentityResult.Success); } //Create the `Admin` Role if it does not exist var adminRole = await _roleManager.FindByNameAsync(roleName); if (adminRole == null) { adminRole = new AppRole(roleName); var adminRoleResult = await _roleManager.CreateAsync(adminRole); if (adminRoleResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminRole CreateAsync failed. {adminRoleResult.DumpErrors()}"); return(IdentityResult.Failed()); } } else { _logger.LogInformation($"{thisMethodName}: adminRole already exists."); } adminUser = new AppUser { UserName = name, Email = email, EmailConfirmed = true, LockoutEnabled = true, RegisterDateTime = DateTime.Now, FirstName = firstName, LastName = lastName, //Gender=null, IsActive = true }; var adminUserResult = await _applicationUserManager.CreateAsync(adminUser, password); if (adminUserResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminUser CreateAsync failed. {adminUserResult.DumpErrors()}"); return(IdentityResult.Failed()); } var setLockoutResult = await _applicationUserManager.SetLockoutEnabledAsync(adminUser, enabled : false); if (setLockoutResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminUser SetLockoutEnabledAsync failed."); return(IdentityResult.Failed()); } var addToRoleResult = await _applicationUserManager.AddToRoleAsync(adminUser, adminRole.Name); if (addToRoleResult == IdentityResult.Failed()) { _logger.LogError($"{thisMethodName}: adminUser AddToRoleAsync failed. {addToRoleResult.DumpErrors()}"); return(IdentityResult.Failed()); } ICollection <ControllerViewModel> securedControllerActions = _mvcActionsDiscovery.GetAllSecuredControllerActionsWithPolicy(ConstantPolicies.DynamicPermission); IList <string> allSecuredActions = securedControllerActions.SelectMany(s => s.MvcActions).ToList().Select(a => a.ActionId).ToList(); await _roleManager.AddOrUpdateClaimsAsync(adminRole.Id, ConstantPolicies.DynamicPermissionClaimType, allSecuredActions); return(IdentityResult.Success); }