Example #1
0
        public async Task <ActionResult> Create(UserCreateUpdateModel model)
        {
            if (ModelState.IsValid)
            {
                var checkingUser = await _userService.GetUserByUserNameAsync(model.UserName);

                if (checkingUser != null)
                {
                    return(RedirectToAction("List").WithError($"User with same username {model.UserName} alredy exists."));
                }

                var user = new User
                {
                    UserName      = model.UserName.ToLowerInvariant(),
                    FirstName     = model.FirstName,
                    LastName      = model.LastName,
                    Active        = model.Active,
                    LastLoginDate = _dateTime.Now,
                    CreatedBy     = _webUserSession.UserName,
                    CreatedOn     = _dateTime.Now,
                    ModifiedBy    = _webUserSession.UserName,
                    ModifiedOn    = _dateTime.Now
                };

                bool isDeveloper = _webUserSession.IsInRole(Constants.RoleNames.Developer);
                var  allRoles    = await _roleService.GetAllRoles();

                foreach (var role in allRoles)
                {
                    // Only developer can add developer role.
                    if (role.Name == Constants.RoleNames.Developer && !isDeveloper)
                    {
                        continue;
                    }

                    if (model.SelectedRoleIds.Any(r => r == role.Id))
                    {
                        user.Roles.Add(role);
                    }
                }
                await _userService.AddUserAsync(user);

                await _messageService.SendAddNewUserNotification(user);

                return(RedirectToAction("List").WithSuccess($"{user.FirstName}'s account was created successfully."));
            }

            // If we got this far, something failed, redisplay form
            model.AvailableRoleNames = await GetAvailableRoleNames();

            return(View("Create", model));
        }