Exemplo n.º 1
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = new ApplicationUser {
                UserName = model.Email, Email = model.Email
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                foreach (string error in result.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }
            var _user = await _userManager.FindByEmailAsync(model.Email);

            var _role = await _roleManager.FindByNameAsync(RolesList.User);

            var setRole = await _userManager.AddToRoleAsync(_user.Id, _role.Name);

            return(RedirectToAction("Login", "Account"));
        }
Exemplo n.º 2
0
        public async Task SetInitialDataAsync(User adminDto, List <string> roles)
        {
            foreach (var roleName in roles)
            {
                var role = await _roleManager.FindByNameAsync(roleName);

                if (role == null)
                {
                    role = new ApplicationRole {
                        Name = roleName
                    };
                    await _roleManager.CreateAsync(role);
                }
            }

            await CreateAsync(adminDto);
        }
Exemplo n.º 3
0
        public async Task CreateRoleAsync(RoleDTO role)
        {
            var existingRole = await _roleManager.FindByNameAsync(role.Name);

            if (existingRole == null)
            {
                IdentityRole roleToCreate = new IdentityRole {
                    Name = role.Name
                };
                await _roleManager.CreateAsync(roleToCreate);
            }

            else
            {
                throw new RoleException($"The role with name: {existingRole.Name} already exists!");
            }
        }
        private async Task <bool> CheckAndCreateRoleAsync(ApplicationRole role)
        {
            if ((await _roleManager.FindByNameAsync(role.Name)) == null)
            {
                var result = await _roleManager.CreateAsync(role);

                return(result.Succeeded);
            }
            return(true);
        }
        public async Task Add_ForRoleManager_ShouldAddRole_Test()
        {
            var roleManager = new ApplicationRoleManager(new RoleStore <IdentityRole>(MongoUtil <IdentityUser> .GetDefaultConnectionString()));
            var role        = "TestRole";


            await roleManager.CreateAsync(new IdentityRole(role));

            Assert.That(await roleManager.FindByNameAsync(role) != null);
        }
Exemplo n.º 6
0
        public async Task <RoleModel> GetRoleByNameAsync(string name)
        {
            var role = await _roleManager.FindByNameAsync(name);

            if (role == null)
            {
                throw new NotFoundException($"Could not locate entity with Id {name}");
            }

            return(_mapper.Map <RoleModel>(role));
        }
Exemplo n.º 7
0
        public async Task FirstDBInitializationAsync()
        {
            var userManager = new ApplicationUserManager(new ApplicationUserStore(this));
            var roleManager = new ApplicationRoleManager(new ApplicationRoleStore(this));

            try
            {
                //TODO: ошибка типа: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
                var testRole = await roleManager.FindByNameAsync(RoleTypeEnum.Administrator.ToString());

                if (testRole != null)
                {
                    return;
                }
            }
            catch
            {
            }

            #region Добавляем роли
            var roleAdmin = new ApplicationRole {
                Id = Guid.NewGuid(), Name = RoleTypeEnum.Administrator.ToString()
            };
            var roleUserApp = new ApplicationRole {
                Id = Guid.NewGuid(), Name = RoleTypeEnum.UserApp.ToString()
            };

            // добавляем роли в бд
            var res = await roleManager.CreateAsync(roleAdmin);

            var res2 = await roleManager.CreateAsync(roleUserApp);

            #endregion

            #region создаем пользователей
            ApplicationUser admin  = CreateUser("Бобров", "Олег", "Тимофеевич");
            var             result = await userManager.CreateAsync(admin, PasswordResource.Password_Default);

            ApplicationUser user = CreateUser("Иванов", "Иван", "Иванович");
            await userManager.CreateAsync(user, PasswordResource.Password_Default);

            //если создание пользователя прошло успешно
            if (result.Succeeded)
            {
                // добавляем для пользователя роль
                await userManager.AddToRolesAsync(admin.Id, new string[] { roleAdmin.Name, roleUserApp.Name });

                await userManager.AddToRoleAsync(user.Id, roleUserApp.Name);
            }
            #endregion

            SaveChanges();
        }
Exemplo n.º 8
0
        public async Task <ICollection <UserDTO> > GetAll()
        {
            var users = await userManager.Users.Include(x => x.Roles).ToListAsync();

            List <UserDTO> userDTOs = Mapper.Map <List <User>, List <UserDTO> >(users);

            foreach (var item in userDTOs)
            {
                var            rolesName = userManager.GetRoles(item.Id);
                List <RoleDTO> roles     = new List <RoleDTO>();
                foreach (var roleIter in rolesName)
                {
                    var role = await roleManager.FindByNameAsync(roleIter);

                    var roleDto = Mapper.Map <Role, RoleDTO>(role);
                    roles.Add(roleDto);
                }
                item.Roles = roles;
            }
            return(userDTOs);
        }
        public async Task <List <AccountDto> > GetAccounts()
        {
            UserRole employrole = await _roleManager.FindByNameAsync("Employee");

            return
                (await
                 Task.FromResult(
                     UserManager.Users.Where(u => u.Roles.Select(r => r.RoleId).Contains(employrole.Id))
                     .OrderBy(u => u.LastName)
                     .Select(AccountDto.MapDto)
                     .ToList()));
        }
Exemplo n.º 10
0
        public async Task <ActionResult> Index(string roleName = "User", int page = 1, int pageSize = 10)
        {
            var role = await RoleManager.FindByNameAsync(roleName);

            var profiles = await _profileSuperAdminService.GetProfilesByRoleIdAsync(role.Id, page, pageSize);

            var model = new IndexViewModel
            {
                Role     = roleName,
                PageInfo = profiles,
                Profiles = profiles.Results
            };

            return(View(model));
        }
Exemplo n.º 11
0
        public async Task <ActionResult> DeleteRole_POST(DeleteRoleViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var role = await RoleManager.FindByNameAsync(model.Role);

            if (role == null)
            {
                ModelState.AddModelError("Role",
                                         $"The role '{model.Role}' does not exist!");
            }
            else
            {
                await RoleManager.DeleteAsync(role);

                TempData["Message"] = $"Role '{model.Role}' deleted successfully!";
                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Exemplo n.º 12
0
        public async Task <RoleModel> AddRoleAsync(ApplicationRoleManager roleManager, RoleModel role)
        {
            ApplicationRole newRole = new ApplicationRole()
            {
                Description = role.Description,
                Level       = role.Level,
                Name        = role.Name
            };

            await roleManager.CreateAsync(newRole);

            newRole = await roleManager.FindByNameAsync(role.Name);

            role.Id = newRole.Id;
            return(role);
        }
Exemplo n.º 13
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (!await RoleManager.RoleExistsAsync("Users"))
                {
                    var roleResult = await RoleManager.CreateAsync(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole("Users"));

                    if (!roleResult.Succeeded)
                    {
                        AddErrors(roleResult);
                        return(View(model));
                    }
                }
                var role = await RoleManager.FindByNameAsync("Users");

                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);



                if (result.Succeeded)
                {
                    result = await UserManager.AddToRoleAsync(user.Id, "Users");

                    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);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 14
0
        public async Task<IdentityResult> DeleteRole(JObject deleteRole)
        {
            string roleName = ((dynamic)deleteRole).Name.Value;
            string roleId = ((dynamic)deleteRole).Id.Value;

            IdentityResult result = null;
            var roleStore = new RoleStore<IdentityRole>(_contextProvider.Context);
            var roleManager = new ApplicationRoleManager(roleStore);

            var role = await roleManager.FindByNameAsync(roleName);
            //var role = await roleManager.FindByIdAsync(roleId);
            if (role != null)
            {
                result = await roleManager.DeleteAsync(role);
            }

            return result;
        }
Exemplo n.º 15
0
        public async Task AddAdminAndRoles(ApplicationContext context, List <string> roles)
        {
            ApplicationRoleManager roleManager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));

            foreach (string roleName in roles)
            {
                var role = await roleManager.FindByNameAsync(roleName);

                if (role == null)
                {
                    role = new ApplicationRole {
                        Name = roleName
                    };
                    await roleManager.CreateAsync(role);
                }
            }
            await CreateAdmin(context);
        }
Exemplo n.º 16
0
        public async Task <IActionResult> GetUserRoles(int id)
        {
            ApplicationUser user = await usermanager.FindByIdAsync(id.ToString());

            if (user == null)
            {
                return(NotFound());
            }

            List <ApplicationRole> roles     = new List <ApplicationRole>();
            IList <string>         rolenames = await usermanager.GetRolesAsync(user);

            foreach (string rolename in rolenames)
            {
                roles.Add(await rolemanager.FindByNameAsync(rolename));
            }

            return(Ok(roles));
        }
Exemplo n.º 17
0
        public async Task <RoleResponseResult> Create([FromBody] ApplicationRole role)
        {
            return(await this._roleManager.CreateAsync(role)
                   .ContinueWith <RoleResponseResult>((r) =>
            {
                if (r.IsCompleted && !r.IsFaulted && r.Result.Succeeded)
                {
                    var result2 = _roleManager.FindByNameAsync(role.Name);
                    result2.Wait();

                    return new RoleResponseResult()
                    {
                        Code = 200,
                        Data = result2.Result
                    };
                }
                else if (r.IsFaulted)
                {
                    return new RoleResponseResult()
                    {
                        Code = 400,
                        Message = r.Exception?.Message,
                    };
                }
                else if (!r.Result.Succeeded)
                {
                    return new RoleResponseResult()
                    {
                        Code = (int)System.Net.HttpStatusCode.ExpectationFailed,
                        Message = r.Result.Errors?.FirstOrDefault()?.Description
                    };
                }

                return new RoleResponseResult()
                {
                    Code = 200
                };                                                 //, Data = r.Result };
            }));
        }
Exemplo n.º 18
0
        public bool Add(RoleDTO roleDto)
        {
            try
            {
                var checkNameExits = _roleManager.FindByNameAsync(roleDto.Name);
                if (checkNameExits.Result != null)
                {
                    return(false);
                }
                var role = _mapper.Map <Role>(roleDto);
                role.CreatedBy   = GetCurrentUserId();
                role.CreatedDate = DateTime.Now;

                _roleRepository.Insert(role);
                _unitOfWork.Commit();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public async Task <IActionResult> RegisterWithPassword([FromBody] RegistrationWithPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Tries to map the model to an object of type ApplicationUser
            var userIdentity = _mapper.Map <ApplicationUser>(model);

            // Verify the role the user is attempted added to exists
            var role = await _roleManager.FindByNameAsync(model.RoleName);

            if (role == null)
            {
                return(BadRequest($"The role \"{model.RoleName}\" does not exist! User not created."));
            }

            // Validate user and try to create new user with given password in the backing store
            var result = await _userManager.CreateAsync(userIdentity, model.Password);

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState)));
            }

            // Add the user to the specified role
            result = await _userManager.AddToRoleAsync(userIdentity, model.RoleName);

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState)));
            }

            return(new OkObjectResult("Account created"));
        }
Exemplo n.º 20
0
 public async Task <IdentityRole> FindByNameAsync(string roleName)
 {
     return(await _appRoleManager.FindByNameAsync(roleName));
 }
Exemplo n.º 21
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                int?tenantId = null;

                if (Input.SelectedTenantId != null)
                {
                    tenantId = Input.SelectedTenantId;

                    Input.IsAdmin = false;
                }

                var user = new IzendaUser
                {
                    UserName = Input.UserID,
                    Email    = Input.UserID,
                    TenantId = tenantId,
                };

                var result = await _userManager.CreateAsync(user);                                                  // Save new user into client DB

                if (result.Succeeded)                                                                               // if successful, then start creating a user at Izenda DB
                {
                    var assignedRole = !string.IsNullOrEmpty(Input.SelectedRole) ? Input.SelectedRole : "Employee"; // set default role if required. As an example, Employee is set by default

                    var isRoleExisting = _roleManager.FindByNameAsync(assignedRole);                                // check assigned role exist in client DB. if not, assigned role is null

                    if (isRoleExisting == null)
                    {
                        try
                        {
                            await _roleManager.CreateAsync(new Microsoft.AspNetCore.Identity.IdentityRole(assignedRole));

                            result = await _userManager.AddToRoleAsync(user, assignedRole);
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e);
                        }
                    }
                    else
                    {
                        result = await _userManager.AddToRoleAsync(user, assignedRole);
                    }

                    if (result.Succeeded)
                    {
                        var izendaAdminAuthToken = IzendaTokenAuthorization.GetIzendaAdminToken();
                        user.Tenant = _tenantManager.GetTenantById(Input.SelectedTenantId); // set client DB application user's tenant
                        var tenantName = user.Tenant?.Name ?? null;

                        // Create a new user at Izenda DB
                        var success = await IzendaUtilities.CreateIzendaUser(
                            tenantName,
                            Input.UserID,
                            Input.LastName,
                            Input.FirstName,
                            Input.IsAdmin,
                            assignedRole,
                            izendaAdminAuthToken);

                        if (success)
                        {
                            return(LocalRedirect(returnUrl));
                        }
                    }
                    ModelState.AddModelError(string.Empty, "Failed to create a new user. User already exists in DB.");
                    return(Page());
                }
            }
            ModelState.AddModelError(string.Empty, "Failed to create a new user. Invalid model.");
            return(Page());
        }
Exemplo n.º 22
0
 public async Task <ApplicationRole> FindByNameAsync(string roleName)
 {
     return(await _roleManager.FindByNameAsync(roleName));
 }
Exemplo n.º 23
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = await UserManager.FindByNameAsync(model.Email);

            if (user != null && user.Disabled == true)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[Your username is disabled, please contact the administrator.]]]";
                return(RedirectToAction("Login", "Account"));
            }
            // Require the user to have a confirmed email before they can log on.
            //if (!CacheHelper.Settings.EmailConfirmedRequired)
            //{
            //	var user = await UserManager.FindByNameAsync(model.Email);
            //             if (user != null)
            //             {
            //                 var roleAdministrator = await RoleManager.FindByNameAsync(Enum_UserType.Administrator.ToString());
            //                 var isAdministrator = user.Roles.Any(x => x.RoleId == roleAdministrator.Id);

            //		Skip email check unless it's an administrator
            //                 if (!isAdministrator && !await UserManager.IsEmailConfirmedAsync(user.Id))
            //		{
            //			ModelState.AddModelError("", "[[[You must have a confirmed email to log on.]]]");
            //			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);

            {
                var casa = "go";
            }
            switch (result)
            {
            case SignInStatus.Success:
                if (string.IsNullOrEmpty(returnUrl))
                {
                    var administrator = await RoleManager.FindByNameAsync(Enum_UserType.Administrator.ToString());

                    var isAdministrator = user.Roles.Any(x => x.RoleId == administrator.Id);
                    var owner           = await RoleManager.FindByNameAsync(Enum_UserType.Owner.ToString());

                    var isOwner = user.Roles.Any(x => x.RoleId == owner.Id);
                    if (isAdministrator)
                    {
                        return(RedirectToAction("Index", "Manage", new { area = "Admin" }));
                    }
                    if (isOwner)
                    {
                        return(RedirectToAction("Index", "Manage"));
                    }
                    if (!isOwner && !isAdministrator)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }

                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.º 24
0
 public Task <IdentityRole> GetRole(string role)
 {
     return(_applicationRoleManager.FindByNameAsync(role));
 }
Exemplo n.º 25
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var tenant = !string.IsNullOrWhiteSpace(model.Tenant) ? new Tenant {
                    Name = model.Tenant
                } : null;
                var tenantManager = new Managers.TenantManager();
                var exstingTenant = tenantManager.GetTenantByName(model.Tenant);

                if (exstingTenant != null)
                {
                    tenant = exstingTenant;
                }
                else
                {
                    tenant = tenant != null ? await tenantManager.SaveTenantAsync(tenant) : null;
                }

                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, Tenant_Id = tenant != null ? (int?)tenant.Id : null
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                //If role = "Employee" => add user to this role

                string assignedRole   = "Employee";
                string assignedRoleId = "";

                if (RoleManager.RoleExists(assignedRole))
                {
                    result = await UserManager.AddToRoleAsync(user.Id, assignedRole);

                    assignedRoleId = (RoleManager.FindByNameAsync(assignedRole)).Result.Id;
                }
                else
                {
                    assignedRole = null;
                }
                if (result.Succeeded)
                {
                    user.Tenant = tenant;

                    ////izenda
                    var izendaAdminAuthToken = IzendaBoundary.IzendaTokenAuthorization.GetIzendaAdminToken();

                    if (tenant != null)
                    {
                        await IzendaBoundary.IzendaUtilities.CreateTenant(tenant.Name, izendaAdminAuthToken);
                    }

                    //CreateUser is Deprecated in favor of CreateIzendaUser
                    //await IzendaBoundary.IzendaUtilities.CreateUser(user, assignedRole, izendaAdminAuthToken);
                    await IzendaBoundary.IzendaUtilities.CreateIzendaUser(user, assignedRoleId, izendaAdminAuthToken);

                    /// end izenda


                    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);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 26
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                IdentityRole irs = await _roleManager.FindByNameAsync("supplier");

                IdentityRole supplierRole = new IdentityRole("supplier");
                IdentityRole irw          = await _roleManager.FindByNameAsync("wholesaler");

                IdentityRole wholesalerRole = new IdentityRole("wholesaler");

                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (model.Role == "Supplier")
                {
                    if (irs == null)
                    {
                        await _roleManager.CreateAsync(supplierRole);
                    }
                    createSupplier(model.Location, model.CompanyName, model.Email, model.Phone, model.Name);
                    await _userManager.AddToRoleAsync(user, "supplier");
                }
                else if (model.Role == "Wholesaler")
                {
                    if (irw == null)
                    {
                        await _roleManager.CreateAsync(wholesalerRole);
                    }
                    createWholesaler(model.Location, model.Name, model.Email, model.Phone);
                    await _userManager.AddToRoleAsync(user, "wholesaler");
                }
                else if (model.Role == "Both")
                {
                    createSupplier(model.Location, model.CompanyName, model.Email, model.Phone, model.Name);
                    createWholesaler(model.Location, model.Name, model.Email, model.Phone);
                    await _userManager.AddToRoleAsync(user, "wholesaler");

                    await _userManager.AddToRoleAsync(user, "supplier");
                }


                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                    //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                    //await _userManager.AddToRoleAsync(user, "admin");
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation(3, "User created a new account with password.");

                    if (model.Role == "Supplier" || model.Role == "Both")
                    {
                        return(RedirectToAction("authen", new { returnUrl = "/Supplier/SupplierEdit" }));
                    }
                    //return RedirectToAction("Index", "Supplier");
                    else
                    {
                        return(RedirectToAction("authen", new { returnUrl = "/Wholesaler/Account" }));
                    }
                    //return RedirectToAction("Index", "Wholesaler");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 27
0
        public async Task <IEnumerable <ApplicationUserRole> > GetAllUserAsync(string name)
        {
            var users = await _manager.FindByNameAsync(name);

            return(users.Users);
        }
Exemplo n.º 28
0
        public async Task <ActionResult> Edit([Bind(Include = "Id")] ApplicationUser applicationUser, params string[] rolesSelectedOnView)
        {
            if (ModelState.IsValid)
            {
                // If the user is currently stored having the Admin role,
                var rolesCurrentlyPersistedForUser = await UserManager.GetRolesAsync(applicationUser.Id);

                bool isThisUserAnAdmin = rolesCurrentlyPersistedForUser.Contains("Admin");

                // and the user did not have the Admin role checked,
                rolesSelectedOnView = rolesSelectedOnView ?? new string[] { };
                bool isThisUserAdminDeselected = !rolesSelectedOnView.Contains("Admin");

                // and the current stored count of users with the Admin role == 1,
                var role = await RoleManager.FindByNameAsync("Admin");

                bool isOnlyOneUserAnAdmin = role.Users.Count == 1;

                // (populate the roles list in case we have to return to the Edit view)
                applicationUser = await UserManager.FindByIdAsync(applicationUser.Id);

                applicationUser.RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
                {
                    Selected = rolesCurrentlyPersistedForUser.Contains(x.Name),
                    Text     = x.Name,
                    Value    = x.Name
                });

                // then prevent the removal of the Admin role.
                if (isThisUserAnAdmin && isThisUserAdminDeselected && isOnlyOneUserAnAdmin)
                {
                    ModelState.AddModelError("", "At least one user must retain the Admin role; you are attempting to delete the Admin role from the last user who has been assigned to it.");
                    return(View(applicationUser));
                }

                var result = await UserManager.AddToRolesAsync(
                    applicationUser.Id,
                    rolesSelectedOnView.Except(rolesCurrentlyPersistedForUser).ToArray());

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return(View(applicationUser));
                }

                result = await UserManager.RemoveFromRolesAsync(
                    applicationUser.Id,
                    rolesCurrentlyPersistedForUser.Except(rolesSelectedOnView).ToArray());

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return(View(applicationUser));
                }

                return(RedirectToAction("Index"));
            }

            ModelState.AddModelError("", "Something failed.");
            return(View(applicationUser));
        }
Exemplo n.º 29
0
        public async Task <IdentityResult> RegisterAccount(RegisterViewModel model)
        {
            var user = new ApplicationUser
            {
                UserName       = model.Email,
                Email          = model.Email,
                FirstName      = model.FirstName,
                LastName       = model.LastName,
                RegisterDate   = DateTime.Now,
                RegisterIP     = System.Web.HttpContext.Current.Request.GetVisitorIP(),
                LastAccessDate = DateTime.Now,
                LastAccessIP   = System.Web.HttpContext.Current.Request.GetVisitorIP()
            };

            var result = await UserManager.CreateAsync(user, model.Password);

            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>");

                // Send Message
                var roleAdministrator = await RoleManager.FindByNameAsync(BeYourMarket.Model.Enum.Enum_UserType.Administrator.ToString());

                var administrator = roleAdministrator.Users.FirstOrDefault();

                var message = new MessageSendModel()
                {
                    UserFrom = administrator.UserId,
                    UserTo   = user.Id,
                    Subject  = HttpContext.ParseAndTranslate(string.Format("[[[Welcome to {0}!]]]", CacheHelper.Settings.Name)),
                    Body     = HttpContext.ParseAndTranslate(string.Format("[[[Hi, Welcome to {0}! I am happy to assist you if you has any questions.]]]", CacheHelper.Settings.Name))
                };

                await MessageHelper.SendMessage(message);

                // Send an email with this link
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                var urlHelper   = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
                var callbackUrl = urlHelper.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: System.Web.HttpContext.Current.Request.Url.Scheme);

                var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "signup").SelectAsync();

                var emailTemplate = emailTemplateQuery.FirstOrDefault();

                if (emailTemplate != null)
                {
                    dynamic email = new Postal.Email("Email");
                    email.To          = CacheHelper.Settings.EmailContact;
                    email.From        = CacheHelper.Settings.EmailContact;
                    email.Subject     = emailTemplate.Subject;
                    email.Body        = emailTemplate.Body;
                    email.CallbackUrl = callbackUrl;
                    EmailHelper.SendEmail(email);
                }
            }

            return(result);
        }