public static UserInfo SyncUserLDAP(UserInfo ldapUserInfo) { UserInfo result = null; if (string.IsNullOrEmpty(ldapUserInfo.FirstName)) { ldapUserInfo.FirstName = Resource.FirstName; } if (string.IsNullOrEmpty(ldapUserInfo.LastName)) { ldapUserInfo.FirstName = Resource.LastName; } var foundDbUser = SearchExistingUser(ldapUserInfo); var asVisitor = TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers; if (Equals(foundDbUser, ASC.Core.Users.Constants.LostUser)) { if (ldapUserInfo.Status != EmployeeStatus.Active) { return(ASC.Core.Users.Constants.LostUser); } result = AddLDAPUser(ldapUserInfo, asVisitor); } else { if (!NeedUpdateUser(foundDbUser, ldapUserInfo)) { return(foundDbUser); } // Update info on existing user from LDAP info if (!foundDbUser.IsLDAP() || Equals(foundDbUser.Email, ldapUserInfo.Email) || Equals(foundDbUser.Sid, ldapUserInfo.Sid)) { result = UpdateUserWithLDAPInfo(foundDbUser, ldapUserInfo); } else if (foundDbUser.IsLDAP()) { if (foundDbUser.IsOwner()) { result = UpdateUserWithLDAPInfo(foundDbUser, ldapUserInfo); } else { CoreContext.UserManager.DeleteUser(foundDbUser.ID); result = AddLDAPUser(ldapUserInfo, asVisitor); } } else if (!Equals(foundDbUser.Email, ldapUserInfo.Email)) { var userByNewEmail = CoreContext.UserManager.GetUserByEmail(ldapUserInfo.Email); if (Equals(userByNewEmail, ASC.Core.Users.Constants.LostUser)) { result = UpdateUserWithLDAPInfo(foundDbUser, ldapUserInfo); } else { if (foundDbUser.IsOwner()) { result = UpdateUserWithLDAPInfo(foundDbUser, ldapUserInfo); } else { CoreContext.UserManager.DeleteUser(foundDbUser.ID); result = UpdateUserWithLDAPInfo(userByNewEmail, ldapUserInfo); } } } } return(result); }
private static Tuple <string, string> GetTariffNotify() { var tariff = TenantExtra.GetCurrentTariff(); var count = tariff.DueDate.Date.Subtract(DateTime.Today).Days; if (tariff.State == TariffState.Trial) { if (count <= 5) { var text = String.Format(CoreContext.Configuration.Standalone ? Resource.TariffLinkStandalone : Resource.TrialPeriodInfoText, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>"); if (count <= 0) { return(new Tuple <string, string>(Resource.TrialPeriodExpired, text)); } var end = GetNumeralResourceByCount(count, Resource.Day, Resource.DaysOne, Resource.DaysTwo); return(new Tuple <string, string>(string.Format(Resource.TrialPeriod, count, end), text)); } if (CoreContext.Configuration.Standalone) { return(new Tuple <string, string>(Resource.TrialPeriodInfoTextLicense, string.Empty)); } } if (tariff.State == TariffState.Paid) { if (CoreContext.Configuration.Standalone) { if (count < 10) { var text = String.Format(Resource.TariffLinkStandalone, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>"); if (count <= 0) { return(new Tuple <string, string>(Resource.PaidPeriodExpiredStandalone, text)); } var end = GetNumeralResourceByCount(count, Resource.Day, Resource.DaysOne, Resource.DaysTwo); return(new Tuple <string, string>(string.Format(Resource.PaidPeriodStandalone, count, end), text)); } if (tariff.QuotaId.Equals(Tenant.DEFAULT_TENANT) && TenantExtra.EnableTarrifSettings) { var text = String.Format(Resource.TariffLinkStandalone, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>"); return(new Tuple <string, string>(Resource.TariffOverdueStandalone, text)); } } else { var quota = TenantExtra.GetTenantQuota(); long notifySize; long.TryParse(ConfigurationManager.AppSettings["web.tariff-notify.storage"] ?? "314572800", out notifySize); //300 MB if (notifySize > 0 && quota.MaxTotalSize - TenantStatisticsProvider.GetUsedSize() < notifySize) { var head = string.Format(Resource.TariffExceedLimit, FileSizeComment.FilesSizeToString(quota.MaxTotalSize)); var text = String.Format(Resource.TariffExceedLimitInfoText, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>"); return(new Tuple <string, string>(head, text)); } } } if (tariff.State == TariffState.Delay) { var text = String.Format(Resource.TariffPaymentDelayText, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>", tariff.DelayDueDate.Date.ToLongDateString()); return(new Tuple <string, string>(Resource.TariffPaymentDelay, text)); } return(null); }
public void RunJob() { Status = (int)Operation.Success; CoreContext.TenantManager.SetCurrentTenant((int)Id); SecurityContext.AuthenticateMe(UserId); if (!SecurityContext.CheckPermissions(Constants.Action_AddRemoveUser)) { Error = Resource.ErrorAccessDenied; IsCompleted = true; return; } try { var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var ruleObj = jsSerializer.Deserialize <List <UserData> >(userList); var error = 0; Address address; GetUserCounter = ruleObj.Count; foreach (var userData in ruleObj) { var isValidEmail = Parser.TryParseAddress(userData.Email, out address); if (!isValidEmail || String.IsNullOrEmpty(userData.FirstName) || String.IsNullOrEmpty(userData.LastName)) { Data.Add(new UserResults { Email = userData.Email, Result = Resource.ImportContactsIncorrectFields, Class = !isValidEmail ? "error3" : "error1" }); error++; Percentage++; continue; } var us = CoreContext.UserManager.GetUserByEmail(userData.Email); if (us.ID != Constants.LostUser.ID) { Data.Add(new UserResults { Email = userData.Email, Result = CustomNamingPeople.Substitute <Resource>("ImportContactsAlreadyExists"), Class = "error2" }); error++; Percentage++; continue; } if (!importUsersAsCollaborators && TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers) { importUsersAsCollaborators = true; } var userInfo = new UserInfo { Email = userData.Email, FirstName = userData.FirstName, LastName = userData.LastName }; UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), false, true, importUsersAsCollaborators); var messageAction = importUsersAsCollaborators ? MessageAction.GuestImported : MessageAction.UserImported; MessageService.Send(httpHeaders, messageAction, MessageTarget.Create(userInfo.ID), userInfo.DisplayUserName(false)); Data.Add(new UserResults { Email = userData.Email, Result = String.Empty }); Percentage++; } } catch (Exception ex) { Status = (int)Operation.Error; Error = ex.Message; } IsCompleted = true; }
public int GetRemainingCountUsers() { return(GetTenantQuota().ActiveUsers - TenantStatisticsProvider.GetUsersCount()); }
protected void Page_Load(object sender, EventArgs e) { Page.RegisterBodyScripts(ResolveUrl("~/usercontrols/management/confirminviteactivation/js/confirm_invite_activation.js")); Page.RegisterStyleControl(VirtualPathUtility.ToAbsolute("~/usercontrols/management/confirminviteactivation/css/confirm_invite_activation.less")); _tenantInfoSettings = SettingsManager.Instance.LoadSettings <TenantInfoSettings>(TenantProvider.CurrentTenantID); var uid = Guid.Empty; try { uid = new Guid(Request["uid"]); } catch { } var email = GetEmailAddress(); if (_type != ConfirmType.Activation && AccountLinkControl.IsNotEmpty && !CoreContext.Configuration.Personal) { var thrd = (AccountLinkControl)LoadControl(AccountLinkControl.Location); thrd.InviteView = true; thrd.ClientCallback = "loginJoinCallback"; thrdParty.Visible = true; thrdParty.Controls.Add(thrd); } Page.Title = HeaderStringHelper.GetPageTitle(Resource.Authorization); UserInfo user; try { SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem); user = CoreContext.UserManager.GetUserByEmail(email); var usr = CoreContext.UserManager.GetUsers(uid); if (usr.ID.Equals(ASC.Core.Users.Constants.LostUser.ID) || usr.ID.Equals(ASC.Core.Configuration.Constants.Guest.ID)) { usr = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId); } _userAvatar = usr.GetMediumPhotoURL(); _userName = usr.DisplayUserName(true); _userPost = (usr.Title ?? "").HtmlEncode(); } finally { SecurityContext.Logout(); } if (_type == ConfirmType.LinkInvite || _type == ConfirmType.EmpInvite) { if (TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers&& _employeeType == EmployeeType.User) { ShowError(UserControlsCommonResource.TariffUserLimitReason); return; } if (!user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID)) { ShowError(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists")); return; } } else if (_type == ConfirmType.Activation) { if (user.IsActive) { ShowError(Resource.ErrorConfirmURLError); return; } if (user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID) || user.Status == EmployeeStatus.Terminated) { ShowError(string.Format(Resource.ErrorUserNotFoundByEmail, email)); return; } } var tenant = CoreContext.TenantManager.GetCurrentTenant(); if (tenant != null) { var settings = SettingsManager.Instance.LoadSettings <IPRestrictionsSettings>(tenant.TenantId); if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant.TenantId)) { ShowError(Resource.ErrorAccessRestricted); return; } } if (!IsPostBack) { return; } var firstName = GetFirstName(); var lastName = GetLastName(); var pwd = (Request["pwdInput"] ?? "").Trim(); var mustChangePassword = false; LoginProfile thirdPartyProfile; //thirdPartyLogin confirmInvite if (Request["__EVENTTARGET"] == "thirdPartyLogin") { var valueRequest = Request["__EVENTARGUMENT"]; thirdPartyProfile = new LoginProfile(valueRequest); if (!string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError)) { // ignore cancellation if (thirdPartyProfile.AuthorizationError != "Canceled at provider") { ShowError(HttpUtility.HtmlEncode(thirdPartyProfile.AuthorizationError)); } return; } if (string.IsNullOrEmpty(thirdPartyProfile.EMail)) { ShowError(HttpUtility.HtmlEncode(Resource.ErrorNotCorrectEmail)); return; } } if (Request["__EVENTTARGET"] == "confirmInvite") { if (String.IsNullOrEmpty(email)) { _errorMessage = Resource.ErrorEmptyUserEmail; return; } if (!email.TestEmailRegex()) { _errorMessage = Resource.ErrorNotCorrectEmail; return; } if (String.IsNullOrEmpty(firstName)) { _errorMessage = Resource.ErrorEmptyUserFirstName; return; } if (String.IsNullOrEmpty(lastName)) { _errorMessage = Resource.ErrorEmptyUserLastName; return; } var checkPassResult = CheckPassword(pwd); if (!String.IsNullOrEmpty(checkPassResult)) { _errorMessage = checkPassResult; return; } } var userID = Guid.Empty; try { SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem); if (_type == ConfirmType.EmpInvite || _type == ConfirmType.LinkInvite) { if (TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers&& _employeeType == EmployeeType.User) { ShowError(UserControlsCommonResource.TariffUserLimitReason); return; } UserInfo newUser; if (Request["__EVENTTARGET"] == "confirmInvite") { var fromInviteLink = _type == ConfirmType.LinkInvite; newUser = CreateNewUser(firstName, lastName, email, pwd, _employeeType, fromInviteLink); var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite; MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, newUser.DisplayUserName(false)); userID = newUser.ID; } if (Request["__EVENTTARGET"] == "thirdPartyLogin") { if (!String.IsNullOrEmpty(CheckPassword(pwd))) { pwd = UserManagerWrapper.GeneratePassword(); mustChangePassword = true; } var valueRequest = Request["__EVENTARGUMENT"]; thirdPartyProfile = new LoginProfile(valueRequest); newUser = CreateNewUser(GetFirstName(thirdPartyProfile), GetLastName(thirdPartyProfile), GetEmailAddress(thirdPartyProfile), pwd, _employeeType, false); var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite; MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, newUser.DisplayUserName(false)); userID = newUser.ID; if (!String.IsNullOrEmpty(thirdPartyProfile.Avatar)) { SaveContactImage(userID, thirdPartyProfile.Avatar); } var linker = new AccountLinker("webstudio"); linker.AddLink(userID.ToString(), thirdPartyProfile); } } else if (_type == ConfirmType.Activation) { user.ActivationStatus = EmployeeActivationStatus.Activated; user.FirstName = firstName; user.LastName = lastName; CoreContext.UserManager.SaveUserInfo(user); SecurityContext.SetUserPassword(user.ID, pwd); userID = user.ID; //notify if (user.IsVisitor()) { StudioNotifyService.Instance.GuestInfoAddedAfterInvite(user, pwd); MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.GuestActivated, user.DisplayUserName(false)); } else { StudioNotifyService.Instance.UserInfoAddedAfterInvite(user, pwd); MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.UserActivated, user.DisplayUserName(false)); } } } catch (Exception exception) { _errorMessage = HttpUtility.HtmlEncode(exception.Message); return; } finally { SecurityContext.Logout(); } user = CoreContext.UserManager.GetUsers(userID); try { var cookiesKey = SecurityContext.AuthenticateMe(user.Email, pwd); CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey); MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess); StudioNotifyService.Instance.UserHasJoin(); if (mustChangePassword) { StudioNotifyService.Instance.UserPasswordChange(user); } } catch (Exception exception) { (Page as Confirm).ErrorMessage = HttpUtility.HtmlEncode(exception.Message); return; } UserHelpTourHelper.IsNewUser = true; if (CoreContext.Configuration.Personal) { PersonalSettings.IsNewUser = true; } Response.Redirect("~/"); }
public static ConverterData StartCreationFileAsync(Invoice data) { using (var docxStream = GetStreamDocx(data)) { var documentService = new DocumentService(StudioKeySettings.GetKey(), StudioKeySettings.GetSKey(), TenantStatisticsProvider.GetUsersCount()); var revisionId = DocumentService.GenerateRevisionId(Guid.NewGuid().ToString()); var crmStorageUrl = WebConfigurationManager.AppSettings["crm.invoice.url.storage"]; if (string.IsNullOrEmpty(crmStorageUrl)) { crmStorageUrl = FilesLinkUtility.DocServiceStorageUrl; } var crmConverterUrl = WebConfigurationManager.AppSettings["crm.invoice.url.converter"]; if (string.IsNullOrEmpty(crmConverterUrl)) { crmConverterUrl = FilesLinkUtility.DocServiceConverterUrl; } var externalUri = documentService.GetExternalUri(crmStorageUrl, docxStream, "text/plain", revisionId); string urlToFile; documentService.GetConvertedUri(crmConverterUrl, externalUri, FormatDocx, FormatPdf, revisionId, true, out urlToFile); return new ConverterData { ConverterUrl = crmConverterUrl, StorageUrl = externalUri, RevisionId = revisionId, InvoiceId = data.ID, UrlToFile = urlToFile }; } }
protected void Page_Load(object sender, EventArgs e) { var userInfo = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); IsAdmin = userInfo.IsAdmin() || WebItemSecurity.IsProductAdministrator(WebItemManager.PeopleProductID, userInfo.ID); Actions = new AllowedActions(userInfo); var quota = TenantExtra.GetTenantQuota(); IsFreeTariff = quota.Free && !quota.Open; IsStandalone = CoreContext.Configuration.Standalone; DisplayPayments = TenantExtra.EnableTariffSettings && (!CoreContext.Configuration.Standalone || quota.ActiveUsers != LicenseReader.MaxUserCount); if (DisplayPayments) { int notifyCount; int.TryParse(ConfigurationManagerExtension.AppSettings["web.tariff-notify.user"] ?? "5", out notifyCount); DisplayPaymentsFirstUser = notifyCount > 0 && quota.ActiveUsers - TenantStatisticsProvider.GetUsersCount() < notifyCount; DisplayPaymentsFirstGuest = !IsStandalone && notifyCount > 0 && quota.ActiveUsers * Constants.CoefficientOfVisitors - TenantStatisticsProvider.GetVisitorsCount() < notifyCount; } var controlEmailChange = (UserEmailChange)LoadControl(UserEmailChange.Location); controlEmailChange.UserInfo = userInfo; controlEmailChange.RegisterStylesAndScripts = true; userEmailChange.Controls.Add(controlEmailChange); loaderHolder.Controls.Add(LoadControl(LoaderPage.Location)); userConfirmationDelete.Controls.Add(LoadControl(ConfirmationDeleteUser.Location)); if (Actions.AllowEdit) { userPwdChange.Controls.Add(LoadControl(PwdTool.Location)); } Title = HeaderStringHelper.GetPageTitle(PeopleResource.ProductName); HelpLink = CommonLinkUtility.GetHelpLink(); }
private void RegisterScript() { Page.RegisterStyleControl(VirtualPathUtility.ToAbsolute("~/usercontrols/users/importusers/css/import.less")); Page.RegisterBodyScripts(ResolveUrl("~/js/uploader/ajaxupload.js")); Page.RegisterBodyScripts(ResolveUrl("~/js/third-party/zeroclipboard.js")); Page.RegisterBodyScripts(ResolveUrl("~/usercontrols/users/ImportUsers/js/ImportUsers.js")); var script = new StringBuilder(); script.AppendFormat("ImportUsersManager.FName = '{0}';", Resources.Resource.ImportContactsFirstName.ReplaceSingleQuote()); script.AppendFormat("ImportUsersManager.EmptyFName = '{0}';", Resources.Resource.ImportContactsEmptyFirstName.ReplaceSingleQuote()); script.AppendFormat("ImportUsersManager.LName = '{0}';", Resources.Resource.ImportContactsLastName.ReplaceSingleQuote().Replace("\n", "")); script.AppendFormat("ImportUsersManager.EmptyLName = '{0}';", Resources.Resource.ImportContactsEmptyLastName.ReplaceSingleQuote()); script.AppendFormat("ImportUsersManager.Email = '{0}';", Resources.Resource.ImportContactsEmail.ReplaceSingleQuote()); script.AppendFormat("ImportUsersManager._errorImport = '{0}';", String.Format(Resources.Resource.ImportContactsFromFileError.ReplaceSingleQuote(), "<br />")); script.AppendFormat("ImportUsersManager._errorEmail = '{0}';", Resources.Resource.ImportContactsIncorrectFields.ReplaceSingleQuote()); script.AppendFormat("ImportUsersManager._emptySocImport = '{0}';", String.Format(Resources.Resource.ImportContactsEmptyData.ReplaceSingleQuote().Replace("\n", ""), "<br />")); script.AppendFormat("ImportUsersManager._portalLicence.maxUsers = '{0}';", TenantExtra.GetTenantQuota().ActiveUsers); script.AppendFormat("ImportUsersManager._portalLicence.currectUsers = '{0}';", TenantStatisticsProvider.GetUsersCount()); script.Append("jq(document).click(function(event) {"); script.Append("jq.dropdownToggle().registerAutoHide(event, '.file', '.fileSelector');"); script.Append("jq('#upload img').attr('src', StudioManager.GetImage('loader_16.gif'));"); script.Append("});"); Page.RegisterInlineScript(script.ToString()); var sb = new StringBuilder(); sb.AppendFormat(@"ZeroClipboard.setMoviePath('{0}');", CommonLinkUtility.ToAbsolute("~/js/flash/zeroclipboard/ZeroClipboard10.swf") ); Page.RegisterInlineScript(sb.ToString(), true); }
public object SaveUsers(string userList, bool importUsersAsCollaborators) { if (!SecurityContext.CheckPermissions(Constants.Action_AddRemoveUser)) { return new { Status = (int)Operation.Error, Message = Resources.Resource.ErrorAccessDenied } } ; var coll = new List <UserResults>(); try { var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var ruleObj = jsSerializer.Deserialize <List <UserData> >(userList); var error = 0; foreach (var userData in ruleObj) { var validateEmail = UserManagerWrapper.ValidateEmail(userData.Email); if (!validateEmail || String.IsNullOrEmpty(userData.FirstName) || String.IsNullOrEmpty(userData.LastName)) { coll.Add(new UserResults { Email = userData.Email, Result = Resources.Resource.ImportContactsIncorrectFields, Class = !validateEmail ? "error3" : "error1" }); error++; continue; } var us = CoreContext.UserManager.GetUserByEmail(userData.Email); if (us.ID != Constants.LostUser.ID) { coll.Add(new UserResults { Email = userData.Email, Result = Resources.Resource.ImportContactsAlreadyExists, Class = "error2" }); error++; continue; } if (error != 0) { continue; } if (!importUsersAsCollaborators && TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers) { importUsersAsCollaborators = true; } UserManagerWrapper.AddUser(new UserInfo { Email = userData.Email, FirstName = userData.FirstName, LastName = userData.LastName }, UserManagerWrapper.GeneratePassword(), false, true, importUsersAsCollaborators); coll.Add(new UserResults { Email = userData.Email, Result = String.Empty }); } return(new { Status = (int)Operation.Success, Data = coll }); } catch (Exception ex) { return(new { Status = (int)Operation.Error, Message = ex.Message }); } }
/// <summary> /// Max possible file size for not chunked upload. Less or equal than 100 mb. /// </summary> public long MaxUploadSize(TenantExtra tenantExtra, TenantStatisticsProvider tenantStatisticsProvider) { return(Math.Min(AvailableFileSize, MaxChunkedUploadSize(tenantExtra, tenantStatisticsProvider))); }
public bool CanAddVisitor() { return(CoreContext.Configuration.Standalone || TenantStatisticsProvider.GetVisitorsCount() < TenantExtra.GetTenantQuota().ActiveUsers *Constants.CoefficientOfVisitors); }
public BackupHelper(TenantManager tenantManager, CoreBaseSettings coreBaseSettings, TenantStatisticsProvider tenantStatisticsProvider) { TenantManager = tenantManager; CoreBaseSettings = coreBaseSettings; TenantStatisticsProvider = tenantStatisticsProvider; }
protected void Page_PreInit(object sender, EventArgs e) { if (CheckWizardCompleted) { var s = WizardSettings.Load(); if (!s.Completed) { Response.Redirect("~/wizard.aspx"); } } //check auth if (!SecurityContext.IsAuthenticated && !AuthByCookies() && !MayNotAuth) { if (TenantAccessSettings.Load().Anyone) { OutsideAuth(); } else { var refererURL = GetRefererUrl(); Session["refererURL"] = refererURL; var authUrl = "~/auth.aspx"; if (Request.DesktopApp()) { authUrl += "?desktop=" + Request["desktop"]; } Response.Redirect(authUrl, true); } } var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); if (!MayNotPaid && (TenantStatisticsProvider.IsNotPaid() || TenantExtra.UpdatedWithoutLicense)) { if (TariffSettings.HidePricingPage && !user.IsAdmin()) { Response.StatusCode = (int)HttpStatusCode.PaymentRequired; Response.End(); } else { Response.Redirect(TenantExtra.GetTariffPageLink() + (Request.DesktopApp() ? "?desktop=true" : ""), true); } } //check disable and public var webitem = CommonLinkUtility.GetWebItemByUrl(Request.Url.ToString()); var parentIsDisabled = false; if (webitem != null && webitem.IsSubItem()) { var parentItemID = WebItemManager.Instance.GetParentItemID(webitem.ID); parentIsDisabled = WebItemManager.Instance[parentItemID].IsDisabled(); } if (webitem != null && (webitem.IsDisabled() || parentIsDisabled) && !MayNotAuth) { if (webitem.ID == WebItemManager.PeopleProductID && string.Equals(GetType().BaseType.FullName, "ASC.Web.People.Profile")) { Response.Redirect("~/my.aspx", true); } Response.Redirect("~/", true); } if (SecurityContext.IsAuthenticated && !CoreContext.Configuration.Personal) { try { StatisticManager.SaveUserVisit(TenantProvider.CurrentTenantID, SecurityContext.CurrentAccount.ID, CommonLinkUtility.GetProductID()); } catch (Exception exc) { Log.Error("failed save user visit", exc); } } }
public QuotaWrapper(Tenant tenant, CoreBaseSettings coreBaseSettings, CoreConfiguration configuration, TenantExtra tenantExtra, TenantStatisticsProvider tenantStatisticsProvider, AuthContext authContext, SettingsManager settingsManager, WebItemManager webItemManager) { TenantExtra = tenantExtra; TenantStatisticsProvider = tenantStatisticsProvider; WebItemManager = webItemManager; var quota = TenantExtra.GetTenantQuota(); var quotaRows = TenantStatisticsProvider.GetQuotaRows(tenant.TenantId).ToList(); StorageSize = (ulong)Math.Max(0, quota.MaxTotalSize); UsedSize = (ulong)Math.Max(0, quotaRows.Sum(r => r.Counter)); MaxUsersCount = TenantExtra.GetTenantQuota().ActiveUsers; UsersCount = coreBaseSettings.Personal ? 1 : TenantStatisticsProvider.GetUsersCount(); StorageUsage = quotaRows .Select(x => new QuotaUsage { Path = x.Path.TrimStart('/').TrimEnd('/'), Size = x.Counter, }) .ToList(); if (coreBaseSettings.Personal && SetupInfo.IsVisibleSettings("PersonalMaxSpace")) { UserStorageSize = configuration.PersonalMaxSpace(settingsManager); var webItem = WebItemManager[WebItemManager.DocumentsProductID]; if (webItem.Context.SpaceUsageStatManager is IUserSpaceUsage spaceUsageManager) { UserUsedSize = spaceUsageManager.GetUserSpaceUsage(authContext.CurrentAccount.ID); } } MaxFileSize = Math.Min(AvailableSize, (ulong)quota.MaxFileSize); }
private void RegisterScript() { Page.RegisterStyle("~/usercontrols/users/importusers/css/import.less") .RegisterBodyScripts("~/js/uploader/ajaxupload.js", "~/usercontrols/users/ImportUsers/js/ImportUsers.js"); var script = new StringBuilder(); script.AppendFormat("ImportUsersManager.FName = '{0}';", Resource.ImportContactsFirstName.ReplaceSingleQuote()); script.AppendFormat("ImportUsersManager.EmptyFName = '{0}';", Resource.ImportContactsEmptyFirstName.ReplaceSingleQuote()); script.AppendFormat("ImportUsersManager.LName = '{0}';", Resource.ImportContactsLastName.ReplaceSingleQuote().Replace("\n", "")); script.AppendFormat("ImportUsersManager.EmptyLName = '{0}';", Resource.ImportContactsEmptyLastName.ReplaceSingleQuote()); script.AppendFormat("ImportUsersManager.Email = '{0}';", Resource.ImportContactsEmail.ReplaceSingleQuote()); script.AppendFormat("ImportUsersManager._errorImport = '{0}';", String.Format(Resource.ImportContactsFromFileError.ReplaceSingleQuote(), "<br />")); script.AppendFormat("ImportUsersManager._errorEmail = '{0}';", Resource.ImportContactsIncorrectFields.ReplaceSingleQuote()); script.AppendFormat("ImportUsersManager._emptySocImport = '{0}';", String.Format(Resource.ImportContactsEmptyData.ReplaceSingleQuote().Replace("\n", ""), "<br />")); script.AppendFormat("ImportUsersManager._portalLicence.maxUsers = '{0}';", TenantExtra.GetTenantQuota().ActiveUsers); script.AppendFormat("ImportUsersManager._portalLicence.currectUsers = '{0}';", TenantStatisticsProvider.GetUsersCount()); script.Append("jq(document).click(function(event) {"); script.Append("jq.dropdownToggle({rightPos: true}).registerAutoHide(event, '.file', '.fileSelector');"); script.Append("jq('#upload img').attr('src', StudioManager.GetImage('loader_16.gif'));"); script.Append("});"); Page.RegisterInlineScript(script.ToString()); }
public override void OnProcessRequest(HttpContext context) { var action = context.Request[CommonLinkUtility.Action]; if (string.IsNullOrEmpty(action)) { throw new HttpException((int)HttpStatusCode.BadRequest, FilesCommonResource.ErrorMassage_BadRequest); } action = action.ToLower(); var publicActions = new[] { "view", "download", "save", "stream" }; if (!publicActions.Contains(action) && !SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey))) { context.Response.Redirect("~/"); return; } if (TenantStatisticsProvider.IsNotPaid()) { context.Response.Redirect(TenantExtra.GetTariffPageLink()); } try { switch (action) { case "view": DownloadFile(context, true); break; case "download": DownloadFile(context, false); break; case "bulk": BulkDownloadFile(context); break; case "save": SaveFile(context); break; case "stream": StreamFile(context); break; case "create": CreateFile(context); break; case "redirect": Redirect(context); break; default: throw new InvalidOperationException(); } } catch (InvalidOperationException e) { throw new HttpException((int)HttpStatusCode.InternalServerError, FilesCommonResource.ErrorMassage_BadRequest, e); } }
private static string GetUrlToFile(Stream docxStream) { var documentService = new DocumentService(StudioKeySettings.GetKey(), StudioKeySettings.GetSKey(), TenantStatisticsProvider.GetUsersCount()); var revisionId = DocumentService.GenerateRevisionId(Guid.NewGuid().ToString()); var crmStorageUrl = WebConfigurationManager.AppSettings["crm.invoice.url.storage"]; if (string.IsNullOrEmpty(crmStorageUrl)) { crmStorageUrl = FilesLinkUtility.DocServiceStorageUrl; } var crmConverterUrl = WebConfigurationManager.AppSettings["crm.invoice.url.converter"]; if (string.IsNullOrEmpty(crmConverterUrl)) { crmConverterUrl = FilesLinkUtility.DocServiceConverterUrl; } var externalUri = documentService.GetExternalUri(crmStorageUrl, docxStream, "text/plain", revisionId); log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. externalUri = {0}", externalUri); string urlToFile; documentService.GetConvertedUri(crmConverterUrl, externalUri, FormatDocx, FormatPdf, revisionId, false, out urlToFile); log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. urlToFile = {0}", urlToFile); return urlToFile; }
protected void Page_Load(object sender, EventArgs e) { Page.RegisterBodyScripts(ResolveUrl("~/usercontrols/management/tariffsettings/js/tariffusage.js")); Page.RegisterStyleControl(VirtualPathUtility.ToAbsolute("~/usercontrols/management/tariffsettings/css/tariffusage.less")); UsersCount = TenantStatisticsProvider.GetUsersCount(); UsedSize = TenantStatisticsProvider.GetUsedSize(); CurrentTariff = TenantExtra.GetCurrentTariff(); CurrentQuota = TenantExtra.GetTenantQuota(); var partner = CoreContext.PaymentManager.GetApprovedPartner(); if (partner != null) { Partner = partner; _quotaList = CoreContext.PaymentManager.GetPartnerTariffs(Partner.Id); if (!string.IsNullOrEmpty(Partner.Currency)) { _region = new RegionInfo(Partner.Currency); } var control = (TariffPartner)LoadControl(TariffPartner.Location); control.CurPartner = Partner; control.TariffNotPaid = CurrentTariff.State >= TariffState.NotPaid; control.TariffProlongable = CurrentTariff.Prolongable; PaymentsCodeHolder.Controls.Add(control); } if (_quotaList == null || !_quotaList.Any()) { _quotaList = TenantExtra.GetTenantQuotas(); } else if (!CurrentQuota.Trial) { CurrentQuota = _quotaList.FirstOrDefault(q => q.Id == CurrentQuota.Id) ?? CurrentQuota; } _quotaList = _quotaList.OrderBy(r => r.ActiveUsers).ToList().Where(r => !r.Trial); QuotasYear = _quotaList.Where(r => r.Year).ToList(); HideBuyRecommendation = CurrentTariff.Autorenewal || TariffSettings.HideRecommendation || Partner != null; AnnualDiscount = QuotasYear.All(q => q.Price2 != decimal.Zero); HideAnnualRecomendation = !AnnualDiscount || (CurrentQuota.Year && !CurrentQuota.Free && !CurrentQuota.Trial) || TariffSettings.HideAnnualRecomendation || CurrentQuota.NonProfit; if (!HideAnnualRecomendation) { AnnualQuotaForDisplay = QuotaForDisplay; if (AnnualQuotaForDisplay == null || AnnualQuotaForDisplay.Free || AnnualQuotaForDisplay.Trial || !AnnualQuotaForDisplay.Visible) { HideAnnualRecomendation = true; } else if (!AnnualQuotaForDisplay.Year) { AnnualQuotaForDisplay = _quotaList.FirstOrDefault(r => r.ActiveUsers == AnnualQuotaForDisplay.ActiveUsers && r.Year); if (AnnualQuotaForDisplay == null) { HideAnnualRecomendation = true; } } } downgradeInfoContainer.Options.IsPopup = true; buyRecommendationContainer.Options.IsPopup = true; annualRecomendationContainer.Options.IsPopup = true; AjaxPro.Utility.RegisterTypeForAjax(GetType()); if (StudioSmsNotificationSettings.IsVisibleSettings && (SettingsManager.Instance.LoadSettings <StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID).EnableSetting || CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID)) && Partner == null) { SmsEnable = true; var smsBuy = (SmsBuy)LoadControl(SmsBuy.Location); smsBuy.ShowLink = !SettingsManager.Instance.LoadSettings <StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID).EnableSetting; SmsBuyHolder.Controls.Add(smsBuy); } if (VoipPaymentSettings.IsVisibleSettings && CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID) && Partner == null) { VoipEnable = true; var voipBuy = (VoipBuy)LoadControl(VoipBuy.Location); VoipBuyHolder.Controls.Add(voipBuy); } if (Partner == null) { RegisterScript(); } if (Partner == null && Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName == "ru") { _region = new RegionInfo("RU"); RateRuble = SetupInfo.ExchangeRateRuble; SetStar(string.Format(Resource.TariffsCurrencyRu, RateRuble)); } }
public static ASC.Files.Core.File GetConvertedFile(ConverterData data) { if (string.IsNullOrEmpty(data.ConverterUrl) || string.IsNullOrEmpty(data.StorageUrl) || string.IsNullOrEmpty(data.RevisionId)) { return null; } var documentService = new DocumentService(StudioKeySettings.GetKey(), StudioKeySettings.GetSKey(), TenantStatisticsProvider.GetUsersCount()); string urlToFile; documentService.GetConvertedUri(data.ConverterUrl, data.StorageUrl, FormatDocx, FormatPdf, data.RevisionId, true, out urlToFile); if (string.IsNullOrEmpty(urlToFile)) { return null; } var invoice = Global.DaoFactory.GetInvoiceDao().GetByID(data.InvoiceId); return SaveFile(invoice, urlToFile); }
protected void Page_Load(object sender, EventArgs e) { if (!SecurityContext.CheckPermissions(Constants.Action_AddRemoveUser)) { Response.Redirect(CommonLinkUtility.GetDefault()); } EnableUsers = TenantExtra.GetTenantQuota().ActiveUsers - TenantStatisticsProvider.GetUsersCount(); EnableGuests = Constants.CoefficientOfVisitors * TenantExtra.GetTenantQuota().ActiveUsers - TenantStatisticsProvider.GetVisitorsCount(); EnableGuests = EnableGuests >= 0 ? EnableGuests : 0; IsStandalone = CoreContext.Configuration.Standalone; var tariff = (Studio.UserControls.Management.TariffLimitExceed)LoadControl(Studio.UserControls.Management.TariffLimitExceed.Location); Tariff.Controls.Add(tariff); var quota = TenantExtra.GetTenantQuota(); PeopleLimit = Math.Min(quota.ActiveUsers - TenantStatisticsProvider.GetUsersCount(), 0); FreeTariff = (quota.Free || quota.NonProfit || quota.Trial) && !quota.Open; HelpLink = CommonLinkUtility.GetHelpLink(); icon.Options.IsPopup = true; icon.Options.PopupContainerCssClass = "okcss popupContainerClass"; icon.Options.OnCancelButtonClick = "ASC.People.Import.hideInfoWindow('okcss');"; limitPanel.Options.IsPopup = true; limitPanel.Options.OnCancelButtonClick = "ASC.People.Import.hideImportUserLimitPanel();"; Utility.RegisterTypeForAjax(GetType()); RegisterScript(); }
protected void Page_PreInit(object sender, EventArgs e) { if (CheckWizardCompleted) { var s = WizardSettings.Load(); if (!s.Completed) { Response.Redirect("~/wizard.aspx"); } } //check auth if (!SecurityContext.IsAuthenticated && !AuthByCookies() && !MayNotAuth) { if (TenantAccessSettings.Load().Anyone) { OutsideAuth(); } else { var refererURL = GetRefererUrl(); Session["refererURL"] = refererURL; Response.Redirect("~/auth.aspx", true); } } var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); if (!MayNotPaid && TenantStatisticsProvider.IsNotPaid()) { if (TariffSettings.HidePricingPage && !user.IsAdmin()) { Response.StatusCode = (int)HttpStatusCode.PaymentRequired; Response.End(); } else { Response.Redirect(TenantExtra.GetTariffPageLink(), true); } } if (SecurityContext.IsAuthenticated && StudioSmsNotificationSettings.IsVisibleSettings && StudioSmsNotificationSettings.Enable && !MayPhoneNotActivate) { if (!CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID) && (string.IsNullOrEmpty(user.MobilePhone) || user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)) { Response.Redirect(CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PhoneActivation), true); } } //check disable and public var webitem = CommonLinkUtility.GetWebItemByUrl(Request.Url.ToString()); var parentIsDisabled = false; if (webitem != null && webitem.IsSubItem()) { var parentItemID = WebItemManager.Instance.GetParentItemID(webitem.ID); parentIsDisabled = WebItemManager.Instance[parentItemID].IsDisabled(); } if (webitem != null && (webitem.IsDisabled() || parentIsDisabled) && !MayNotAuth) { if (webitem.ID == WebItemManager.PeopleProductID && string.Equals(GetType().BaseType.FullName, "ASC.Web.People.Profile")) { Response.Redirect("~/my.aspx", true); } Response.Redirect("~/", true); } if (SecurityContext.IsAuthenticated && !CoreContext.Configuration.Personal) { try { StatisticManager.SaveUserVisit(TenantProvider.CurrentTenantID, SecurityContext.CurrentAccount.ID, CommonLinkUtility.GetProductID()); } catch (Exception exc) { Log.Error("failed save user visit", exc); } } }
private bool CheckStartupEnabled(TenantQuota currentQuota, TenantQuota startupQuota, out string errorMessage) { errorMessage = string.Empty; if (!currentQuota.Trial) { errorMessage = UserControlsCommonResource.SaasTariffErrorTrial; return(false); } if (TenantStatisticsProvider.GetUsersCount() > startupQuota.ActiveUsers) { errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorUsers, startupQuota.ActiveUsers); return(false); } if (TenantStatisticsProvider.GetVisitorsCount() > 0) { errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorGuests, 0); return(false); } if (TenantStatisticsProvider.GetAdminsCount() > 1) { errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorAdmins, 1); return(false); } if (TenantStatisticsProvider.GetUsedSize() > startupQuota.MaxTotalSize) { errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorStorage, FileSizeComment.FilesSizeToString(startupQuota.MaxTotalSize)); return(false); } var authServiceList = new AuthorizationKeys().AuthServiceList.Where(x => x.CanSet); foreach (var service in authServiceList) { if (service.Props.Any(r => !string.IsNullOrEmpty(r.Value))) { errorMessage = UserControlsCommonResource.SaasTariffErrorThirparty; return(false); } } if (!TenantWhiteLabelSettings.Load().IsDefault) { errorMessage = UserControlsCommonResource.SaasTariffErrorWhiteLabel; return(false); } var currentTenant = CoreContext.TenantManager.GetCurrentTenant(); if (!string.IsNullOrEmpty(currentTenant.MappedDomain)) { errorMessage = UserControlsCommonResource.SaasTariffErrorDomain; return(false); } var accountLinker = new AccountLinker("webstudio"); foreach (var user in CoreContext.UserManager.GetUsers(EmployeeStatus.All)) { var linkedAccounts = accountLinker.GetLinkedProfiles(user.ID.ToString()); if (linkedAccounts.Any()) { errorMessage = UserControlsCommonResource.SaasTariffErrorOauth; return(false); } } if (SsoSettingsV2.Load().EnableSso) { errorMessage = UserControlsCommonResource.SaasTariffErrorSso; return(false); } if (ActiveDirectory.Base.Settings.LdapSettings.Load().EnableLdapAuthentication) { errorMessage = UserControlsCommonResource.SaasTariffErrorLdap; return(false); } using (var service = new BackupServiceClient()) { var scheduleResponse = service.GetSchedule(currentTenant.TenantId); if (scheduleResponse != null) { errorMessage = UserControlsCommonResource.SaasTariffErrorAutoBackup; return(false); } } return(true); }
public AjaxResponse SendJoinInviteMail(string email) { email = (email ?? "").Trim(); var resp = new AjaxResponse { rs1 = "0" }; try { if (String.IsNullOrEmpty(email)) { resp.rs2 = Resource.ErrorNotCorrectEmail; return(resp); } if (!email.TestEmailRegex()) { resp.rs2 = Resource.ErrorNotCorrectEmail; } var user = CoreContext.UserManager.GetUserByEmail(email); if (!user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID)) { resp.rs1 = "0"; resp.rs2 = CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists").HtmlEncode(); return(resp); } var tenant = CoreContext.TenantManager.GetCurrentTenant(); if (tenant != null) { var settings = SettingsManager.Instance.LoadSettings <IPRestrictionsSettings>(tenant.TenantId); if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant.TenantId)) { resp.rs2 = Resource.ErrorAccessRestricted; return(resp); } } var trustedDomainSettings = SettingsManager.Instance.LoadSettings <StudioTrustedDomainSettings>(TenantProvider.CurrentTenantID); var emplType = trustedDomainSettings.InviteUsersAsVisitors ? EmployeeType.Visitor : EmployeeType.User; var enableInviteUsers = TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers; if (!enableInviteUsers) { emplType = EmployeeType.Visitor; } switch (tenant.TrustedDomainsType) { case TenantTrustedDomainsType.Custom: { var address = new MailAddress(email); if (tenant.TrustedDomains.Any(d => address.Address.EndsWith("@" + d, StringComparison.InvariantCultureIgnoreCase))) { StudioNotifyService.Instance.InviteUsers(email, "", true, emplType); MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.SentInviteInstructions, email); resp.rs1 = "1"; resp.rs2 = Resource.FinishInviteJoinEmailMessage; return(resp); } else { resp.rs2 = Resource.ErrorEmailDomainNotAllowed; } } break; case TenantTrustedDomainsType.All: StudioNotifyService.Instance.InviteUsers(email, "", true, emplType); MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.SentInviteInstructions, email); resp.rs1 = "1"; resp.rs2 = Resource.FinishInviteJoinEmailMessage; return(resp); default: resp.rs2 = Resource.ErrorNotCorrectEmail; break; } } catch (FormatException) { resp.rs2 = Resource.ErrorNotCorrectEmail; } catch (Exception e) { resp.rs2 = HttpUtility.HtmlEncode(e.Message); } return(resp); }
private Tuple <string, string> GetTariffNotify() { var hidePricingPage = !CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin() && (TariffSettings.HidePricingPage || CoreContext.Configuration.Standalone); var tariff = TenantExtra.GetCurrentTariff(); var count = tariff.DueDate.Date.Subtract(DateTime.Today).Days; if (tariff.State == TariffState.Trial) { if (!hidePricingPage && count <= 5) { var text = String.Format(CoreContext.Configuration.Standalone ? Resource.TariffLinkStandalone : Resource.TrialPeriodInfoText, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>"); if (count <= 0) { return(new Tuple <string, string>(Resource.TrialPeriodExpired, text)); } var end = GetNumeralResourceByCount(count, Resource.Day, Resource.DaysOne, Resource.DaysTwo); return(new Tuple <string, string>(string.Format(Resource.TrialPeriod, count, end), text)); } if (CoreContext.Configuration.Standalone) { return(new Tuple <string, string>(Resource.TrialPeriodInfoTextLicense, string.Empty)); } } if (!hidePricingPage && tariff.State == TariffState.Paid) { if (CoreContext.Configuration.Standalone) { if (TenantControlPanelSettings.Instance.LimitedAccess) { return(null); } CanClose = true; var text = String.Format(Resource.TariffLinkStandaloneLife, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>"); if (count <= 0) { return(new Tuple <string, string>(Resource.PaidPeriodExpiredStandaloneLife, text)); } if (count < 10) { var end = GetNumeralResourceByCount(count, Resource.Day, Resource.DaysOne, Resource.DaysTwo); return(new Tuple <string, string>(string.Format(Resource.PaidPeriodStandaloneLife, count, end), text)); } } else { var quota = TenantExtra.GetTenantQuota(); long notifySize; long.TryParse(ConfigurationManagerExtension.AppSettings["web.tariff-notify.storage"] ?? "314572800", out notifySize); //300 MB if (notifySize > 0 && quota.MaxTotalSize - TenantStatisticsProvider.GetUsedSize() < notifySize) { var head = string.Format(Resource.TariffExceedLimit, FileSizeComment.FilesSizeToString(quota.MaxTotalSize)); var text = String.Format(Resource.TariffExceedLimitInfoText, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>"); return(new Tuple <string, string>(head, text)); } } } if (!hidePricingPage && tariff.State == TariffState.Delay) { var text = String.Format(Resource.TariffPaymentDelayText, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>", tariff.DelayDueDate.Date.ToLongDateString()); return(new Tuple <string, string>(Resource.TariffPaymentDelay, text)); } return(null); }
private UserInfo CreateUsersAndGroups(LDAPSupportSettings settings) { AscCache.Default.Insert("SaveLdapSettingTaskStatus", Resource.LdapSettingsStatusGettingGroupsFromLdap, TimeSpan.FromMinutes(15)); List <GroupInfo> existingGroups; var groups = importer.GetDiscoveredGroupsByAttributes(settings, out existingGroups); if (groups != null && groups.Count == 0 && existingGroups.Count == 0) { log.Error("Not found any group which would contain users. groups.Count == 0."); throw new GroupsNotFoundException(); } AscCache.Default.Insert("SaveLdapSettingTaskPercentage", 15, TimeSpan.FromMinutes(15)); AscCache.Default.Insert("SaveLdapSettingTaskStatus", Resource.LdapSettingsStatusGettingUsersFromLdap, TimeSpan.FromMinutes(15)); var users = importer.GetDiscoveredUsersByAttributes(settings); AscCache.Default.Insert("SaveLdapSettingTaskPercentage", 20, TimeSpan.FromMinutes(15)); AscCache.Default.Insert("SaveLdapSettingTaskStatus", Resource.LdapSettingsStatusSavingGroups, TimeSpan.FromMinutes(15)); AddGroupsToCore(groups); AscCache.Default.Insert("SaveLdapSettingTaskPercentage", 40, TimeSpan.FromMinutes(15)); AscCache.Default.Insert("SaveLdapSettingTaskStatus", Resource.LdapSettingsStatusSavingUsers, TimeSpan.FromMinutes(15)); double percents = 35; var step = percents / users.Count; double percentage = Convert.ToDouble(AscCache.Default.Get <string>("SaveLdapSettingTaskPercentage") ?? "0"); if (users != null && users.Count != 0) { for (int i = 0; i < users.Count; i++) { if (users[i].FirstName == string.Empty) { users[i].FirstName = Resource.FirstName; } if (users[i].LastName == string.Empty) { users[i].LastName = Resource.LastName; } } users = users.SortByUserName(); for (int i = 0; i < users.Count; i++) { if (!CheckEmail(users[i].Email)) { return(users[i]); } } for (int i = 0; i < users.Count; i++) { importer.CheckEmailIsNew(users[i]); if (TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers) { users[i] = UserManagerWrapper.AddUser(users[i], UserManagerWrapper.GeneratePassword(), true, false); } else { users[i] = UserManagerWrapper.AddUser(users[i], UserManagerWrapper.GeneratePassword(), true, false, true); } percentage += step; AscCache.Default.Insert("SaveLdapSettingTaskPercentage", Convert.ToInt32(percentage), TimeSpan.FromMinutes(15)); } } AscCache.Default.Insert("SaveLdapSettingTaskPercentage", 75, TimeSpan.FromMinutes(15)); var allLdapUsers = CoreContext.UserManager.GetUsers().Where(u => u.Sid != null).ToArray(); percents = 15; step = percents / allLdapUsers.Length; percentage = Convert.ToDouble(AscCache.Default.Get <string>("SaveLdapSettingTaskPercentage") ?? "0"); for (int i = 0; i < allLdapUsers.Length; i++) { importer.AddUserIntoGroups(allLdapUsers[i], settings); percentage += step; AscCache.Default.Insert("SaveLdapSettingTaskPercentage", Convert.ToInt32(percentage), TimeSpan.FromMinutes(15)); } AscCache.Default.Insert("SaveLdapSettingTaskPercentage", 90, TimeSpan.FromMinutes(15)); AddUsersInCacheGroups(); RemoveEmptyGroups(); return(null); }
protected void Page_Load(object sender, EventArgs e) { Page.RegisterBodyScripts("~/usercontrols/management/tariffsettings/js/tariffusage.js"); Page.RegisterStyle("~/usercontrols/management/tariffsettings/css/tariff.less"); Page.RegisterStyle("~/usercontrols/management/tariffsettings/css/tariffusage.less"); UsersCount = TenantStatisticsProvider.GetUsersCount(); UsedSize = TenantStatisticsProvider.GetUsedSize(); CurrentTariff = TenantExtra.GetCurrentTariff(); CurrentQuota = TenantExtra.GetTenantQuota(); var partner = CoreContext.PaymentManager.GetApprovedPartner(); if (partner != null) { Partner = partner; _quotaList = CoreContext.PaymentManager.GetPartnerTariffs(Partner.Id); if (!string.IsNullOrEmpty(Partner.Currency)) { _region = new RegionInfo(Partner.Currency); } var control = (TariffPartner)LoadControl(TariffPartner.Location); control.CurPartner = Partner; control.TariffNotPaid = CurrentTariff.State >= TariffState.NotPaid; control.TariffProlongable = CurrentTariff.Prolongable; PaymentsCodeHolder.Controls.Add(control); } if (_quotaList == null || !_quotaList.Any()) { _quotaList = TenantExtra.GetTenantQuotas(); } else if (!CurrentQuota.Trial) { CurrentQuota = _quotaList.FirstOrDefault(q => q.Id == CurrentQuota.Id) ?? CurrentQuota; } _quotaList = _quotaList.OrderBy(r => r.ActiveUsers).ToList().Where(r => !r.Trial); QuotasYear = _quotaList.Where(r => r.Year).ToList(); MonthIsDisable = !CurrentQuota.Free && (CurrentQuota.Year || CurrentQuota.Year3) && CurrentTariff.State == TariffState.Paid; YearIsDisable = !CurrentQuota.Free && CurrentQuota.Year3 && CurrentTariff.State == TariffState.Paid; var minYearQuota = QuotasYear.FirstOrDefault(q => q.ActiveUsers >= UsersCount && q.MaxTotalSize >= UsedSize); MinActiveUser = minYearQuota != null ? minYearQuota.ActiveUsers : (QuotasYear.Last().ActiveUsers + 1); HideBuyRecommendation = CurrentTariff.Autorenewal || TariffSettings.HideRecommendation || Partner != null; downgradeInfoContainer.Options.IsPopup = true; buyRecommendationContainer.Options.IsPopup = true; AjaxPro.Utility.RegisterTypeForAjax(GetType()); if (StudioSmsNotificationSettings.IsVisibleSettings && (SettingsManager.Instance.LoadSettings <StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID).EnableSetting || CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID)) && Partner == null) { SmsEnable = true; var smsBuy = (SmsBuy)LoadControl(SmsBuy.Location); smsBuy.ShowLink = !SettingsManager.Instance.LoadSettings <StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID).EnableSetting; SmsBuyHolder.Controls.Add(smsBuy); } if (VoipPaymentSettings.IsVisibleSettings && CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID) && Partner == null) { VoipEnable = true; var voipBuy = (VoipBuy)LoadControl(VoipBuy.Location); VoipBuyHolder.Controls.Add(voipBuy); } if (Partner == null) { RegisterScript(); } if (Partner == null && Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName == "ru") { _region = new RegionInfo("RU"); _currencyFormat = "{price}{currency}"; RateRuble = SetupInfo.ExchangeRateRuble; SetStar(string.Format(Resource.TariffsCurrencyRu, RateRuble)); } }
public EmployeeWraperFull UpdateMember(bool isVisitor, string userid, string email, string firstname, string lastname, string comment, Guid[] department, string title, string location, string sex, ApiDateTime birthday, ApiDateTime worksfrom, IEnumerable <Contact> contacts, string files, bool?disable) { SecurityContext.DemandPermissions(new UserSecurityProvider(new Guid(userid)), Core.Users.Constants.Action_EditUser); var user = GetUserInfo(userid); var self = SecurityContext.CurrentAccount.ID.Equals(new Guid(userid)); //Update it //Validate email if (!string.IsNullOrEmpty(email)) { var address = new MailAddress(email); user.Email = address.Address; } //Set common fields user.FirstName = firstname ?? user.FirstName; user.LastName = lastname ?? user.LastName; user.Title = title ?? user.Title; user.Location = location ?? user.Location; user.Notes = comment ?? user.Notes; user.Sex = ("male".Equals(sex, StringComparison.OrdinalIgnoreCase) ? true : ("female".Equals(sex, StringComparison.OrdinalIgnoreCase) ? (bool?)false : null)) ?? user.Sex; user.BirthDate = birthday != null?TenantUtil.DateTimeFromUtc(Convert.ToDateTime(birthday)) : user.BirthDate; user.WorkFromDate = worksfrom != null?TenantUtil.DateTimeFromUtc(Convert.ToDateTime(worksfrom)) : user.WorkFromDate; //Update contacts UpdateContacts(contacts, user); UpdateDepartments(department, user); if (files != UserPhotoManager.GetPhotoAbsoluteWebPath(user.ID)) { UpdatePhotoUrl(files, user); } if (disable.HasValue) { user.Status = disable.Value ? EmployeeStatus.Terminated : EmployeeStatus.Active; user.TerminatedDate = disable.Value ? DateTime.UtcNow : (DateTime?)null; } if (self && !CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, ASC.Core.Users.Constants.GroupAdmin.ID)) { StudioNotifyService.Instance.SendMsgToAdminAboutProfileUpdated(); } // change user type var canBeGuestFlag = !user.IsOwner() && !user.IsAdmin() && !user.IsMe(); if (isVisitor && !user.IsVisitor() && canBeGuestFlag) { CoreContext.UserManager.AddUserIntoGroup(user.ID, Core.Users.Constants.GroupVisitor.ID); WebItemSecurity.ClearCache(); } if (!self && !isVisitor && user.IsVisitor()) { var usersQuota = TenantExtra.GetTenantQuota().ActiveUsers; if (TenantStatisticsProvider.GetUsersCount() < usersQuota) { CoreContext.UserManager.RemoveUserFromGroup(user.ID, Core.Users.Constants.GroupVisitor.ID); WebItemSecurity.ClearCache(); } else { throw new TenantQuotaException(string.Format("Exceeds the maximum active users ({0})", usersQuota)); } } CoreContext.UserManager.SaveUserInfo(user); return(new EmployeeWraperFull(user)); }
private UserInfo AddUser(UserInfo userInfo) { UserInfo newUserInfo; try { newUserInfo = userInfo.Clone() as UserInfo; if (newUserInfo == null) { return(Constants.LostUser); } _log.DebugFormat("Adding or updating user in database, userId={0}", userInfo.ID); SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem); if (string.IsNullOrEmpty(newUserInfo.UserName)) { if (string.IsNullOrWhiteSpace(newUserInfo.FirstName)) { newUserInfo.FirstName = Resource.FirstName; } if (string.IsNullOrWhiteSpace(newUserInfo.LastName)) { newUserInfo.LastName = Resource.LastName; } if (TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers) { newUserInfo = UserManagerWrapper.AddUser(newUserInfo, UserManagerWrapper.GeneratePassword(), true, false); } else { newUserInfo = UserManagerWrapper.AddUser(newUserInfo, UserManagerWrapper.GeneratePassword(), true, false, true); } } else { if (!UserFormatter.IsValidUserName(userInfo.FirstName, userInfo.LastName)) { throw new Exception(Resource.ErrorIncorrectUserName); } CoreContext.UserManager.SaveUserInfo(newUserInfo); } /*var photoUrl = samlResponse.GetRemotePhotoUrl(); * if (!string.IsNullOrEmpty(photoUrl)) * { * var photoLoader = new UserPhotoLoader(); * photoLoader.SaveOrUpdatePhoto(photoUrl, userInfo.ID); * }*/ } finally { SecurityContext.Logout(); } return(newUserInfo); }
public object SendJoinInviteMail(string email) { try { if (!EnabledJoin) { throw new MethodAccessException("Method not available"); } if (!email.TestEmailRegex()) { throw new Exception(Resource.ErrorNotCorrectEmail); } var user = CoreContext.UserManager.GetUserByEmail(email); if (!user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID)) { throw new Exception(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists")); } var tenant = CoreContext.TenantManager.GetCurrentTenant(); var settings = IPRestrictionsSettings.Load(); if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant)) { throw new Exception(Resource.ErrorAccessRestricted); } var trustedDomainSettings = StudioTrustedDomainSettings.Load(); var emplType = trustedDomainSettings.InviteUsersAsVisitors ? EmployeeType.Visitor : EmployeeType.User; var enableInviteUsers = TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers; if (!enableInviteUsers) { emplType = EmployeeType.Visitor; } switch (tenant.TrustedDomainsType) { case TenantTrustedDomainsType.Custom: { var address = new MailAddress(email); if ( tenant.TrustedDomains.Any( d => address.Address.EndsWith("@" + d, StringComparison.InvariantCultureIgnoreCase))) { StudioNotifyService.Instance.InviteUsers(email, string.Empty, true, emplType); MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.SentInviteInstructions, email); return(new { Status = 1, Message = Resource.FinishInviteJoinEmailMessage }); } throw new Exception(Resource.ErrorEmailDomainNotAllowed); } case TenantTrustedDomainsType.All: { StudioNotifyService.Instance.InviteUsers(email, string.Empty, true, emplType); MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.SentInviteInstructions, email); return(new { Status = 1, Message = Resource.FinishInviteJoinEmailMessage }); } default: throw new Exception(Resource.ErrorNotCorrectEmail); } } catch (FormatException) { return(new { Status = 0, Message = Resource.ErrorNotCorrectEmail }); } catch (Exception e) { return(new { Status = 0, Message = e.Message.HtmlEncode() }); } }
public AjaxResponse SendJoinInviteMail(string email) { email = (email ?? "").Trim(); var resp = new AjaxResponse { rs1 = "0" }; try { if (String.IsNullOrEmpty(email)) { resp.rs2 = Resources.Resource.ErrorNotCorrectEmail; return(resp); } if (!email.TestEmailRegex()) { resp.rs2 = Resources.Resource.ErrorNotCorrectEmail; } var user = CoreContext.UserManager.GetUserByEmail(email); if (!user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID)) { resp.rs1 = "0"; resp.rs2 = CustomNamingPeople.Substitute <Resources.Resource>("ErrorEmailAlreadyExists").HtmlEncode(); return(resp); } var tenant = CoreContext.TenantManager.GetCurrentTenant(); var trustedDomainSettings = SettingsManager.Instance.LoadSettings <StudioTrustedDomainSettings>(TenantProvider.CurrentTenantID); var emplType = trustedDomainSettings.InviteUsersAsVisitors ? EmployeeType.Visitor : EmployeeType.User; var enableInviteUsers = TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers; if (!enableInviteUsers) { emplType = EmployeeType.Visitor; } if (tenant.TrustedDomainsType == TenantTrustedDomainsType.Custom) { var address = new MailAddress(email); foreach (var d in tenant.TrustedDomains) { if (address.Address.EndsWith("@" + d, StringComparison.InvariantCultureIgnoreCase)) { StudioNotifyService.Instance.InviteUsers(email, "", true, emplType); resp.rs1 = "1"; resp.rs2 = Resources.Resource.FinishInviteJoinEmailMessage; return(resp); } } } else if (tenant.TrustedDomainsType == TenantTrustedDomainsType.All) { StudioNotifyService.Instance.InviteUsers(email, "", true, emplType); resp.rs1 = "1"; resp.rs2 = Resources.Resource.FinishInviteJoinEmailMessage; return(resp); } resp.rs2 = Resources.Resource.ErrorNotCorrectEmail; } catch (FormatException) { resp.rs2 = Resources.Resource.ErrorNotCorrectEmail; } catch (Exception e) { resp.rs2 = HttpUtility.HtmlEncode(e.Message); } return(resp); }