public List <Tenant> FindTenants(string login, string password, string passwordHash = null) { var result = new List <Tenant>(); Exception error = null; foreach (var service in GetRegionServices()) { try { if (string.IsNullOrEmpty(passwordHash) && !string.IsNullOrEmpty(password)) { passwordHash = PasswordHasher.GetClientPassword(password); } result.AddRange(service.FindTenants(login, passwordHash)); } catch (SecurityException exception) { error = exception; } } if (!result.Any() && error != null) { throw error; } return(result); }
private UserInfo GetUser(int tenantId, AuthModel memberModel) { memberModel.PasswordHash = (memberModel.PasswordHash ?? "").Trim(); if (string.IsNullOrEmpty(memberModel.PasswordHash)) { memberModel.Password = (memberModel.Password ?? "").Trim(); if (!string.IsNullOrEmpty(memberModel.Password)) { memberModel.PasswordHash = PasswordHasher.GetClientPassword(memberModel.Password); } } var user = UserManager.GetUsersByPasswordHash( tenantId, memberModel.UserName, memberModel.PasswordHash); if (user == null || !UserManager.UserExists(user)) { throw new Exception("user not found"); } return(user); }
protected virtual void Authentificate(string username, string password) { var u = CoreContext.UserManager.GetUserByEmail(username) ?? CoreContext.UserManager.GetUserByUserName(username) ?? CoreContext.UserManager.GetUsers(new Guid(username)); if (!Core.Users.Constants.LostUser.Equals(u)) { var passwordHash = PasswordHasher.GetClientPassword(password); SecurityContext.AuthenticateMe(u.Email, passwordHash); } }
//todo: remove private void RegeneratePassword(int tenant, Guid userId) { var h2 = UserDbContext.UserSecurity .Where(r => r.Tenant == tenant) .Where(r => r.UserId == userId) .Select(r => r.PwdHashSha512) .FirstOrDefault(); if (string.IsNullOrEmpty(h2)) { return; } var password = Crypto.GetV(h2, 1, false); var passwordHash = PasswordHasher.GetClientPassword(password); SetUserPasswordHash(tenant, userId, passwordHash); }
public static bool ProcessBasicAuthorization(HttpContext context, out string authCookie) { authCookie = null; try { //Try basic var authorization = context.Request.Headers["Authorization"]; if (string.IsNullOrEmpty(authorization)) { return(false); } authorization = authorization.Trim(); if (0 <= authorization.IndexOf("Basic", 0)) { var arr = Encoding.ASCII.GetString(Convert.FromBase64String(authorization.Substring(6))).Split(new[] { ':' }); var username = arr[0]; var password = arr[1]; var u = CoreContext.UserManager.GetUserByEmail(username); if (u != null && u.ID != ASC.Core.Users.Constants.LostUser.ID) { var passwordHash = PasswordHasher.GetClientPassword(password); authCookie = SecurityContext.AuthenticateMe(u.Email, passwordHash); } } else if (0 <= authorization.IndexOf("Bearer", 0)) { authorization = authorization.Substring("Bearer ".Length); if (SecurityContext.AuthenticateMe(authorization)) { authCookie = authorization; } } else { if (SecurityContext.AuthenticateMe(authorization)) { authCookie = authorization; } } } catch (Exception) { } return(SecurityContext.IsAuthenticated); }
//todo: remove private void RegeneratePassword(int tenant, Guid userId) { var q = new SqlQuery("core_usersecurity") .Select("tenant", "pwdhashsha512") .Where("userid", userId.ToString()); if (tenant != Tenant.DEFAULT_TENANT) { q.Where("tenant", tenant); } var result = ExecList(q) .ConvertAll(r => new Tuple <int, string>(Convert.ToInt32(r[0]), (string)r[1])) .FirstOrDefault(); if (result == null || string.IsNullOrEmpty(result.Item2)) { return; } var password = Crypto.GetV(result.Item2, 1, false); var passwordHash = PasswordHasher.GetClientPassword(password); SetUserPasswordHash(result.Item1, userId, passwordHash); }
public IActionResult Register(TenantModel model) { if (model == null) { return(BadRequest(new { errors = "Tenant data is required." })); } if (!ModelState.IsValid) { var errors = new JArray(); foreach (var k in ModelState.Keys) { errors.Add(ModelState[k].Errors.FirstOrDefault().ErrorMessage); } return(Ok(new { errors })); } var sw = Stopwatch.StartNew(); object error; if (string.IsNullOrEmpty(model.PasswordHash) && !string.IsNullOrEmpty(model.Password)) { if (!CheckPasswordPolicy(model.Password, out error)) { sw.Stop(); return(BadRequest(error)); } model.PasswordHash = PasswordHasher.GetClientPassword(model.Password); } if (!CheckValidName(model.FirstName.Trim() + model.LastName.Trim(), out error)) { sw.Stop(); return(BadRequest(error)); } var checkTenantBusyPesp = CheckExistingNamePortal(model.PortalName.Trim()); if (checkTenantBusyPesp != null) { sw.Stop(); return(checkTenantBusyPesp); } Log.DebugFormat("PortalName = {0}; Elapsed ms. CheckExistingNamePortal: {1}", model.PortalName, sw.ElapsedMilliseconds); var clientIP = CommonMethods.GetClientIp(); Log.DebugFormat("clientIP = {0}", clientIP); if (CommonMethods.CheckMuchRegistration(model, clientIP, sw)) { return(BadRequest(new { errors = new[] { "tooMuchAttempts" } })); } if (CommonConstants.RecaptchaRequired && !CommonMethods.IsTestEmail(model.Email)) { /*** validate recaptcha ***/ if (!CommonMethods.ValidateRecaptcha(model.RecaptchaResponse, clientIP)) { Log.DebugFormat("PortalName = {0}; Elapsed ms. ValidateRecaptcha: {1}", model.PortalName, sw.ElapsedMilliseconds); sw.Stop(); return(BadRequest(new { errors = new[] { "recaptchaInvalid" }, message = "Recaptcha is invalid" })); } Log.DebugFormat("PortalName = {0}; Elapsed ms. ValidateRecaptcha: {1}", model.PortalName, sw.ElapsedMilliseconds); } //check payment portal count if (Configuration["core:base-domain"] == "localhost") { var tenants = HostedSolution.GetTenants(DateTime.MinValue); var firstTenant = tenants.FirstOrDefault(); if (firstTenant != null) { var activePortals = tenants.Count(r => r.Status != TenantStatus.Suspended && r.Status != TenantStatus.RemovePending); var quota = HostedSolution.GetTenantQuota(firstTenant.TenantId); if (quota.CountPortals > 0 && quota.CountPortals <= activePortals) { return(BadRequest(new { errors = new[] { "portalsCountTooMuch" }, message = "Too much portals registered already", })); } } } var language = model.Language ?? string.Empty; var tz = TimeZonesProvider.GetCurrentTimeZoneInfo(language); Log.DebugFormat("PortalName = {0}; Elapsed ms. TimeZonesProvider.GetCurrentTimeZoneInfo: {1}", model.PortalName, sw.ElapsedMilliseconds); if (!string.IsNullOrEmpty(model.TimeZoneName)) { tz = TimeZoneConverter.GetTimeZone(model.TimeZoneName.Trim(), false) ?? tz; Log.DebugFormat("PortalName = {0}; Elapsed ms. TimeZonesProvider.OlsonTimeZoneToTimeZoneInfo: {1}", model.PortalName, sw.ElapsedMilliseconds); } var lang = TimeZonesProvider.GetCurrentCulture(language); Log.DebugFormat("PortalName = {0}; model.Language = {1}, resultLang.DisplayName = {2}", model.PortalName, language, lang.DisplayName); var info = new TenantRegistrationInfo { Name = Configuration["web:portal-name"] ?? "Cloud Office Applications", Address = model.PortalName, Culture = lang, FirstName = model.FirstName.Trim(), LastName = model.LastName.Trim(), PasswordHash = String.IsNullOrEmpty(model.PasswordHash) ? null : model.PasswordHash, Email = model.Email.Trim(), TimeZoneInfo = tz, MobilePhone = string.IsNullOrEmpty(model.Phone) ? null : model.Phone.Trim(), Industry = (TenantIndustry)model.Industry, Spam = model.Spam, Calls = model.Calls, Analytics = model.Analytics, LimitedControlPanel = model.LimitedControlPanel }; if (!string.IsNullOrEmpty(model.PartnerId)) { if (Guid.TryParse(model.PartnerId, out Guid guid)) { // valid guid info.PartnerId = model.PartnerId; } } if (!string.IsNullOrEmpty(model.AffiliateId)) { info.AffiliateId = model.AffiliateId; } Tenant t; try { /****REGISTRATION!!!*****/ if (!string.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl)) { ApiSystemHelper.AddTenantToCache(info.Address, SecurityContext.CurrentAccount.ID); Log.DebugFormat("PortalName = {0}; Elapsed ms. CacheController.AddTenantToCache: {1}", model.PortalName, sw.ElapsedMilliseconds); } HostedSolution.RegisterTenant(info, out t); /*********/ Log.DebugFormat("PortalName = {0}; Elapsed ms. HostedSolution.RegisterTenant: {1}", model.PortalName, sw.ElapsedMilliseconds); } catch (Exception e) { sw.Stop(); Log.Error(e); return(StatusCode(StatusCodes.Status500InternalServerError, new { errors = new[] { "registerNewTenantError" }, message = e.Message, stacktrace = e.StackTrace })); } var isFirst = true; string sendCongratulationsAddress = null; if (!String.IsNullOrEmpty(model.PasswordHash)) { isFirst = !CommonMethods.SendCongratulations(Request.Scheme, t, model.SkipWelcome, out sendCongratulationsAddress); } else if (Configuration["core:base-domain"] == "localhost") { try { /* set wizard not completed*/ TenantManager.SetCurrentTenant(t); var settings = SettingsManager.Load <WizardSettings>(); settings.Completed = false; SettingsManager.Save(settings); } catch (Exception e) { Log.Error(e); } } var reference = CommonMethods.CreateReference(Request.Scheme, t.GetTenantDomain(CoreSettings), info.Email, isFirst, model.Module); Log.DebugFormat("PortalName = {0}; Elapsed ms. CreateReferenceByCookie...: {1}", model.PortalName, sw.ElapsedMilliseconds); sw.Stop(); return(Ok(new { errors = "", reference, tenant = ToTenantWrapper(t), referenceWelcome = sendCongratulationsAddress, })); }
public IActionResult Register(TenantModel model) { if (model == null) { return BadRequest(new { error = "portalNameEmpty", message = "PortalName is required" }); } if (!ModelState.IsValid) { var message = new JArray(); foreach (var k in ModelState.Keys) { message.Add(ModelState[k].Errors.FirstOrDefault().ErrorMessage); } return BadRequest(new { error = "params", message }); } var sw = Stopwatch.StartNew(); if (string.IsNullOrEmpty(model.PasswordHash)) { if (!CheckPasswordPolicy(model.Password, out var error1)) { sw.Stop(); return BadRequest(error1); } if (!string.IsNullOrEmpty(model.Password)) { model.PasswordHash = PasswordHasher.GetClientPassword(model.Password); } } model.FirstName = (model.FirstName ?? "").Trim(); model.LastName = (model.LastName ?? "").Trim(); if (!CheckValidName(model.FirstName + model.LastName, out var error)) { sw.Stop(); return BadRequest(error); } model.PortalName = (model.PortalName ?? "").Trim(); if (!CheckExistingNamePortal(model.PortalName, out error)) { sw.Stop(); return BadRequest(error); } Log.DebugFormat("PortalName = {0}; Elapsed ms. CheckExistingNamePortal: {1}", model.PortalName, sw.ElapsedMilliseconds); var clientIP = CommonMethods.GetClientIp(); if (CommonMethods.CheckMuchRegistration(model, clientIP, sw)) { return BadRequest(new { error = "tooMuchAttempts", message = "Too much attempts already" }); } if (!CheckRecaptcha(model, clientIP, sw, out error)) { return BadRequest(error); } if (!CheckRegistrationPayment(out error)) { return BadRequest(error); } var language = model.Language ?? string.Empty; var tz = TimeZonesProvider.GetCurrentTimeZoneInfo(language); Log.DebugFormat("PortalName = {0}; Elapsed ms. TimeZonesProvider.GetCurrentTimeZoneInfo: {1}", model.PortalName, sw.ElapsedMilliseconds); if (!string.IsNullOrEmpty(model.TimeZoneName)) { tz = TimeZoneConverter.GetTimeZone(model.TimeZoneName.Trim(), false) ?? tz; Log.DebugFormat("PortalName = {0}; Elapsed ms. TimeZonesProvider.OlsonTimeZoneToTimeZoneInfo: {1}", model.PortalName, sw.ElapsedMilliseconds); } var lang = TimeZonesProvider.GetCurrentCulture(language); Log.DebugFormat("PortalName = {0}; model.Language = {1}, resultLang.DisplayName = {2}", model.PortalName, language, lang.DisplayName); var info = new TenantRegistrationInfo { Name = Configuration["web:portal-name"] ?? "Cloud Office Applications", Address = model.PortalName, Culture = lang, FirstName = model.FirstName, LastName = model.LastName, PasswordHash = string.IsNullOrEmpty(model.PasswordHash) ? null : model.PasswordHash, Email = (model.Email ?? "").Trim(), TimeZoneInfo = tz, MobilePhone = string.IsNullOrEmpty(model.Phone) ? null : model.Phone.Trim(), Industry = (TenantIndustry)model.Industry, Spam = model.Spam, Calls = model.Calls, Analytics = model.Analytics, LimitedControlPanel = model.LimitedControlPanel }; if (!string.IsNullOrEmpty(model.PartnerId)) { if (Guid.TryParse(model.PartnerId, out _)) { // valid guid info.PartnerId = model.PartnerId; } } if (!string.IsNullOrEmpty(model.AffiliateId)) { info.AffiliateId = model.AffiliateId; } if (!string.IsNullOrEmpty(model.Campaign)) { info.Campaign = model.Campaign; } Tenant t; try { /****REGISTRATION!!!*****/ if (!string.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl)) { ApiSystemHelper.AddTenantToCache(info.Address, SecurityContext.CurrentAccount.ID); Log.DebugFormat("PortalName = {0}; Elapsed ms. CacheController.AddTenantToCache: {1}", model.PortalName, sw.ElapsedMilliseconds); } HostedSolution.RegisterTenant(info, out t); /*********/ Log.DebugFormat("PortalName = {0}; Elapsed ms. HostedSolution.RegisterTenant: {1}", model.PortalName, sw.ElapsedMilliseconds); } catch (Exception e) { sw.Stop(); Log.Error(e); return StatusCode(StatusCodes.Status500InternalServerError, new { error = "registerNewTenantError", message = e.Message, stacktrace = e.StackTrace }); } var trialQuota = Configuration["trial-quota"]; if (!string.IsNullOrEmpty(trialQuota)) { if (int.TryParse(trialQuota, out var trialQuotaId)) { var dueDate = DateTime.MaxValue; if (int.TryParse(Configuration["trial-due"], out var dueTrial)) { dueDate = DateTime.UtcNow.AddDays(dueTrial); } var tariff = new Tariff { QuotaId = trialQuotaId, DueDate = dueDate }; HostedSolution.SetTariff(t.TenantId, tariff); } } var isFirst = true; string sendCongratulationsAddress = null; if (!string.IsNullOrEmpty(model.PasswordHash)) { isFirst = !CommonMethods.SendCongratulations(Request.Scheme, t, model.SkipWelcome, out sendCongratulationsAddress); } else if (Configuration["core:base-domain"] == "localhost") { try { /* set wizard not completed*/ TenantManager.SetCurrentTenant(t); var settings = SettingsManager.Load<WizardSettings>(); settings.Completed = false; SettingsManager.Save(settings); } catch (Exception e) { Log.Error(e); } } var reference = CommonMethods.CreateReference(Request.Scheme, t.GetTenantDomain(CoreSettings), info.Email, isFirst); Log.DebugFormat("PortalName = {0}; Elapsed ms. CreateReferenceByCookie...: {1}", model.PortalName, sw.ElapsedMilliseconds); sw.Stop(); return Ok(new { reference, tenant = CommonMethods.ToTenantWrapper(t), referenceWelcome = sendCongratulationsAddress }); }
private static UserInfo GetUser(string userName, string password, string provider, string accessToken, out bool viaEmail, string codeOAuth = null) { viaEmail = true; var action = MessageAction.LoginFailViaApi; UserInfo user = null; try { if (string.IsNullOrEmpty(provider) || provider == "email") { userName.ThrowIfNull(new ArgumentException(@"userName empty", "userName")); password.ThrowIfNull(new ArgumentException(@"password empty", "password")); int counter; int.TryParse(Cache.Get <String>("loginsec/" + userName), out counter); if (++counter > SetupInfo.LoginThreshold && !SetupInfo.IsSecretEmail(userName)) { throw new Authorize.BruteForceCredentialException(); } Cache.Insert("loginsec/" + userName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); if (EnableLdap) { var localization = new LdapLocalization(Resource.ResourceManager); var ldapUserManager = new LdapUserManager(localization); ldapUserManager.TryGetAndSyncLdapUserInfo(userName, password, out user); } if (user == null || !CoreContext.UserManager.UserExists(user.ID)) { var passwordHash = PasswordHasher.GetClientPassword(password); user = CoreContext.UserManager.GetUsersByPasswordHash( CoreContext.TenantManager.GetCurrentTenant().TenantId, userName, passwordHash); } if (user == null || !CoreContext.UserManager.UserExists(user.ID)) { throw new Exception("user not found"); } Cache.Insert("loginsec/" + userName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); } else { if (!(CoreContext.Configuration.Standalone || CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Oauth)) { throw new Exception(Resource.ErrorNotAllowedOption); } viaEmail = false; action = MessageAction.LoginFailViaApiSocialAccount; var thirdPartyProfile = ProviderManager.GetLoginProfile(provider, accessToken, codeOAuth); userName = thirdPartyProfile.EMail; user = LoginWithThirdParty.GetUserByThirdParty(thirdPartyProfile); } } catch (Authorize.BruteForceCredentialException) { MessageService.Send(Request, !string.IsNullOrEmpty(userName) ? userName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce); throw new AuthenticationException("Login Fail. Too many attempts"); } catch { MessageService.Send(Request, !string.IsNullOrEmpty(userName) ? userName : AuditResource.EmailNotSpecified, action); throw new AuthenticationException("User authentication failed"); } var tenant = CoreContext.TenantManager.GetCurrentTenant(); var settings = IPRestrictionsSettings.Load(); if (settings.Enable && user.ID != tenant.OwnerId && !IPSecurity.IPSecurity.Verify(tenant)) { throw new IPSecurityException(); } return(user); }
private UserInfo GetUser(AuthModel memberModel, out bool viaEmail) { viaEmail = true; var action = MessageAction.LoginFailViaApi; UserInfo user; try { if ((string.IsNullOrEmpty(memberModel.Provider) && string.IsNullOrEmpty(memberModel.SerializedProfile)) || memberModel.Provider == "email") { memberModel.UserName.ThrowIfNull(new ArgumentException(@"userName empty", "userName")); if (!string.IsNullOrEmpty(memberModel.Password)) { memberModel.Password.ThrowIfNull(new ArgumentException(@"password empty", "password")); } else { memberModel.PasswordHash.ThrowIfNull(new ArgumentException(@"PasswordHash empty", "PasswordHash")); } int counter; int.TryParse(Cache.Get <string>("loginsec/" + memberModel.UserName), out counter); if (++counter > SetupInfo.LoginThreshold && !SetupInfo.IsSecretEmail(memberModel.UserName)) { throw new BruteForceCredentialException(); } Cache.Insert("loginsec/" + memberModel.UserName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); memberModel.PasswordHash = (memberModel.PasswordHash ?? "").Trim(); if (string.IsNullOrEmpty(memberModel.PasswordHash)) { memberModel.Password = (memberModel.Password ?? "").Trim(); if (!string.IsNullOrEmpty(memberModel.Password)) { memberModel.PasswordHash = PasswordHasher.GetClientPassword(memberModel.Password); } } user = UserManager.GetUsersByPasswordHash( TenantManager.GetCurrentTenant().TenantId, memberModel.UserName, memberModel.PasswordHash); if (user == null || !UserManager.UserExists(user)) { throw new Exception("user not found"); } Cache.Insert("loginsec/" + memberModel.UserName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); } else { viaEmail = false; action = MessageAction.LoginFailViaApiSocialAccount; LoginProfile thirdPartyProfile; if (!string.IsNullOrEmpty(memberModel.SerializedProfile)) { thirdPartyProfile = new LoginProfile(Signature, InstanceCrypto, memberModel.SerializedProfile); } else { thirdPartyProfile = ProviderManager.GetLoginProfile(memberModel.Provider, memberModel.AccessToken); } memberModel.UserName = thirdPartyProfile.EMail; user = GetUserByThirdParty(thirdPartyProfile); } } catch (BruteForceCredentialException) { MessageService.Send(!string.IsNullOrEmpty(memberModel.UserName) ? memberModel.UserName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce); throw new AuthenticationException("Login Fail. Too many attempts"); } catch { MessageService.Send(!string.IsNullOrEmpty(memberModel.UserName) ? memberModel.UserName : AuditResource.EmailNotSpecified, action); throw new AuthenticationException("User authentication failed"); } return(user); }