Пример #1
0
        /// <summary>
        /// Редактирование таблици PLATFORM_USER.
        /// </summary>
        /// <param name="userModelData">Уникальный идентификатор всегда прежний, вся остальныя информация может меняться</param>
        /// <returns>Результат выполнения опрерации</returns>
        /// <remarks>Тестируется</remarks>
        public bool EditUserInfo(AccountUserModel userModelData)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(x => x.ID == userModelData.UserId);

                    if (user == null)
                    {
                        return(false);
                    }
                    user.Name        = userModelData.UserName;
                    user.Surname     = userModelData.UserSurname;
                    user.Patronym    = userModelData.UserPatronym;
                    user.Description = userModelData.UserDescription;
                    user.Email       = userModelData.UserEmail;
                    user.Login       = userModelData.UserLogin;
                    user.Password    = userModelData.UserPassword;
                    user.Phone1      = userModelData.UserPhone1;
                    user.Phone2      = userModelData.UserPhone2;
                    user.RoleMask    = (int)userModelData.UserRoleMask;

                    ctx.SaveChanges();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(String.Format("Не удалось сохранить изменения данных пользователе {0}", userModelData.UserId), ex);
            }
            return(false);
        }
        public ActionResult OwnerDetails(AccountUserModel upDateOwner)
        {
            var result = userRepository.EditUserInfo(upDateOwner) ?
                         string.Format("{0} (#{1}).", Resource.MessageEditingMade, upDateOwner.UserLogin) :
                         string.Format("{0} ({1} #{2}).", Resource.ErrorMessageSaveDataChanges, Resource.TitleUser, upDateOwner.UserLogin);

            return(RedirectToAction("Accounts", new { message = result }));
        }
        public IActionResult GetMainAccountView()
        {
            AccountUserModel userAccountModel = new AccountUserModel();

            SetLoggedUserForAccountUserModel(userAccountModel);
            SetLoggedUserInfoArticles(userAccountModel);

            return(View("AccountGeneral", userAccountModel));
        }
        private void SetLoggedUserInfoArticles(AccountUserModel userAccountModel)
        {
            long lUserId = -1;
            IEnumerable <UserArticles> userArticlesList = null;

            if (userAccountModel != null &&
                long.TryParse(TokenProvider.GetRegisterUserPropertyString(User.Identity, UserTools.USER_ID_PROPERTY_STRING), out lUserId))
            {
                userArticlesList = _repositoryWrapper.UserArticles.GetUserArticles(lUserId);
                userAccountModel.iAmountOfArticles = userArticlesList.Count();
            }
        }
        private void SetLoggedUserForAccountUserModel(AccountUserModel userAccountModel)
        {
            long lUserId    = -1;
            User loggedUser = null;

            if (userAccountModel != null &&
                long.TryParse(TokenProvider.GetRegisterUserPropertyString(User.Identity, UserTools.USER_ID_PROPERTY_STRING), out lUserId))
            {
                loggedUser          = _repositoryWrapper.Account.GetUser(lUserId);
                loggedUser.Password = string.Empty;
                loggedUser.Id       = -1;

                userAccountModel.User = loggedUser;
            }
        }
Пример #6
0
        public IHttpActionResult UpdateAccount(int accountId, AccountUserModel accountModel)
        {
            var account = _accountService.GetAccountUserById(accountId);

            if (account == null || account.Deleted)
            {
                return(NotFound());
            }
            account = accountModel.ToEntity(account);

            var registerRole = _accountService.GetAccountUserRoleBySystemName(SystemAccountUserRoleNames.Registered);

            account.AccountUserRoles.Clear();

            var role = _accountService.GetAccountUserRoleBySystemName(accountModel.RoleName);

            if (role != null && accountModel.RoleName != SystemAccountUserRoleNames.Registered)
            {
                account.AccountUserRoles.Add(role);
            }
            account.AccountUserRoles.Add(registerRole);

            if (accountModel.InitPassword)
            {
                account.Password = "******";                             //设置初始密码
            }
            //单位更新
            if (accountModel.GovernmentId != account.Government.Id)
            {
                var governament = _governmentService.GetGovernmentUnitById(accountModel.GovernmentId);
                if (governament == null)
                {
                    return(BadRequest("用户所属单位不存在"));
                }
                account.Government = governament;
            }

            //保存用户
            _accountService.UpdateAccountUser(account);

            //activity log
            _accountUserActivityService.InsertActivity("UpdateAccount", "更新 名为 {0} 的用户的基本信息", account.UserName);

            //SuccessNotification(_localizationService.GetResource("Admin.Catalog.Categories.Added"));

            return(Ok(account.ToModel()));
        }
Пример #7
0
        public IHttpActionResult Create(AccountUserModel accountModel)
        {
            var account = accountModel.ToEntity();

            //问题: An entity object cannot be referenced by multiple instances of IEntityChangeTracker
            //状态:Fixed
            //原因:不明,但是应该和缓存机制有关
            var government = _governmentService.GetGovernmentUnitById(accountModel.GovernmentId);

            if (government == null)
            {
                return(BadRequest("用户所属单位不存在"));
            }
            account.Government = government;

            var registerRole = _accountService.GetAccountUserRoleBySystemName(SystemAccountUserRoleNames.Registered);
            var adminRole    = _accountService.GetAccountUserRoleBySystemName(SystemAccountUserRoleNames.Administrators);

            account.Password = "******";  //设置初始密码

            var role = _accountService.GetAccountUserRoleBySystemName(accountModel.RoleName);

            if (role != null && accountModel.RoleName != SystemAccountUserRoleNames.Registered)
            {
                account.AccountUserRoles.Add(role);
            }

            var registrationRequest = new AccountUserRegistrationRequest(account, account.UserName,
                                                                         account.Password, _accountUserSettings.DefaultPasswordFormat, accountModel.Active);

            var registrationResult = _accountUserRegistrationService.RegisterAccountUser(registrationRequest);

            if (registrationResult.Success)
            {
                //保存用户
                _accountService.InsertAccountUser(account);

                //activity log
                _accountUserActivityService.InsertActivity("AddNewAccount", "增加 名为 {0} 的用户", account.UserName);

                return(Ok(account.ToModel()));
            }
            else
            {
                return(BadRequest("添加用户失败"));
            }
        }
Пример #8
0
        public IActionResult Index(string username, string password)
        {
            if (string.IsNullOrEmpty(username))
            {
                return(Json(new { status = 0, msg = "请输入用户名" }));
            }
            if (string.IsNullOrEmpty(password))
            {
                return(Json(new { status = 0, msg = "请输入密码!" }));
            }
            var _Account_User = _account_UserService.FindByClause(p => p.Account_Name == username);

            if (_Account_User == null)
            {
                return(Json(new { status = 0, msg = "账号不存在!" }));
            }
            if (_Account_User.Account_Pwd.ToStr().Trim() != Tools.MD5Encryption(password))
            {
                return(Json(new { status = 0, msg = "密码错误!" }));
            }
            var claim = new Claim[] {
                new Claim("ID", _Account_User.Account_Uid.ToStr()),
                new Claim("UserName", _Account_User.Account_Name)
            };
            //对称秘钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
            //签名证书(秘钥,加密算法)
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //生成token  [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包,并引用System.IdentityModel.Tokens.Jwt命名空间
            var    token  = new JwtSecurityToken(_jwtSettings.Issuer, _jwtSettings.Audience, claim, DateTime.Now, DateTime.Now.AddHours(2), creds);
            string tokens = new JwtSecurityTokenHandler().WriteToken(token);

            HttpContext.Response.Cookies.Append("token", tokens, new CookieOptions()
            {
                HttpOnly = true,
                Expires  = DateTime.Now.AddHours(2)
            });
            CacheHelper.Set(_Account_User.Account_Name, _Account_User.Account_Uid, DateTimeOffset.Now.AddMinutes(120));
            AccountUserModel model = new AccountUserModel();

            model.apptoken     = tokens;
            model.Account_Name = _Account_User.Account_Name;
            model.Mobile       = _Account_User.Mobile;
            return(Json(new { status = 200, msg = "登录成功", data = model }));
        }
        public IActionResult ChangeUserAvatarAccount([FromBody] AccountUserModel userAccountModel)
        {
            if (userAccountModel == null ||
                (userAccountModel != null &&
                 userAccountModel.User == null &&
                 userAccountModel.User.AvatarId == -1))
            {
                return(BadRequest());
            }

            long lUserId = TokenProvider.GetLoggedUserId(User.Identity);

            if (lUserId != -1 &&
                _repositoryWrapper.Account.UpdateUserData(lUserId, userAccountModel.User, true))
            {
                _repositoryWrapper.Save();
            }

            return(Ok());
        }
Пример #10
0
        /// <summary>
        /// Получаем из таблици PLATFORM_USER пользователя по его уникальному идентификатору.
        /// "преобразуем" полученные данный в объект типа "AccountUserModel"
        /// Из таблици "PLATFORM_USER_ACCOUNT" вытаскиваем все записи (пользователь --- какой-либо счёт этого пользователя --- права на этот счёт этого пользователя)
        /// преобразуем полученные записи в словарь и записываем в свойство UserRightsMask
        ///
        /// так же получает данные о кошельке пользователя
        /// </summary>
        /// <param name="id">Уникальный идентификатор пользователя, по которому нужно пудучить детальную информацию</param>
        /// <remarks>Тестируется в методе NuAccountDbEditUserInfo</remarks>
        public AccountUserModel GetUserInfoById(int id)
        {
            AccountUserModel result = null;

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(x => x.ID == id);

                    if (user != null)
                    {
                        result = SiteAdminLinqToEntity.DecoratePlatformUser(user);
                        var userRights = user.PLATFORM_USER_ACCOUNT.Where(x => x.PlatformUser == id);
                        result.UserRightsMask = userRights.ToDictionary(x => x.Account, y => (UserAccountRights)y.RightsMask);

                        var wallet = ctx.WALLET.FirstOrDefault(x => x.User == id);
                        if (wallet != null)
                        {
                            result.WalletBalance  = wallet.Balance;
                            result.WalletCurrency = wallet.Currency;
                        }
                        else
                        {
                            Logger.InfoFormat("GetWalletDetailsById() - не найдено кошелька для пользователя {0}", id);
                        }
                    }
                }
            }
            #region catch
            catch (EntityException ex)
            {
                Logger.Error(String.Format("Не удалось получить данные о пользователе {0}, из за невозможности обратиться к серверу", id), ex);
            }
            catch (Exception ex)
            {
                Logger.Error("GetUserInfoById", ex);
            }
            #endregion
            return(result);
        }
Пример #11
0
        public static AccountUserModel DecoratePlatformUser(PLATFORM_USER platformUser)
        {
            var result = new AccountUserModel
            {
                UserId               = platformUser.ID,
                UserName             = platformUser.Name,
                UserSurname          = platformUser.Surname,
                UserPatronym         = platformUser.Patronym,
                UserDescription      = platformUser.Description,
                UserEmail            = platformUser.Email,
                UserLogin            = platformUser.Login,
                UserPassword         = platformUser.Password,
                UserPhone1           = platformUser.Phone1,
                UserPhone2           = platformUser.Phone2,
                UserRoleMask         = (UserRole)platformUser.RoleMask,
                UserRightsMask       = new Dictionary <int, UserAccountRights>(),
                UserRegistrationDate = platformUser.RegistrationDate
            };

            return(result);
        }
        public IActionResult ChangeUserDataAccount([FromForm] AccountUserModel userChangeModel)
        {
            if (userChangeModel == null ||
                (userChangeModel != null && userChangeModel.User == null))
            {
                return(BadRequest());
            }
            else if (userChangeModel.User.Password != null &&
                     userChangeModel.ConfirmPassword != null &&
                     userChangeModel.User.Password != userChangeModel.ConfirmPassword)
            {
                return(BadRequest("Hasło i jego potwierdzenie nie są zgodne!"));
            }

            long lUserId = TokenProvider.GetLoggedUserId(User.Identity);

            if (lUserId != -1 &&
                _repositoryWrapper.Account.UpdateUserData(lUserId, userChangeModel.User, false))
            {
                _repositoryWrapper.Save();
            }

            return(Ok());
        }
Пример #13
0
        public IMessageProvider Save( )
        {
            Account account = null;


            var currentUser = SecurityHelper.GetCurrentUser();
            AccountUserModel accountUser = currentUser as AccountUserModel;

            if (accountUser != null)
            {
                account = accountUser.Accounts.FirstOrDefault();
            }
            if (account == null || (account.State != AccountStates.Normal && account.State != AccountStates.Invalid))
            {
                AddError(LogTypes.AccountChangePassword, "accountNoExisting");
                return(this);
            }
            account.SetPassword(Password);
            TransactionHelper.BeginTransaction();
            AccountService.Update(account);
            Logger.LogWithSerialNo(LogTypes.AccountChangePassword, SerialNoHelper.Create(), account.AccountId, AccountName);
            AddMessage("success");
            return(TransactionHelper.CommitAndReturn(this));
        }
Пример #14
0
 public static AccountUser ToEntity(this AccountUserModel model, AccountUser destination)
 {
     return(model.MapTo(destination));
 }
Пример #15
0
 public static AccountUser ToEntity(this AccountUserModel model)
 {
     return(model.MapTo <AccountUserModel, AccountUser>());
 }
Пример #16
0
 public async Task <GenericResponseModel <AccountUserModel> > Update([FromUri] Guid id, [FromBody] AccountUserModel viewModel)
 {
     return(await Task.Run(async() => {
         Account account = new Account();
         bool passwordGenerate = appConfigManager.AppSetting <bool>("PasswordAutoGenerator", true, new AppConfigSettingsModel {
             Value = "false", Group = "Admin"
         });
         bool useDefaultPassword = appConfigManager.AppSetting <bool>("UseDefaultPassword", true, new AppConfigSettingsModel {
             Value = "false", Group = "Admin"
         });
         string defaultPassword = appConfigManager.AppSetting <string>("DefaultPassword", true, new AppConfigSettingsModel {
             Value = "patCHES214#", Group = "Admin"
         });
         ErrorCode = "800.5";
         try {
                  #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null'
             if (id == null)
             {
                  #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null'
                 ErrorCode = "800.51";
                 throw new Exception("Invalid data reference.");
             }
             if (id == Guid.Empty)
             {
                 ErrorCode = "800.51";
                 throw new Exception("Invalid data reference.");
             }
             if (!viewModel.Id.HasValue)
             {
                 ErrorCode = "800.52";
                 throw new Exception("Invalid data reference. Data didn't match.");
             }
             if (id != viewModel.Id)
             {
                 ErrorCode = "800.53";
                 throw new Exception("Invalid data reference. Data didn't match.");
             }
             var oldModel = await Service.Get(id);
             if (oldModel == null)
             {
                 ErrorCode = "800.54";
                 throw new Exception("Invalid data reference. No data found.");
             }
             var accounts = Service.GetAll().Where(a => a.Id != viewModel.Id.Value).ToList();
             if (accounts != null)
             {
                 if (accounts.Count > 0)
                 {
                     account = accounts.Where(a => a.Username.ToLower() == viewModel.Username.ToLower()).FirstOrDefault();
                     if (account != null)
                     {
                         ErrorCode = "800.55";
                         throw new Exception(viewModel.Username + " was already exist!");
                     }
                 }
             }
             string decryptedPassword = crypto.Decrypt(oldModel.Password);
             string encryptedPassword = string.Empty;
             if (decryptedPassword != viewModel.Password)
             {
                 encryptedPassword = crypto.Encrypt((passwordGenerate ? (useDefaultPassword ? defaultPassword : Generator.StringGenerator(10)) : viewModel.Password));
             }
             else
             {
                 encryptedPassword = oldModel.Password;
             }
             oldModel.AccountInformationId = oldModel.AccountInformationId;
             oldModel.EmailAddress = viewModel.EmailAddress;
             oldModel.RoleId = viewModel.RoleId;
             oldModel.Username = viewModel.Username;
             oldModel.Password = encryptedPassword;
             oldModel.DateUpdated = DateTime.Now;
             account = await Service.UpdateReturnAsync(oldModel);
             account.AccountInformation = await accountInformationService.Get(oldModel.AccountInformationId);
             account.Role = await roleService.Get(account.RoleId);
             await accountService.GenerateUserJsonData(account);
             viewModel.DateCreated = account.DateCreated;
             viewModel.DateUpdated = account.DateUpdated;
             viewModel.Id = id;
         } catch (Exception ex) {
             string message = ex.Message + (!string.IsNullOrEmpty(ex.InnerException.Message) && ex.Message != ex.InnerException.Message ? " Reason : " + ex.InnerException.Message : string.Empty);
             ErrorDetails.Add(message);
             ErrorMessage = message;
             MethodBase m = MethodBase.GetCurrentMethod();
             StackTrace trace = new StackTrace(ex, true);
             string sourceFile = trace.GetFrame(0).GetFileName();
             await ErrorLogs.Write(new ErrorLogsModel {
                 Application = Assembly.GetExecutingAssembly().GetName().Name,
                 Controller = GetType().Name,
                 CurrentAction = m.Name.Split('>')[0].TrimStart('<'),
                 ErrorCode = ErrorCode,
                 Message = message,
                 SourceFile = sourceFile,
                 LineNumber = trace.GetFrame(0).GetFileLineNumber(),
                 StackTrace = ex.ToString(),
                 Method = m.Name.Split('>')[0].TrimStart('<')
             }, ex);
         }
         return new GenericResponseModel <AccountUserModel>()
         {
             Code = string.IsNullOrEmpty(ErrorMessage) ? Utilities.Enums.CodeStatus.Success : Utilities.Enums.CodeStatus.Error,
             CodeStatus = string.IsNullOrEmpty(ErrorMessage) ? Utilities.Enums.CodeStatus.Success.ToString() : Utilities.Enums.CodeStatus.Error.ToString(),
             ReferenceObject = string.IsNullOrEmpty(ErrorMessage) ? viewModel : null,
             ErrorMessage = string.IsNullOrEmpty(ErrorMessage) ? null : new ErrorMessage {
                 Details = ErrorDetails,
                 ErrNumber = ErrorCode,
                 Message = ErrorMessage
             }
         };
     }));
 }