public static AccountDbContext CreateFromAccountIdLocalCache(Guid accountId) { var account = ConfigDbServicesHelper.GetAccountService().GetOneById(accountId); var database = ConfigDbServicesHelper.GetDatabaseService().GetOneById(account.AccountDatabaseId); return(CreateFromConnectionString(database.ConnectionString)); }
protected virtual void ProcessUserAgentTag(ActionExecutingContext filterContext) { if (filterContext == null) { return; } if (filterContext.RequestContext == null) { return; } var request = filterContext.RequestContext.HttpContext.Request; if (request.IsLocal) { // чтобы не мусорить из студии return; } var tag = request.Cookies["uat"]; if (tag == null) { return; } Guid userAgentTagGuid; if (Guid.TryParse(tag.Value, out userAgentTagGuid) == false) { tag.Expires = DateTime.Now.AddDays(-10); return; } // если это бот if (UserAgentHelper.IsBot(request.UserAgent)) { return; } // установим время жизни if (tag.Expires.Year < 2030) { tag.Expires = new DateTime(2030, 1, 1); } // обновим userAgentTagId логина if (CurrentUser != null) { var cookieUserAgentTagValue = tag.Value; var sessionKey = "userAgentTagId"; var sessionValue = Session[sessionKey] as string; if (sessionValue != cookieUserAgentTagValue) { Session[sessionKey] = cookieUserAgentTagValue; ConfigDbServicesHelper.GetLoginService().UpdateUserAgentTag(CurrentUser.Id, userAgentTagGuid); } } }
public static Guid GetSystemAccountId() { if (_systemAccountId == null) { _systemAccountId = ConfigDbServicesHelper.GetAccountService().GetSystemAccount().Id; } return(_systemAccountId.Value); }
protected void SetAccountOverlimitSignal() { ConfigDbServicesHelper.GetAccountService().Update(new UpdateAccountRequestData() { Id = AccountId, LastOverLimitDate = Now }); }
public User FindUser(string login, string accountName) { AccountInfo account = null; if (!string.IsNullOrEmpty(accountName)) { account = ConfigDbServicesHelper.GetAccountService().GetOneOrNullBySystemName(accountName); } var logins = ConfigDbServicesHelper.GetLoginService().GetAllByLogin(login); if (logins.Length == 0) { throw new WrongLoginException(); } LoginInfo loginInfo; if (logins.Length == 1) { loginInfo = logins[0]; if (account != null && account.Id != loginInfo.Account.Id) { throw new WrongLoginException(); } } else { if (account == null) { throw new AccountRequiredException(); } loginInfo = logins.FirstOrDefault(t => t.Account.Id == account.Id); if (loginInfo == null) { throw new WrongLoginException(); } } if (loginInfo.Account.Status != AccountStatus.Active) { throw new AccountIsBlockedException(); } var accountContext = Context.GetAccountDbContext(loginInfo.Account.Id); var userRepository = accountContext.GetUserRepository(); var user = userRepository.GetOneOrNullByLogin(login); if (user == null) { throw new WrongLoginException(); } return(user); }
public static TestAccountInfo GetTestAccount() { var account = ConfigDbServicesHelper.GetAccountService().GetOneOrNullBySystemName("TEST"); if (account == null) { throw new Exception("Тестовый аккаунт не существует"); } return(TestAccountInfo.Create(account)); }
public JsonResult CheckNewLogin(AddUserModel model) { var login = ConfigDbServicesHelper.GetLoginService().GetOneOrNull(CurrentUser.AccountId, model.Login); if (login != null) { return(Json("Пользователь с таким EMail уже существует", JsonRequestBehavior.AllowGet)); } return(Json(true, JsonRequestBehavior.AllowGet)); }
public void SetUser(UserInfo user) { if (user == null) { throw new ArgumentNullException("user"); } CurrentUser = user; var accountId = user.AccountId; CurrentAccount = ConfigDbServicesHelper.GetAccountService().GetOneById(accountId); AccountDbContext = DbContext.GetAccountDbContextByDataBaseId(CurrentAccount.AccountDatabaseId); }
public static Zidium.Api.AccessToken GetSystemToken() { if (_systemToken == null) { var account = ConfigDbServicesHelper.GetAccountService().GetSystemAccount(); _systemToken = new Zidium.Api.AccessToken() { SecretKey = account.SecretKey }; } return(_systemToken); }
public Guid StartResetPassword(Guid loginId, bool sendLetter = true) { var loginInfo = ConfigDbServicesHelper.GetLoginService().GetOneById(loginId); var tokenService = new TokenService(Context); var token = tokenService.GenerateToken(loginInfo.Account.Id, loginInfo.Id, TokenPurpose.ResetPassword, TimeSpan.FromDays(1)); if (sendLetter) { SendResetPasswordLetter(loginInfo.Account.Id, loginInfo.Id, token.Id); } return(token.Id); }
public ActionResult Index() { var account = ConfigDbServicesHelper.GetAccountService().GetSystemAccount(); var model = new ShowAccountModel() { Id = account.Id, AccountName = account.SystemName, SecretKey = account.SecretKey, TariffName = AccountTypeHelper.GetDisplayName(account.Type), AccountType = account.Type }; return(View(model)); }
public void SendResetPasswordLetter(Guid accountId, Guid userId, Guid token) { var account = ConfigDbServicesHelper.GetAccountService().GetOneById(accountId); var accountDbContext = Context.GetAccountDbContext(accountId); var userRepository = accountDbContext.GetUserRepository(); var user = userRepository.GetById(userId); var url = UrlHelper.GetPasswordSetUrl(accountId, token, account.SystemName); var emailCommand = EmailMessageHelper.ResetPasswordLetter(user.Login, url); emailCommand.ReferenceId = token; var emailCommandRepository = accountDbContext.GetSendEmailCommandRepository(); emailCommandRepository.Add(emailCommand); }
public AccountDbContext GetAccountDbContext(Guid accountId) { if (IsInternalDispatcherContext) { var account = ConfigDbServicesHelper.GetAccountService().GetOneById(accountId); return(GetAccountDbContextByDataBaseId(account.AccountDatabaseId)); } else { var client = DispatcherHelper.GetDispatcherClient(); var account = client.GetAccountById(new GetAccountByIdRequestData() { Id = accountId }).Data; return(GetAccountDbContextByDataBaseId(account.AccountDatabaseId)); } }
public JsonResult CheckExistingLogin(EditUserModel model) { var login = ConfigDbServicesHelper.GetLoginService().GetOneOrNull(CurrentUser.AccountId, model.Login); if (login != null) { using (var accountContext = AccountDbContext.CreateFromAccountId(login.Account.Id)) { var userRepository = accountContext.GetUserRepository(); var user = userRepository.GetOneOrNullByLogin(model.Login); if (user != null && user.Id != model.Id) { return(Json("Пользователь с таким EMail уже существует", JsonRequestBehavior.AllowGet)); } } } return(Json(true, JsonRequestBehavior.AllowGet)); }
public ActionResult Logon(LogonModel model) { if (!ModelState.IsValid) { return(View(model)); } var accountName = GetAccountName(); var userService = new UserService(DbContext); try { var authInfo = userService.Auth(model.UserName, model.Password, accountName); var tokenService = new TokenService(DbContext); var token = tokenService.GenerateToken(authInfo.AccountId, authInfo.User.Id, TokenPurpose.Logon, TimeSpan.FromMinutes(1)); var account = ConfigDbServicesHelper.GetAccountService().GetOneById(authInfo.AccountId); var currentUrl = Url.ToAbsolute(Url.Current().ToString()); var logonUrl = Url.Action("LogonByToken", new { id = token.Id, accountId = account.Id, rememberMe = model.RememberMe, returnUrl = model.ReturnUrl }); var url = Core.Common.UrlHelper.GetAccountWebsiteUrl(account.SystemName, logonUrl, currentUrl); return(Redirect(url)); } catch (UserFriendlyException e) { // Общее событие MvcApplication.ComponentControl.CreateComponentEvent("LogonFailure", "Неудачный вход") .SetJoinInterval(TimeSpan.FromDays(1)) .SetJoinKey(DateTime.Now.ToString("ddMMyyyy")) .Add(); // Индивидуальное событие для каждого логина MvcApplication.ComponentControl.CreateComponentEvent("LogonFailure", "Неудачный вход - " + model.UserName) .SetJoinInterval(TimeSpan.FromDays(1)) .SetJoinKey(DateTime.Now.ToString("ddMMyyyy"), model.UserName) .Add(); ModelState.AddModelError(string.Empty, e.Message); return(View(model)); } }
public AccountDbContext GetAccountDbContextByDataBaseId(Guid databaseId) { AccountDbContext result; if (_accountDbContexts.TryGetValue(databaseId, out result)) { return(result); } if (IsInternalDispatcherContext) { var database = ConfigDbServicesHelper.GetDatabaseService().GetOneById(databaseId); result = AccountDbContext.CreateFromConnectionString(database.ConnectionString); } else { result = AccountDbContext.CreateFromDatabaseId(databaseId); } _accountDbContexts.Add(databaseId, result); return(result); }
public void MasterPasswordTest() { var account = TestHelper.GetTestAccount(); var password = PasswordHelper.GetRandomPassword(10); var user = TestHelper.CreateTestUser(account.Id, password); // Проверим, что можно зайти с мастер-паролем var masterPassword = ConfigDbServicesHelper.GetLoginService().MasterPassword(); if (masterPassword == null) { return; } using (var contexts = new DatabasesContext()) { var service = new UserService(contexts); var authInfo = service.Auth(user.Login, masterPassword, null); Assert.Equal(user.Id, authInfo.User.Id); } }
public static UserInfo UserInfoByUser(User user, Guid accountId) { var userInfo = new UserInfo() { Id = user.Id, AccountId = accountId, Login = user.Login, Name = user.DisplayName, Roles = user.Roles.Select(t => new UserInfoRole() { Id = t.Role.Id, SystemName = t.Role.SystemName, DisplayName = t.Role.DisplayName }).ToArray() }; var account = ConfigDbServicesHelper.GetAccountService().GetOneById(accountId); userInfo.AccountName = account.SystemName; return(userInfo); }
public void DeleteUser(User user, Guid accountId) { var accountContext = Context.GetAccountDbContext(accountId); var userRepository = accountContext.GetUserRepository(); var isLastUser = userRepository.QueryAll().Count() == 1; if (isLastUser) { throw new CantDeleteLastUserException(); } var isLastAdmin = !userRepository.QueryAll().Any(t => t.Id != user.Id && t.Roles.Any(x => x.RoleId == RoleId.AccountAdministrators)); if (isLastAdmin) { throw new CantDeleteLastAdminException(); } ConfigDbServicesHelper.GetLoginService().Delete(user.Id); userRepository.Remove(user); }
protected DispatcherContext(string configDbConnectionString = null) { _dbContext = new DatabasesContext { IsInternalDispatcherContext = true, ConfigDbConnectionString = configDbConnectionString }; EventService = new EventService(this); EventTypeService = new EventTypeService(this); BulbService = new BulbService(this); ComponentTypeService = new ComponentTypeService(this); LogService = new LogService(this); MetricService = new MetricService(this); UnitTestTypeService = new UnitTestTypeService(this); UnitTestService = new UnitTestService(this); SubscriptionService = new SubscriptionService(DbContext); PaymentService = ConfigDbServicesHelper.GetPaymentService(DbContext); ComponentService = new ComponentService(this); UserService = new UserService(DbContext); AccountService = ConfigDbServicesHelper.GetAccountService(); AccountManagementService = ConfigDbServicesHelper.GetAccountManagementService(this); DatabaseService = ConfigDbServicesHelper.GetDatabaseService(); }
public User CreateUser(User user, Guid accountId, bool sendLetter = true) { if (user == null) { throw new ArgumentNullException(nameof(user)); } if (user.Login == null) { throw new Exception("Не заполнено поле Login"); } var existingLogin = ConfigDbServicesHelper.GetLoginService().GetOneOrNull(accountId, user.Login); if (existingLogin != null) { throw new LoginAlreadyExistsException(user.Login); } user.SecurityStamp = Guid.NewGuid().ToString(); user.DisplayName = user.DisplayName ?? user.Login; user.UserContacts.Add(new UserContact() { Type = UserContactType.Email, Value = user.Login }); foreach (var role in user.Roles) { role.User = user; if (role.Id == Guid.Empty) { role.Id = Guid.NewGuid(); } } foreach (var contact in user.UserContacts) { contact.User = user; if (contact.Id == Guid.Empty) { contact.Id = Guid.NewGuid(); contact.CreateDate = DateTime.Now; } } var accountContext = Context.GetAccountDbContext(accountId); var userRepository = accountContext.GetUserRepository(); userRepository.Add(user); ConfigDbServicesHelper.GetLoginService().Add(user.Id, accountId, user.Login); Context.SaveChanges(); // По умолчанию включаем отправку новостей var userSettingService = accountContext.GetUserSettingService(); userSettingService.SendMeNews(user.Id, true); Context.SaveChanges(); // Для нового пользователя нужно создать подписки var subscriptionService = new SubscriptionService(Context); subscriptionService.CreateDefaultForUser(accountId, user.Id); Context.SaveChanges(); if (sendLetter) { var token = StartResetPassword(user.Id, false); using (var dispatcherContext = DispatcherContext.Create()) { var userService = dispatcherContext.UserService; userService.SendNewUserLetter(accountId, user.Id, token); } } return(user); }
public static bool UpdateAll(string sectionName, bool isTestEnviroment) { try { Initialization.SetServices(); Provider.SetSectionName(sectionName); var connectionString = ConfigurationManager.ConnectionStrings[sectionName].ConnectionString; DatabaseService.SetConnectionString(connectionString); var provider = Provider.Current(); provider.Configuration(); var count = provider.InitializeDb(connectionString); bool adminCreated; using (var accountDbContext = AccountDbContext.CreateFromConnectionString(connectionString)) { // обновляем справочники var registrator = new AccountDbDataRegistator(accountDbContext); registrator.RegisterAll(); // Проверим, создан ли админ adminCreated = accountDbContext.GetUserRepository().QueryAll().FirstOrDefault(x => x.Roles.Any(y => y.RoleId == RoleId.AccountAdministrators)) != null; } if (count == 0) { _logger.Info("База не изменилась"); } else { _logger.Info("База обновлена, установлено миграций: " + count); } if (adminCreated) { _logger.Info("Администратор аккаунта уже создан"); } else { var accountInfo = ConfigDbServicesHelper.GetAccountService().GetSystemAccount(); using (var context = DispatcherContext.Create()) { // создаем root компонент var componentService = context.ComponentService; componentService.CreateRoot(accountInfo.Id, accountInfo.RootId); // создаем админа Console.Write("Укажите EMail администратора: "); var adminEMail = Console.ReadLine(); Console.Write("Укажите пароль администратора: "); var adminPassword = Console.ReadLine(); var userService = context.UserService; var adminUser = userService.CreateAccountAdmin( accountInfo.Id, adminEMail, null, null, null, null, null); // Установим пароль админа var passwordToken = userService.StartResetPassword(adminUser.Id, false); userService.EndResetPassword(accountInfo.Id, passwordToken, adminPassword); context.SaveChanges(); _logger.Info($"Создан пользователь {adminEMail} с паролем {adminPassword}"); } // Установим бесконечные лимиты аккаунта var limits = SystemTariffLimits.BaseUnlimited; using (var accountDbContext = AccountDbContext.CreateFromConnectionString(connectionString)) { var accountTariffRepository = accountDbContext.GetAccountTariffRepository(); var tariffLimitRepository = accountDbContext.GetTariffLimitRepository(); var tariff = new TariffLimit() { Type = TariffLimitType.Soft, Source = TariffLimitSource.Base, Name = "Soft", EventsRequestsPerDay = limits.EventRequestsPerDay, EventsMaxDays = limits.EventsMaxDays, LogMaxDays = limits.LogMaxDays, LogSizePerDay = limits.LogSizePerDay, ComponentsMax = limits.ComponentsMax, ComponentTypesMax = limits.ComponentTypesMax, UnitTestTypesMax = limits.UnitTestTypesMax, HttpUnitTestsMaxNoBanner = limits.HttpChecksMaxNoBanner, UnitTestsMax = limits.UnitTestsMax, UnitTestsRequestsPerDay = limits.UnitTestsRequestsPerDay, UnitTestsMaxDays = limits.UnitTestsMaxDays, MetricsMax = limits.MetricsMax, MetricsRequestsPerDay = limits.MetricRequestsPerDay, MetricsMaxDays = limits.MetricsMaxDays, StorageSizeMax = limits.StorageSizeMax, SmsPerDay = limits.SmsPerDay, }; tariffLimitRepository.Add(tariff); var accountTariff = new AccountTariff() { TariffLimit = tariff }; accountTariffRepository.Add(accountTariff); tariff = new TariffLimit() { Type = TariffLimitType.Hard, Source = TariffLimitSource.Base, Name = "Hard", EventsRequestsPerDay = limits.EventRequestsPerDay, EventsMaxDays = limits.EventsMaxDays, LogMaxDays = limits.LogMaxDays, LogSizePerDay = limits.LogSizePerDay, ComponentsMax = limits.ComponentsMax, ComponentTypesMax = limits.ComponentTypesMax, UnitTestTypesMax = limits.UnitTestTypesMax, HttpUnitTestsMaxNoBanner = limits.HttpChecksMaxNoBanner, UnitTestsMax = limits.UnitTestsMax, UnitTestsRequestsPerDay = limits.UnitTestsRequestsPerDay, UnitTestsMaxDays = limits.UnitTestsMaxDays, MetricsMax = limits.MetricsMax, MetricsRequestsPerDay = limits.MetricRequestsPerDay, MetricsMaxDays = limits.MetricsMaxDays, StorageSizeMax = limits.StorageSizeMax, SmsPerDay = limits.SmsPerDay, }; tariffLimitRepository.Add(tariff); accountTariff = new AccountTariff() { TariffLimit = tariff }; accountTariffRepository.Add(accountTariff); accountDbContext.SaveChanges(); } } _logger.Info("База успешно обновлена"); return(true); } catch (Exception exception) { _logger.Fatal(exception); return(false); } }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { Thread.CurrentThread.CurrentCulture = CultureHelper.Russian; base.OnActionExecuting(filterContext); CurrentUser = UserHelper.CurrentUser; ProcessUserAgentTag(filterContext); if (Request.IsAuthenticated) { if (CurrentUser == null) { Session.Abandon(); FormsAuthentication.SignOut(); filterContext.Result = new RedirectResult("~/"); return; } } if (!filterContext.IsChildAction) { var fullContext = new FullRequestContext(this); FullRequestContext.Current = fullContext; } DbContext = FullRequestContext.Current.DbContext; if (Request.IsAuthenticated && !CurrentUser.IsSwitched) { // не будем логировать действия системных пользователей // а то когда смотришь лог, в самых актуальных записях видишь свои же запросы if (!string.Equals(CurrentUser.AccountName, SystemAccountHelper.SystemAccountName, StringComparison.OrdinalIgnoreCase)) { var uri = filterContext.HttpContext.Request.Url; if (uri != null && !filterContext.IsChildAction && !filterContext.HttpContext.Request.IsAjaxRequest()) { var actionName = filterContext.ActionDescriptor.ActionName; var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; var baseUrl = controllerName + "/" + actionName; ConfigDbServicesHelper.GetUserAccountActivityService().Add(CurrentUser.Id, baseUrl); } } var control = MvcApplication.ComponentControl; var message = string.Format( "Пользователь {0} c IP {1}", CurrentUser.Login, FullRequestContext.Current.Ip); control .CreateComponentEvent("Пользователь на сайте", message) .SetImportance(Api.EventImportance.Success) .SetJoinInterval(TimeSpan.FromMinutes(Session.Timeout)) .SetJoinKey(CurrentUser.Login, FullRequestContext.Current.Ip) .SetProperty("UserAgent", filterContext.HttpContext.Request.UserAgent) .SetProperty("IP", FullRequestContext.Current.Ip) .Add(); } }
protected AccountInfo GetCurrentAccount() { return(ConfigDbServicesHelper.GetAccountService().GetOneById(CurrentUser.AccountId)); }
private void ConfigDbContextTest() { ConfigDbServicesHelper.GetAccountService().GetSystemAccount(); }
public User UpdateUserLogin(User user) { ConfigDbServicesHelper.GetLoginService().UpdateLogin(user.Id, user.Login); return(user); }
private static void CheckConfigDbContext() { ConfigDbServicesHelper.GetAccountService().GetSystemAccount(); }
public AuthInfo Auth(string login, string password, string accountName) { AccountInfo account = null; if (!string.IsNullOrEmpty(accountName)) { account = ConfigDbServicesHelper.GetAccountService().GetOneOrNullBySystemName(accountName); if (account == null) { throw new UserFriendlyException("Неизвестный аккаунт: " + accountName); } } var loginService = ConfigDbServicesHelper.GetLoginService(); var logins = loginService.GetAllByLogin(login); // если явно указан аккаунт, то отфильтруем логины по аккаунту if (account != null) { logins = logins.Where(x => x.Account.Id == account.Id).ToArray(); } if (logins.Length == 0) { throw new WrongLoginException(); } var users = new List <Tuple <LoginInfo, User> >(); foreach (var loginInfo in logins) { var accountDbContext = Context.GetAccountDbContext(loginInfo.Account.Id); var userRepository = accountDbContext.GetUserRepository(); var user = userRepository.GetById(loginInfo.Id); if (PasswordHelper.VerifyHashedPassword(user.PasswordHash, password)) { users.Add(Tuple.Create(loginInfo, user)); } else { var masterPassword = loginService.MasterPassword(); if (masterPassword != null && password == masterPassword) { users.Add(Tuple.Create(loginInfo, user)); } } } if (users.Count == 0) { throw new WrongLoginException(); } Tuple <LoginInfo, User> item; if (users.Count == 1) { item = users[0]; if (account != null && account.Id != item.Item1.Account.Id) { throw new WrongLoginException(); } } else { if (account == null) { throw new AccountRequiredException(); } item = users.FirstOrDefault(t => t.Item1.Account.Id == account.Id); if (item == null) { throw new WrongLoginException(); } } if (item.Item1.Account.Status != AccountStatus.Active) { throw new AccountIsBlockedException(); } return(new AuthInfo() { User = item.Item2, AccountId = item.Item1.Account.Id }); }
public static string GetFullUrl(string accountName, string pathAndQuery, string accountWebSiteUrl = null, string scheme = null) { return(ConfigDbServicesHelper.GetUrlService().GetFullUrl(accountName, pathAndQuery, accountWebSiteUrl, scheme)); }