Esempio n. 1
0
        public async Task <IActionResult> Create(AppUserCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser
                {
                    UserName = model.Email,
                    Email    = model.Email,
                    FullName = model.FullName,
                };

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

                if (result.Succeeded)
                {
                    if (_signInManager.IsSignedIn(User) && User.IsInRole("Admin"))
                    {
                        return(RedirectToAction(nameof(Index)));
                    }
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            return(View(model));
        }
Esempio n. 2
0
        public async Task <IActionResult> Create(AppUserCreateViewModel vm)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser
                {
                    UserName  = vm.Email,
                    Email     = vm.Email,
                    FirstName = vm.FirstName,
                    LastName  = vm.LastName,
                    ChangedAt = DateTime.Now,
                    CreatedAt = DateTime.Now,
                    CreatedBy = _userManager.GetUserId(User),
                    ChangedBy = _userManager.GetUserId(User)
                };

                var result = await _userManager.CreateAsync(user, vm.Password);

                if (result.Succeeded)
                {
                    var errorList = new List <string?>()
                    {
                        vm.ScheduleManagement
                            ? await AddUserToRoleAsync(user, nameof(RoleNamesEnum.ScheduleSettingsAdmin))
                            : null,
                        vm.ScreenManagement
                            ? await AddUserToRoleAsync(user, nameof(RoleNamesEnum.ScreenSettingsAdmin))
                            : null,
                        vm.EventsManagement
                            ? await AddUserToRoleAsync(user, nameof(RoleNamesEnum.EventSettingsAdmin))
                            : null
                    };
                    if (errorList.TrueForAll(e => e == null))
                    {
                        var screen = await _bll.Screens.AllAsync();

                        // If there is only one screen!
                        var screens = screen.ToList();

                        if (screens.Count == 1)
                        {
                            await _bll.AppUsersScreens.AddAsync(new AppUsersScreen
                            {
                                CreatedAt = DateTime.Now,
                                CreatedBy = _userManager.GetUserId(User),
                                AppUserId = user.Id,
                                ScreenId  = screens.First().Id
                            });

                            await _bll.SaveChangesAsync();
                        }

                        var passwordCode = await _userManager.GeneratePasswordResetTokenAsync(user);

                        passwordCode = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(passwordCode));

                        var accountCode = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        accountCode = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(accountCode));

                        var callbackUrl = Url.Action(
                            "ActivateAccountAndResetPassword",
                            "Account",
                            new { Area = "", accountCode, passwordCode },
                            Request.Scheme);

                        var htmlMessageText = "<h4>Timeable registration notification!</h4>" +
                                              "<p>You have been registered to Timeable application! " +
                                              $"Your email can be verified by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking this link</a>.</p>";

                        await _emailSender.SendEmailAsync(
                            vm.Email,
                            "You have been registered to Timeable",
                            htmlMessageText);

                        return(RedirectToAction(nameof(Index)));
                    }

                    foreach (var error in errorList)
                    {
                        ModelState.AddModelError("UserAdditionFailed", error);
                    }
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("UserAdditionFailed", error.Description);
                }
            }

            return(View(vm));
        }
        public async Task <IActionResult> EditUser(AppUserCreateViewModel appUserCreateViewModel)
        {
            if (ModelState.IsValid) //如果验证通过
            {                       //通过接收的AppUserVM的邮件找到AppUser
                var user = await _userManager.FindByEmailAsync(appUserCreateViewModel.Email);

                //如果找到User
                if (user != null)
                {
                    //============更新AppUser前  先判定志愿者的,并且取到,变更前和变更后的  VId=============
                    //如果传进来的AppUserVM的VId不为空:即用户设定了新的Volunteer
                    if (appUserCreateViewModel.VolunteerId != null)
                    {
                        //通过AppUserVM的VId,找到志愿者, 赋值给 currentVolunteer
                        var currentVolunteer = await _context.Volunteer.FindAsync(appUserCreateViewModel.VolunteerId);

                        //通过AppUserVM的VId,如果找到志愿者
                        if (currentVolunteer != null)
                        {   //看是否有前任:如果AppUser之前的Vid(该AppUser的前任Volunteer) 不为空,
                            if (user.VolunteerId != null)
                            {
                                //找到 前任,还原为 未分配。
                                var previousVolunteer = await _context.Volunteer.FindAsync(user.VolunteerId);

                                if (previousVolunteer != null && previousVolunteer.IsAssignedUserAccount == true)
                                {
                                    previousVolunteer.IsAssignedUserAccount = false;
                                }
                            }
                            //新任志愿者  标记为 已分配
                            currentVolunteer.IsAssignedUserAccount = true;
                            await _context.SaveChangesAsync();
                        }
                    }
                    else//如果传进来的AppUser 的Vid 为空: 即用户不打算分配任何志愿者
                    {
                        //看是否有前任:如果AppUser之前的Vid(该AppUser的前任Volunteer) 不为空,
                        if (user.VolunteerId != null)
                        {
                            //找到 前任,还原为 未分配。
                            var previousVolunteer = await _context.Volunteer.FindAsync(user.VolunteerId);

                            if (previousVolunteer != null && previousVolunteer.IsAssignedUserAccount == true)
                            {
                                previousVolunteer.IsAssignedUserAccount = false;
                            }
                        }
                    }
                    //============更新AppUser前  先判定志愿者的选择状态,并且取到,变更前和变更后的  VId=============



                    user.AppRoleId   = appUserCreateViewModel.AppUserRoleId;
                    user.VolunteerId = appUserCreateViewModel.VolunteerId;

                    try
                    {
                        await _userManager.UpdateAsync(user);

                        await _context.SaveChangesAsync();

                        var role = await _roleManager.FindByIdAsync(appUserCreateViewModel.AppUserRoleId.ToString());

                        if (role != null)
                        {
                            var resultAddToRole = await _userManager.AddToRoleAsync(user, role.Name);//Add AppUser to role table

                            if (resultAddToRole.Succeeded)
                            {
                                return(RedirectToAction("Index"));
                            }
                        }
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        throw;
                    }
                    return(RedirectToAction("index"));
                }
            }//如果验证没通过 , 直接返回
            ViewData["Volunteers"]   = new SelectList(await _context.GetVolunteersForSelection(-1), "VId", "IdFullName", appUserCreateViewModel.VolunteerId);
            ViewData["AppUserRoles"] = new SelectList(await _roleManager.Roles.ToListAsync(), "Id", "Name", appUserCreateViewModel.AppUserRoleId);
            return(View(appUserCreateViewModel));
        }
        public async Task <IActionResult> CreateAppUser(AppUserCreateViewModel appUserCreateViewModel)
        {
            if (ModelState.IsValid)//If not valid, return that model
            {
                var user = new ApplicationUser();

                user.VolunteerId = appUserCreateViewModel.VolunteerId;
                user.AppRoleId   = appUserCreateViewModel.AppUserRoleId;
                user.UserName    = appUserCreateViewModel.Email;
                user.Email       = appUserCreateViewModel.Email;
                var resultPassword = await _userManager.CreateAsync(user, appUserCreateViewModel.Password);

                if (resultPassword.Succeeded)
                {
                    //通过AppUserVM的VId,找到志愿者, 赋值给 currentVolunteer
                    var Volunteer = await _context.Volunteer.FindAsync(appUserCreateViewModel.VolunteerId);

                    //通过AppUserVM的VId,如果找到志愿者
                    if (Volunteer != null)
                    {
                        //新任志愿者  标记为 已分配
                        Volunteer.IsAssignedUserAccount = true;
                        await _context.SaveChangesAsync();
                    }


                    if (appUserCreateViewModel.AppUserRoleId != null)
                    {
                        var role = await _roleManager.FindByIdAsync(appUserCreateViewModel.AppUserRoleId.ToString());

                        var resultAddToRole = await _userManager.AddToRoleAsync(user, role.Name);//Add AppUser to role table

                        if (resultAddToRole.Succeeded)
                        {
                            return(RedirectToAction("Index"));
                        }

                        foreach (var error in resultAddToRole.Errors)
                        {
                            ModelState.AddModelError(string.Empty, error.Description);
                        }
                        return(await ReturnToCreateGet());
                    }
                    return(RedirectToAction("Index"));
                }

                foreach (var error in resultPassword.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }


                // otherwise load all errors


                return(await ReturnToCreateGet());
            }

            return(await ReturnToCreateGet());

            async Task <IActionResult> ReturnToCreateGet()
            {
                ViewData["Volunteers"]   = new SelectList(await _context.GetVolunteersForSelection(-1), "VId", "IdFullName");
                ViewData["AppUserRoles"] = new SelectList(await _roleManager.Roles.ToListAsync(), "Id", "Name");
                return(View(appUserCreateViewModel));
            }
        }