コード例 #1
0
        public async Task <IActionResult> Manage(ManageViewModel vm)
        {
            if (vm.HasBranch)
            {
                vm.AllBranches = await _branchesDao.GetAllAsync();
            }
            if (vm.HasCar)
            {
                vm.AllCars = await _carsDao.GetAllAsync();
            }

            if (!ModelState.IsValid)
            {
                return(View(vm));
            }

            var user = new User
            {
                Id        = vm.UserId,
                UserName  = vm.UserName,
                Email     = vm.Email,
                FirstName = vm.FirstName,
                LastName  = vm.LastName
            };

            if (!await _usersDao.CheckPasswordAsync(user.Id, vm.Password))
            {
                ModelState.AddModelError(nameof(vm.Password), "Wrong password");
                return(View(vm));
            }

            try
            {
                await _usersDao.UpdateAsync(user);

                if (vm.HasBranch)
                {
                    if (!await _currentUserService.SetBranchAsync(vm.BranchId))
                    {
                        throw new Exception("Failed to set current branch");
                    }
                }

                if (vm.HasCar)
                {
                    if (!await _currentUserService.SetCarAsync(vm.CarId))
                    {
                        throw new Exception("Failed to set current car");
                    }
                }
            }
            catch (IdentityException e)
            {
                foreach (var error in e.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
            }

            return(View(vm));
        }