Exemplo n.º 1
0
        public async Task <ActionResult> Edit(string id, AccountEditModel model)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView("_Edit", model));
            }
            if (id != model.Id)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var account = await _accountDbCommand.FindAsync(model.Id);

            if (account == null)
            {
                return(HttpNotFound());
            }
            if (account.Owner != User.Identity.Name)
            {
                return(new HttpUnauthorizedResult());
            }

            Mapper.Map(model, account);

            account.LastModifiedUtcDateTime = DateTime.UtcNow;

            await _accountDbCommand.UpdateAsync(account.Id, account);

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
Exemplo n.º 2
0
        public ActionResult Edit(AccountEditModel model)
        {
            ViewBag.Role     = new SelectList(_roleService.GetAll(), "IdRole", "RoleName");
            ViewBag.IsInsert = false;
            model.IdRoles    = string.Join(",", model.SelectedValues);
            if (ModelState.IsValid)
            {
                var    entity = _mapper.Map <Account>(model);
                string error  = _accountService.Update(entity);

                if (error != null)
                {
                    ModelState.AddModelError(string.Empty, error);
                    return(View("Update", model));
                }

                return(RedirectToAction("Index"));
            }
            else
            {
                ModelState.AddModelError(string.Empty, LocalResources.Resource.CannotInsertData);
                ViewBag.AccountRole = model.IdRoles.Split(',').Select(o => int.Parse(o)).ToArray();
                return(View("Update", model));
            }
        }
        /// <summary>
        /// Initialize the Create form.
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            var accountModel = new AccountEditModel();

            PopulateDropDownLists(accountModel);

            return(View(accountModel));
        }
Exemplo n.º 4
0
 public void EditBankAccount(AccountEditModel model, string userId)
 {
     using (var httpClient = new HttpClientExtended())
     {
         var dto = AutoMapper.Mapper.Map <PersonalFinanceManager.DTOs.Account.AccountDetails>(model);
         httpClient.Put($"/BankAccount/Edit/{model.Id}/{userId}", dto);
     }
 }
Exemplo n.º 5
0
        public async Task <LoginResultStruct> LoginRequest(string account, string pwd)
        {
            LoginResultStruct result = new LoginResultStruct();

            result.loginResult = LoginResult.Ok;
            result.acc         = null;

            if (string.IsNullOrEmpty(account) || string.IsNullOrEmpty(pwd))
            {
                return(result);
            }
            account = account.ToLower();
            pwd     = pwd.ToLower();

            var acc = await context.Accounts.FirstOrDefaultAsync(d => d.Mail.ToLower() == account || d.Phone == account);

            if (acc != null)
            {
                var model = new AccountEditModel();
                model.Id             = acc.Id;
                model.Frozened       = acc.Frozened;
                model.ActivationTime = DataHelper.FormatDateTime(acc.ActivationTime);
                model.ExpireTime     = DataHelper.FormatDateTime(acc.ExpireTime);
                model.Password       = acc.Password;
                result.acc           = model;
            }

            if (result.acc == null)
            {
                result.loginResult = LoginResult.AccOrPasswordWrong;
            }
            else
            {
                if (result.acc.Frozened)
                {
                    result.loginResult = LoginResult.Frozen;
                }

                var now = DateTime.UtcNow;
                if (now < DataHelper.ParseDateTime(result.acc.ActivationTime).AddDays(-1))
                {
                    result.loginResult = LoginResult.NotActivation;
                }

                if (now > DataHelper.ParseDateTime(result.acc.ExpireTime))
                {
                    result.loginResult = LoginResult.Expired;
                }

                if (result.acc.Password != pwd)
                {
                    result.loginResult = LoginResult.AccOrPasswordWrong;
                }
            }


            return(result);
        }
        public ActionResult Edit(AccountEditModel accountEditModel)
        {
            if (ModelState.IsValid)
            {
                _bankAccountService.EditBankAccount(accountEditModel, User.Identity.GetUserId());

                return(RedirectToAction("Index"));
            }
            return(View(accountEditModel));
        }
Exemplo n.º 7
0
        public ActionResult DisplayInfo()
        {
            DatabaseAccess client = DatabaseAccess.Instance;
            var            result = client.GetUserInfo(SessionAccess.UserLogin);
            var            model  = new AccountEditModel {
                UserLogin = result.Item1, Status = result.Item2
            };

            return(View("EditAccountInfo", model));
        }
 /// <summary>
 /// Populate the list of currencies and banks for the Create / Edit form.
 /// </summary>
 /// <param name="accountModel"></param>
 private void PopulateDropDownLists(AccountEditModel accountModel)
 {
     accountModel.AvailableCurrencies = _currencyService.GetCurrencies().Select(x => new SelectListItem()
     {
         Value = x.Id.ToString(), Text = x.Name
     }).ToList();
     accountModel.AvailableBanks = _bankService.GetBanks().Select(x => new SelectListItem()
     {
         Value = x.Id.ToString(), Text = x.Name
     }).ToList();
 }
Exemplo n.º 9
0
        public AccountEditModel GetById(int id)
        {
            AccountEditModel result = null;

            using (var httpClient = new HttpClientExtended())
            {
                var response = httpClient.GetSingle <PersonalFinanceManager.DTOs.Account.AccountDetails>($"/BankAccount/Get/{id}");
                result = AutoMapper.Mapper.Map <AccountEditModel>(response);
            }
            return(result);
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Create(AccountEditModel model)
        {
            if (_accountService.Exist(model.Username))
            {
                ModelState.AddModelError("username", $"User '{model.Username}' already exist.");
                return(Conflict(ModelState));
            }

            await _accountService.CreateAsync(model.Username, model.Password);

            return(Ok());
        }
Exemplo n.º 11
0
        public ActionResult Index(AccountEditModel model)
        {
            var userId = Convert.ToInt64(_sessionManagementService.GetUserLoggedId());
            var user   = _userRepository.GetById(userId);

            if (model.Email != null)
            {
                user.Email = model.Email;
            }

            if (model.NewPassword != null)
            {
                if (user.CheckPassword(model.OldPassword))
                {
                    user.Password = model.NewPassword;
                    user.HashPassword();
                }
                else
                {
                    const string title   = "Error!";
                    const string content = "Contraseña Incorrecta.";
                    _viewMessageLogic.SetNewMessage(title, content, ViewMessageType.ErrorMessage);
                    return(View(model));
                }
            }

            try
            {
                if (model.UploadPhoto != null)
                {
                    using (var binaryReader = new BinaryReader(model.UploadPhoto.InputStream))
                    {
                        user.UserOwner.Photo = binaryReader.ReadBytes(model.UploadPhoto.ContentLength);
                    }
                }
            }
            catch (Exception)
            {
                const string title   = "Error!";
                const string content = "Formato de Imagen Incorrecto";
                _viewMessageLogic.SetNewMessage(title, content, ViewMessageType.ErrorMessage);
                return(View(model));
            }

            _userRepository.Update(user);
            const string title2   = "Usuario Actualizado";
            const string content2 = "El usuario ha sido actualizado exitosamente.";

            _viewMessageLogic.SetNewMessage(title2, content2, ViewMessageType.SuccessMessage);

            return(RedirectToAction("Index"));
        }
        public ActionResult Create(AccountEditModel accountEditModel)
        {
            if (ModelState.IsValid)
            {
                _bankAccountService.CreateBankAccount(accountEditModel, User.Identity.GetUserId());

                return(RedirectToAction("Index"));
            }

            PopulateDropDownLists(accountEditModel);

            return(View(accountEditModel));
        }
Exemplo n.º 13
0
        //
        // GET: /MyAccount/

        public ActionResult Index()
        {
            _viewMessageLogic.SetViewMessageIfExist();
            var userId         = Convert.ToInt64(_sessionManagementService.GetUserLoggedId());
            var user           = _userRepository.GetById(userId);
            var myaccountmodel = new AccountEditModel()
            {
                Id    = user.Id,
                Email = user.Email
            };

            return(View(myaccountmodel));
        }
Exemplo n.º 14
0
        public async Task EditPersonalAccountAsync(AccountEditModel personalAccount)
        {
            if (personalAccount == null)
            {
                throw new ArgumentNullException(nameof(personalAccount));
            }

            _dataProtectionService.Validate();
            await ValidateAccountNameAndLoginAsync(personalAccount.EmployeeId, personalAccount.Name, personalAccount.GetLogin(), personalAccount.Id);

            personalAccount.Urls = Validation.VerifyUrls(personalAccount.Urls);

            var employee = await GetEmployeeByIdAsync(personalAccount.EmployeeId);

            if (employee == null)
            {
                throw new HESException(HESCode.EmployeeNotFound);
            }

            var account = await _accountService.GetAccountByIdAsync(personalAccount.Id);

            if (account == null)
            {
                throw new HESException(HESCode.AccountNotFound);
            }

            account = personalAccount.SetNewValue(account);

            // Create tasks if there are vaults
            List <HardwareVaultTask> tasks = new List <HardwareVaultTask>();

            foreach (var vault in employee.HardwareVaults)
            {
                tasks.Add(_hardwareVaultTaskService.GetAccountUpdateTask(vault.Id, personalAccount.Id));
            }

            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                await _accountService.UpdateOnlyPropAsync(account, new string[] { nameof(Account.Name), nameof(Account.Login), nameof(Account.Urls), nameof(Account.Apps), nameof(Account.UpdatedAt) });

                if (tasks.Count > 0)
                {
                    await _hardwareVaultTaskService.AddRangeTasksAsync(tasks);

                    await _hardwareVaultService.UpdateNeedSyncAsync(employee.HardwareVaults, true);
                }

                transactionScope.Complete();
            }
        }
Exemplo n.º 15
0
        public async Task <ActionResult> EditAccount(AccountEditModel model)
        {
            var account = await AccountFacade.GetAccountAccordingToIdAsync(model.AccountId);

            account.FirstName         = model.FirstName;
            account.LastName          = model.LastName;
            account.Email             = model.Email;
            account.Password          = model.Password;
            account.Address           = model.Address;
            account.MobilePhoneNumber = model.MobilePhoneNumber;

            await AccountFacade.EditAccountAsync(account);

            return(RedirectToAction("AccountDetail", new { id = model.AccountId }));
        }
Exemplo n.º 16
0
        private void SetUserRoles(AccountEditModel model, ApplicationUser user, ApplicationDbContext database)
        {
            var userManager = Request.GetOwinContext().GetUserManager <ApplicationUserManager>();

            foreach (var role in model.Roles)
            {
                if (role.IsSelected)
                {
                    userManager.AddToRole(user.Id, role.Name);
                }
                else if (!role.IsSelected)
                {
                    userManager.RemoveFromRole(user.Id, role.Name);
                }
            }
        }
Exemplo n.º 17
0
        public virtual ActionResult Edit(AccountEditModel model)
        {
            if (model.EditingPassword)
            {
                if (!ModelState.IsValid)
                {
                    return(View(Mapper.Map <User, AccountEditModel>(User)));
                }

                if (!User.VerifyPassword(model.Password.ExistingPassword))
                {
                    ModelState.AddModelError("Password.ExistingPassword", "Invalid password.");
                    return(View(Mapper.Map <User, AccountEditModel>(User)));
                }

                User.ChangePasswordUsingExistingPassword(model.Password.ExistingPassword, model.Password.NewPassword);
                this.ValidateMappedModel <User, AccountEditModel>(User, ValidationTag.Required);
                if (!ModelState.IsValid)
                {
                    return(View(Mapper.Map <User, AccountEditModel>(User)));
                }

                Uow.Persist();
                TempData.SetAccountMessage("Your password has been changed");
                return(Redirect(HttpContext.GetDefaultReturnUrl()));
            }

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

                Mapper.Map(model.Details, User);
                this.ValidateMappedModel <User, AccountEditModel>(User, ValidationTag.Required);
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                Uow.Persist();
                TempData.SetAccountMessage("Your account has been saved");
                return(Redirect(HttpContext.GetDefaultReturnUrl()));
            }
            throw new NotImplementedException();
        }
Exemplo n.º 18
0
        public ActionResult Edit(string userId)
        {
            var user  = this.accountService.Get(a => a.SystemUserId == userId);
            var model = new AccountEditModel
            {
                SystemUserId = user.SystemUserId,
                RealName     = user.RealName,
                UserName     = user.UserName,
                Email        = user.Email,
                CreateTime   = user.CreateTime,
                UserType     = user.UserType,
                Mobile       = user.Mobile,
                Status       = user.Status
            };

            return(View(model));
        }
Exemplo n.º 19
0
        public async Task <IActionResult> Put([FromBody] AccountEditModel model)
        {
            var mapping = new Func <Account, Task <Account> >(async(entity) =>
            {
                if (!string.IsNullOrWhiteSpace(model.Name))
                {
                    entity.Name = model.Name;
                }
                if (!string.IsNullOrWhiteSpace(model.Description))
                {
                    entity.Description = model.Description;
                }
                if (!string.IsNullOrWhiteSpace(model.Password))
                {
                    entity.Password = Md5.CalcString(model.Password);
                }
                if (!string.IsNullOrWhiteSpace(model.ActivationTime))
                {
                    entity.ActivationTime = DataHelper.ParseDateTime(model.ActivationTime);
                }
                if (!string.IsNullOrWhiteSpace(model.ExpireTime))
                {
                    entity.ExpireTime = DataHelper.ParseDateTime(model.ExpireTime);
                }

                if (!string.IsNullOrWhiteSpace(model.DepartmentId))
                {
                    entity.DepartmentId = model.DepartmentId;
                }
                //else
                //{
                //    entity.DepartmentId = null;
                //    entity.Department = null;
                //}

                entity.Mail     = model.Mail;
                entity.Location = model.Location;
                entity.Phone    = model.Phone;

                entity.Type = await _GetAccountType(model.IsAdmin, model.Id);
                return(await Task.FromResult(entity));
            });

            return(await _PutRequest(model.Id, mapping));
        }
        public ActionResult Edit(AccountEditModel model)
        {
            if (ModelState.IsValid)
            {
                var user = db.Accounts.Where(u => u.Id == model.ID).SingleOrDefault();
                user.Email       = model.Email;
                user.FirstName   = model.FirstName;
                user.Surname     = model.Surname;
                user.PhoneNumber = model.Phone;
                user.AccountType = model.Type;
                db.Accounts.AddOrUpdate(user);
                db.SaveChanges();

                return(RedirectToAction("List", "Account"));
            }

            return(View(model));
        }
Exemplo n.º 21
0
        public ActionResult Edit(string id, AccountEditModel model)
        {
            if (ModelState.IsValid)
            {
                using (var database = new ApplicationDbContext())
                {
                    var user = database.Users.FirstOrDefault(u => u.Id == id);

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

                    if (!IsAuthorizedToEdit(user.Email))
                    {
                        return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
                    }

                    if (!string.IsNullOrEmpty(model.Password))
                    {
                        var hasher       = new PasswordHasher();
                        var passwordHash = hasher.HashPassword(model.Password);
                        user.PasswordHash = passwordHash;
                    }

                    user.Email       = model.Email;
                    user.Birthday    = model.Birthday;
                    user.FullName    = model.FullName;
                    user.Gender      = model.Gender;
                    user.PhoneNumber = model.PhoneNumber;
                    if (this.User.IsInRole("Admin"))
                    {
                        this.SetUserRoles(model, user, database);
                    }

                    database.Entry(user).State = System.Data.Entity.EntityState.Modified;
                    database.SaveChanges();

                    return(RedirectToAction("Details", "Account", new { @name = user.UserName }));
                }
            }

            return(View(model));
        }
Exemplo n.º 22
0
        public ActionResult AccountEditFormPartial(String Id)
        {
            ViewBag.Roles = RoleManager.Roles.ToList();
            if (Id != null)
            {
                ApplicationUser user = UserManager.FindById(Id);
                DevExpress.Web.TokenCollection tokencol = new DevExpress.Web.TokenCollection();

                foreach (Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole role in  user.Roles)
                {
                    tokencol.Add(role.RoleId);
                }

                AccountEditModel model = new AccountEditModel(user, RoleManager.Roles.ToList());

                return(PartialView("_AccountEditFormPartial", model ?? new AccountEditModel()));
            }
            return(PartialView("_AccountEditFormPartial", new AccountEditModel()));
        }
Exemplo n.º 23
0
        public async Task <IActionResult> EditAccount(string id, AccountEditModel accountDto)
        {
            if (id != accountDto.Id)
            {
                return(BadRequest());
            }

            try
            {
                await _employeeService.EditPersonalAccountAsync(accountDto);

                _remoteDeviceConnectionsService.StartUpdateHardwareVaultAccounts(await _employeeService.GetEmployeeVaultIdsAsync(accountDto.EmployeeId));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(StatusCode(500, new { error = ex.Message }));
            }

            return(NoContent());
        }
Exemplo n.º 24
0
        public async Task <ActionResult> Edit(int id, AccountEditModel model)
        {
            var account = await this.context.Accounts
                          .FirstOrDefaultAsync(x => x.Id == id);

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

            if (this.ModelState.IsValid)
            {
                account.LastName   = model.LastName;
                account.FirstName  = model.FirstName;
                account.MiddleName = model.MiddleName;
                account.BirthDate  = model.BirthDate;
                await this.context.SaveChangesAsync();

                return(NoContent());
            }

            return(BadRequest(this.ModelState));
        }
Exemplo n.º 25
0
 public bool UpdateAccount(AccountEditModel model)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 26
0
        public async Task <IActionResult> PutAccount(int id, AccountEditModel accountEditModel)
        {
            var account = _context.Accounts.Find(id);

            if (account == null)
            {
                return(NotFound());
            }
            String jwt = Request.Headers["Authorization"];

            jwt = jwt.Substring(7);
            //Decode jwt and get payload
            var stream    = jwt;
            var handler   = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadToken(stream);
            var tokenS    = jsonToken as JwtSecurityToken;
            //I can get Claims using:
            var email = tokenS.Claims.First(claim => claim.Type == "email").Value;

            if (account.Email != email)
            {
                return(BadRequest());
            }

            account.Name        = accountEditModel.Name;
            account.RoleId      = accountEditModel.RoleId;
            account.Phone       = accountEditModel.Phone;
            account.Tile        = accountEditModel.Tile;
            account.Description = accountEditModel.Description;
            account.Website     = accountEditModel.Website;
            account.SpecialtyId = accountEditModel.SpecialtyId;
            account.LevelId     = accountEditModel.LevelId;
            account.ProvinceId  = accountEditModel.ProvinceID;
            var arrSkillsRemove   = _context.FreelancerSkills.Where(p => p.FreelancerId == account.Id).ToArray();
            var arrServicesRemove = _context.FreelancerServices.Where(p => p.FreelancerId == account.Id).ToArray();

            _context.FreelancerServices.RemoveRange(arrServicesRemove);
            _context.FreelancerSkills.RemoveRange(arrSkillsRemove);
            await _context.SaveChangesAsync();

            foreach (var item in accountEditModel.Skills)
            {
                _context.FreelancerSkills.Add(new FreelancerSkill()
                {
                    FreelancerId = account.Id,
                    SkillId      = item.Id
                });
            }

            foreach (var item in accountEditModel.Services)
            {
                _context.FreelancerServices.Add(new FreelancerService()
                {
                    FreelancerId = account.Id,
                    ServiceId    = item.Id
                });
            }
            _context.Entry(account).State = EntityState.Modified;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AccountExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(Ok());
        }
Exemplo n.º 27
0
        public ActionResult Edit(int orgId, int accountId)
        {
            var currentOrg = DataSession.Single <Org>(orgId);

            if (currentOrg == null)
            {
                return(RedirectToAction("Index", new { orgId }));
            }

            var model = new AccountEditModel
            {
                AccountID  = accountId,
                CurrentOrg = currentOrg
            };

            var fundingSources = DataSession.Query <FundingSource>().OrderBy(x => x.FundingSourceName).ToList();

            model.FundingSources = fundingSources;

            var technicalFields = DataSession.Query <TechnicalField>().OrderBy(x => x.TechnicalFieldName).ToList();

            model.TechnicalFields = technicalFields;

            var specialTopics = DataSession.Query <SpecialTopic>().OrderBy(x => x.SpecialTopicName).ToList();

            model.SpecialTopics = specialTopics;

            Account acct = null;

            if (accountId > 0)
            {
                acct = DataSession.Single <Account>(accountId);

                if (acct == null && accountId > 0)
                {
                    return(RedirectToAction("Index", new { orgId }));
                }

                if (acct.Org.OrgID != orgId)
                {
                    return(RedirectToAction("Index", new { orgId }));
                }

                model.AccountName = acct.Name;
            }

            AccountEdit acctEdit;

            IAccount a = acct.CreateModel <IAccount>();
            IOrg     o = currentOrg.CreateModel <IOrg>();

            if (Session["AccountEdit"] == null)
            {
                InitAccountEdit(a, o);
            }
            else
            {
                acctEdit = (AccountEdit)Session["AccountEdit"];

                if (acctEdit.OrgID != currentOrg.OrgID || acctEdit.AccountID != accountId)
                {
                    InitAccountEdit(a, o);
                }
            }

            acctEdit = (AccountEdit)Session["AccountEdit"];

            model.AvailableManagers = AccountEditUtility.GetAvailableManagers(acctEdit);

            model.IsChartFieldOrg = AccountChartFields.IsChartFieldOrg(o);

            return(View(model));
        }
Exemplo n.º 28
0
        /// <summary>
        /// 账号及密码设置
        /// </summary>
        /// <returns></returns>
        public ActionResult AccountSetting()
        {
            var model = new AccountEditModel();

            return(View(model));
        }