From c3981206b5103bb0501553a2c7d765a2d1bff2e9 Mon Sep 17 00:00:00 2001 From: Ilya Oleshko Date: Thu, 8 Aug 2019 12:17:43 +0300 Subject: [PATCH 1/5] web: Components: Disabled user-select for Avatar at ContentRow component --- web/ASC.Web.Components/src/components/content-row/index.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/web/ASC.Web.Components/src/components/content-row/index.js b/web/ASC.Web.Components/src/components/content-row/index.js index 06719d2860..3b4d10a5d2 100644 --- a/web/ASC.Web.Components/src/components/content-row/index.js +++ b/web/ASC.Web.Components/src/components/content-row/index.js @@ -62,6 +62,12 @@ const StyledCheckbox = styled.div` const StyledAvatar = styled.div` flex: 0 0 32px; display: flex; + + -webkit-touch-callout: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; `; const StyledOptionButton = styled.div` From 11bd28c36509cfa76f2047ea7eda2434ead01a91 Mon Sep 17 00:00:00 2001 From: Ilya Oleshko Date: Thu, 8 Aug 2019 12:24:20 +0300 Subject: [PATCH 2/5] web: Components: Disabled user-select for ImageStyled at Avatar component --- .../src/components/avatar/index.js | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/web/ASC.Web.Components/src/components/avatar/index.js b/web/ASC.Web.Components/src/components/avatar/index.js index 09fa2380c0..d53f11579d 100644 --- a/web/ASC.Web.Components/src/components/avatar/index.js +++ b/web/ASC.Web.Components/src/components/avatar/index.js @@ -1,5 +1,5 @@ import React from 'react' -import styled from 'styled-components' +import styled, { css } from 'styled-components' import PropTypes from 'prop-types' import { Icons } from '../icons' import Link from '../link' @@ -8,6 +8,14 @@ const whiteColor = '#FFFFFF'; const avatarBackground = '#ECEEF1'; const namedAvatarBackground = '#2DA7DB'; +const noneUserSelect = css` + -webkit-touch-callout: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +`; + const StyledAvatar = styled.div` position: relative; width: ${props => @@ -51,6 +59,8 @@ const ImageStyled = styled.img` max-width: 100%; height: auto; border-radius: 50%; + + ${noneUserSelect} `; const AvatarWrapper = styled.div` @@ -84,11 +94,7 @@ const NamedAvatar = styled.div` }; color: ${whiteColor}; - -webkit-touch-callout: none; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; + ${noneUserSelect} `; const EditContainer = styled.div` From f85711b7362a22ea46e243f34632c80b16840462 Mon Sep 17 00:00:00 2001 From: pavelbannov Date: Thu, 8 Aug 2019 12:26:58 +0300 Subject: [PATCH 3/5] Optimization --- common/ASC.Api.Core/Core/ApiContext.cs | 20 +- .../Middleware/ProductSecurityFilter.cs | 2 +- common/ASC.Common/ASC.Common.csproj | 5 + .../Collections/HttpRequestDictionary.cs | 12 - .../ASC.Common/Utils/HttpRequestExtensions.cs | 21 +- .../ASC.Core.Common/BaseCommonLinkUtility.cs | 100 ++++---- .../Billing/License/LicenseReader.cs | 2 +- .../Context/Impl/AuthManager.cs | 5 +- .../Context/Impl/TenantManager.cs | 29 ++- .../Context/Impl/UserManager.cs | 223 ++++++++-------- .../Context/SecurityContext.cs | 29 +-- common/ASC.Core.Common/Core/UserInfo.cs | 11 +- .../Notify/Channels/ISenderChannel.cs | 0 .../Notify/Channels/SenderChannel.cs | 0 .../Notify/Context.cs | 0 .../Notify/Cron/CronExpression.cs | 0 .../Notify/Cron/ISet.cs | 0 .../Notify/Cron/ISortedSet.cs | 0 .../Notify/Cron/TreeSet.cs | 0 .../Notify/DirectSubscriptionProvider.cs | 13 +- .../Notify/Engine/CallContext.cs | 0 .../Notify/Engine/DispatchEngine.cs | 0 .../Notify/Engine/INotifyEngine.cs | 0 .../Notify/Engine/InterceptorStorage.cs | 0 .../Notify/Engine/NotifyEngine.cs | 38 +-- .../Notify/Engine/NotifyRequest.cs | 0 .../Notify/Engine/SendInterceptorSkeleton.cs | 0 .../Engine/SingleRecipientInterceptor.cs | 0 .../Notify/INotifyClient.cs | 2 +- .../Notify/INotifyRegistry.cs | 0 .../Notify}/IRecipientsProvider.cs | 10 +- .../Notify/ISendInterceptor.cs | 0 .../Notify/InitiatorInterceptor.cs | 0 .../Notify/InterceptorLifetime.cs | 0 .../Notify/InterceptorPlace.cs | 0 .../Notify/Messages/INoticeMessage.cs | 0 .../Notify/Messages/NoticeMessage.cs | 0 .../Notify/Messages/SendResponse.cs | 0 .../Notify/Messages/SendResult.cs | 0 .../Notify/Model/ConstActionProvider.cs | 0 .../Notify/Model/IActionProvider.cs | 0 .../Notify/Model/INotifyAction.cs | 0 .../Notify/Model/INotifySource.cs | 0 .../Notify/Model/ISubscriptionProvider.cs | 19 +- .../Notify/Model/NotifyAction.cs | 0 .../Notify/Model/NotifyClientImpl.cs | 4 +- .../Notify/NotifyException.cs | 0 .../Notify/NotifyResult.cs | 0 .../Notify/Patterns/IPattern.cs | 0 .../Notify/Patterns/IPatternFormatter.cs | 0 .../Notify/Patterns/IPatternProvider.cs | 0 .../Notify/Patterns/IPatternStyler.cs | 0 .../Notify/Patterns/ITagValue.cs | 0 .../Patterns/NVelocityPatternFormatter.cs | 0 .../Notify/Patterns/Pattern.cs | 0 .../Notify/Patterns/PatternFormatter.cs | 0 .../Patterns/ReplacePatternFormatter.cs | 0 .../Notify/Patterns/TagValue.cs | 0 .../Notify/Patterns/XmlPatternProvider2.cs | 0 .../Notify/RecipientProviderImpl.cs | 22 +- .../Notify/Recipients/DirectRecipient.cs | 0 .../Notify/Recipients/IDirectRecipient.cs | 0 .../Notify/Recipients/IRecipient.cs | 0 .../Notify/Recipients/IRecipientsGroup.cs | 0 .../Notify/Recipients/RecipientsGroup.cs | 0 .../Notify/Sinks/DispatchSink.cs | 0 .../Notify/Sinks/ISink.cs | 0 .../Notify/Sinks/Sink.cs | 0 .../Notify}/TopSubscriptionProvider.cs | 39 +-- .../Security/Authorizing/AzManager.cs | 17 +- .../Security/Authorizing/Domain.cs | 0 .../Authorizing}/IPermissionResolver.cs | 11 +- .../Authorizing/PermissionResolver.cs | 21 +- .../Security/Authorizing/RoleProvider.cs | 15 +- .../Security/IRoleProvider.cs | 7 +- .../Tests}/AzManagerTest.cs | 60 ++--- .../Tests}/Class1.cs | 0 .../Tests}/DomainStub.cs | 9 +- .../Tests/TopSubscriptionProviderTest.cs | 28 +-- .../ASC.Core.Common/Tests/UserManagerTest.cs | 67 +++-- .../Tests}/XmlPatternProvider2Test.cs | 0 .../ASC.Core.Common/Users/UserExtensions.cs | 25 +- .../ReassignProgressItem.cs | 15 +- .../ASC.Data.Reassigns/RemoveProgressItem.cs | 14 +- .../LoginProviders/BlockchainLoginProvider.cs | 7 +- .../Twilio/TwilioVoipSettings.cs | 3 +- .../Server/Controllers/GroupController.cs | 69 +++-- .../Server/Controllers/PeopleController.cs | 238 +++++++++--------- .../ASC.People/Server/JsonStringConverter.cs | 9 - .../Server/Models/EmployeeWraper.cs | 33 +-- .../Server/Models/EmployeeWraperFull.cs | 37 ++- .../Server/Models/GroupWrapperFull.cs | 7 +- .../Server/Models/GroupWrapperSummary.cs | 5 +- .../Server/Models/ThumbnailsDataWrapper.cs | 15 +- .../Controllers/AuthenticationController.cs | 12 +- .../Controllers/ModulesController.cs | 3 +- web/ASC.Web.Core/Calendars/CalendarManager.cs | 11 +- web/ASC.Web.Core/Calendars/SharingOptions.cs | 7 +- web/ASC.Web.Core/CookiesManager.cs | 17 +- .../Extensions/UserInfoExtension.cs | 37 +-- .../Extensions/WebItemExtension.cs | 9 +- .../Helpers/AuthorizationHelper.cs | 2 +- web/ASC.Web.Core/Mail/MailServiceHelper.cs | 2 +- .../Notify/NotifyConfiguration.cs | 19 +- web/ASC.Web.Core/Notify/StudioNotifyHelper.cs | 39 +-- .../Notify/StudioNotifyService.cs | 100 ++++---- .../Notify/StudioNotifyServiceHelper.cs | 4 +- web/ASC.Web.Core/Notify/StudioNotifySource.cs | 21 +- .../Notify/StudioPeriodicNotify.cs | 46 ++-- .../Notify/StudioWhatsNewNotify.cs | 4 +- web/ASC.Web.Core/Users/DisplayUserSettings.cs | 2 +- web/ASC.Web.Core/Users/UserInfoExtension.cs | 13 +- web/ASC.Web.Core/Users/UserManagerWrapper.cs | 32 +-- web/ASC.Web.Core/Users/UserPhotoManager.cs | 103 ++++---- .../Users/UserPhotoThumbnailManager.cs | 96 ++++--- web/ASC.Web.Core/Utility/CommonLinkUtility.cs | 65 +++-- web/ASC.Web.Core/Utility/TenantExtra.cs | 17 +- .../Utility/TenantStatisticsProvider.cs | 4 +- web/ASC.Web.Core/WebItemManager.cs | 17 +- web/ASC.Web.Core/WebItemSecurity.cs | 43 ++-- 120 files changed, 1036 insertions(+), 1007 deletions(-) rename common/{ASC.Common => ASC.Core.Common}/Notify/Channels/ISenderChannel.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Channels/SenderChannel.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Context.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Cron/CronExpression.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Cron/ISet.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Cron/ISortedSet.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Cron/TreeSet.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Engine/CallContext.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Engine/DispatchEngine.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Engine/INotifyEngine.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Engine/InterceptorStorage.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Engine/NotifyEngine.cs (93%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Engine/NotifyRequest.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Engine/SendInterceptorSkeleton.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Engine/SingleRecipientInterceptor.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/INotifyClient.cs (96%) rename common/{ASC.Common => ASC.Core.Common}/Notify/INotifyRegistry.cs (100%) rename common/{ASC.Common/Notify/Recipients => ASC.Core.Common/Notify}/IRecipientsProvider.cs (83%) rename common/{ASC.Common => ASC.Core.Common}/Notify/ISendInterceptor.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/InitiatorInterceptor.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/InterceptorLifetime.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/InterceptorPlace.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Messages/INoticeMessage.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Messages/NoticeMessage.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Messages/SendResponse.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Messages/SendResult.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Model/ConstActionProvider.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Model/IActionProvider.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Model/INotifyAction.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Model/INotifySource.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Model/ISubscriptionProvider.cs (82%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Model/NotifyAction.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Model/NotifyClientImpl.cs (96%) rename common/{ASC.Common => ASC.Core.Common}/Notify/NotifyException.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/NotifyResult.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Patterns/IPattern.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Patterns/IPatternFormatter.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Patterns/IPatternProvider.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Patterns/IPatternStyler.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Patterns/ITagValue.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Patterns/NVelocityPatternFormatter.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Patterns/Pattern.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Patterns/PatternFormatter.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Patterns/ReplacePatternFormatter.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Patterns/TagValue.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Patterns/XmlPatternProvider2.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Recipients/DirectRecipient.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Recipients/IDirectRecipient.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Recipients/IRecipient.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Recipients/IRecipientsGroup.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Recipients/RecipientsGroup.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Sinks/DispatchSink.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Sinks/ISink.cs (100%) rename common/{ASC.Common => ASC.Core.Common}/Notify/Sinks/Sink.cs (100%) rename common/{ASC.Common/Notify/Model => ASC.Core.Common/Notify}/TopSubscriptionProvider.cs (83%) rename common/{ASC.Common => ASC.Core.Common}/Security/Authorizing/AzManager.cs (86%) rename common/{ASC.Common/Tests => ASC.Core.Common}/Security/Authorizing/Domain.cs (100%) rename common/{ASC.Common/Security => ASC.Core.Common/Security/Authorizing}/IPermissionResolver.cs (76%) rename common/{ASC.Common => ASC.Core.Common}/Security/IRoleProvider.cs (90%) rename common/{ASC.Common/Tests/Security/Authorizing => ASC.Core.Common/Tests}/AzManagerTest.cs (67%) rename common/{ASC.Common/Tests/Security/Authorizing => ASC.Core.Common/Tests}/Class1.cs (100%) rename common/{ASC.Common/Tests/Security/Authorizing => ASC.Core.Common/Tests}/DomainStub.cs (97%) rename common/{ASC.Common/Tests/Notify => ASC.Core.Common/Tests}/XmlPatternProvider2Test.cs (100%) delete mode 100644 products/ASC.People/Server/JsonStringConverter.cs diff --git a/common/ASC.Api.Core/Core/ApiContext.cs b/common/ASC.Api.Core/Core/ApiContext.cs index 6f98a41743..a8bc766197 100644 --- a/common/ASC.Api.Core/Core/ApiContext.cs +++ b/common/ASC.Api.Core/Core/ApiContext.cs @@ -27,6 +27,8 @@ using System; using System.Collections.Generic; using System.Linq; +using ASC.Core; +using ASC.Core.Tenants; using Microsoft.AspNetCore.Http; namespace ASC.Api.Core @@ -34,12 +36,20 @@ namespace ASC.Api.Core public class ApiContext : ICloneable { public HttpContext HttpContext { get; set; } + private IQueryCollection Query { get; set; } + private Tenant tenant; + public Tenant Tenant { get { return tenant ?? (tenant = CoreContext.TenantManager.GetCurrentTenant()); } } public ApiContext(HttpContext httpContext) { if (httpContext == null) return; HttpContext = httpContext; + if (HttpContext.Request.QueryString != null) + { + Query = HttpContext.Request.Query; + } + //TODO uint ItemsPerPage = 1000; Count = 0; @@ -90,14 +100,14 @@ namespace ASC.Api.Core private string[] GetRequestArray(string key) { - if (HttpContext.Request.QueryString != null) + if (Query != null) { - var values = HttpContext.Request.Query[key + "[]"]; - if (values.Any()) + var values = Query[key + "[]"]; + if (values.Count > 0) return values; - values = HttpContext.Request.Query[key]; - if (values.Any()) + values = Query[key]; + if (values.Count > 0) { if (values.Count == 1) //If it's only one element { diff --git a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs index 03de8ee66b..e00b3fb9e4 100644 --- a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs +++ b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs @@ -69,7 +69,7 @@ namespace ASC.Api.Core.Middleware { CallContext.SetData("asc.web.product_id", pid); } - if (!WebItemSecurity.IsAvailableForMe(pid)) + if (!WebItemSecurity.IsAvailableForMe(CoreContext.TenantManager.GetCurrentTenant(), pid)) { context.Result = new StatusCodeResult((int)HttpStatusCode.Forbidden); log.WarnFormat("Product {0} denied for user {1}", controllerActionDescriptor.ControllerName, SecurityContext.CurrentAccount); diff --git a/common/ASC.Common/ASC.Common.csproj b/common/ASC.Common/ASC.Common.csproj index 8b6aa200f2..dab255fdcc 100644 --- a/common/ASC.Common/ASC.Common.csproj +++ b/common/ASC.Common/ASC.Common.csproj @@ -61,4 +61,9 @@ + + + + + \ No newline at end of file diff --git a/common/ASC.Common/Collections/HttpRequestDictionary.cs b/common/ASC.Common/Collections/HttpRequestDictionary.cs index 0a7116e6fe..65dcb37ddc 100644 --- a/common/ASC.Common/Collections/HttpRequestDictionary.cs +++ b/common/ASC.Common/Collections/HttpRequestDictionary.cs @@ -23,11 +23,6 @@ * */ - -using Microsoft.AspNetCore.Http.Extensions; -using System; -using System.Diagnostics; - namespace ASC.Collections { public sealed class HttpRequestDictionary : CachedDictionaryBase @@ -87,17 +82,10 @@ namespace ASC.Collections protected override void OnHit(string fullKey) { - Debug.Print("{0} http cache hit:{1}", Common.HttpContext.Current.Request.GetDisplayUrl(), fullKey); } protected override void OnMiss(string fullKey) { - Uri uri = null; - if (Common.HttpContext.Current != null) - { - uri = new Uri(Common.HttpContext.Current.Request.GetDisplayUrl()); - } - Debug.Print("{0} http cache miss:{1}", uri == null ? "no-context" : uri.AbsolutePath, fullKey); } } diff --git a/common/ASC.Common/Utils/HttpRequestExtensions.cs b/common/ASC.Common/Utils/HttpRequestExtensions.cs index a1852da63b..17ffbb7093 100644 --- a/common/ASC.Common/Utils/HttpRequestExtensions.cs +++ b/common/ASC.Common/Utils/HttpRequestExtensions.cs @@ -25,6 +25,7 @@ using System.Globalization; +using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; @@ -40,7 +41,7 @@ namespace System.Web public static Uri GetUrlRewriter(this HttpRequest request) { - return request != null ? GetUrlRewriter(request.Headers, request.Url()) : null; + return request != null ? GetUrlRewriter(request.Headers, request) : null; } public static Uri Url(this HttpRequest request) { @@ -52,20 +53,14 @@ namespace System.Web return request != null ? GetUrlRewriter(request.Headers, request.Url) : null; }*/ - public static Uri GetUrlRewriter(IHeaderDictionary headers, Uri requestUri) + public static Uri GetUrlRewriter(IHeaderDictionary headers, HttpRequest request) { - if (requestUri == null) + if (request.Query != null && request.Query.Any()) { - return null; - } - - if (!string.IsNullOrEmpty(requestUri.Query)) - { - var urlRewriterQuery = HttpUtility.ParseQueryString(requestUri.Query); - var rewriterUri = ParseRewriterUrl(urlRewriterQuery[UrlRewriterHeader]); + var rewriterUri = ParseRewriterUrl(request.Query[UrlRewriterHeader]); if (rewriterUri != null) { - var result = new UriBuilder(requestUri) + var result = new UriBuilder(request.Url()) { Scheme = rewriterUri.Scheme, Host = rewriterUri.Host, @@ -80,7 +75,7 @@ namespace System.Web var rewriterUri = ParseRewriterUrl(headers[UrlRewriterHeader]); if (rewriterUri != null) { - var result = new UriBuilder(requestUri) + var result = new UriBuilder(request.Url()) { Scheme = rewriterUri.Scheme, Host = rewriterUri.Host, @@ -90,7 +85,7 @@ namespace System.Web } } - return requestUri; + return request.Url(); } public static Uri PushRewritenUri(this HttpContext context) diff --git a/common/ASC.Core.Common/BaseCommonLinkUtility.cs b/common/ASC.Core.Common/BaseCommonLinkUtility.cs index 6908afa2a3..dd74d14624 100644 --- a/common/ASC.Core.Common/BaseCommonLinkUtility.cs +++ b/common/ASC.Core.Common/BaseCommonLinkUtility.cs @@ -31,7 +31,7 @@ using ASC.Common.Logging; using ASC.Common.Web; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; -using HttpContext = ASC.Common.HttpContext; +using HttpContext = Microsoft.AspNetCore.Http.HttpContext; namespace ASC.Core.Common { @@ -77,58 +77,58 @@ namespace ASC.Core.Common get { return ToAbsolute("~"); } } - public static string ServerRootPath - { - get - { - var result = new UriBuilder(_serverRoot.Uri); - - // first, take from current request - if (HttpContext.Current != null && ASC.Common.HttpContext.Current.Request != null) - { - var u = ASC.Common.HttpContext.Current.Request.GetUrlRewriter(); - result = new UriBuilder(u.Scheme, u.Host, u.Port); - - if (CoreContext.Configuration.Standalone && !result.Uri.IsLoopback) - { - // save for stanalone - _serverRoot.Host = result.Host; - } - } - - if (result.Uri.IsLoopback) - { - // take values from db if localhost or no http context thread - var tenant = CoreContext.TenantManager.GetCurrentTenant(); - result.Host = tenant.TenantDomain; - + public static string ServerRootPath(HttpContext context) + { + UriBuilder result; + // first, take from current request + if (context != null && context.Request != null) + { + var u = context.Request.GetUrlRewriter(); + result = new UriBuilder(u.Scheme, u.Host, u.Port); + + if (CoreContext.Configuration.Standalone && !result.Uri.IsLoopback) + { + // save for stanalone + _serverRoot.Host = result.Host; + } + } + else + { + result = new UriBuilder(_serverRoot.Uri); + } + + if (result.Uri.IsLoopback) + { + // take values from db if localhost or no http context thread + var tenant = CoreContext.TenantManager.GetCurrentTenant(); + result.Host = tenant.TenantDomain; + #if DEBUG - // for Visual Studio debug - if (tenant.TenantAlias == LOCALHOST) - { - result.Host = LOCALHOST; - } + // for Visual Studio debug + if (tenant.TenantAlias == LOCALHOST) + { + result.Host = LOCALHOST; + } #endif - - if (!string.IsNullOrEmpty(tenant.MappedDomain)) - { - var mapped = tenant.MappedDomain.ToLowerInvariant(); - if (!mapped.Contains(Uri.SchemeDelimiter)) - { - mapped = Uri.UriSchemeHttp + Uri.SchemeDelimiter + mapped; - } - result = new UriBuilder(mapped); - } - } - - return result.Uri.ToString().TrimEnd('/'); - } + + if (!string.IsNullOrEmpty(tenant.MappedDomain)) + { + var mapped = tenant.MappedDomain.ToLowerInvariant(); + if (!mapped.Contains(Uri.SchemeDelimiter)) + { + mapped = Uri.UriSchemeHttp + Uri.SchemeDelimiter + mapped; + } + result = new UriBuilder(mapped); + } + } + + return result.Uri.ToString().TrimEnd('/'); } - public static string GetFullAbsolutePath(string virtualPath) + public static string GetFullAbsolutePath(HttpContext context, string virtualPath) { - if (String.IsNullOrEmpty(virtualPath)) - return ServerRootPath; + if (string.IsNullOrEmpty(virtualPath)) + return ServerRootPath(context); if (virtualPath.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) || virtualPath.StartsWith("mailto:", StringComparison.InvariantCultureIgnoreCase) || @@ -138,9 +138,9 @@ namespace ASC.Core.Common if (string.IsNullOrEmpty(virtualPath) || virtualPath.StartsWith("/")) { - return ServerRootPath + virtualPath; + return ServerRootPath(context) + virtualPath; } - return ServerRootPath + VirtualRoot.TrimEnd('/') + "/" + virtualPath.TrimStart('~', '/'); + return ServerRootPath(context) + VirtualRoot.TrimEnd('/') + "/" + virtualPath.TrimStart('~', '/'); } public static string ToAbsolute(string virtualPath) diff --git a/common/ASC.Core.Common/Billing/License/LicenseReader.cs b/common/ASC.Core.Common/Billing/License/LicenseReader.cs index 8b95b53147..64bcbfea88 100644 --- a/common/ASC.Core.Common/Billing/License/LicenseReader.cs +++ b/common/ASC.Core.Common/Billing/License/LicenseReader.cs @@ -179,7 +179,7 @@ namespace ASC.Core.Billing if (license.ActiveUsers.Equals(default(int)) || license.ActiveUsers < 1) license.ActiveUsers = MaxUserCount; - if (license.ActiveUsers < CoreContext.UserManager.GetUsers(EmployeeStatus.Default, EmployeeType.User).Length) + if (license.ActiveUsers < CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant(), EmployeeStatus.Default, EmployeeType.User).Length) { throw new LicenseQuotaException("License quota", license.OriginalLicense); } diff --git a/common/ASC.Core.Common/Context/Impl/AuthManager.cs b/common/ASC.Core.Common/Context/Impl/AuthManager.cs index 08ed323581..3c9c0adcef 100644 --- a/common/ASC.Core.Common/Context/Impl/AuthManager.cs +++ b/common/ASC.Core.Common/Context/Impl/AuthManager.cs @@ -28,6 +28,7 @@ using System; using System.Linq; using ASC.Common.Security.Authentication; using ASC.Core.Security.Authentication; +using ASC.Core.Tenants; using ASC.Core.Users; namespace ASC.Core @@ -43,9 +44,9 @@ namespace ASC.Core } - public IUserAccount[] GetUserAccounts() + public IUserAccount[] GetUserAccounts(Tenant tenant) { - return CoreContext.UserManager.GetUsers(EmployeeStatus.Active).Select(u => ToAccount(u)).ToArray(); + return CoreContext.UserManager.GetUsers(tenant, EmployeeStatus.Active).Select(u => ToAccount(u)).ToArray(); } public void SetUserPassword(Guid userID, string password) diff --git a/common/ASC.Core.Common/Context/Impl/TenantManager.cs b/common/ASC.Core.Common/Context/Impl/TenantManager.cs index cd1e3b1bb9..39bd71bc62 100644 --- a/common/ASC.Core.Common/Context/Impl/TenantManager.cs +++ b/common/ASC.Core.Common/Context/Impl/TenantManager.cs @@ -145,14 +145,15 @@ namespace ASC.Core public Tenant GetCurrentTenant(bool throwIfNotFound) { - Tenant tenant = null; - if (HttpContext.Current != null) + Tenant tenant = null; + var context = HttpContext.Current; + if (context != null) { - tenant = HttpContext.Current.Items[CURRENT_TENANT] as Tenant; - if (tenant == null && HttpContext.Current.Request != null) + tenant = context.Items[CURRENT_TENANT] as Tenant; + if (tenant == null && context.Request != null) { - tenant = GetTenant(HttpContext.Current.Request.GetUrlRewriter().Host); - HttpContext.Current.Items[CURRENT_TENANT] = tenant; + tenant = GetTenant(context.Request.GetUrlRewriter().Host); + context.Items[CURRENT_TENANT] = tenant; } } if (tenant == null) @@ -180,14 +181,18 @@ namespace ASC.Core } } - public void SetCurrentTenant(int tenantId) - { - SetCurrentTenant(GetTenant(tenantId)); + public Tenant SetCurrentTenant(int tenantId) + { + var result = GetTenant(tenantId); + SetCurrentTenant(result); + return result; } - public void SetCurrentTenant(string domain) - { - SetCurrentTenant(GetTenant(domain)); + public Tenant SetCurrentTenant(string domain) + { + var result = GetTenant(domain); + SetCurrentTenant(result); + return result; } public void CheckTenantAddress(string address) diff --git a/common/ASC.Core.Common/Context/Impl/UserManager.cs b/common/ASC.Core.Common/Context/Impl/UserManager.cs index 63ec349586..167d92833b 100644 --- a/common/ASC.Core.Common/Context/Impl/UserManager.cs +++ b/common/ASC.Core.Common/Context/Impl/UserManager.cs @@ -62,81 +62,84 @@ namespace ASC.Core #region Users - public UserInfo[] GetUsers() + public UserInfo[] GetUsers(Tenant tenant) { - return GetUsers(EmployeeStatus.Default); + return GetUsers(tenant, EmployeeStatus.Default); } - public UserInfo[] GetUsers(EmployeeStatus status) + public UserInfo[] GetUsers(Tenant tenant, EmployeeStatus status) { - return GetUsers(status, EmployeeType.All); + return GetUsers(tenant, status, EmployeeType.All); } - public UserInfo[] GetUsers(EmployeeStatus status, EmployeeType type) + public UserInfo[] GetUsers(Tenant tenant, EmployeeStatus status, EmployeeType type) { - var users = GetUsersInternal().Where(u => (u.Status & status) == u.Status); + var users = GetUsersInternal(tenant.TenantId).Where(u => (u.Status & status) == u.Status); switch (type) { case EmployeeType.User: - users = users.Where(u => !u.IsVisitor()); + users = users.Where(u => !u.IsVisitor(tenant)); break; case EmployeeType.Visitor: - users = users.Where(u => u.IsVisitor()); + users = users.Where(u => u.IsVisitor(tenant)); break; } return users.ToArray(); } - public IEnumerable GetUsers(bool isAdmin, EmployeeStatus? employeeStatus, List includeGroups, List excludeGroups, EmployeeActivationStatus? activationStatus, string text, string sortBy, bool sortOrderAsc, long limit, long offset, out int total) + public IEnumerable GetUsers(int tenantId, bool isAdmin, EmployeeStatus? employeeStatus, List includeGroups, List excludeGroups, EmployeeActivationStatus? activationStatus, string text, string sortBy, bool sortOrderAsc, long limit, long offset, out int total) { - var tenantId = CoreContext.TenantManager.GetCurrentTenant().TenantId; return userService.GetUsers(tenantId, isAdmin, employeeStatus, includeGroups, excludeGroups, activationStatus, text, sortBy, sortOrderAsc, limit, offset, out total).Values; } - public DateTime GetMaxUsersLastModified() + public DateTime GetMaxUsersLastModified(int tenantId) { - return userService.GetUsers(CoreContext.TenantManager.GetCurrentTenant().TenantId, default(DateTime)) + return userService.GetUsers(tenantId, default) .Values .Select(g => g.LastModified) .DefaultIfEmpty() .Max(); } - public string[] GetUserNames(EmployeeStatus status) + public string[] GetUserNames(Tenant tenant, EmployeeStatus status) { - return GetUsers(status) + return GetUsers(tenant, status) .Select(u => u.UserName) .Where(s => !string.IsNullOrEmpty(s)) .ToArray(); } - public UserInfo GetUserByUserName(string username) + public UserInfo GetUserByUserName(int tenantId, string username) { - return GetUsersInternal() + return GetUsersInternal(tenantId) .FirstOrDefault(u => string.Compare(u.UserName, username, StringComparison.CurrentCultureIgnoreCase) == 0) ?? Constants.LostUser; } - public UserInfo GetUserBySid(string sid) + public UserInfo GetUserBySid(int tenantId, string sid) { - return GetUsersInternal() + return GetUsersInternal(tenantId) .FirstOrDefault(u => u.Sid != null && string.Compare(u.Sid, sid, StringComparison.CurrentCultureIgnoreCase) == 0) ?? Constants.LostUser; } - public UserInfo GetSsoUserByNameId(string nameId) + public UserInfo GetSsoUserByNameId(int tenantId, string nameId) { - return GetUsersInternal() + return GetUsersInternal(tenantId) .FirstOrDefault(u => !string.IsNullOrEmpty(u.SsoNameId) && string.Compare(u.SsoNameId, nameId, StringComparison.CurrentCultureIgnoreCase) == 0) ?? Constants.LostUser; } - public bool IsUserNameExists(string username) + public bool IsUserNameExists(Tenant tenant, string username) { - return GetUserNames(EmployeeStatus.All) + return GetUserNames(tenant, EmployeeStatus.All) .Contains(username, StringComparer.CurrentCultureIgnoreCase); } public UserInfo GetUsers(Guid id) + { + return GetUsers(id, CoreContext.TenantManager.GetCurrentTenant().TenantId); + } + public UserInfo GetUsers(Guid id, int tenantId) { if (IsSystemUser(id)) return systemUsers[id]; - var u = userService.GetUser(CoreContext.TenantManager.GetCurrentTenant().TenantId, id); + var u = userService.GetUser(tenantId, id); return u != null && !u.Removed ? u : Constants.LostUser; } @@ -146,9 +149,9 @@ namespace ASC.Core return u != null && !u.Removed ? u : Constants.LostUser; } - public bool UserExists(Guid id) + public bool UserExists(Guid id, int tenantId) { - return !GetUsers(id).Equals(Constants.LostUser); + return !GetUsers(id, tenantId).Equals(Constants.LostUser); } public bool IsSystemUser(Guid id) @@ -156,20 +159,20 @@ namespace ASC.Core return systemUsers.ContainsKey(id); } - public UserInfo GetUserByEmail(string email) + public UserInfo GetUserByEmail(int tenantId, string email) { if (string.IsNullOrEmpty(email)) return Constants.LostUser; - return GetUsersInternal() + return GetUsersInternal(tenantId) .FirstOrDefault(u => string.Compare(u.Email, email, StringComparison.CurrentCultureIgnoreCase) == 0) ?? Constants.LostUser; } - public UserInfo[] Search(string text, EmployeeStatus status) + public UserInfo[] Search(Tenant tenant, string text, EmployeeStatus status) { - return Search(text, status, Guid.Empty); + return Search(tenant, text, status, Guid.Empty); } - public UserInfo[] Search(string text, EmployeeStatus status, Guid groupId) + public UserInfo[] Search(Tenant tenant, string text, EmployeeStatus status, Guid groupId) { if (text == null || text.Trim() == string.Empty) return new UserInfo[0]; @@ -177,8 +180,8 @@ namespace ASC.Core if (words.Length == 0) return new UserInfo[0]; var users = groupId == Guid.Empty ? - GetUsers(status) : - GetUsersByGroup(groupId).Where(u => (u.Status & status) == status); + GetUsers(tenant, status) : + GetUsersByGroup(tenant, groupId).Where(u => (u.Status & status) == status); var findUsers = new List(); foreach (var user in users) @@ -199,83 +202,83 @@ namespace ASC.Core return findUsers.ToArray(); } - public UserInfo SaveUserInfo(UserInfo u, bool isVisitor = false) + public UserInfo SaveUserInfo(Tenant tenant, UserInfo u, bool isVisitor = false) { if (IsSystemUser(u.ID)) return systemUsers[u.ID]; - if (u.ID == Guid.Empty) SecurityContext.DemandPermissions(Constants.Action_AddRemoveUser); - else SecurityContext.DemandPermissions(new UserSecurityProvider(u.ID), Constants.Action_EditUser); + if (u.ID == Guid.Empty) SecurityContext.DemandPermissions(tenant, Constants.Action_AddRemoveUser); + else SecurityContext.DemandPermissions(tenant, new UserSecurityProvider(u.ID), Constants.Action_EditUser); - if (Constants.MaxEveryoneCount <= GetUsersByGroup(Constants.GroupEveryone.ID).Length) + if (Constants.MaxEveryoneCount <= GetUsersByGroup(tenant, Constants.GroupEveryone.ID).Length) { throw new TenantQuotaException("Maximum number of users exceeded"); } if (u.Status == EmployeeStatus.Active) { - var q = CoreContext.TenantManager.GetTenantQuota(CoreContext.TenantManager.GetCurrentTenant().TenantId); - if (q.ActiveUsers < GetUsersByGroup(Constants.GroupUser.ID).Length) + var q = CoreContext.TenantManager.GetTenantQuota(tenant.TenantId); + if (q.ActiveUsers < GetUsersByGroup(tenant, Constants.GroupUser.ID).Length) { throw new TenantQuotaException(string.Format("Exceeds the maximum active users ({0})", q.ActiveUsers)); } } - var newUser = userService.SaveUser(CoreContext.TenantManager.GetCurrentTenant().TenantId, u); + var newUser = userService.SaveUser(tenant.TenantId, u); return newUser; } - public void DeleteUser(Guid id) + public void DeleteUser(Tenant tenant, Guid id) { if (IsSystemUser(id)) return; - SecurityContext.DemandPermissions(Constants.Action_AddRemoveUser); - if (id == CoreContext.TenantManager.GetCurrentTenant().OwnerId) + SecurityContext.DemandPermissions(tenant, Constants.Action_AddRemoveUser); + if (id == tenant.OwnerId) { throw new InvalidOperationException("Can not remove tenant owner."); } - userService.RemoveUser(CoreContext.TenantManager.GetCurrentTenant().TenantId, id); + userService.RemoveUser(tenant.TenantId, id); } - public void SaveUserPhoto(Guid id, byte[] photo) + public void SaveUserPhoto(Tenant tenant, Guid id, byte[] photo) { if (IsSystemUser(id)) return; - SecurityContext.DemandPermissions(new UserSecurityProvider(id), Constants.Action_EditUser); + SecurityContext.DemandPermissions(tenant, new UserSecurityProvider(id), Constants.Action_EditUser); - userService.SetUserPhoto(CoreContext.TenantManager.GetCurrentTenant().TenantId, id, photo); + userService.SetUserPhoto(tenant.TenantId, id, photo); } - public byte[] GetUserPhoto(Guid id) + public byte[] GetUserPhoto(int tenantId, Guid id) { if (IsSystemUser(id)) return null; - return userService.GetUserPhoto(CoreContext.TenantManager.GetCurrentTenant().TenantId, id); + return userService.GetUserPhoto(tenantId, id); } - public IEnumerable GetUserGroupsId(Guid id) + public IEnumerable GetUserGroupsId(int tenantId, Guid id) { - return GetUsers(id).GetUserGroupsId(); + return GetUsers(id, tenantId).GetUserGroupsId(tenantId); } - public GroupInfo[] GetUserGroups(Guid id) + public GroupInfo[] GetUserGroups(Tenant tenant, Guid id) { - return GetUsers(id).GetGroups(IncludeType.Distinct, Guid.Empty); + return GetUsers(id, tenant.TenantId).GetGroups(tenant, IncludeType.Distinct, Guid.Empty); } - public GroupInfo[] GetUserGroups(Guid id, Guid categoryID) + public GroupInfo[] GetUserGroups(Tenant tenant, Guid id, Guid categoryID) { - return GetUsers(id).GetGroups(IncludeType.Distinct, categoryID); + return GetUsers(id, tenant.TenantId).GetGroups(tenant, IncludeType.Distinct, categoryID); } - public GroupInfo[] GetUserGroups(Guid userID, IncludeType includeType) + public GroupInfo[] GetUserGroups(Tenant tenant, Guid userID, IncludeType includeType) { - return GetUsers(userID).GetGroups(includeType, null); + return GetUsers(userID, tenant.TenantId).GetGroups(tenant, includeType, null); } - internal GroupInfo[] GetUserGroups(Guid userID, IncludeType includeType, Guid? categoryId) + internal GroupInfo[] GetUserGroups(Tenant tenant, Guid userID, IncludeType includeType, Guid? categoryId) { var result = new List(); var distinctUserGroups = new List(); - var refs = GetRefsInternal(); + var refs = GetRefsInternal(tenant.TenantId); IEnumerable userRefs = null; var store = refs as UserGroupRefStore; if (store != null) @@ -285,9 +288,9 @@ namespace ASC.Core var userRefsContainsNotRemoved = userRefs != null ? userRefs.Where(r => !r.Removed && r.RefType == UserGroupRefType.Contains).ToList() : null; - foreach (var g in GetGroupsInternal().Where(g => !categoryId.HasValue || g.CategoryID == categoryId)) + foreach (var g in GetGroupsInternal(tenant.TenantId).Where(g => !categoryId.HasValue || g.CategoryID == categoryId)) { - if (((g.CategoryID == Constants.SysGroupCategoryId || userRefs == null) && IsUserInGroupInternal(userID, g.ID, refs)) || + if (((g.CategoryID == Constants.SysGroupCategoryId || userRefs == null) && IsUserInGroupInternal(tenant, userID, g.ID, refs)) || (userRefsContainsNotRemoved != null && userRefsContainsNotRemoved.Any(r => r.GroupId == g.ID))) { distinctUserGroups.Add(g); @@ -304,11 +307,11 @@ namespace ASC.Core return result.ToArray(); } - internal IEnumerable GetUserGroupsGuids(Guid userID) + internal IEnumerable GetUserGroupsGuids(int tenantId, Guid userID) { var result = new List(); - var refs = GetRefsInternal(); + var refs = GetRefsInternal(tenantId); var store = refs as UserGroupRefStore; if (store != null) @@ -328,38 +331,36 @@ namespace ASC.Core return result; } - public bool IsUserInGroup(Guid userId, Guid groupId) + public bool IsUserInGroup(Tenant tenant, Guid userId, Guid groupId) { - return IsUserInGroupInternal(userId, groupId, GetRefsInternal()); + return IsUserInGroupInternal(tenant, userId, groupId, GetRefsInternal(tenant.TenantId)); } - public UserInfo[] GetUsersByGroup(Guid groupId, EmployeeStatus employeeStatus = EmployeeStatus.Default) + public UserInfo[] GetUsersByGroup(Tenant tenant, Guid groupId, EmployeeStatus employeeStatus = EmployeeStatus.Default) { - var refs = GetRefsInternal(); - return GetUsers(employeeStatus).Where(u => IsUserInGroupInternal(u.ID, groupId, refs)).ToArray(); + var refs = GetRefsInternal(tenant.TenantId); + return GetUsers(tenant, employeeStatus).Where(u => IsUserInGroupInternal(tenant, u.ID, groupId, refs)).ToArray(); } - public void AddUserIntoGroup(Guid userId, Guid groupId) + public void AddUserIntoGroup(Tenant tenant, Guid userId, Guid groupId) { if (Constants.LostUser.ID == userId || Constants.LostGroupInfo.ID == groupId) { return; } - SecurityContext.DemandPermissions(Constants.Action_EditGroups); + SecurityContext.DemandPermissions(tenant, Constants.Action_EditGroups); - userService.SaveUserGroupRef( - CoreContext.TenantManager.GetCurrentTenant().TenantId, - new UserGroupRef(userId, groupId, UserGroupRefType.Contains)); + userService.SaveUserGroupRef(tenant.TenantId, new UserGroupRef(userId, groupId, UserGroupRefType.Contains)); GetUsers(userId).ResetGroupCache(); } - public void RemoveUserFromGroup(Guid userId, Guid groupId) + public void RemoveUserFromGroup(Tenant tenant, Guid userId, Guid groupId) { if (Constants.LostUser.ID == userId || Constants.LostGroupInfo.ID == groupId) return; - SecurityContext.DemandPermissions(Constants.Action_EditGroups); + SecurityContext.DemandPermissions(tenant, Constants.Action_EditGroups); - userService.RemoveUserGroupRef(CoreContext.TenantManager.GetCurrentTenant().TenantId, userId, groupId, UserGroupRefType.Contains); + userService.RemoveUserGroupRef(tenant.TenantId, userId, groupId, UserGroupRefType.Contains); GetUsers(userId).ResetGroupCache(); } @@ -369,46 +370,46 @@ namespace ASC.Core #region Company - public GroupInfo[] GetDepartments() + public GroupInfo[] GetDepartments(int tenantId) { - return CoreContext.UserManager.GetGroups(); + return GetGroups(tenantId); } - public Guid GetDepartmentManager(Guid deparmentID) + public Guid GetDepartmentManager(int tenantId, Guid deparmentID) { - return GetRefsInternal() + return GetRefsInternal(tenantId) .Values .Where(r => r.RefType == UserGroupRefType.Manager && r.GroupId == deparmentID && !r.Removed) .Select(r => r.UserId) .SingleOrDefault(); } - public void SetDepartmentManager(Guid deparmentID, Guid userID) + public void SetDepartmentManager(int tenantId, Guid deparmentID, Guid userID) { - var managerId = GetDepartmentManager(deparmentID); + var managerId = GetDepartmentManager(tenantId, deparmentID); if (managerId != Guid.Empty) { userService.RemoveUserGroupRef( - CoreContext.TenantManager.GetCurrentTenant().TenantId, + tenantId, managerId, deparmentID, UserGroupRefType.Manager); } if (userID != Guid.Empty) { userService.SaveUserGroupRef( - CoreContext.TenantManager.GetCurrentTenant().TenantId, + tenantId, new UserGroupRef(userID, deparmentID, UserGroupRefType.Manager)); } } - public UserInfo GetCompanyCEO() + public UserInfo GetCompanyCEO(int tenantId) { - var id = GetDepartmentManager(Guid.Empty); + var id = GetDepartmentManager(tenantId, Guid.Empty); return id != Guid.Empty ? GetUsers(id) : null; } - public void SetCompanyCEO(Guid userId) + public void SetCompanyCEO(int tenantId, Guid userId) { - SetDepartmentManager(Guid.Empty, userId); + SetDepartmentManager(tenantId, Guid.Empty, userId); } #endregion Company @@ -416,56 +417,56 @@ namespace ASC.Core #region Groups - public GroupInfo[] GetGroups() + public GroupInfo[] GetGroups(int tenantId) { - return GetGroups(Guid.Empty); + return GetGroups(tenantId, Guid.Empty); } - public GroupInfo[] GetGroups(Guid categoryID) + public GroupInfo[] GetGroups(int tenantId, Guid categoryID) { - return GetGroupsInternal() + return GetGroupsInternal(tenantId) .Where(g => g.CategoryID == categoryID) .ToArray(); } - public GroupInfo GetGroupInfo(Guid groupID) + public GroupInfo GetGroupInfo(int tenantId, Guid groupID) { - return GetGroupsInternal() + return GetGroupsInternal(tenantId) .SingleOrDefault(g => g.ID == groupID) ?? Constants.LostGroupInfo; } - public GroupInfo GetGroupInfoBySid(string sid) + public GroupInfo GetGroupInfoBySid(int tenantId, string sid) { - return GetGroupsInternal() + return GetGroupsInternal(tenantId) .SingleOrDefault(g => g.Sid == sid) ?? Constants.LostGroupInfo; } - public DateTime GetMaxGroupsLastModified() + public DateTime GetMaxGroupsLastModified(int tenantId) { - return userService.GetGroups(CoreContext.TenantManager.GetCurrentTenant().TenantId, default(DateTime)) + return userService.GetGroups(tenantId, default) .Values .Select(g => g.LastModified) .DefaultIfEmpty() .Max(); } - public GroupInfo SaveGroupInfo(GroupInfo g) + public GroupInfo SaveGroupInfo(Tenant tenant, GroupInfo g) { if (Constants.LostGroupInfo.Equals(g)) return Constants.LostGroupInfo; if (Constants.BuildinGroups.Any(b => b.ID == g.ID)) return Constants.BuildinGroups.Single(b => b.ID == g.ID); - SecurityContext.DemandPermissions(Constants.Action_EditGroups); + SecurityContext.DemandPermissions(tenant, Constants.Action_EditGroups); - var newGroup = userService.SaveGroup(CoreContext.TenantManager.GetCurrentTenant().TenantId, ToGroup(g)); + var newGroup = userService.SaveGroup(tenant.TenantId, ToGroup(g)); return new GroupInfo(newGroup.CategoryId) { ID = newGroup.Id, Name = newGroup.Name, Sid = newGroup.Sid }; } - public void DeleteGroup(Guid id) + public void DeleteGroup(Tenant tenant, Guid id) { if (Constants.LostGroupInfo.Equals(id)) return; if (Constants.BuildinGroups.Any(b => b.ID == id)) return; - SecurityContext.DemandPermissions(Constants.Action_EditGroups); + SecurityContext.DemandPermissions(tenant, Constants.Action_EditGroups); - userService.RemoveGroup(CoreContext.TenantManager.GetCurrentTenant().TenantId, id); + userService.RemoveGroup(tenant.TenantId, id); } #endregion Groups @@ -487,31 +488,29 @@ namespace ASC.Core } - private IEnumerable GetUsersInternal() + private IEnumerable GetUsersInternal(int tenantId) { - return userService.GetUsers(CoreContext.TenantManager.GetCurrentTenant().TenantId, default(DateTime)) + return userService.GetUsers(tenantId, default) .Values .Where(u => !u.Removed); } - private IEnumerable GetGroupsInternal() + private IEnumerable GetGroupsInternal(int tenantId) { - return userService.GetGroups(CoreContext.TenantManager.GetCurrentTenant().TenantId, default(DateTime)) + return userService.GetGroups(tenantId, default) .Values .Where(g => !g.Removed) .Select(g => new GroupInfo(g.CategoryId) { ID = g.Id, Name = g.Name, Sid = g.Sid }) .Concat(Constants.BuildinGroups); } - private IDictionary GetRefsInternal() + private IDictionary GetRefsInternal(int tenantId) { - return userService.GetUserGroupRefs(CoreContext.TenantManager.GetCurrentTenant().TenantId, default(DateTime)); + return userService.GetUserGroupRefs(tenantId, default); } - private bool IsUserInGroupInternal(Guid userId, Guid groupId, IDictionary refs) + private bool IsUserInGroupInternal(Tenant tenant, Guid userId, Guid groupId, IDictionary refs) { - var tenant = CoreContext.TenantManager.GetCurrentTenant(); - if (groupId == Constants.GroupEveryone.ID) { return true; diff --git a/common/ASC.Core.Common/Context/SecurityContext.cs b/common/ASC.Core.Common/Context/SecurityContext.cs index e1d2f65356..cfea4da51c 100644 --- a/common/ASC.Core.Common/Context/SecurityContext.cs +++ b/common/ASC.Core.Common/Context/SecurityContext.cs @@ -199,15 +199,16 @@ namespace ASC.Core { throw new SecurityException("Account disabled."); } + var tenant = CoreContext.TenantManager.GetCurrentTenant(); // for LDAP users only if (u.Sid != null) { - if (!CoreContext.TenantManager.GetTenantQuota(CoreContext.TenantManager.GetCurrentTenant().TenantId).Ldap) + if (!CoreContext.TenantManager.GetTenantQuota(tenant.TenantId).Ldap) { throw new BillingException("Your tariff plan does not support this option.", "Ldap"); } } - if (CoreContext.UserManager.IsUserInGroup(u.ID, Users.Constants.GroupAdmin.ID)) + if (CoreContext.UserManager.IsUserInGroup(tenant, u.ID, Users.Constants.GroupAdmin.ID)) { roles.Add(Role.Administrators); } @@ -238,34 +239,34 @@ namespace ASC.Core } - public static bool CheckPermissions(params IAction[] actions) + public static bool CheckPermissions(Tenant tenant, params IAction[] actions) { - return PermissionResolver.Check(CurrentAccount, actions); + return PermissionResolver.Check(tenant, CurrentAccount, actions); } - public static bool CheckPermissions(ISecurityObject securityObject, params IAction[] actions) + public static bool CheckPermissions(Tenant tenant, ISecurityObject securityObject, params IAction[] actions) { - return CheckPermissions(securityObject, null, actions); + return CheckPermissions(tenant, securityObject, null, actions); } - public static bool CheckPermissions(ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions) + public static bool CheckPermissions(Tenant tenant, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions) { - return PermissionResolver.Check(CurrentAccount, objectId, securityObjProvider, actions); + return PermissionResolver.Check(tenant, CurrentAccount, objectId, securityObjProvider, actions); } - public static void DemandPermissions(params IAction[] actions) + public static void DemandPermissions(Tenant tenant, params IAction[] actions) { - PermissionResolver.Demand(CurrentAccount, actions); + PermissionResolver.Demand(tenant, CurrentAccount, actions); } - public static void DemandPermissions(ISecurityObject securityObject, params IAction[] actions) + public static void DemandPermissions(Tenant tenant, ISecurityObject securityObject, params IAction[] actions) { - DemandPermissions(securityObject, null, actions); + DemandPermissions(tenant, securityObject, null, actions); } - public static void DemandPermissions(ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions) + public static void DemandPermissions(Tenant tenant, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions) { - PermissionResolver.Demand(CurrentAccount, objectId, securityObjProvider, actions); + PermissionResolver.Demand(tenant, CurrentAccount, objectId, securityObjProvider, actions); } diff --git a/common/ASC.Core.Common/Core/UserInfo.cs b/common/ASC.Core.Common/Core/UserInfo.cs index 422797ff5f..ddc38c13d6 100644 --- a/common/ASC.Core.Common/Core/UserInfo.cs +++ b/common/ASC.Core.Common/Core/UserInfo.cs @@ -31,7 +31,8 @@ using System.Text; using System.Linq; using ASC.Collections; using ASC.Notify.Recipients; - +using ASC.Core.Tenants; + namespace ASC.Core.Users { [Serializable] @@ -150,9 +151,9 @@ namespace ASC.Core.Users return MemberwiseClone(); } - internal GroupInfo[] GetGroups(IncludeType includeType, Guid? categoryId) + internal GroupInfo[] GetGroups(Tenant tenant, IncludeType includeType, Guid? categoryId) { - var groups = groupCache.Get(ID.ToString(), () => CoreContext.UserManager.GetUserGroups(ID, IncludeType.Distinct, null)); + var groups = groupCache.Get(ID.ToString(), () => CoreContext.UserManager.GetUserGroups(tenant, ID, IncludeType.Distinct, null)); if (categoryId.HasValue) { @@ -162,9 +163,9 @@ namespace ASC.Core.Users return groups; } - internal IEnumerable GetUserGroupsId() + internal IEnumerable GetUserGroupsId(int tenantId) { - return groupCacheId.Get(ID.ToString(), () => CoreContext.UserManager.GetUserGroupsGuids(ID)); + return groupCacheId.Get(ID.ToString(), () => CoreContext.UserManager.GetUserGroupsGuids(tenantId, ID)); } internal void ResetGroupCache() diff --git a/common/ASC.Common/Notify/Channels/ISenderChannel.cs b/common/ASC.Core.Common/Notify/Channels/ISenderChannel.cs similarity index 100% rename from common/ASC.Common/Notify/Channels/ISenderChannel.cs rename to common/ASC.Core.Common/Notify/Channels/ISenderChannel.cs diff --git a/common/ASC.Common/Notify/Channels/SenderChannel.cs b/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs similarity index 100% rename from common/ASC.Common/Notify/Channels/SenderChannel.cs rename to common/ASC.Core.Common/Notify/Channels/SenderChannel.cs diff --git a/common/ASC.Common/Notify/Context.cs b/common/ASC.Core.Common/Notify/Context.cs similarity index 100% rename from common/ASC.Common/Notify/Context.cs rename to common/ASC.Core.Common/Notify/Context.cs diff --git a/common/ASC.Common/Notify/Cron/CronExpression.cs b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs similarity index 100% rename from common/ASC.Common/Notify/Cron/CronExpression.cs rename to common/ASC.Core.Common/Notify/Cron/CronExpression.cs diff --git a/common/ASC.Common/Notify/Cron/ISet.cs b/common/ASC.Core.Common/Notify/Cron/ISet.cs similarity index 100% rename from common/ASC.Common/Notify/Cron/ISet.cs rename to common/ASC.Core.Common/Notify/Cron/ISet.cs diff --git a/common/ASC.Common/Notify/Cron/ISortedSet.cs b/common/ASC.Core.Common/Notify/Cron/ISortedSet.cs similarity index 100% rename from common/ASC.Common/Notify/Cron/ISortedSet.cs rename to common/ASC.Core.Common/Notify/Cron/ISortedSet.cs diff --git a/common/ASC.Common/Notify/Cron/TreeSet.cs b/common/ASC.Core.Common/Notify/Cron/TreeSet.cs similarity index 100% rename from common/ASC.Common/Notify/Cron/TreeSet.cs rename to common/ASC.Core.Common/Notify/Cron/TreeSet.cs diff --git a/common/ASC.Core.Common/Notify/DirectSubscriptionProvider.cs b/common/ASC.Core.Common/Notify/DirectSubscriptionProvider.cs index ad055348ba..002ccf5e5a 100644 --- a/common/ASC.Core.Common/Notify/DirectSubscriptionProvider.cs +++ b/common/ASC.Core.Common/Notify/DirectSubscriptionProvider.cs @@ -26,6 +26,7 @@ using System; using System.Linq; +using ASC.Core.Tenants; using ASC.Notify.Model; using ASC.Notify.Recipients; @@ -50,7 +51,7 @@ namespace ASC.Core.Notify } - public object GetSubscriptionRecord(INotifyAction action, IRecipient recipient, string objectID) + public object GetSubscriptionRecord(Tenant tenant, INotifyAction action, IRecipient recipient, string objectID) { if (action == null) throw new ArgumentNullException("action"); if (recipient == null) throw new ArgumentNullException("recipient"); @@ -58,7 +59,7 @@ namespace ASC.Core.Notify return subscriptionManager.GetSubscriptionRecord(sourceID, action.ID, recipient.ID, objectID); } - public string[] GetSubscriptions(INotifyAction action, IRecipient recipient, bool checkSubscribe = true) + public string[] GetSubscriptions(Tenant tenant, INotifyAction action, IRecipient recipient, bool checkSubscribe = true) { if (action == null) throw new ArgumentNullException("action"); if (recipient == null) throw new ArgumentNullException("recipient"); @@ -66,17 +67,17 @@ namespace ASC.Core.Notify return subscriptionManager.GetSubscriptions(sourceID, action.ID, recipient.ID, checkSubscribe); } - public IRecipient[] GetRecipients(INotifyAction action, string objectID) + public IRecipient[] GetRecipients(int tenantId, INotifyAction action, string objectID) { if (action == null) throw new ArgumentNullException("action"); return subscriptionManager.GetRecipients(sourceID, action.ID, objectID) - .Select(r => recipientProvider.GetRecipient(r)) + .Select(r => recipientProvider.GetRecipient(tenantId, r)) .Where(r => r != null) .ToArray(); } - public string[] GetSubscriptionMethod(INotifyAction action, IRecipient recipient) + public string[] GetSubscriptionMethod(Tenant tenant, INotifyAction action, IRecipient recipient) { if (action == null) throw new ArgumentNullException("action"); if (recipient == null) throw new ArgumentNullException("recipient"); @@ -130,7 +131,7 @@ namespace ASC.Core.Notify } [Obsolete("Use UnSubscribe(INotifyAction, string, IRecipient)", true)] - public void UnSubscribe(INotifyAction action, IRecipient recipient) + public void UnSubscribe(Tenant tenant, INotifyAction action, IRecipient recipient) { throw new NotSupportedException("use UnSubscribe(INotifyAction, string, IRecipient )"); } diff --git a/common/ASC.Common/Notify/Engine/CallContext.cs b/common/ASC.Core.Common/Notify/Engine/CallContext.cs similarity index 100% rename from common/ASC.Common/Notify/Engine/CallContext.cs rename to common/ASC.Core.Common/Notify/Engine/CallContext.cs diff --git a/common/ASC.Common/Notify/Engine/DispatchEngine.cs b/common/ASC.Core.Common/Notify/Engine/DispatchEngine.cs similarity index 100% rename from common/ASC.Common/Notify/Engine/DispatchEngine.cs rename to common/ASC.Core.Common/Notify/Engine/DispatchEngine.cs diff --git a/common/ASC.Common/Notify/Engine/INotifyEngine.cs b/common/ASC.Core.Common/Notify/Engine/INotifyEngine.cs similarity index 100% rename from common/ASC.Common/Notify/Engine/INotifyEngine.cs rename to common/ASC.Core.Common/Notify/Engine/INotifyEngine.cs diff --git a/common/ASC.Common/Notify/Engine/InterceptorStorage.cs b/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs similarity index 100% rename from common/ASC.Common/Notify/Engine/InterceptorStorage.cs rename to common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs diff --git a/common/ASC.Common/Notify/Engine/NotifyEngine.cs b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs similarity index 93% rename from common/ASC.Common/Notify/Engine/NotifyEngine.cs rename to common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs index 65b984a2b9..f7e3cdd451 100644 --- a/common/ASC.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -31,6 +31,8 @@ using System.Threading; using System.Threading.Tasks; using ASC.Common.Logging; using ASC.Common.Notify.Patterns; +using ASC.Core; +using ASC.Core.Tenants; using ASC.Notify.Channels; using ASC.Notify.Cron; using ASC.Notify.Messages; @@ -217,7 +219,7 @@ namespace ASC.Notify.Engine } try { - SendNotify(request); + SendNotify(CoreContext.TenantManager.GetCurrentTenant(), request); } catch (Exception e) { @@ -241,7 +243,7 @@ namespace ASC.Notify.Engine } - private NotifyResult SendNotify(NotifyRequest request) + private NotifyResult SendNotify(Tenant tenant, NotifyRequest request) { var sendResponces = new List(); @@ -252,7 +254,7 @@ namespace ASC.Notify.Engine } else { - sendResponces.AddRange(SendGroupNotify(request)); + sendResponces.AddRange(SendGroupNotify(tenant, request)); } NotifyResult result = null; @@ -273,14 +275,14 @@ namespace ASC.Notify.Engine return request.Intercept(place) ? new SendResponse(request.NotifyAction, sender, request.Recipient, SendResult.Prevented) : null; } - private List SendGroupNotify(NotifyRequest request) + private List SendGroupNotify(Tenant tenant, NotifyRequest request) { var responces = new List(); - SendGroupNotify(request, responces); + SendGroupNotify(tenant, request, responces); return responces; } - private void SendGroupNotify(NotifyRequest request, List responces) + private void SendGroupNotify(Tenant tenant, NotifyRequest request, List responces) { if (request.Recipient is IDirectRecipient) { @@ -290,7 +292,7 @@ namespace ASC.Notify.Engine var directresponses = new List(1); try { - directresponses = SendDirectNotify(request); + directresponses = SendDirectNotify(tenant, request); } catch (Exception exc) { @@ -314,13 +316,13 @@ namespace ASC.Notify.Engine try { - var recipients = recipientProvider.GetGroupEntries(request.Recipient as IRecipientsGroup) ?? new IRecipient[0]; + var recipients = recipientProvider.GetGroupEntries(tenant, request.Recipient as IRecipientsGroup) ?? new IRecipient[0]; foreach (var recipient in recipients) { try { var newRequest = request.Split(recipient); - SendGroupNotify(newRequest, responces); + SendGroupNotify(tenant, newRequest, responces); } catch (Exception exc) { @@ -345,7 +347,7 @@ namespace ASC.Notify.Engine } } - private List SendDirectNotify(NotifyRequest request) + private List SendDirectNotify(Tenant tenant, NotifyRequest request) { if (!(request.Recipient is IDirectRecipient)) throw new ArgumentException("request.Recipient not IDirectRecipient", "request"); @@ -359,7 +361,7 @@ namespace ASC.Notify.Engine try { - PrepareRequestFillSenders(request); + PrepareRequestFillSenders(tenant, request); PrepareRequestFillPatterns(request); PrepareRequestFillTags(request); } @@ -377,7 +379,7 @@ namespace ASC.Notify.Engine { try { - response = SendDirectNotify(request, channel); + response = SendDirectNotify(tenant.TenantId, request, channel); } catch (Exception exc) { @@ -399,7 +401,7 @@ namespace ASC.Notify.Engine return responses; } - private SendResponse SendDirectNotify(NotifyRequest request, ISenderChannel channel) + private SendResponse SendDirectNotify(int tenantId, NotifyRequest request, ISenderChannel channel) { var recipient = request.Recipient as IDirectRecipient; if (recipient == null) throw new ArgumentException("request.Recipient not IDirectRecipient", "request"); @@ -407,7 +409,7 @@ namespace ASC.Notify.Engine request.CurrentSender = channel.SenderName; NoticeMessage noticeMessage; - var oops = CreateNoticeMessageFromNotifyRequest(request, channel.SenderName, out noticeMessage); + var oops = CreateNoticeMessageFromNotifyRequest(tenantId, request, channel.SenderName, out noticeMessage); if (oops != null) return oops; request.CurrentMessage = noticeMessage; @@ -419,7 +421,7 @@ namespace ASC.Notify.Engine return new SendResponse(noticeMessage, channel.SenderName, SendResult.Inprogress); } - private SendResponse CreateNoticeMessageFromNotifyRequest(NotifyRequest request, string sender, out NoticeMessage noticeMessage) + private SendResponse CreateNoticeMessageFromNotifyRequest(int tenantId, NotifyRequest request, string sender, out NoticeMessage noticeMessage) { if (request == null) throw new ArgumentNullException("request"); @@ -433,7 +435,7 @@ namespace ASC.Notify.Engine recipient = new DirectRecipient(request.Recipient.ID, request.Recipient.Name, addresses); } - recipient = recipientProvider.FilterRecipientAddresses(recipient); + recipient = recipientProvider.FilterRecipientAddresses(tenantId, recipient); noticeMessage = request.CreateMessage(recipient); addresses = recipient.Addresses; @@ -503,14 +505,14 @@ namespace ASC.Notify.Engine } } - private void PrepareRequestFillSenders(NotifyRequest request) + private void PrepareRequestFillSenders(Tenant tenant, NotifyRequest request) { if (request.SenderNames == null) { var subscriptionProvider = request.NotifySource.GetSubscriptionProvider(); var senderNames = new List(); - senderNames.AddRange(subscriptionProvider.GetSubscriptionMethod(request.NotifyAction, request.Recipient) ?? new string[0]); + senderNames.AddRange(subscriptionProvider.GetSubscriptionMethod(tenant, request.NotifyAction, request.Recipient) ?? new string[0]); senderNames.AddRange(request.Arguments.OfType().Select(tag => (string) tag.Value)); request.SenderNames = senderNames.ToArray(); diff --git a/common/ASC.Common/Notify/Engine/NotifyRequest.cs b/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs similarity index 100% rename from common/ASC.Common/Notify/Engine/NotifyRequest.cs rename to common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs diff --git a/common/ASC.Common/Notify/Engine/SendInterceptorSkeleton.cs b/common/ASC.Core.Common/Notify/Engine/SendInterceptorSkeleton.cs similarity index 100% rename from common/ASC.Common/Notify/Engine/SendInterceptorSkeleton.cs rename to common/ASC.Core.Common/Notify/Engine/SendInterceptorSkeleton.cs diff --git a/common/ASC.Common/Notify/Engine/SingleRecipientInterceptor.cs b/common/ASC.Core.Common/Notify/Engine/SingleRecipientInterceptor.cs similarity index 100% rename from common/ASC.Common/Notify/Engine/SingleRecipientInterceptor.cs rename to common/ASC.Core.Common/Notify/Engine/SingleRecipientInterceptor.cs diff --git a/common/ASC.Common/Notify/INotifyClient.cs b/common/ASC.Core.Common/Notify/INotifyClient.cs similarity index 96% rename from common/ASC.Common/Notify/INotifyClient.cs rename to common/ASC.Core.Common/Notify/INotifyClient.cs index a34f2ad641..e117ab28a9 100644 --- a/common/ASC.Common/Notify/INotifyClient.cs +++ b/common/ASC.Core.Common/Notify/INotifyClient.cs @@ -44,7 +44,7 @@ namespace ASC.Notify void SendNoticeToAsync(INotifyAction action, string objectID, IRecipient[] recipients, bool checkSubscription, params ITagValue[] args); - void SendNoticeAsync(INotifyAction action, string objectID, params ITagValue[] args); + void SendNoticeAsync(int tenantId, INotifyAction action, string objectID, params ITagValue[] args); void SendNoticeAsync(INotifyAction action, string objectID, IRecipient recipient, params ITagValue[] args); diff --git a/common/ASC.Common/Notify/INotifyRegistry.cs b/common/ASC.Core.Common/Notify/INotifyRegistry.cs similarity index 100% rename from common/ASC.Common/Notify/INotifyRegistry.cs rename to common/ASC.Core.Common/Notify/INotifyRegistry.cs diff --git a/common/ASC.Common/Notify/Recipients/IRecipientsProvider.cs b/common/ASC.Core.Common/Notify/IRecipientsProvider.cs similarity index 83% rename from common/ASC.Common/Notify/Recipients/IRecipientsProvider.cs rename to common/ASC.Core.Common/Notify/IRecipientsProvider.cs index 48e5266cd6..82ae2fff75 100644 --- a/common/ASC.Common/Notify/Recipients/IRecipientsProvider.cs +++ b/common/ASC.Core.Common/Notify/IRecipientsProvider.cs @@ -24,18 +24,20 @@ */ +using ASC.Core.Tenants; + namespace ASC.Notify.Recipients { public interface IRecipientProvider { - IRecipient GetRecipient(string id); + IRecipient GetRecipient(int tenantId, string id); - IRecipient[] GetGroupEntries(IRecipientsGroup group); + IRecipient[] GetGroupEntries(Tenant tenant, IRecipientsGroup group); - IRecipientsGroup[] GetGroups(IRecipient recipient); + IRecipientsGroup[] GetGroups(Tenant tenant, IRecipient recipient); string[] GetRecipientAddresses(IDirectRecipient recipient, string senderName); - IDirectRecipient FilterRecipientAddresses(IDirectRecipient recipient); + IDirectRecipient FilterRecipientAddresses(int tenantId, IDirectRecipient recipient); } } \ No newline at end of file diff --git a/common/ASC.Common/Notify/ISendInterceptor.cs b/common/ASC.Core.Common/Notify/ISendInterceptor.cs similarity index 100% rename from common/ASC.Common/Notify/ISendInterceptor.cs rename to common/ASC.Core.Common/Notify/ISendInterceptor.cs diff --git a/common/ASC.Common/Notify/InitiatorInterceptor.cs b/common/ASC.Core.Common/Notify/InitiatorInterceptor.cs similarity index 100% rename from common/ASC.Common/Notify/InitiatorInterceptor.cs rename to common/ASC.Core.Common/Notify/InitiatorInterceptor.cs diff --git a/common/ASC.Common/Notify/InterceptorLifetime.cs b/common/ASC.Core.Common/Notify/InterceptorLifetime.cs similarity index 100% rename from common/ASC.Common/Notify/InterceptorLifetime.cs rename to common/ASC.Core.Common/Notify/InterceptorLifetime.cs diff --git a/common/ASC.Common/Notify/InterceptorPlace.cs b/common/ASC.Core.Common/Notify/InterceptorPlace.cs similarity index 100% rename from common/ASC.Common/Notify/InterceptorPlace.cs rename to common/ASC.Core.Common/Notify/InterceptorPlace.cs diff --git a/common/ASC.Common/Notify/Messages/INoticeMessage.cs b/common/ASC.Core.Common/Notify/Messages/INoticeMessage.cs similarity index 100% rename from common/ASC.Common/Notify/Messages/INoticeMessage.cs rename to common/ASC.Core.Common/Notify/Messages/INoticeMessage.cs diff --git a/common/ASC.Common/Notify/Messages/NoticeMessage.cs b/common/ASC.Core.Common/Notify/Messages/NoticeMessage.cs similarity index 100% rename from common/ASC.Common/Notify/Messages/NoticeMessage.cs rename to common/ASC.Core.Common/Notify/Messages/NoticeMessage.cs diff --git a/common/ASC.Common/Notify/Messages/SendResponse.cs b/common/ASC.Core.Common/Notify/Messages/SendResponse.cs similarity index 100% rename from common/ASC.Common/Notify/Messages/SendResponse.cs rename to common/ASC.Core.Common/Notify/Messages/SendResponse.cs diff --git a/common/ASC.Common/Notify/Messages/SendResult.cs b/common/ASC.Core.Common/Notify/Messages/SendResult.cs similarity index 100% rename from common/ASC.Common/Notify/Messages/SendResult.cs rename to common/ASC.Core.Common/Notify/Messages/SendResult.cs diff --git a/common/ASC.Common/Notify/Model/ConstActionProvider.cs b/common/ASC.Core.Common/Notify/Model/ConstActionProvider.cs similarity index 100% rename from common/ASC.Common/Notify/Model/ConstActionProvider.cs rename to common/ASC.Core.Common/Notify/Model/ConstActionProvider.cs diff --git a/common/ASC.Common/Notify/Model/IActionProvider.cs b/common/ASC.Core.Common/Notify/Model/IActionProvider.cs similarity index 100% rename from common/ASC.Common/Notify/Model/IActionProvider.cs rename to common/ASC.Core.Common/Notify/Model/IActionProvider.cs diff --git a/common/ASC.Common/Notify/Model/INotifyAction.cs b/common/ASC.Core.Common/Notify/Model/INotifyAction.cs similarity index 100% rename from common/ASC.Common/Notify/Model/INotifyAction.cs rename to common/ASC.Core.Common/Notify/Model/INotifyAction.cs diff --git a/common/ASC.Common/Notify/Model/INotifySource.cs b/common/ASC.Core.Common/Notify/Model/INotifySource.cs similarity index 100% rename from common/ASC.Common/Notify/Model/INotifySource.cs rename to common/ASC.Core.Common/Notify/Model/INotifySource.cs diff --git a/common/ASC.Common/Notify/Model/ISubscriptionProvider.cs b/common/ASC.Core.Common/Notify/Model/ISubscriptionProvider.cs similarity index 82% rename from common/ASC.Common/Notify/Model/ISubscriptionProvider.cs rename to common/ASC.Core.Common/Notify/Model/ISubscriptionProvider.cs index 036cb8df20..1b6244c7e4 100644 --- a/common/ASC.Common/Notify/Model/ISubscriptionProvider.cs +++ b/common/ASC.Core.Common/Notify/Model/ISubscriptionProvider.cs @@ -24,26 +24,23 @@ */ -#region usings - using System; using System.Linq; using ASC.Common.Logging; +using ASC.Core.Tenants; using ASC.Notify.Recipients; -#endregion - namespace ASC.Notify.Model { public interface ISubscriptionProvider { - string[] GetSubscriptions(INotifyAction action, IRecipient recipient, bool checkSubscribe = true); + string[] GetSubscriptions(Tenant tenant, INotifyAction action, IRecipient recipient, bool checkSubscribe = true); - string[] GetSubscriptionMethod(INotifyAction action, IRecipient recipient); + string[] GetSubscriptionMethod(Tenant tenant, INotifyAction action, IRecipient recipient); - IRecipient[] GetRecipients(INotifyAction action, string objectID); + IRecipient[] GetRecipients(int tenantId, INotifyAction action, string objectID); - object GetSubscriptionRecord(INotifyAction action, IRecipient recipient, string objectID); + object GetSubscriptionRecord(Tenant tenant, INotifyAction action, IRecipient recipient, string objectID); bool IsUnsubscribe(IDirectRecipient recipient, INotifyAction action, string objectID); @@ -55,20 +52,20 @@ namespace ASC.Notify.Model void UnSubscribe(INotifyAction action); - void UnSubscribe(INotifyAction action, IRecipient recipient); + void UnSubscribe(Tenant tenant, INotifyAction action, IRecipient recipient); void UpdateSubscriptionMethod(INotifyAction action, IRecipient recipient, params string[] senderNames); } public static class SubscriptionProviderHelper { - public static bool IsSubscribed(this ISubscriptionProvider provider, INotifyAction action, IRecipient recipient, string objectID) + public static bool IsSubscribed(this ISubscriptionProvider provider, Tenant tenant, INotifyAction action, IRecipient recipient, string objectID) { var result = false; try { - var subscriptionRecord = provider.GetSubscriptionRecord(action, recipient, objectID); + var subscriptionRecord = provider.GetSubscriptionRecord(tenant, action, recipient, objectID); if (subscriptionRecord != null) { var properties = subscriptionRecord.GetType().GetProperties(); diff --git a/common/ASC.Common/Notify/Model/NotifyAction.cs b/common/ASC.Core.Common/Notify/Model/NotifyAction.cs similarity index 100% rename from common/ASC.Common/Notify/Model/NotifyAction.cs rename to common/ASC.Core.Common/Notify/Model/NotifyAction.cs diff --git a/common/ASC.Common/Notify/Model/NotifyClientImpl.cs b/common/ASC.Core.Common/Notify/Model/NotifyClientImpl.cs similarity index 96% rename from common/ASC.Common/Notify/Model/NotifyClientImpl.cs rename to common/ASC.Core.Common/Notify/Model/NotifyClientImpl.cs index 861f289b02..608dc23e9b 100644 --- a/common/ASC.Common/Notify/Model/NotifyClientImpl.cs +++ b/common/ASC.Core.Common/Notify/Model/NotifyClientImpl.cs @@ -69,10 +69,10 @@ namespace ASC.Notify.Model SendNoticeToAsync(action, objectID, new[] { recipient }, null, false, args); } - public void SendNoticeAsync(INotifyAction action, string objectID, params ITagValue[] args) + public void SendNoticeAsync(int tenantId, INotifyAction action, string objectID, params ITagValue[] args) { var subscriptionSource = notifySource.GetSubscriptionProvider(); - var recipients = subscriptionSource.GetRecipients(action, objectID); + var recipients = subscriptionSource.GetRecipients(tenantId, action, objectID); SendNoticeToAsync(action, objectID, recipients, null, false, args); } diff --git a/common/ASC.Common/Notify/NotifyException.cs b/common/ASC.Core.Common/Notify/NotifyException.cs similarity index 100% rename from common/ASC.Common/Notify/NotifyException.cs rename to common/ASC.Core.Common/Notify/NotifyException.cs diff --git a/common/ASC.Common/Notify/NotifyResult.cs b/common/ASC.Core.Common/Notify/NotifyResult.cs similarity index 100% rename from common/ASC.Common/Notify/NotifyResult.cs rename to common/ASC.Core.Common/Notify/NotifyResult.cs diff --git a/common/ASC.Common/Notify/Patterns/IPattern.cs b/common/ASC.Core.Common/Notify/Patterns/IPattern.cs similarity index 100% rename from common/ASC.Common/Notify/Patterns/IPattern.cs rename to common/ASC.Core.Common/Notify/Patterns/IPattern.cs diff --git a/common/ASC.Common/Notify/Patterns/IPatternFormatter.cs b/common/ASC.Core.Common/Notify/Patterns/IPatternFormatter.cs similarity index 100% rename from common/ASC.Common/Notify/Patterns/IPatternFormatter.cs rename to common/ASC.Core.Common/Notify/Patterns/IPatternFormatter.cs diff --git a/common/ASC.Common/Notify/Patterns/IPatternProvider.cs b/common/ASC.Core.Common/Notify/Patterns/IPatternProvider.cs similarity index 100% rename from common/ASC.Common/Notify/Patterns/IPatternProvider.cs rename to common/ASC.Core.Common/Notify/Patterns/IPatternProvider.cs diff --git a/common/ASC.Common/Notify/Patterns/IPatternStyler.cs b/common/ASC.Core.Common/Notify/Patterns/IPatternStyler.cs similarity index 100% rename from common/ASC.Common/Notify/Patterns/IPatternStyler.cs rename to common/ASC.Core.Common/Notify/Patterns/IPatternStyler.cs diff --git a/common/ASC.Common/Notify/Patterns/ITagValue.cs b/common/ASC.Core.Common/Notify/Patterns/ITagValue.cs similarity index 100% rename from common/ASC.Common/Notify/Patterns/ITagValue.cs rename to common/ASC.Core.Common/Notify/Patterns/ITagValue.cs diff --git a/common/ASC.Common/Notify/Patterns/NVelocityPatternFormatter.cs b/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs similarity index 100% rename from common/ASC.Common/Notify/Patterns/NVelocityPatternFormatter.cs rename to common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs diff --git a/common/ASC.Common/Notify/Patterns/Pattern.cs b/common/ASC.Core.Common/Notify/Patterns/Pattern.cs similarity index 100% rename from common/ASC.Common/Notify/Patterns/Pattern.cs rename to common/ASC.Core.Common/Notify/Patterns/Pattern.cs diff --git a/common/ASC.Common/Notify/Patterns/PatternFormatter.cs b/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs similarity index 100% rename from common/ASC.Common/Notify/Patterns/PatternFormatter.cs rename to common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs diff --git a/common/ASC.Common/Notify/Patterns/ReplacePatternFormatter.cs b/common/ASC.Core.Common/Notify/Patterns/ReplacePatternFormatter.cs similarity index 100% rename from common/ASC.Common/Notify/Patterns/ReplacePatternFormatter.cs rename to common/ASC.Core.Common/Notify/Patterns/ReplacePatternFormatter.cs diff --git a/common/ASC.Common/Notify/Patterns/TagValue.cs b/common/ASC.Core.Common/Notify/Patterns/TagValue.cs similarity index 100% rename from common/ASC.Common/Notify/Patterns/TagValue.cs rename to common/ASC.Core.Common/Notify/Patterns/TagValue.cs diff --git a/common/ASC.Common/Notify/Patterns/XmlPatternProvider2.cs b/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs similarity index 100% rename from common/ASC.Common/Notify/Patterns/XmlPatternProvider2.cs rename to common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs diff --git a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs index 3620fca096..59318a34bd 100644 --- a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs +++ b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs @@ -27,6 +27,8 @@ using System; using System.Collections.Generic; using System.Linq; + +using ASC.Core.Tenants; using ASC.Core.Users; using ASC.Notify.Recipients; @@ -34,7 +36,7 @@ namespace ASC.Core.Notify { public class RecipientProviderImpl : IRecipientProvider { - public virtual IRecipient GetRecipient(string id) + public virtual IRecipient GetRecipient(int tenantId, string id) { var recID = Guid.Empty; if (TryParseGuid(id, out recID)) @@ -42,13 +44,13 @@ namespace ASC.Core.Notify var user = CoreContext.UserManager.GetUsers(recID); if (user.ID != Constants.LostUser.ID) return new DirectRecipient(user.ID.ToString(), user.ToString()); - var group = CoreContext.UserManager.GetGroupInfo(recID); + var group = CoreContext.UserManager.GetGroupInfo(tenantId, recID); if (group.ID != Constants.LostGroupInfo.ID) return new RecipientsGroup(group.ID.ToString(), group.Name); } return null; } - public virtual IRecipient[] GetGroupEntries(IRecipientsGroup group) + public virtual IRecipient[] GetGroupEntries(Tenant tenant, IRecipientsGroup group) { if (group == null) throw new ArgumentNullException("group"); @@ -56,17 +58,17 @@ namespace ASC.Core.Notify var groupID = Guid.Empty; if (TryParseGuid(group.ID, out groupID)) { - var coreGroup = CoreContext.UserManager.GetGroupInfo(groupID); + var coreGroup = CoreContext.UserManager.GetGroupInfo(tenant.TenantId, groupID); if (coreGroup.ID != Constants.LostGroupInfo.ID) { - var users = CoreContext.UserManager.GetUsersByGroup(coreGroup.ID); + var users = CoreContext.UserManager.GetUsersByGroup(tenant, coreGroup.ID); Array.ForEach(users, u => result.Add(new DirectRecipient(u.ID.ToString(), u.ToString()))); } } return result.ToArray(); } - public virtual IRecipientsGroup[] GetGroups(IRecipient recipient) + public virtual IRecipientsGroup[] GetGroups(Tenant tenant, IRecipient recipient) { if (recipient == null) throw new ArgumentNullException("recipient"); @@ -76,7 +78,7 @@ namespace ASC.Core.Notify { if (recipient is IRecipientsGroup) { - var group = CoreContext.UserManager.GetGroupInfo(recID); + var group = CoreContext.UserManager.GetGroupInfo(tenant.TenantId, recID); while (group != null && group.Parent != null) { result.Add(new RecipientsGroup(group.Parent.ID.ToString(), group.Parent.Name)); @@ -85,7 +87,7 @@ namespace ASC.Core.Notify } else if (recipient is IDirectRecipient) { - foreach (var group in CoreContext.UserManager.GetUserGroups(recID, IncludeType.Distinct)) + foreach (var group in CoreContext.UserManager.GetUserGroups(tenant, recID, IncludeType.Distinct)) { result.Add(new RecipientsGroup(group.ID.ToString(), group.Name)); } @@ -117,7 +119,7 @@ namespace ASC.Core.Notify /// /// /// - public IDirectRecipient FilterRecipientAddresses(IDirectRecipient recipient) + public IDirectRecipient FilterRecipientAddresses(int tenantId, IDirectRecipient recipient) { //Check activation if (recipient.CheckActivation) @@ -127,7 +129,7 @@ namespace ASC.Core.Notify { //Filtering only missing users and users who activated already var filteredAddresses = from address in recipient.Addresses - let user = CoreContext.UserManager.GetUserByEmail(address) + let user = CoreContext.UserManager.GetUserByEmail(tenantId, address) where user.ID == Constants.LostUser.ID || (user.IsActive && (user.Status & EmployeeStatus.Default) == user.Status) select address; diff --git a/common/ASC.Common/Notify/Recipients/DirectRecipient.cs b/common/ASC.Core.Common/Notify/Recipients/DirectRecipient.cs similarity index 100% rename from common/ASC.Common/Notify/Recipients/DirectRecipient.cs rename to common/ASC.Core.Common/Notify/Recipients/DirectRecipient.cs diff --git a/common/ASC.Common/Notify/Recipients/IDirectRecipient.cs b/common/ASC.Core.Common/Notify/Recipients/IDirectRecipient.cs similarity index 100% rename from common/ASC.Common/Notify/Recipients/IDirectRecipient.cs rename to common/ASC.Core.Common/Notify/Recipients/IDirectRecipient.cs diff --git a/common/ASC.Common/Notify/Recipients/IRecipient.cs b/common/ASC.Core.Common/Notify/Recipients/IRecipient.cs similarity index 100% rename from common/ASC.Common/Notify/Recipients/IRecipient.cs rename to common/ASC.Core.Common/Notify/Recipients/IRecipient.cs diff --git a/common/ASC.Common/Notify/Recipients/IRecipientsGroup.cs b/common/ASC.Core.Common/Notify/Recipients/IRecipientsGroup.cs similarity index 100% rename from common/ASC.Common/Notify/Recipients/IRecipientsGroup.cs rename to common/ASC.Core.Common/Notify/Recipients/IRecipientsGroup.cs diff --git a/common/ASC.Common/Notify/Recipients/RecipientsGroup.cs b/common/ASC.Core.Common/Notify/Recipients/RecipientsGroup.cs similarity index 100% rename from common/ASC.Common/Notify/Recipients/RecipientsGroup.cs rename to common/ASC.Core.Common/Notify/Recipients/RecipientsGroup.cs diff --git a/common/ASC.Common/Notify/Sinks/DispatchSink.cs b/common/ASC.Core.Common/Notify/Sinks/DispatchSink.cs similarity index 100% rename from common/ASC.Common/Notify/Sinks/DispatchSink.cs rename to common/ASC.Core.Common/Notify/Sinks/DispatchSink.cs diff --git a/common/ASC.Common/Notify/Sinks/ISink.cs b/common/ASC.Core.Common/Notify/Sinks/ISink.cs similarity index 100% rename from common/ASC.Common/Notify/Sinks/ISink.cs rename to common/ASC.Core.Common/Notify/Sinks/ISink.cs diff --git a/common/ASC.Common/Notify/Sinks/Sink.cs b/common/ASC.Core.Common/Notify/Sinks/Sink.cs similarity index 100% rename from common/ASC.Common/Notify/Sinks/Sink.cs rename to common/ASC.Core.Common/Notify/Sinks/Sink.cs diff --git a/common/ASC.Common/Notify/Model/TopSubscriptionProvider.cs b/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs similarity index 83% rename from common/ASC.Common/Notify/Model/TopSubscriptionProvider.cs rename to common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs index 2f65f8cdb5..00f8a7aa16 100644 --- a/common/ASC.Common/Notify/Model/TopSubscriptionProvider.cs +++ b/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs @@ -26,6 +26,7 @@ using System; using System.Collections.Generic; +using ASC.Core.Tenants; using ASC.Notify.Recipients; @@ -54,18 +55,18 @@ namespace ASC.Notify.Model } - public virtual string[] GetSubscriptionMethod(INotifyAction action, IRecipient recipient) + public virtual string[] GetSubscriptionMethod(Tenant tenant,INotifyAction action, IRecipient recipient) { if (action == null) throw new ArgumentNullException("action"); if (recipient == null) throw new ArgumentNullException("recipient"); - var senders = subscriptionProvider.GetSubscriptionMethod(action, recipient); + var senders = subscriptionProvider.GetSubscriptionMethod(tenant, action, recipient); if (senders == null || senders.Length == 0) { - var parents = WalkUp(recipient); + var parents = WalkUp(tenant, recipient); foreach (var parent in parents) { - senders = subscriptionProvider.GetSubscriptionMethod(action, parent); + senders = subscriptionProvider.GetSubscriptionMethod(tenant, action, parent); if (senders != null && senders.Length != 0) break; } } @@ -73,12 +74,12 @@ namespace ASC.Notify.Model return senders != null && 0 < senders.Length ? senders : defaultSenderMethods; } - public virtual IRecipient[] GetRecipients(INotifyAction action, string objectID) + public virtual IRecipient[] GetRecipients(int tenantId, INotifyAction action, string objectID) { if (action == null) throw new ArgumentNullException("action"); var recipents = new List(5); - var directRecipients = subscriptionProvider.GetRecipients(action, objectID) ?? new IRecipient[0]; + var directRecipients = subscriptionProvider.GetRecipients(tenantId, action, objectID) ?? new IRecipient[0]; recipents.AddRange(directRecipients); return recipents.ToArray(); } @@ -122,9 +123,9 @@ namespace ASC.Notify.Model subscriptionProvider.UnSubscribe(action); } - public virtual void UnSubscribe(INotifyAction action, IRecipient recipient) + public virtual void UnSubscribe(Tenant tenant, INotifyAction action, IRecipient recipient) { - var objects = GetSubscriptions(action, recipient); + var objects = GetSubscriptions(tenant, action, recipient); foreach (string objectID in objects) { subscriptionProvider.UnSubscribe(action, objectID, recipient); @@ -140,20 +141,20 @@ namespace ASC.Notify.Model subscriptionProvider.UpdateSubscriptionMethod(action, recipient, senderNames); } - public virtual object GetSubscriptionRecord(INotifyAction action, IRecipient recipient, string objectID) + public virtual object GetSubscriptionRecord(Tenant tenant, INotifyAction action, IRecipient recipient, string objectID) { if (recipient == null) throw new ArgumentNullException("recipient"); if (action == null) throw new ArgumentNullException("action"); - var subscriptionRecord = subscriptionProvider.GetSubscriptionRecord(action, recipient, objectID); + var subscriptionRecord = subscriptionProvider.GetSubscriptionRecord(tenant, action, recipient, objectID); if (subscriptionRecord != null) return subscriptionRecord; - var parents = WalkUp(recipient); + var parents = WalkUp(tenant, recipient); foreach (var parent in parents) { - subscriptionRecord = subscriptionProvider.GetSubscriptionRecord(action, parent, objectID); + subscriptionRecord = subscriptionProvider.GetSubscriptionRecord(tenant, action, parent, objectID); if (subscriptionRecord != null) break; } @@ -161,18 +162,18 @@ namespace ASC.Notify.Model return subscriptionRecord; } - public virtual string[] GetSubscriptions(INotifyAction action, IRecipient recipient, bool checkSubscription = true) + public virtual string[] GetSubscriptions(Tenant tenant, INotifyAction action, IRecipient recipient, bool checkSubscription = true) { if (recipient == null) throw new ArgumentNullException("recipient"); if (action == null) throw new ArgumentNullException("action"); var objects = new List(); - var direct = subscriptionProvider.GetSubscriptions(action, recipient, checkSubscription) ?? new string[0]; + var direct = subscriptionProvider.GetSubscriptions(tenant, action, recipient, checkSubscription) ?? new string[0]; MergeObjects(objects, direct); - var parents = WalkUp(recipient); + var parents = WalkUp(tenant, recipient); foreach (var parent in parents) { - direct = subscriptionProvider.GetSubscriptions(action, parent, checkSubscription) ?? new string[0]; + direct = subscriptionProvider.GetSubscriptions(tenant, action, parent, checkSubscription) ?? new string[0]; if (recipient is IDirectRecipient) { foreach (var groupsubscr in direct) @@ -192,14 +193,14 @@ namespace ASC.Notify.Model } - private List WalkUp(IRecipient recipient) + private List WalkUp(Tenant tenant,IRecipient recipient) { var parents = new List(); - var groups = recipientProvider.GetGroups(recipient) ?? new IRecipientsGroup[0]; + var groups = recipientProvider.GetGroups(tenant, recipient) ?? new IRecipientsGroup[0]; foreach (var group in groups) { parents.Add(group); - parents.AddRange(WalkUp(group)); + parents.AddRange(WalkUp(tenant, group)); } return parents; } diff --git a/common/ASC.Common/Security/Authorizing/AzManager.cs b/common/ASC.Core.Common/Security/Authorizing/AzManager.cs similarity index 86% rename from common/ASC.Common/Security/Authorizing/AzManager.cs rename to common/ASC.Core.Common/Security/Authorizing/AzManager.cs index 760ede71d3..a3246b3065 100644 --- a/common/ASC.Common/Security/Authorizing/AzManager.cs +++ b/common/ASC.Core.Common/Security/Authorizing/AzManager.cs @@ -26,7 +26,8 @@ using System; using System.Collections.Generic; - +using ASC.Core.Tenants; + namespace ASC.Common.Security.Authorizing { public class AzManager @@ -50,22 +51,22 @@ namespace ASC.Common.Security.Authorizing } - public bool CheckPermission(ISubject subject, IAction action, ISecurityObjectId objectId, + public bool CheckPermission(Tenant tenant, ISubject subject, IAction action, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, out ISubject denySubject, out IAction denyAction) { if (subject == null) throw new ArgumentNullException("subject"); if (action == null) throw new ArgumentNullException("action"); - var acl = GetAzManagerAcl(subject, action, objectId, securityObjProvider); + var acl = GetAzManagerAcl(tenant, subject, action, objectId, securityObjProvider); denySubject = acl.DenySubject; denyAction = acl.DenyAction; return acl.IsAllow; } - internal AzManagerAcl GetAzManagerAcl(ISubject subject, IAction action, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider) + internal AzManagerAcl GetAzManagerAcl(Tenant tenant, ISubject subject, IAction action, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider) { - if (action.AdministratorAlwaysAllow && (Constants.Admin.ID == subject.ID || roleProvider.IsSubjectInRole(subject, Constants.Admin))) + if (action.AdministratorAlwaysAllow && (Constants.Admin.ID == subject.ID || roleProvider.IsSubjectInRole(tenant, subject, Constants.Admin))) { return AzManagerAcl.Allow; } @@ -73,7 +74,7 @@ namespace ASC.Common.Security.Authorizing var acl = AzManagerAcl.Default; var exit = false; - foreach (var s in GetSubjects(subject, objectId, securityObjProvider)) + foreach (var s in GetSubjects(tenant, subject, objectId, securityObjProvider)) { var aceList = permissionProvider.GetAcl(s, action, objectId, securityObjProvider); foreach (var ace in aceList) @@ -101,12 +102,12 @@ namespace ASC.Common.Security.Authorizing return acl; } - internal IEnumerable GetSubjects(ISubject subject, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider) + internal IEnumerable GetSubjects(Tenant tenant, ISubject subject, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider) { var subjects = new List(); subjects.Add(subject); subjects.AddRange( - roleProvider.GetRoles(subject) + roleProvider.GetRoles(tenant, subject) .ConvertAll(r => { return (ISubject)r; }) ); if (objectId != null) diff --git a/common/ASC.Common/Tests/Security/Authorizing/Domain.cs b/common/ASC.Core.Common/Security/Authorizing/Domain.cs similarity index 100% rename from common/ASC.Common/Tests/Security/Authorizing/Domain.cs rename to common/ASC.Core.Common/Security/Authorizing/Domain.cs diff --git a/common/ASC.Common/Security/IPermissionResolver.cs b/common/ASC.Core.Common/Security/Authorizing/IPermissionResolver.cs similarity index 76% rename from common/ASC.Common/Security/IPermissionResolver.cs rename to common/ASC.Core.Common/Security/Authorizing/IPermissionResolver.cs index 9157c56831..42b43003ea 100644 --- a/common/ASC.Common/Security/IPermissionResolver.cs +++ b/common/ASC.Core.Common/Security/Authorizing/IPermissionResolver.cs @@ -25,17 +25,18 @@ using ASC.Common.Security.Authorizing; - +using ASC.Core.Tenants; + namespace ASC.Common.Security { public interface IPermissionResolver { - bool Check(ISubject subject, params IAction[] actions); + bool Check(Tenant tenant, ISubject subject, params IAction[] actions); - bool Check(ISubject subject, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions); + bool Check(Tenant tenant, ISubject subject, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions); - void Demand(ISubject subject, params IAction[] actions); + void Demand(Tenant tenant, ISubject subject, params IAction[] actions); - void Demand(ISubject subject, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions); + void Demand(Tenant tenant, ISubject subject, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions); } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Security/Authorizing/PermissionResolver.cs b/common/ASC.Core.Common/Security/Authorizing/PermissionResolver.cs index 0dc9e913f4..c74823c5cd 100644 --- a/common/ASC.Core.Common/Security/Authorizing/PermissionResolver.cs +++ b/common/ASC.Core.Common/Security/Authorizing/PermissionResolver.cs @@ -30,6 +30,7 @@ using System.Linq; using ASC.Common.Security; using ASC.Common.Security.Authentication; using ASC.Common.Security.Authorizing; +using ASC.Core.Tenants; using Constants = ASC.Core.Configuration.Constants; namespace ASC.Core.Security.Authorizing @@ -46,25 +47,25 @@ namespace ASC.Core.Security.Authorizing } - public bool Check(ISubject subject, params IAction[] actions) + public bool Check(Tenant tenant, ISubject subject, params IAction[] actions) { - return Check(subject, null, null, actions); + return Check(tenant, subject, null, null, actions); } - public bool Check(ISubject subject, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions) + public bool Check(Tenant tenant, ISubject subject, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions) { - var denyActions = GetDenyActions(subject, actions, objectId, securityObjProvider); + var denyActions = GetDenyActions(tenant, subject, actions, objectId, securityObjProvider); return denyActions.Length == 0; } - public void Demand(ISubject subject, params IAction[] actions) + public void Demand(Tenant tenant, ISubject subject, params IAction[] actions) { - Demand(subject, null, null, actions); + Demand(tenant, subject, null, null, actions); } - public void Demand(ISubject subject, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions) + public void Demand(Tenant tenant, ISubject subject, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions) { - var denyActions = GetDenyActions(subject, actions, objectId, securityObjProvider); + var denyActions = GetDenyActions(tenant, subject, actions, objectId, securityObjProvider); if (0 < denyActions.Length) { throw new AuthorizingException( @@ -76,7 +77,7 @@ namespace ASC.Core.Security.Authorizing } - private DenyResult[] GetDenyActions(ISubject subject, IAction[] actions, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider) + private DenyResult[] GetDenyActions(Tenant tenant, ISubject subject, IAction[] actions, ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider) { var denyActions = new List(); if (actions == null) actions = new IAction[0]; @@ -95,7 +96,7 @@ namespace ASC.Core.Security.Authorizing IAction denyAction = null; foreach (var action in actions) { - var allow = azManager.CheckPermission(subject, action, objectId, securityObjProvider, out denySubject, out denyAction); + var allow = azManager.CheckPermission(tenant, subject, action, objectId, securityObjProvider, out denySubject, out denyAction); if (!allow) { denyActions.Add(new DenyResult(action, denySubject, denyAction)); diff --git a/common/ASC.Core.Common/Security/Authorizing/RoleProvider.cs b/common/ASC.Core.Common/Security/Authorizing/RoleProvider.cs index dcdb9401b9..896fd212bf 100644 --- a/common/ASC.Core.Common/Security/Authorizing/RoleProvider.cs +++ b/common/ASC.Core.Common/Security/Authorizing/RoleProvider.cs @@ -30,6 +30,7 @@ using System.Linq; using ASC.Common.Security; using ASC.Common.Security.Authentication; using ASC.Common.Security.Authorizing; +using ASC.Core.Tenants; using ASC.Core.Users; using AuthConst = ASC.Common.Security.Authorizing.Constants; using ConfConst = ASC.Core.Configuration.Constants; @@ -38,19 +39,19 @@ namespace ASC.Core.Security.Authorizing { class RoleProvider : IRoleProvider { - public List GetRoles(ISubject account) + public List GetRoles(Tenant tenant, ISubject account) { var roles = new List(); if (!(account is ISystemAccount)) { if (account is IRole) { - roles = GetParentRoles(account.ID).ToList(); + roles = GetParentRoles(tenant.TenantId, account.ID).ToList(); } else if (account is IUserAccount) { roles = CoreContext.UserManager - .GetUserGroups(account.ID, IncludeType.Distinct | IncludeType.InParent) + .GetUserGroups(tenant, account.ID, IncludeType.Distinct | IncludeType.InParent) .Select(g => (IRole) g) .ToList(); } @@ -58,15 +59,15 @@ namespace ASC.Core.Security.Authorizing return roles; } - public bool IsSubjectInRole(ISubject account, IRole role) + public bool IsSubjectInRole(Tenant tenant, ISubject account, IRole role) { - return CoreContext.UserManager.IsUserInGroup(account.ID, role.ID); + return CoreContext.UserManager.IsUserInGroup(tenant, account.ID, role.ID); } - private static List GetParentRoles(Guid roleID) + private static List GetParentRoles(int tenantId, Guid roleID) { var roles = new List(); - var gi = CoreContext.UserManager.GetGroupInfo(roleID); + var gi = CoreContext.UserManager.GetGroupInfo(tenantId, roleID); if (gi != null) { var parent = gi.Parent; diff --git a/common/ASC.Common/Security/IRoleProvider.cs b/common/ASC.Core.Common/Security/IRoleProvider.cs similarity index 90% rename from common/ASC.Common/Security/IRoleProvider.cs rename to common/ASC.Core.Common/Security/IRoleProvider.cs index d2d7d618cc..c00b448dde 100644 --- a/common/ASC.Common/Security/IRoleProvider.cs +++ b/common/ASC.Core.Common/Security/IRoleProvider.cs @@ -26,12 +26,13 @@ using System.Collections.Generic; using ASC.Common.Security.Authorizing; - +using ASC.Core.Tenants; + namespace ASC.Common.Security { public interface IRoleProvider { - List GetRoles(ISubject account); - bool IsSubjectInRole(ISubject account, IRole role); + List GetRoles(Tenant tenant, ISubject account); + bool IsSubjectInRole(Tenant tenant, ISubject account, IRole role); } } \ No newline at end of file diff --git a/common/ASC.Common/Tests/Security/Authorizing/AzManagerTest.cs b/common/ASC.Core.Common/Tests/AzManagerTest.cs similarity index 67% rename from common/ASC.Common/Tests/Security/Authorizing/AzManagerTest.cs rename to common/ASC.Core.Common/Tests/AzManagerTest.cs index 22b26a09d7..ec76b338fb 100644 --- a/common/ASC.Common/Tests/Security/Authorizing/AzManagerTest.cs +++ b/common/ASC.Core.Common/Tests/AzManagerTest.cs @@ -38,16 +38,16 @@ namespace ASC.Common.Tests.Security.Authorizing [Test] public void CollectInheritSubjects_Test() { - AzManager azMan = new AzManager(Domain.RoleProvider, Domain.PermissionProvider); + var azMan = new AzManager(Domain.RoleProvider, Domain.PermissionProvider); - var subjects = new List(azMan.GetSubjects(Domain.roleNET, null, null)); + var subjects = new List(azMan.GetSubjects(null, Domain.roleNET, null, null)); Assert.IsNotNull(subjects); CollectionAssert.Contains(subjects, Domain.roleNET); CollectionAssert.Contains(subjects, Domain.roleAVS); CollectionAssert.Contains(subjects, Constants.Everyone); Assert.AreEqual(3, subjects.Count); - subjects = new List(azMan.GetSubjects(Domain.accountValery, null, null)); + subjects = new List(azMan.GetSubjects(null, Domain.accountValery, null, null)); Assert.IsNotNull(subjects); CollectionAssert.Contains(subjects, Domain.accountValery); CollectionAssert.Contains(subjects, Domain.roleNET); @@ -56,7 +56,7 @@ namespace ASC.Common.Tests.Security.Authorizing CollectionAssert.Contains(subjects, Constants.User); Assert.AreEqual(5, subjects.Count); - subjects = new List(azMan.GetSubjects(Domain.accountLev, null, null)); + subjects = new List(azMan.GetSubjects(null, Domain.accountLev, null, null)); Assert.IsNotNull(subjects); CollectionAssert.Contains(subjects, Domain.accountLev); CollectionAssert.Contains(subjects, Domain.roleAdministration); @@ -66,14 +66,14 @@ namespace ASC.Common.Tests.Security.Authorizing CollectionAssert.Contains(subjects, Constants.User); Assert.AreEqual(6, subjects.Count); - subjects = new List(azMan.GetSubjects(Domain.accountAlient, null, null)); + subjects = new List(azMan.GetSubjects(null, Domain.accountAlient, null, null)); Assert.IsNotNull(subjects); CollectionAssert.Contains(subjects, Domain.accountAlient); CollectionAssert.Contains(subjects, Constants.Everyone); CollectionAssert.Contains(subjects, Constants.User); Assert.AreEqual(3, subjects.Count); - subjects = new List(azMan.GetSubjects(Domain.accountMessangerService, null, null)); + subjects = new List(azMan.GetSubjects(null, Domain.accountMessangerService, null, null)); Assert.IsNotNull(subjects); CollectionAssert.Contains(subjects, Domain.accountMessangerService); CollectionAssert.Contains(subjects, Constants.Everyone); @@ -85,52 +85,52 @@ namespace ASC.Common.Tests.Security.Authorizing public void GetAzManagerAcl() { - AzManager azMan = new AzManager(Domain.RoleProvider, Domain.PermissionProvider); + var azMan = new AzManager(Domain.RoleProvider, Domain.PermissionProvider); AzManager.AzManagerAcl acl = null; - acl = azMan.GetAzManagerAcl(Constants.Admin, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Constants.Admin, Domain.actionAddUser, null, null); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Constants.Everyone, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Constants.Everyone, Domain.actionAddUser, null, null); Assert.IsFalse(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Constants.Owner, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Constants.Owner, Domain.actionAddUser, null, null); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Constants.Self, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Constants.Self, Domain.actionAddUser, null, null); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Constants.User, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Constants.User, Domain.actionAddUser, null, null); Assert.IsFalse(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.roleAVS, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Domain.roleAVS, Domain.actionAddUser, null, null); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.roleHR, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Domain.roleHR, Domain.actionAddUser, null, null); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.roleNET, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Domain.roleNET, Domain.actionAddUser, null, null); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.roleAdministration, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Domain.roleAdministration, Domain.actionAddUser, null, null); Assert.IsFalse(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.accountAlient, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Domain.accountAlient, Domain.actionAddUser, null, null); Assert.IsFalse(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.accountAnton, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Domain.accountAnton, Domain.actionAddUser, null, null); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.accountKat, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Domain.accountKat, Domain.actionAddUser, null, null); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.accountLev, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Domain.accountLev, Domain.actionAddUser, null, null); Assert.IsFalse(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.accountNik, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Domain.accountNik, Domain.actionAddUser, null, null); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.accountValery, Domain.actionAddUser, null, null); + acl = azMan.GetAzManagerAcl(null, Domain.accountValery, Domain.actionAddUser, null, null); Assert.IsFalse(acl.IsAllow); } @@ -151,32 +151,32 @@ namespace ASC.Common.Tests.Security.Authorizing Domain.PermissionProvider.SetObjectAcesInheritance(c2Id, false); Domain.PermissionProvider.AddAce(Constants.Owner, Domain.actionAddUser, c1Id, AceType.Allow); - acl = azMan.GetAzManagerAcl(Domain.accountNik, Domain.actionAddUser, c1Id, sop); + acl = azMan.GetAzManagerAcl(null, Domain.accountNik, Domain.actionAddUser, c1Id, sop); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.accountNik, Domain.actionAddUser, c2Id, sop); + acl = azMan.GetAzManagerAcl(null, Domain.accountNik, Domain.actionAddUser, c2Id, sop); Assert.IsFalse(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.accountAnton, Domain.actionAddUser, c1Id, sop); + acl = azMan.GetAzManagerAcl(null, Domain.accountAnton, Domain.actionAddUser, c1Id, sop); Assert.IsFalse(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.accountAnton, Domain.actionAddUser, c2Id, sop); + acl = azMan.GetAzManagerAcl(null, Domain.accountAnton, Domain.actionAddUser, c2Id, sop); Assert.IsFalse(acl.IsAllow); Domain.PermissionProvider.SetObjectAcesInheritance(c2Id, true); - acl = azMan.GetAzManagerAcl(Domain.accountNik, Domain.actionAddUser, c2Id, sop); + acl = azMan.GetAzManagerAcl(null, Domain.accountNik, Domain.actionAddUser, c2Id, sop); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.accountAnton, Domain.actionAddUser, c1Id, sop); + acl = azMan.GetAzManagerAcl(null, Domain.accountAnton, Domain.actionAddUser, c1Id, sop); Assert.IsFalse(acl.IsAllow); Domain.PermissionProvider.SetObjectAcesInheritance(c1Id, true); - acl = azMan.GetAzManagerAcl(Domain.accountNik, Domain.actionAddUser, c2Id, sop); + acl = azMan.GetAzManagerAcl(null, Domain.accountNik, Domain.actionAddUser, c2Id, sop); Assert.IsTrue(acl.IsAllow); - acl = azMan.GetAzManagerAcl(Domain.accountLev, Domain.actionAddUser, c2Id, sop); + acl = azMan.GetAzManagerAcl(null, Domain.accountLev, Domain.actionAddUser, c2Id, sop); Assert.IsFalse(acl.IsAllow); } } diff --git a/common/ASC.Common/Tests/Security/Authorizing/Class1.cs b/common/ASC.Core.Common/Tests/Class1.cs similarity index 100% rename from common/ASC.Common/Tests/Security/Authorizing/Class1.cs rename to common/ASC.Core.Common/Tests/Class1.cs diff --git a/common/ASC.Common/Tests/Security/Authorizing/DomainStub.cs b/common/ASC.Core.Common/Tests/DomainStub.cs similarity index 97% rename from common/ASC.Common/Tests/Security/Authorizing/DomainStub.cs rename to common/ASC.Core.Common/Tests/DomainStub.cs index a0b36baf27..ce5ff97044 100644 --- a/common/ASC.Common/Tests/Security/Authorizing/DomainStub.cs +++ b/common/ASC.Core.Common/Tests/DomainStub.cs @@ -30,7 +30,8 @@ using System.Collections.Generic; using ASC.Common.Security; using ASC.Common.Security.Authentication; using ASC.Common.Security.Authorizing; - +using ASC.Core.Tenants; + namespace ASC.Common.Tests.Security.Authorizing { class UserAccount : Account, IUserAccount @@ -159,7 +160,7 @@ namespace ASC.Common.Tests.Security.Authorizing #region IRoleProvider Members - public List GetRoles(ISubject account) + public List GetRoles(Tenant tenant, ISubject account) { List roles = null; if (!AccountRoles.TryGetValue(account, out roles)) roles = new List(); @@ -173,9 +174,9 @@ namespace ASC.Common.Tests.Security.Authorizing return accounts; } - public bool IsSubjectInRole(ISubject account, IRole role) + public bool IsSubjectInRole(Tenant tenant, ISubject account, IRole role) { - List roles = GetRoles(account); + var roles = GetRoles(tenant, account); return roles.Contains(role); } diff --git a/common/ASC.Core.Common/Tests/TopSubscriptionProviderTest.cs b/common/ASC.Core.Common/Tests/TopSubscriptionProviderTest.cs index dcb9818228..c5e77b6b4b 100644 --- a/common/ASC.Core.Common/Tests/TopSubscriptionProviderTest.cs +++ b/common/ASC.Core.Common/Tests/TopSubscriptionProviderTest.cs @@ -26,9 +26,7 @@ #if DEBUG using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using ASC.Core.Notify; using ASC.Notify.Model; using NUnit.Framework; @@ -83,17 +81,17 @@ namespace ASC.Core.Common.Tests IRecipient[] res; //GetRecipients - res = subProvider.GetRecipients(nAction, objectId); + res = subProvider.GetRecipients(tenant.TenantId, nAction, objectId); var cnt = res.Count(); //Subscribe subProvider.Subscribe(nAction, objectId, testRec); - res = subProvider.GetRecipients(nAction, objectId); + res = subProvider.GetRecipients(tenant.TenantId, nAction, objectId); Assert.AreEqual(cnt + 1, res.Count()); //UnSubscribe - subProvider.UnSubscribe(nAction, testRec); - res = subProvider.GetRecipients(nAction, objectId); + subProvider.UnSubscribe(tenant, nAction, testRec); + res = subProvider.GetRecipients(tenant.TenantId, nAction, objectId); Assert.AreEqual(cnt, res.Count()); String[] objs; @@ -102,34 +100,34 @@ namespace ASC.Core.Common.Tests //Получаем подписки юзера //for (int i = 0; i < 6; i++) subProvider.Subscribe(nAction, new Random().Next().ToString(), testRec2); - objs = subProvider.GetSubscriptions(nAction, testRec2); + objs = subProvider.GetSubscriptions(tenant, nAction, testRec2); Assert.AreNotEqual(0, objs.Count()); CollectionAssert.AllItemsAreUnique(objs); //Получаем список групп к которым он принадлежит - var parents = recProvider.GetGroups(testRec2); + var parents = recProvider.GetGroups(tenant, testRec2); Assert.AreNotEqual(0, parents.Count()); otdel = parents.First(); everyone = parents.Last(); - var objsGroup = subProvider.GetSubscriptions(nAction, otdel); + var objsGroup = subProvider.GetSubscriptions(tenant, nAction, otdel); CollectionAssert.AllItemsAreUnique(objsGroup); //Подписываем весь отдел на объект rndObj = String.Concat("TestObject#", new Random().Next().ToString()); subProvider.Subscribe(nAction, rndObj, otdel); //Проверяем подписался ли юзер вместе со всем отделом двумя способами. - Assert.AreEqual(objsGroup.Count() + 1, subProvider.GetSubscriptions(nAction, otdel).Count()); - Assert.AreEqual(objs.Count() + 1, subProvider.GetSubscriptions(nAction, testRec2).Count()); - Assert.AreEqual(true, subProvider.IsSubscribed(nAction, testRec2, rndObj)); + Assert.AreEqual(objsGroup.Count() + 1, subProvider.GetSubscriptions(tenant, nAction, otdel).Count()); + Assert.AreEqual(objs.Count() + 1, subProvider.GetSubscriptions(tenant, nAction, testRec2).Count()); + Assert.AreEqual(true, subProvider.IsSubscribed(tenant, nAction, testRec2, rndObj)); //Подписываем Everybody rndObj2 = String.Concat("TestObject#", new Random().Next().ToString()); - objs = subProvider.GetSubscriptions(nAction, testRec2); + objs = subProvider.GetSubscriptions(tenant, nAction, testRec2); subProvider.Subscribe(nAction, rndObj2, everyone); //Проверяем подписался ли user двумя способами. - Assert.AreEqual(objs.Count() + 1, subProvider.GetSubscriptions(nAction, testRec2).Count()); - Assert.AreEqual(true, subProvider.IsSubscribed(nAction, testRec2, rndObj2)); + Assert.AreEqual(objs.Count() + 1, subProvider.GetSubscriptions(tenant, nAction, testRec2).Count()); + Assert.AreEqual(true, subProvider.IsSubscribed(tenant, nAction, testRec2, rndObj2)); } finally diff --git a/common/ASC.Core.Common/Tests/UserManagerTest.cs b/common/ASC.Core.Common/Tests/UserManagerTest.cs index 952a84aa4f..91eb8c1537 100644 --- a/common/ASC.Core.Common/Tests/UserManagerTest.cs +++ b/common/ASC.Core.Common/Tests/UserManagerTest.cs @@ -39,98 +39,95 @@ namespace ASC.Core.Common.Tests [Test] public void SearchUsers() { - CoreContext.TenantManager.SetCurrentTenant(0); - - var users = CoreContext.UserManager.Search(null, EmployeeStatus.Active); + var tenant = CoreContext.TenantManager.SetCurrentTenant(0); + var users = CoreContext.UserManager.Search(tenant, null, EmployeeStatus.Active); Assert.AreEqual(0, users.Length); - users = CoreContext.UserManager.Search("", EmployeeStatus.Active); + users = CoreContext.UserManager.Search(tenant, "", EmployeeStatus.Active); Assert.AreEqual(0, users.Length); - users = CoreContext.UserManager.Search(" ", EmployeeStatus.Active); + users = CoreContext.UserManager.Search(tenant, " ", EmployeeStatus.Active); Assert.AreEqual(0, users.Length); - users = CoreContext.UserManager.Search("АбРаМсКй", EmployeeStatus.Active); + users = CoreContext.UserManager.Search(tenant, "АбРаМсКй", EmployeeStatus.Active); Assert.AreEqual(0, users.Length); - users = CoreContext.UserManager.Search("АбРаМсКий", EmployeeStatus.Active); + users = CoreContext.UserManager.Search(tenant, "АбРаМсКий", EmployeeStatus.Active); Assert.AreEqual(0, users.Length);//Абрамский уволился - users = CoreContext.UserManager.Search("АбРаМсКий", EmployeeStatus.All); + users = CoreContext.UserManager.Search(tenant, "АбРаМсКий", EmployeeStatus.All); Assert.AreNotEqual(0, users.Length); - users = CoreContext.UserManager.Search("иванов николай", EmployeeStatus.Active); + users = CoreContext.UserManager.Search(tenant, "иванов николай", EmployeeStatus.Active); Assert.AreNotEqual(0, users.Length); - users = CoreContext.UserManager.Search("ведущий програм", EmployeeStatus.Active); + users = CoreContext.UserManager.Search(tenant, "ведущий програм", EmployeeStatus.Active); Assert.AreNotEqual(0, users.Length); - users = CoreContext.UserManager.Search("баннов лев", EmployeeStatus.Active, new Guid("613fc896-3ddd-4de1-a567-edbbc6cf1fc8")); + users = CoreContext.UserManager.Search(tenant, "баннов лев", EmployeeStatus.Active, new Guid("613fc896-3ddd-4de1-a567-edbbc6cf1fc8")); Assert.AreNotEqual(0, users.Length); - users = CoreContext.UserManager.Search("иванов николай", EmployeeStatus.Active, new Guid("613fc896-3ddd-4de1-a567-edbbc6cf1fc8")); + users = CoreContext.UserManager.Search(tenant, "иванов николай", EmployeeStatus.Active, new Guid("613fc896-3ddd-4de1-a567-edbbc6cf1fc8")); Assert.AreEqual(0, users); } [Test] public void DepartmentManagers() { - CoreContext.TenantManager.SetCurrentTenant(1024); + var tenant = CoreContext.TenantManager.SetCurrentTenant(1024); - var deps = CoreContext.UserManager.GetDepartments(); - var users = CoreContext.UserManager.GetUsers(); + var deps = CoreContext.UserManager.GetDepartments(tenant.TenantId); + var users = CoreContext.UserManager.GetUsers(tenant); var g1 = deps[0]; var ceo = users[0]; var u1 = users[1]; var u2 = users[2]; - //проверка кэша ceo - var ceoTemp = CoreContext.UserManager.GetCompanyCEO(); - CoreContext.UserManager.SetCompanyCEO(ceo.ID); - ceoTemp = CoreContext.UserManager.GetCompanyCEO(); + var ceoTemp = CoreContext.UserManager.GetCompanyCEO(tenant.TenantId); + CoreContext.UserManager.SetCompanyCEO(tenant.TenantId, ceo.ID); + ceoTemp = CoreContext.UserManager.GetCompanyCEO(tenant.TenantId); Assert.AreEqual(ceo, ceoTemp); Thread.Sleep(TimeSpan.FromSeconds(6)); - ceoTemp = CoreContext.UserManager.GetCompanyCEO(); + ceoTemp = CoreContext.UserManager.GetCompanyCEO(tenant.TenantId); Assert.AreEqual(ceo, ceoTemp); - //установка манагеров - CoreContext.UserManager.SetDepartmentManager(g1.ID, u1.ID); + CoreContext.UserManager.SetDepartmentManager(tenant.TenantId, g1.ID, u1.ID); - CoreContext.UserManager.SetDepartmentManager(g1.ID, u2.ID); + CoreContext.UserManager.SetDepartmentManager(tenant.TenantId, g1.ID, u2.ID); } [Test] public void UserGroupsPerformanceTest() { - CoreContext.TenantManager.SetCurrentTenant(0); + var tenant = CoreContext.TenantManager.SetCurrentTenant(0); - foreach (var u in CoreContext.UserManager.GetUsers()) + foreach (var u in CoreContext.UserManager.GetUsers(tenant)) { - var groups = CoreContext.UserManager.GetGroups(Guid.Empty); + var groups = CoreContext.UserManager.GetGroups(tenant.TenantId, Guid.Empty); Assert.IsNotNull(groups); - foreach (var g in CoreContext.UserManager.GetUserGroups(u.ID)) + foreach (var g in CoreContext.UserManager.GetUserGroups(tenant, u.ID)) { - var manager = CoreContext.UserManager.GetUsers(CoreContext.UserManager.GetDepartmentManager(g.ID)).UserName; + var manager = CoreContext.UserManager.GetUsers(CoreContext.UserManager.GetDepartmentManager(tenant.TenantId, g.ID), tenant.TenantId).UserName; } } var stopwatch = Stopwatch.StartNew(); - foreach (var u in CoreContext.UserManager.GetUsers()) + foreach (var u in CoreContext.UserManager.GetUsers(tenant)) { - var groups = CoreContext.UserManager.GetGroups(Guid.Empty); + var groups = CoreContext.UserManager.GetGroups(tenant.TenantId, Guid.Empty); Assert.IsNotNull(groups); - foreach (var g in CoreContext.UserManager.GetUserGroups(u.ID)) + foreach (var g in CoreContext.UserManager.GetUserGroups(tenant, u.ID)) { - var manager = CoreContext.UserManager.GetUsers(CoreContext.UserManager.GetDepartmentManager(g.ID)).UserName; + var manager = CoreContext.UserManager.GetUsers(CoreContext.UserManager.GetDepartmentManager(tenant.TenantId, g.ID), tenant.TenantId).UserName; } } stopwatch.Stop(); stopwatch.Restart(); - var users = CoreContext.UserManager.GetUsersByGroup(Constants.GroupUser.ID); - var visitors = CoreContext.UserManager.GetUsersByGroup(Constants.GroupVisitor.ID); - var all = CoreContext.UserManager.GetUsers(); + var users = CoreContext.UserManager.GetUsersByGroup(tenant, Constants.GroupUser.ID); + var visitors = CoreContext.UserManager.GetUsersByGroup(tenant, Constants.GroupVisitor.ID); + var all = CoreContext.UserManager.GetUsers(tenant); Assert.IsNotNull(users); Assert.IsNotNull(visitors); Assert.IsNotNull(all); diff --git a/common/ASC.Common/Tests/Notify/XmlPatternProvider2Test.cs b/common/ASC.Core.Common/Tests/XmlPatternProvider2Test.cs similarity index 100% rename from common/ASC.Common/Tests/Notify/XmlPatternProvider2Test.cs rename to common/ASC.Core.Common/Tests/XmlPatternProvider2Test.cs diff --git a/common/ASC.Core.Common/Users/UserExtensions.cs b/common/ASC.Core.Common/Users/UserExtensions.cs index ee0ba39a5a..e54dbf8136 100644 --- a/common/ASC.Core.Common/Users/UserExtensions.cs +++ b/common/ASC.Core.Common/Users/UserExtensions.cs @@ -25,16 +25,17 @@ using System.Collections.Generic; - +using ASC.Core.Tenants; +using Microsoft.AspNetCore.Http; + namespace ASC.Core.Users { public static class UserExtensions { - public static bool IsOwner(this UserInfo ui) + public static bool IsOwner(this UserInfo ui, Tenant tenant) { if (ui == null) return false; - var tenant = CoreContext.TenantManager.GetCurrentTenant(); return tenant != null && tenant.OwnerId.Equals(ui.ID); } @@ -43,19 +44,19 @@ namespace ASC.Core.Users return ui != null && ui.ID == SecurityContext.CurrentAccount.ID; } - public static bool IsAdmin(this UserInfo ui) + public static bool IsAdmin(this UserInfo ui, Tenant tenant) { - return ui != null && CoreContext.UserManager.IsUserInGroup(ui.ID, Constants.GroupAdmin.ID); + return ui != null && CoreContext.UserManager.IsUserInGroup(tenant, ui.ID, Constants.GroupAdmin.ID); + } + + public static bool IsVisitor(this UserInfo ui, Tenant tenant) + { + return ui != null && CoreContext.UserManager.IsUserInGroup(tenant, ui.ID, Constants.GroupVisitor.ID); } - public static bool IsVisitor(this UserInfo ui) + public static bool IsOutsider(this UserInfo ui, Tenant tenant) { - return ui != null && CoreContext.UserManager.IsUserInGroup(ui.ID, Constants.GroupVisitor.ID); - } - - public static bool IsOutsider(this UserInfo ui) - { - return IsVisitor(ui) && ui.ID == Constants.OutsideUser.ID; + return IsVisitor(ui, tenant) && ui.ID == Constants.OutsideUser.ID; } public static bool IsLDAP(this UserInfo ui) diff --git a/common/ASC.Data.Reassigns/ReassignProgressItem.cs b/common/ASC.Data.Reassigns/ReassignProgressItem.cs index 7ca2594f7f..80b9747777 100644 --- a/common/ASC.Data.Reassigns/ReassignProgressItem.cs +++ b/common/ASC.Data.Reassigns/ReassignProgressItem.cs @@ -40,6 +40,7 @@ using ASC.Web.Studio.Core.Notify; //using CrmDaoFactory = ASC.CRM.Core.Dao.DaoFactory; using Microsoft.AspNetCore.Http; using ASC.Common.Logging; +using ASC.Core.Tenants; namespace ASC.Data.Reassigns { @@ -102,7 +103,7 @@ namespace ASC.Data.Reassigns Percentage = 0; Status = ProgressStatus.Started; - CoreContext.TenantManager.SetCurrentTenant(_tenantId); + var tenant = CoreContext.TenantManager.SetCurrentTenant(_tenantId); SecurityContext.AuthenticateMe(_currentUserId); logger.InfoFormat("reassignment of data from {0} to {1}", _fromUserId, _toUserId); @@ -139,7 +140,7 @@ namespace ASC.Data.Reassigns if (_deleteProfile) { - DeleteUserProfile(); + DeleteUserProfile(tenant); } } catch (Exception ex) @@ -166,7 +167,7 @@ namespace ASC.Data.Reassigns var fromUser = CoreContext.UserManager.GetUsers(_fromUserId); var toUser = CoreContext.UserManager.GetUsers(_toUserId); - StudioNotifyService.SendMsgReassignsCompleted(_currentUserId, fromUser, toUser); + StudioNotifyService.SendMsgReassignsCompleted(_tenantId, _currentUserId, fromUser, toUser); var fromUserName = fromUser.DisplayUserName(false); var toUserName = toUser.DisplayUserName(false); @@ -182,16 +183,16 @@ namespace ASC.Data.Reassigns var fromUser = CoreContext.UserManager.GetUsers(_fromUserId); var toUser = CoreContext.UserManager.GetUsers(_toUserId); - StudioNotifyService.SendMsgReassignsFailed(_currentUserId, fromUser, toUser, errorMessage); + StudioNotifyService.SendMsgReassignsFailed(_tenantId, _currentUserId, fromUser, toUser, errorMessage); } - private void DeleteUserProfile() + private void DeleteUserProfile(Tenant tenant) { var user = CoreContext.UserManager.GetUsers(_fromUserId); var userName = user.DisplayUserName(false); - UserPhotoManager.RemovePhoto(user.ID); - CoreContext.UserManager.DeleteUser(user.ID); + UserPhotoManager.RemovePhoto(tenant, user.ID); + CoreContext.UserManager.DeleteUser(tenant, user.ID); QueueWorkerRemove.Start(_tenantId, user, _currentUserId, false); if (_httpHeaders != null) diff --git a/common/ASC.Data.Reassigns/RemoveProgressItem.cs b/common/ASC.Data.Reassigns/RemoveProgressItem.cs index 05ab1bdae9..8ffcb481de 100644 --- a/common/ASC.Data.Reassigns/RemoveProgressItem.cs +++ b/common/ASC.Data.Reassigns/RemoveProgressItem.cs @@ -34,6 +34,7 @@ using System.Web; using ASC.Common.Logging; using ASC.Common.Threading.Progress; using ASC.Core; +using ASC.Core.Tenants; using ASC.Core.Users; using ASC.Data.Storage; //using ASC.Mail.Core.Engine; @@ -104,11 +105,11 @@ namespace ASC.Data.Reassigns Percentage = 0; Status = ProgressStatus.Started; - CoreContext.TenantManager.SetCurrentTenant(_tenantId); + var tenant = CoreContext.TenantManager.SetCurrentTenant(_tenantId); SecurityContext.AuthenticateMe(_currentUserId); long docsSpace, crmSpace, mailSpace, talkSpace; - GetUsageSpace(out docsSpace, out mailSpace, out talkSpace); + GetUsageSpace(tenant, out docsSpace, out mailSpace, out talkSpace); logger.InfoFormat("deleting user data for {0} ", _userId); @@ -168,11 +169,11 @@ namespace ASC.Data.Reassigns return MemberwiseClone(); } - private void GetUsageSpace(out long docsSpace, out long mailSpace, out long talkSpace) + private void GetUsageSpace(Tenant tenant, out long docsSpace, out long mailSpace, out long talkSpace) { docsSpace = mailSpace = talkSpace = 0; - var webItems = WebItemManager.Instance.GetItems(Web.Core.WebZones.WebZoneType.All, ItemAvailableState.All); + var webItems = WebItemManager.Instance.GetItems(tenant, Web.Core.WebZones.WebZoneType.All, ItemAvailableState.All); foreach (var item in webItems) { @@ -225,7 +226,7 @@ namespace ASC.Data.Reassigns private void SendSuccessNotify(long docsSpace, long crmSpace, long mailSpace, long talkSpace) { if (_notify) - StudioNotifyService.SendMsgRemoveUserDataCompleted(_currentUserId, _userId, _userName, + StudioNotifyService.SendMsgRemoveUserDataCompleted(_tenantId, _currentUserId, _userId, _userName, docsSpace, crmSpace, mailSpace, talkSpace); if (_httpHeaders != null) @@ -238,8 +239,7 @@ namespace ASC.Data.Reassigns { if (!_notify) return; - StudioNotifyService.SendMsgRemoveUserDataFailed(_currentUserId, _userId, _userName, - errorMessage); + StudioNotifyService.SendMsgRemoveUserDataFailed(_tenantId, _currentUserId, _userId, _userName, errorMessage); } } } diff --git a/common/ASC.FederatedLogin/LoginProviders/BlockchainLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/BlockchainLoginProvider.cs index e72e5a554d..e7473ae302 100644 --- a/common/ASC.FederatedLogin/LoginProviders/BlockchainLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/BlockchainLoginProvider.cs @@ -38,9 +38,10 @@ namespace ASC.Web.Studio.Core public static class BlockchainLoginProvider { public static void UpdateData(string account) - { - var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); - if (!SecurityContext.IsAuthenticated || user.IsVisitor()) throw new SecurityException(); + { + var tenant = CoreContext.TenantManager.GetCurrentTenant(); + var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID, tenant.TenantId); + if (!SecurityContext.IsAuthenticated || user.IsVisitor(tenant)) throw new SecurityException(); var loginProfile = new LoginProfile { diff --git a/common/ASC.VoipService/Twilio/TwilioVoipSettings.cs b/common/ASC.VoipService/Twilio/TwilioVoipSettings.cs index 789a118592..0e2775b4dd 100644 --- a/common/ASC.VoipService/Twilio/TwilioVoipSettings.cs +++ b/common/ASC.VoipService/Twilio/TwilioVoipSettings.cs @@ -27,6 +27,7 @@ using System; using System.Text; using System.Web; +using ASC.Common; using ASC.Core.Common; using Uri = System.Uri; @@ -69,7 +70,7 @@ namespace ASC.VoipService.Twilio private string GetEcho(string method, bool user = true) { - return new TwilioResponseHelper(this, BaseCommonLinkUtility.GetFullAbsolutePath("")).GetEcho(method, user); + return new TwilioResponseHelper(this, BaseCommonLinkUtility.GetFullAbsolutePath(HttpContext.Current,"")).GetEcho(method, user); } } } diff --git a/products/ASC.People/Server/Controllers/GroupController.cs b/products/ASC.People/Server/Controllers/GroupController.cs index 8d8111b508..ee6440aef9 100644 --- a/products/ASC.People/Server/Controllers/GroupController.cs +++ b/products/ASC.People/Server/Controllers/GroupController.cs @@ -19,41 +19,40 @@ namespace ASC.Employee.Core.Controllers public class GroupController : ControllerBase { public Common.Logging.LogManager LogManager { get; } - - private ApiContext apiContext; - public ApiContext ApiContext { get { return apiContext ?? (apiContext = HttpContext); } } + public ApiContext ApiContext { get; } public MessageService MessageService { get; } - public GroupController(Common.Logging.LogManager logManager, MessageService messageService) + public GroupController(Common.Logging.LogManager logManager, MessageService messageService, ApiContext apiContext) { LogManager = logManager; MessageService = messageService; + ApiContext = apiContext; } [Read] public IEnumerable GetAll() { - return CoreContext.UserManager.GetDepartments().Select(x => new GroupWrapperSummary(x)); + return CoreContext.UserManager.GetDepartments(ApiContext.Tenant.TenantId).Select(x => new GroupWrapperSummary(x, ApiContext)); } [Read("{groupid}")] public GroupWrapperFull GetById(Guid groupid) { - return new GroupWrapperFull(GetGroupInfo(groupid), true); + return new GroupWrapperFull(GetGroupInfo(groupid), true, ApiContext); } [Read("user/{userid}")] public IEnumerable GetByUserId(Guid userid) { - return CoreContext.UserManager.GetUserGroups(userid).Select(x => new GroupWrapperSummary(x)); + return CoreContext.UserManager.GetUserGroups(ApiContext.Tenant, userid).Select(x => new GroupWrapperSummary(x, ApiContext)); } [Create] public GroupWrapperFull AddGroup(Guid groupManager, string groupName, IEnumerable members) { - SecurityContext.DemandPermissions(Constants.Action_EditGroups, Constants.Action_AddRemoveUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditGroups, Constants.Action_AddRemoveUser); - var group = CoreContext.UserManager.SaveGroupInfo(new GroupInfo { Name = groupName }); + var group = CoreContext.UserManager.SaveGroupInfo(ApiContext.Tenant, new GroupInfo { Name = groupName }); TransferUserToDepartment(groupManager, @group, true); if (members != null) @@ -66,23 +65,23 @@ namespace ASC.Employee.Core.Controllers MessageService.Send(MessageAction.GroupCreated, MessageTarget.Create(group.ID), group.Name); - return new GroupWrapperFull(group, true); + return new GroupWrapperFull(group, true, ApiContext); } [Update("{groupid}")] public GroupWrapperFull UpdateGroup(Guid groupid, Guid groupManager, string groupName, IEnumerable members) { - SecurityContext.DemandPermissions(Constants.Action_EditGroups, Constants.Action_AddRemoveUser); - var group = CoreContext.UserManager.GetGroups().SingleOrDefault(x => x.ID == groupid).NotFoundIfNull("group not found"); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditGroups, Constants.Action_AddRemoveUser); + var group = CoreContext.UserManager.GetGroups(ApiContext.Tenant.TenantId).SingleOrDefault(x => x.ID == groupid).NotFoundIfNull("group not found"); if (group.ID == Constants.LostGroupInfo.ID) { throw new ItemNotFoundException("group not found"); } group.Name = groupName ?? group.Name; - CoreContext.UserManager.SaveGroupInfo(group); + CoreContext.UserManager.SaveGroupInfo(ApiContext.Tenant, group); - RemoveMembersFrom(groupid, CoreContext.UserManager.GetUsersByGroup(groupid, EmployeeStatus.All).Select(u => u.ID).Where(id => !members.Contains(id))); + RemoveMembersFrom(groupid, CoreContext.UserManager.GetUsersByGroup(ApiContext.Tenant, groupid, EmployeeStatus.All).Select(u => u.ID).Where(id => !members.Contains(id))); TransferUserToDepartment(groupManager, @group, true); if (members != null) @@ -101,20 +100,20 @@ namespace ASC.Employee.Core.Controllers [Delete("{groupid}")] public GroupWrapperFull DeleteGroup(Guid groupid) { - SecurityContext.DemandPermissions(Constants.Action_EditGroups, Constants.Action_AddRemoveUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditGroups, Constants.Action_AddRemoveUser); var @group = GetGroupInfo(groupid); - var groupWrapperFull = new GroupWrapperFull(group, false); + var groupWrapperFull = new GroupWrapperFull(group, false, ApiContext); - CoreContext.UserManager.DeleteGroup(groupid); + CoreContext.UserManager.DeleteGroup(ApiContext.Tenant, groupid); MessageService.Send(MessageAction.GroupDeleted, MessageTarget.Create(group.ID), group.Name); return groupWrapperFull; } - private static GroupInfo GetGroupInfo(Guid groupid) + private GroupInfo GetGroupInfo(Guid groupid) { - var group = CoreContext.UserManager.GetGroups().SingleOrDefault(x => x.ID == groupid).NotFoundIfNull("group not found"); + var group = CoreContext.UserManager.GetGroups(ApiContext.Tenant.TenantId).SingleOrDefault(x => x.ID == groupid).NotFoundIfNull("group not found"); if (group.ID == Constants.LostGroupInfo.ID) throw new ItemNotFoundException("group not found"); return @group; @@ -123,12 +122,12 @@ namespace ASC.Employee.Core.Controllers [Update("{groupid}/members/{newgroupid}")] public GroupWrapperFull TransferMembersTo(Guid groupid, Guid newgroupid) { - SecurityContext.DemandPermissions(Constants.Action_EditGroups, Constants.Action_AddRemoveUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditGroups, Constants.Action_AddRemoveUser); var oldgroup = GetGroupInfo(groupid); var newgroup = GetGroupInfo(newgroupid); - var users = CoreContext.UserManager.GetUsersByGroup(oldgroup.ID); + var users = CoreContext.UserManager.GetUsersByGroup(ApiContext.Tenant, oldgroup.ID); foreach (var userInfo in users) { TransferUserToDepartment(userInfo.ID, newgroup, false); @@ -139,7 +138,7 @@ namespace ASC.Employee.Core.Controllers [Create("{groupid}/members")] public GroupWrapperFull SetMembersTo(Guid groupid, IEnumerable members) { - RemoveMembersFrom(groupid, CoreContext.UserManager.GetUsersByGroup(groupid).Select(x => x.ID)); + RemoveMembersFrom(groupid, CoreContext.UserManager.GetUsersByGroup(ApiContext.Tenant, groupid).Select(x => x.ID)); AddMembersTo(groupid, members); return GetById(groupid); } @@ -147,7 +146,7 @@ namespace ASC.Employee.Core.Controllers [Update("{groupid}/members")] public GroupWrapperFull AddMembersTo(Guid groupid, IEnumerable members) { - SecurityContext.DemandPermissions(Constants.Action_EditGroups, Constants.Action_AddRemoveUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditGroups, Constants.Action_AddRemoveUser); var group = GetGroupInfo(groupid); foreach (var userId in members) @@ -161,9 +160,9 @@ namespace ASC.Employee.Core.Controllers public GroupWrapperFull SetManager(Guid groupid, Guid userid) { var group = GetGroupInfo(groupid); - if (CoreContext.UserManager.UserExists(userid)) + if (CoreContext.UserManager.UserExists(userid, ApiContext.Tenant.TenantId)) { - CoreContext.UserManager.SetDepartmentManager(group.ID, userid); + CoreContext.UserManager.SetDepartmentManager(ApiContext.Tenant.TenantId, group.ID, userid); } else { @@ -175,7 +174,7 @@ namespace ASC.Employee.Core.Controllers [Delete("{groupid}/members")] public GroupWrapperFull RemoveMembersFrom(Guid groupid, IEnumerable members) { - SecurityContext.DemandPermissions(Constants.Action_EditGroups, Constants.Action_AddRemoveUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditGroups, Constants.Action_AddRemoveUser); var group = GetGroupInfo(groupid); foreach (var userId in members) @@ -185,24 +184,24 @@ namespace ASC.Employee.Core.Controllers return GetById(group.ID); } - private static void RemoveUserFromDepartment(Guid userId, GroupInfo @group) + private void RemoveUserFromDepartment(Guid userId, GroupInfo @group) { - if (!CoreContext.UserManager.UserExists(userId)) return; + if (!CoreContext.UserManager.UserExists(userId, ApiContext.Tenant.TenantId)) return; - var user = CoreContext.UserManager.GetUsers(userId); - CoreContext.UserManager.RemoveUserFromGroup(user.ID, @group.ID); - CoreContext.UserManager.SaveUserInfo(user); + var user = CoreContext.UserManager.GetUsers(userId, ApiContext.Tenant.TenantId); + CoreContext.UserManager.RemoveUserFromGroup(ApiContext.Tenant, user.ID, @group.ID); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, user); } - private static void TransferUserToDepartment(Guid userId, GroupInfo group, bool setAsManager) + private void TransferUserToDepartment(Guid userId, GroupInfo group, bool setAsManager) { - if (!CoreContext.UserManager.UserExists(userId) && userId != Guid.Empty) return; + if (!CoreContext.UserManager.UserExists(userId, ApiContext.Tenant.TenantId) && userId != Guid.Empty) return; if (setAsManager) { - CoreContext.UserManager.SetDepartmentManager(@group.ID, userId); + CoreContext.UserManager.SetDepartmentManager(ApiContext.Tenant.TenantId, @group.ID, userId); } - CoreContext.UserManager.AddUserIntoGroup(userId, @group.ID); + CoreContext.UserManager.AddUserIntoGroup(ApiContext.Tenant, userId, @group.ID); } } } \ No newline at end of file diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index 76a94c1dd7..8735811a4b 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -86,42 +86,42 @@ namespace ASC.Employee.Core.Controllers public IEnumerable GetByStatus(EmployeeStatus status) { if (CoreContext.Configuration.Personal) throw new Exception("Method not available"); - var query = CoreContext.UserManager.GetUsers(status).AsEnumerable(); + var query = CoreContext.UserManager.GetUsers(ApiContext.Tenant, status).AsEnumerable(); if ("group".Equals(ApiContext.FilterBy, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(ApiContext.FilterValue)) { var groupId = new Guid(ApiContext.FilterValue); //Filter by group - query = query.Where(x => CoreContext.UserManager.IsUserInGroup(x.ID, groupId)); + query = query.Where(x => CoreContext.UserManager.IsUserInGroup(ApiContext.Tenant, x.ID, groupId)); ApiContext.SetDataFiltered(); } - return query.Select(x => new EmployeeWraperFull(x)); + return query.Select(x => new EmployeeWraperFull(x, ApiContext)); } [Read("@self")] public EmployeeWraper Self() { - return new EmployeeWraperFull(CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID)); + return new EmployeeWraperFull(CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID), ApiContext); } [Read("email")] public EmployeeWraperFull GetByEmail([FromQuery]string email) { - if (CoreContext.Configuration.Personal && !CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsOwner()) + if (CoreContext.Configuration.Personal && !CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsOwner(ApiContext.Tenant)) throw new MethodAccessException("Method not available"); - var user = CoreContext.UserManager.GetUserByEmail(email); + var user = CoreContext.UserManager.GetUserByEmail(ApiContext.Tenant.TenantId, email); if (user.ID == Constants.LostUser.ID) { throw new ItemNotFoundException("User not found"); } - return new EmployeeWraperFull(user); + return new EmployeeWraperFull(user, ApiContext); } [Read("{username}", order: int.MaxValue)] public EmployeeWraperFull GetById(string username) { if (CoreContext.Configuration.Personal) throw new MethodAccessException("Method not available"); - var user = CoreContext.UserManager.GetUserByUserName(username); + var user = CoreContext.UserManager.GetUserByUserName(ApiContext.Tenant.TenantId, username); if (user.ID == Constants.LostUser.ID) { if (Guid.TryParse(username, out var userId)) @@ -139,7 +139,7 @@ namespace ASC.Employee.Core.Controllers throw new ItemNotFoundException("User not found"); } - return new EmployeeWraperFull(user); + return new EmployeeWraperFull(user, ApiContext); } [Read("@search/{query}")] @@ -154,7 +154,7 @@ namespace ASC.Employee.Core.Controllers groupId = new Guid(ApiContext.FilterValue); } - return CoreContext.UserManager.Search(query, EmployeeStatus.Active, groupId).Select(x => new EmployeeWraperFull(x)); + return CoreContext.UserManager.Search(ApiContext.Tenant, query, EmployeeStatus.Active, groupId).Select(x => new EmployeeWraperFull(x, ApiContext)); } catch (Exception error) { @@ -175,20 +175,20 @@ namespace ASC.Employee.Core.Controllers if (CoreContext.Configuration.Personal) throw new MethodAccessException("Method not available"); try { - var list = CoreContext.UserManager.GetUsers(status).AsEnumerable(); + var list = CoreContext.UserManager.GetUsers(ApiContext.Tenant, status).AsEnumerable(); if ("group".Equals(ApiContext.FilterBy, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(ApiContext.FilterValue)) { var groupId = new Guid(ApiContext.FilterValue); //Filter by group - list = list.Where(x => CoreContext.UserManager.IsUserInGroup(x.ID, groupId)); + list = list.Where(x => CoreContext.UserManager.IsUserInGroup(ApiContext.Tenant, x.ID, groupId)); ApiContext.SetDataFiltered(); } list = list.Where(x => x.FirstName != null && x.FirstName.IndexOf(query, StringComparison.OrdinalIgnoreCase) > -1 || (x.LastName != null && x.LastName.IndexOf(query, StringComparison.OrdinalIgnoreCase) != -1) || (x.UserName != null && x.UserName.IndexOf(query, StringComparison.OrdinalIgnoreCase) != -1) || (x.Email != null && x.Email.IndexOf(query, StringComparison.OrdinalIgnoreCase) != -1) || (x.Contacts != null && x.Contacts.Any(y => y.IndexOf(query, StringComparison.OrdinalIgnoreCase) != -1))); - return list.Select(x => new EmployeeWraperFull(x)); + return list.Select(x => new EmployeeWraperFull(x, ApiContext)); } catch (Exception error) { @@ -263,14 +263,14 @@ namespace ASC.Employee.Core.Controllers { var users = GetByFilter(employeeStatus, groupId, activationStatus, employeeType, isAdministrator); - return users.Select(u => new EmployeeWraper(u)); + return users.Select(u => new EmployeeWraper(u, ApiContext)); } private IEnumerable GetByFilter(EmployeeStatus? employeeStatus, Guid? groupId, EmployeeActivationStatus? activationStatus, EmployeeType? employeeType, bool? isAdministrator) { if (CoreContext.Configuration.Personal) throw new MethodAccessException("Method not available"); - var isAdmin = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin() || - WebItemSecurity.IsProductAdministrator(WebItemManager.PeopleProductID, SecurityContext.CurrentAccount.ID); + var isAdmin = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin(ApiContext.Tenant) || + WebItemSecurity.IsProductAdministrator(ApiContext.Tenant, WebItemManager.PeopleProductID, SecurityContext.CurrentAccount.ID); var includeGroups = new List(); if (groupId.HasValue) @@ -302,7 +302,7 @@ namespace ASC.Employee.Core.Controllers includeGroups.AddRange(products.Select(r=> r.ID)); } - var users = CoreContext.UserManager.GetUsers(isAdmin, employeeStatus, includeGroups, excludeGroups, activationStatus, ApiContext.FilterValue, ApiContext.SortBy, !ApiContext.SortDescending, ApiContext.Count - 1, ApiContext.StartIndex, out int total); + var users = CoreContext.UserManager.GetUsers(ApiContext.Tenant.TenantId, isAdmin, employeeStatus, includeGroups, excludeGroups, activationStatus, ApiContext.FilterValue, ApiContext.SortBy, !ApiContext.SortDescending, ApiContext.Count - 1, ApiContext.StartIndex, out int total); ApiContext.SetTotalCount(total); @@ -312,7 +312,7 @@ namespace ASC.Employee.Core.Controllers [Create] public EmployeeWraperFull AddMember(MemberModel memberModel) { - SecurityContext.DemandPermissions(Constants.Action_AddRemoveUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_AddRemoveUser); if (string.IsNullOrEmpty(memberModel.Password)) memberModel.Password = UserManagerWrapper.GeneratePassword(); @@ -339,7 +339,7 @@ namespace ASC.Employee.Core.Controllers UpdateContacts(memberModel.Contacts, user); - user = UserManagerWrapper.AddUser(user, memberModel.Password, false, true, memberModel.IsVisitor); + user = UserManagerWrapper.AddUser(ApiContext.Tenant, user, memberModel.Password, false, true, memberModel.IsVisitor); var messageAction = memberModel.IsVisitor ? MessageAction.GuestCreated : MessageAction.UserCreated; MessageService.Send(messageAction, MessageTarget.Create(user.ID), user.DisplayUserName(false)); @@ -351,13 +351,13 @@ namespace ASC.Employee.Core.Controllers UpdatePhotoUrl(memberModel.Files, user); } - return new EmployeeWraperFull(user); + return new EmployeeWraperFull(user, ApiContext); } [Create("active")] public EmployeeWraperFull AddMemberAsActivated(MemberModel memberModel) { - SecurityContext.DemandPermissions(Constants.Action_AddRemoveUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_AddRemoveUser); var user = new UserInfo(); @@ -382,7 +382,7 @@ namespace ASC.Employee.Core.Controllers UpdateContacts(memberModel.Contacts, user); - user = UserManagerWrapper.AddUser(user, memberModel.Password, false, false, memberModel.IsVisitor); + user = UserManagerWrapper.AddUser(ApiContext.Tenant, user, memberModel.Password, false, false, memberModel.IsVisitor); user.ActivationStatus = EmployeeActivationStatus.Activated; @@ -393,7 +393,7 @@ namespace ASC.Employee.Core.Controllers UpdatePhotoUrl(memberModel.Files, user); } - return new EmployeeWraperFull(user); + return new EmployeeWraperFull(user, ApiContext); } [Update("{userid}")] @@ -404,7 +404,7 @@ namespace ASC.Employee.Core.Controllers if (CoreContext.UserManager.IsSystemUser(user.ID)) throw new SecurityException(); - SecurityContext.DemandPermissions(new UserSecurityProvider(user.ID), Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, new UserSecurityProvider(user.ID), Constants.Action_EditUser); var self = SecurityContext.CurrentAccount.ID.Equals(user.ID); var resetDate = new DateTime(1900, 01, 01); @@ -413,7 +413,7 @@ namespace ASC.Employee.Core.Controllers var isLdap = user.IsLDAP(); var isSso = user.IsSSO(); - var isAdmin = WebItemSecurity.IsProductAdministrator(WebItemManager.PeopleProductID, SecurityContext.CurrentAccount.ID); + var isAdmin = WebItemSecurity.IsProductAdministrator(ApiContext.Tenant, WebItemManager.PeopleProductID, SecurityContext.CurrentAccount.ID); if (!isLdap && !isSso) { @@ -455,7 +455,7 @@ namespace ASC.Employee.Core.Controllers UpdateContacts(memberModel.Contacts, user); UpdateDepartments(memberModel.Department, user); - if (memberModel.Files != UserPhotoManager.GetPhotoAbsoluteWebPath(user.ID)) + if (memberModel.Files != UserPhotoManager.GetPhotoAbsoluteWebPath(ApiContext.Tenant, user.ID)) { UpdatePhotoUrl(memberModel.Files, user); } @@ -467,24 +467,24 @@ namespace ASC.Employee.Core.Controllers if (self && !isAdmin) { - StudioNotifyService.SendMsgToAdminAboutProfileUpdated(); + StudioNotifyService.SendMsgToAdminAboutProfileUpdated(ApiContext.Tenant.TenantId); } // change user type - var canBeGuestFlag = !user.IsOwner() && !user.IsAdmin() && !user.GetListAdminModules().Any() && !user.IsMe(); + var canBeGuestFlag = !user.IsOwner(ApiContext.Tenant) && !user.IsAdmin(ApiContext.Tenant) && !user.GetListAdminModules(ApiContext.Tenant).Any() && !user.IsMe(); - if (memberModel.IsVisitor && !user.IsVisitor() && canBeGuestFlag) + if (memberModel.IsVisitor && !user.IsVisitor(ApiContext.Tenant) && canBeGuestFlag) { - CoreContext.UserManager.AddUserIntoGroup(user.ID, Constants.GroupVisitor.ID); + CoreContext.UserManager.AddUserIntoGroup(ApiContext.Tenant, user.ID, Constants.GroupVisitor.ID); WebItemSecurity.ClearCache(); } - if (!self && !memberModel.IsVisitor && user.IsVisitor()) + if (!self && !memberModel.IsVisitor && user.IsVisitor(ApiContext.Tenant)) { var usersQuota = TenantExtra.GetTenantQuota().ActiveUsers; - if (TenantStatisticsProvider.GetUsersCount() < usersQuota) + if (TenantStatisticsProvider.GetUsersCount(ApiContext.Tenant) < usersQuota) { - CoreContext.UserManager.RemoveUserFromGroup(user.ID, Constants.GroupVisitor.ID); + CoreContext.UserManager.RemoveUserFromGroup(ApiContext.Tenant, user.ID, Constants.GroupVisitor.ID); WebItemSecurity.ClearCache(); } else @@ -493,7 +493,7 @@ namespace ASC.Employee.Core.Controllers } } - CoreContext.UserManager.SaveUserInfo(user, memberModel.IsVisitor); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, user, memberModel.IsVisitor); MessageService.Send(MessageAction.UserUpdated, MessageTarget.Create(user.ID), user.DisplayUserName(false)); if (memberModel.Disable.HasValue && memberModel.Disable.Value) @@ -502,13 +502,13 @@ namespace ASC.Employee.Core.Controllers MessageService.Send(MessageAction.CookieSettingsUpdated); } - return new EmployeeWraperFull(user); + return new EmployeeWraperFull(user, ApiContext); } [Delete("{userid}")] public EmployeeWraperFull DeleteMember(string userid) { - SecurityContext.DemandPermissions(Constants.Action_AddRemoveUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_AddRemoveUser); var user = GetUserInfo(userid); @@ -522,13 +522,13 @@ namespace ASC.Employee.Core.Controllers var userName = user.DisplayUserName(false); - UserPhotoManager.RemovePhoto(user.ID); - CoreContext.UserManager.DeleteUser(user.ID); + UserPhotoManager.RemovePhoto(ApiContext.Tenant, user.ID); + CoreContext.UserManager.DeleteUser(ApiContext.Tenant, user.ID); QueueWorkerRemove.Start(TenantProvider.CurrentTenantID, user, SecurityContext.CurrentAccount.ID, false); MessageService.Send(MessageAction.UserDeleted, MessageTarget.Create(user.ID), userName); - return new EmployeeWraperFull(user); + return new EmployeeWraperFull(user, ApiContext); } [Update("{userid}/contacts")] @@ -540,8 +540,8 @@ namespace ASC.Employee.Core.Controllers throw new SecurityException(); UpdateContacts(memberModel.Contacts, user); - CoreContext.UserManager.SaveUserInfo(user); - return new EmployeeWraperFull(user); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, user); + return new EmployeeWraperFull(user, ApiContext); } [Create("{userid}/contacts")] @@ -554,8 +554,8 @@ namespace ASC.Employee.Core.Controllers user.Contacts.Clear(); UpdateContacts(memberModel.Contacts, user); - CoreContext.UserManager.SaveUserInfo(user); - return new EmployeeWraperFull(user); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, user); + return new EmployeeWraperFull(user, ApiContext); } [Delete("{userid}/contacts")] @@ -567,8 +567,8 @@ namespace ASC.Employee.Core.Controllers throw new SecurityException(); DeleteContacts(memberModel.Contacts, user); - CoreContext.UserManager.SaveUserInfo(user); - return new EmployeeWraperFull(user); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, user); + return new EmployeeWraperFull(user, ApiContext); } [Read("{userid}/photo")] @@ -579,7 +579,7 @@ namespace ASC.Employee.Core.Controllers if (CoreContext.UserManager.IsSystemUser(user.ID)) throw new SecurityException(); - return new ThumbnailsDataWrapper(user.ID); + return new ThumbnailsDataWrapper(ApiContext.Tenant, user.ID); } [Create("{userid}/photo")] @@ -600,7 +600,7 @@ namespace ASC.Employee.Core.Controllers userId = SecurityContext.CurrentAccount.ID; } - SecurityContext.DemandPermissions(new UserSecurityProvider(userId), Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, new UserSecurityProvider(userId), Constants.Action_EditUser); var userPhoto = model.Files[0]; @@ -625,17 +625,17 @@ namespace ASC.Employee.Core.Controllers if (data.Length > SetupInfo.MaxImageUploadSize) throw new ImageSizeLimitException(); - var mainPhoto = UserPhotoManager.SaveOrUpdatePhoto(userId, data); + var mainPhoto = UserPhotoManager.SaveOrUpdatePhoto(ApiContext.Tenant, userId, data); result.Data = new { main = mainPhoto, - retina = UserPhotoManager.GetRetinaPhotoURL(userId), - max = UserPhotoManager.GetMaxPhotoURL(userId), - big = UserPhotoManager.GetBigPhotoURL(userId), - medium = UserPhotoManager.GetMediumPhotoURL(userId), - small = UserPhotoManager.GetSmallPhotoURL(userId), + retina = UserPhotoManager.GetRetinaPhotoURL(ApiContext.Tenant.TenantId, userId), + max = UserPhotoManager.GetMaxPhotoURL(ApiContext.Tenant.TenantId, userId), + big = UserPhotoManager.GetBigPhotoURL(ApiContext.Tenant.TenantId, userId), + medium = UserPhotoManager.GetMediumPhotoURL(ApiContext.Tenant.TenantId, userId), + small = UserPhotoManager.GetSmallPhotoURL(ApiContext.Tenant.TenantId, userId), }; } else @@ -684,15 +684,15 @@ namespace ASC.Employee.Core.Controllers if (CoreContext.UserManager.IsSystemUser(user.ID)) throw new SecurityException(); - if (model.Files != UserPhotoManager.GetPhotoAbsoluteWebPath(user.ID)) + if (model.Files != UserPhotoManager.GetPhotoAbsoluteWebPath(ApiContext.Tenant, user.ID)) { UpdatePhotoUrl(model.Files, user); } - CoreContext.UserManager.SaveUserInfo(user); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, user); MessageService.Send(MessageAction.UserAddedAvatar, MessageTarget.Create(user.ID), user.DisplayUserName(false)); - return new ThumbnailsDataWrapper(user.ID); + return new ThumbnailsDataWrapper(ApiContext.Tenant, user.ID); } [Delete("{userid}/photo")] @@ -703,14 +703,14 @@ namespace ASC.Employee.Core.Controllers if (CoreContext.UserManager.IsSystemUser(user.ID)) throw new SecurityException(); - SecurityContext.DemandPermissions(new UserSecurityProvider(user.ID), Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, new UserSecurityProvider(user.ID), Constants.Action_EditUser); - UserPhotoManager.RemovePhoto(user.ID); + UserPhotoManager.RemovePhoto(ApiContext.Tenant, user.ID); - CoreContext.UserManager.SaveUserInfo(user); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, user); MessageService.Send(MessageAction.UserDeletedAvatar, MessageTarget.Create(user.ID), user.DisplayUserName(false)); - return new ThumbnailsDataWrapper(user.ID); + return new ThumbnailsDataWrapper(ApiContext.Tenant, user.ID); } @@ -722,7 +722,7 @@ namespace ASC.Employee.Core.Controllers if (CoreContext.UserManager.IsSystemUser(user.ID)) throw new SecurityException(); - SecurityContext.DemandPermissions(new UserSecurityProvider(user.ID), Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, new UserSecurityProvider(user.ID), Constants.Action_EditUser); if (!string.IsNullOrEmpty(thumbnailsModel.TmpFile)) { @@ -732,18 +732,18 @@ namespace ASC.Employee.Core.Controllers var settings = new UserPhotoThumbnailSettings(thumbnailsModel.X, thumbnailsModel.Y, thumbnailsModel.Width, thumbnailsModel.Height); settings.SaveForUser(user.ID); - UserPhotoManager.SaveOrUpdatePhoto(user.ID, data); + UserPhotoManager.SaveOrUpdatePhoto(ApiContext.Tenant, user.ID, data); UserPhotoManager.RemoveTempPhoto(fileName); } else { - UserPhotoThumbnailManager.SaveThumbnails(thumbnailsModel.X, thumbnailsModel.Y, thumbnailsModel.Width, thumbnailsModel.Height, user.ID); + UserPhotoThumbnailManager.SaveThumbnails(ApiContext.Tenant.TenantId, thumbnailsModel.X, thumbnailsModel.Y, thumbnailsModel.Width, thumbnailsModel.Height, user.ID); } - CoreContext.UserManager.SaveUserInfo(user); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, user); MessageService.Send(MessageAction.UserUpdatedAvatarThumbnails, MessageTarget.Create(user.ID), user.DisplayUserName(false)); - return new ThumbnailsDataWrapper(user.ID); + return new ThumbnailsDataWrapper(ApiContext.Tenant, user.ID); } @@ -751,7 +751,7 @@ namespace ASC.Employee.Core.Controllers [Create("password", false)] public string SendUserPassword(string email) { - var userInfo = UserManagerWrapper.SendUserPassword(email, MessageService, HttpContext); + var userInfo = UserManagerWrapper.SendUserPassword(ApiContext.Tenant.TenantId, email, MessageService, HttpContext); return string.Format(Resource.MessageYourPasswordSuccessfullySendedToEmail, userInfo.Email); } @@ -759,11 +759,11 @@ namespace ASC.Employee.Core.Controllers [Update("{userid}/password")] public EmployeeWraperFull ChangeUserPassword(Guid userid, MemberModel memberModel) { - SecurityContext.DemandPermissions(new UserSecurityProvider(userid), Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, new UserSecurityProvider(userid), Constants.Action_EditUser); - if (!CoreContext.UserManager.UserExists(userid)) return null; + if (!CoreContext.UserManager.UserExists(userid, ApiContext.Tenant.TenantId)) return null; - var user = CoreContext.UserManager.GetUsers(userid); + var user = CoreContext.UserManager.GetUsers(userid, ApiContext.Tenant.TenantId); if (CoreContext.UserManager.IsSystemUser(user.ID)) throw new SecurityException(); @@ -775,7 +775,7 @@ namespace ASC.Employee.Core.Controllers { user.Email = address.Address.ToLowerInvariant(); user.ActivationStatus = EmployeeActivationStatus.Activated; - CoreContext.UserManager.SaveUserInfo(user); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, user); } } @@ -788,20 +788,20 @@ namespace ASC.Employee.Core.Controllers MessageService.Send(MessageAction.CookieSettingsUpdated); } - return new EmployeeWraperFull(GetUserInfo(userid.ToString())); + return new EmployeeWraperFull(GetUserInfo(userid.ToString()), ApiContext); } - private static UserInfo GetUserInfo(string userNameOrId) + private UserInfo GetUserInfo(string userNameOrId) { UserInfo user; try { var userId = new Guid(userNameOrId); - user = CoreContext.UserManager.GetUsers(userId); + user = CoreContext.UserManager.GetUsers(userId, ApiContext.Tenant.TenantId); } catch (FormatException) { - user = CoreContext.UserManager.GetUserByUserName(userNameOrId); + user = CoreContext.UserManager.GetUserByUserName(ApiContext.Tenant.TenantId, userNameOrId); } if (user == null || user.ID == Constants.LostUser.ID) throw new ItemNotFoundException("user not found"); @@ -814,13 +814,13 @@ namespace ASC.Employee.Core.Controllers var retuls = new List(); foreach (var id in model.UserIds.Where(userId => !CoreContext.UserManager.IsSystemUser(userId))) { - SecurityContext.DemandPermissions(new UserSecurityProvider(id), Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, new UserSecurityProvider(id), Constants.Action_EditUser); var u = CoreContext.UserManager.GetUsers(id); if (u.ID == Constants.LostUser.ID || u.IsLDAP()) continue; u.ActivationStatus = activationstatus; - CoreContext.UserManager.SaveUserInfo(u); - retuls.Add(new EmployeeWraperFull(u)); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, u); + retuls.Add(new EmployeeWraperFull(u, ApiContext)); } return retuls; @@ -837,23 +837,23 @@ namespace ASC.Employee.Core.Controllers foreach (var user in users) { - if (user.IsOwner() || user.IsAdmin() || user.IsMe() || user.GetListAdminModules().Any()) + if (user.IsOwner(ApiContext.Tenant) || user.IsAdmin(ApiContext.Tenant) || user.IsMe() || user.GetListAdminModules(ApiContext.Tenant).Any()) continue; switch (type) { case EmployeeType.User: - if (user.IsVisitor()) + if (user.IsVisitor(ApiContext.Tenant)) { - if (TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers) + if (TenantStatisticsProvider.GetUsersCount(ApiContext.Tenant) < TenantExtra.GetTenantQuota().ActiveUsers) { - CoreContext.UserManager.RemoveUserFromGroup(user.ID, Constants.GroupVisitor.ID); + CoreContext.UserManager.RemoveUserFromGroup(ApiContext.Tenant, user.ID, Constants.GroupVisitor.ID); WebItemSecurity.ClearCache(); } } break; case EmployeeType.Visitor: - CoreContext.UserManager.AddUserIntoGroup(user.ID, Constants.GroupVisitor.ID); + CoreContext.UserManager.AddUserIntoGroup(ApiContext.Tenant, user.ID, Constants.GroupVisitor.ID); WebItemSecurity.ClearCache(); break; } @@ -861,13 +861,13 @@ namespace ASC.Employee.Core.Controllers MessageService.Send(MessageAction.UsersUpdatedType, MessageTarget.Create(users.Select(x => x.ID)), users.Select(x => x.DisplayUserName(false))); - return users.Select(user => new EmployeeWraperFull(user)); + return users.Select(user => new EmployeeWraperFull(user, ApiContext)); } [Update("status/{status}")] public IEnumerable UpdateUserStatus(EmployeeStatus status, UpdateMembersModel model) { - SecurityContext.DemandPermissions(Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditUser); var users = model.UserIds.Select(userId => CoreContext.UserManager.GetUsers(userId)) .Where(u => !CoreContext.UserManager.IsSystemUser(u.ID) && !u.IsLDAP()) @@ -875,7 +875,7 @@ namespace ASC.Employee.Core.Controllers foreach (var user in users) { - if (user.IsOwner() || user.IsMe()) + if (user.IsOwner(ApiContext.Tenant) || user.IsMe()) continue; switch (status) @@ -883,16 +883,16 @@ namespace ASC.Employee.Core.Controllers case EmployeeStatus.Active: if (user.Status == EmployeeStatus.Terminated) { - if (TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers || user.IsVisitor()) + if (TenantStatisticsProvider.GetUsersCount(ApiContext.Tenant) < TenantExtra.GetTenantQuota().ActiveUsers || user.IsVisitor(ApiContext.Tenant)) { user.Status = EmployeeStatus.Active; - CoreContext.UserManager.SaveUserInfo(user); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, user); } } break; case EmployeeStatus.Terminated: user.Status = EmployeeStatus.Terminated; - CoreContext.UserManager.SaveUserInfo(user); + CoreContext.UserManager.SaveUserInfo(ApiContext.Tenant, user); HttpContext.ResetUserCookie(user.ID); MessageService.Send(MessageAction.CookieSettingsUpdated); @@ -902,7 +902,7 @@ namespace ASC.Employee.Core.Controllers MessageService.Send(MessageAction.UsersUpdatedStatus, MessageTarget.Create(users.Select(x => x.ID)), users.Select(x => x.DisplayUserName(false))); - return users.Select(user => new EmployeeWraperFull(user)); + return users.Select(user => new EmployeeWraperFull(user, ApiContext)); } @@ -920,7 +920,7 @@ namespace ASC.Employee.Core.Controllers if (user.ActivationStatus == EmployeeActivationStatus.Pending) { - if (user.IsVisitor()) + if (user.IsVisitor(ApiContext.Tenant)) { StudioNotifyService.GuestInfoActivation(user); } @@ -937,13 +937,13 @@ namespace ASC.Employee.Core.Controllers MessageService.Send(MessageAction.UsersSentActivationInstructions, MessageTarget.Create(users.Select(x => x.ID)), users.Select(x => x.DisplayUserName(false))); - return users.Select(user => new EmployeeWraperFull(user)); + return users.Select(user => new EmployeeWraperFull(user, ApiContext)); } [Update("delete")] public IEnumerable RemoveUsers(UpdateMembersModel model) { - SecurityContext.DemandPermissions(Constants.Action_AddRemoveUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_AddRemoveUser); CheckReassignProccess(model.UserIds); @@ -957,14 +957,14 @@ namespace ASC.Employee.Core.Controllers { if (user.Status != EmployeeStatus.Terminated) continue; - UserPhotoManager.RemovePhoto(user.ID); - CoreContext.UserManager.DeleteUser(user.ID); + UserPhotoManager.RemovePhoto(ApiContext.Tenant, user.ID); + CoreContext.UserManager.DeleteUser(ApiContext.Tenant,user.ID); QueueWorkerRemove.Start(TenantProvider.CurrentTenantID, user, SecurityContext.CurrentAccount.ID, false); } MessageService.Send(MessageAction.UsersDeleted, MessageTarget.Create(users.Select(x => x.ID)), userNames); - return users.Select(user => new EmployeeWraperFull(user)); + return users.Select(user => new EmployeeWraperFull(user, ApiContext)); } @@ -1037,7 +1037,7 @@ namespace ASC.Employee.Core.Controllers [Read(@"reassign/progress")] public ReassignProgressItem GetReassignProgress(Guid userId) { - SecurityContext.DemandPermissions(Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditUser); return QueueWorkerReassign.GetProgressItemStatus(TenantProvider.CurrentTenantID, userId); } @@ -1045,7 +1045,7 @@ namespace ASC.Employee.Core.Controllers [Update(@"reassign/terminate")] public void TerminateReassign(Guid userId) { - SecurityContext.DemandPermissions(Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditUser); QueueWorkerReassign.Terminate(TenantProvider.CurrentTenantID, userId); } @@ -1053,14 +1053,14 @@ namespace ASC.Employee.Core.Controllers [Create(@"reassign/start")] public ReassignProgressItem StartReassign(Guid fromUserId, Guid toUserId, bool deleteProfile) { - SecurityContext.DemandPermissions(Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditUser); var fromUser = CoreContext.UserManager.GetUsers(fromUserId); if (fromUser == null || fromUser.ID == Constants.LostUser.ID) throw new ArgumentException("User with id = " + fromUserId + " not found"); - if (fromUser.IsOwner() || fromUser.IsMe() || fromUser.Status != EmployeeStatus.Terminated) + if (fromUser.IsOwner(ApiContext.Tenant) || fromUser.IsMe() || fromUser.Status != EmployeeStatus.Terminated) throw new ArgumentException("Can not delete user with id = " + fromUserId); var toUser = CoreContext.UserManager.GetUsers(toUserId); @@ -1068,7 +1068,7 @@ namespace ASC.Employee.Core.Controllers if (toUser == null || toUser.ID == Constants.LostUser.ID) throw new ArgumentException("User with id = " + toUserId + " not found"); - if (toUser.IsVisitor() || toUser.Status == EmployeeStatus.Terminated) + if (toUser.IsVisitor(ApiContext.Tenant) || toUser.Status == EmployeeStatus.Terminated) throw new ArgumentException("Can not reassign data to user with id = " + toUserId); return QueueWorkerReassign.Start(TenantProvider.CurrentTenantID, fromUserId, toUserId, SecurityContext.CurrentAccount.ID, deleteProfile); @@ -1096,7 +1096,7 @@ namespace ASC.Employee.Core.Controllers [Read(@"remove/progress")] public RemoveProgressItem GetRemoveProgress(Guid userId) { - SecurityContext.DemandPermissions(Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditUser); return QueueWorkerRemove.GetProgressItemStatus(TenantProvider.CurrentTenantID, userId); } @@ -1104,7 +1104,7 @@ namespace ASC.Employee.Core.Controllers [Update(@"remove/terminate")] public void TerminateRemove(Guid userId) { - SecurityContext.DemandPermissions(Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditUser); QueueWorkerRemove.Terminate(TenantProvider.CurrentTenantID, userId); } @@ -1112,14 +1112,14 @@ namespace ASC.Employee.Core.Controllers [Create(@"remove/start")] public RemoveProgressItem StartRemove(Guid userId) { - SecurityContext.DemandPermissions(Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, Constants.Action_EditUser); var user = CoreContext.UserManager.GetUsers(userId); if (user == null || user.ID == Constants.LostUser.ID) throw new ArgumentException("User with id = " + userId + " not found"); - if (user.IsOwner() || user.IsMe() || user.Status != EmployeeStatus.Terminated) + if (user.IsOwner(ApiContext.Tenant) || user.IsMe() || user.Status != EmployeeStatus.Terminated) throw new ArgumentException("Can not delete user with id = " + userId); return QueueWorkerRemove.Start(TenantProvider.CurrentTenantID, user, SecurityContext.CurrentAccount.ID, true); @@ -1127,40 +1127,40 @@ namespace ASC.Employee.Core.Controllers #endregion - private static void UpdateDepartments(IEnumerable department, UserInfo user) + private void UpdateDepartments(IEnumerable department, UserInfo user) { - if (!SecurityContext.CheckPermissions(Constants.Action_EditGroups)) return; + if (!SecurityContext.CheckPermissions(ApiContext.Tenant, Constants.Action_EditGroups)) return; if (department == null) return; - var groups = CoreContext.UserManager.GetUserGroups(user.ID); + var groups = CoreContext.UserManager.GetUserGroups(ApiContext.Tenant, user.ID); var managerGroups = new List(); foreach (var groupInfo in groups) { - CoreContext.UserManager.RemoveUserFromGroup(user.ID, groupInfo.ID); - var managerId = CoreContext.UserManager.GetDepartmentManager(groupInfo.ID); + CoreContext.UserManager.RemoveUserFromGroup(ApiContext.Tenant, user.ID, groupInfo.ID); + var managerId = CoreContext.UserManager.GetDepartmentManager(ApiContext.Tenant.TenantId, groupInfo.ID); if (managerId == user.ID) { managerGroups.Add(groupInfo.ID); - CoreContext.UserManager.SetDepartmentManager(groupInfo.ID, Guid.Empty); + CoreContext.UserManager.SetDepartmentManager(ApiContext.Tenant.TenantId, groupInfo.ID, Guid.Empty); } } foreach (var guid in department) { - var userDepartment = CoreContext.UserManager.GetGroupInfo(guid); + var userDepartment = CoreContext.UserManager.GetGroupInfo(ApiContext.Tenant.TenantId, guid); if (userDepartment != Constants.LostGroupInfo) { - CoreContext.UserManager.AddUserIntoGroup(user.ID, guid); + CoreContext.UserManager.AddUserIntoGroup(ApiContext.Tenant, user.ID, guid); if (managerGroups.Contains(guid)) { - CoreContext.UserManager.SetDepartmentManager(guid, user.ID); + CoreContext.UserManager.SetDepartmentManager(ApiContext.Tenant.TenantId, guid, user.ID); } } } } - private static void UpdateContacts(IEnumerable contacts, UserInfo user) + private void UpdateContacts(IEnumerable contacts, UserInfo user) { - SecurityContext.DemandPermissions(new UserSecurityProvider(user.ID), Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, new UserSecurityProvider(user.ID), Constants.Action_EditUser); user.Contacts.Clear(); if (contacts == null) return; @@ -1171,9 +1171,9 @@ namespace ASC.Employee.Core.Controllers } } - private static void DeleteContacts(IEnumerable contacts, UserInfo user) + private void DeleteContacts(IEnumerable contacts, UserInfo user) { - SecurityContext.DemandPermissions(new UserSecurityProvider(user.ID), Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, new UserSecurityProvider(user.ID), Constants.Action_EditUser); if (contacts == null) return; foreach (var contact in contacts) @@ -1194,7 +1194,7 @@ namespace ASC.Employee.Core.Controllers return; } - SecurityContext.DemandPermissions(new UserSecurityProvider(user.ID), Constants.Action_EditUser); + SecurityContext.DemandPermissions(ApiContext.Tenant, new UserSecurityProvider(user.ID), Constants.Action_EditUser); if (!files.StartsWith("http://") && !files.StartsWith("https://")) { @@ -1205,7 +1205,7 @@ namespace ASC.Employee.Core.Controllers using var inputStream = response.GetResponseStream(); using var br = new BinaryReader(inputStream); var imageByteArray = br.ReadBytes((int)response.ContentLength); - UserPhotoManager.SaveOrUpdatePhoto(user.ID, imageByteArray); + UserPhotoManager.SaveOrUpdatePhoto(ApiContext.Tenant, user.ID, imageByteArray); } private static void CheckImgFormat(byte[] data) diff --git a/products/ASC.People/Server/JsonStringConverter.cs b/products/ASC.People/Server/JsonStringConverter.cs deleted file mode 100644 index f6d0656bf3..0000000000 --- a/products/ASC.People/Server/JsonStringConverter.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace ASC.People -{ - internal class JsonStringConverter - { - public JsonStringConverter() - { - } - } -} \ No newline at end of file diff --git a/products/ASC.People/Server/Models/EmployeeWraper.cs b/products/ASC.People/Server/Models/EmployeeWraper.cs index c69418f513..2bd72745d5 100644 --- a/products/ASC.People/Server/Models/EmployeeWraper.cs +++ b/products/ASC.People/Server/Models/EmployeeWraper.cs @@ -41,11 +41,6 @@ namespace ASC.Web.Api.Models { } - public EmployeeWraper(UserInfo userInfo) - : this(userInfo, null) - { - } - public EmployeeWraper(UserInfo userInfo, ApiContext httpContext) { Id = userInfo.ID; @@ -59,7 +54,13 @@ namespace ASC.Web.Api.Models if (httpContext.Check("avatarSmall")) { - AvatarSmall = UserPhotoManager.GetSmallPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + AvatarSmall = UserPhotoManager.GetSmallPhotoURL(httpContext.Tenant.TenantId, userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + } + + if (Id != Guid.Empty) + { + var profileUrl = CommonLinkUtility.GetUserProfile(Id, userInfo.Tenant, false); + ProfileUrl = CommonLinkUtility.GetFullAbsolutePath(httpContext.HttpContext, profileUrl); } } @@ -76,31 +77,23 @@ namespace ASC.Web.Api.Models public string AvatarSmall { get; set; } [DataMember(Order = 30)] - public string ProfileUrl - { - get - { - if (Id == Guid.Empty) return string.Empty; - var profileUrl = CommonLinkUtility.GetUserProfile(Id.ToString(), false); - return CommonLinkUtility.GetFullAbsolutePath(profileUrl); - } - } + public string ProfileUrl { get; set; } - public static EmployeeWraper Get(Guid userId) + public static EmployeeWraper Get(Guid userId, ApiContext context) { try { - return Get(CoreContext.UserManager.GetUsers(userId)); + return Get(CoreContext.UserManager.GetUsers(userId), context); } catch (Exception) { - return Get(Constants.LostUser); + return Get(Constants.LostUser, context); } } - public static EmployeeWraper Get(UserInfo userInfo) + public static EmployeeWraper Get(UserInfo userInfo, ApiContext context) { - return new EmployeeWraper(userInfo); + return new EmployeeWraper(userInfo, context); } public static EmployeeWraper GetSample() diff --git a/products/ASC.People/Server/Models/EmployeeWraperFull.cs b/products/ASC.People/Server/Models/EmployeeWraperFull.cs index 79a687fa97..da2085571a 100644 --- a/products/ASC.People/Server/Models/EmployeeWraperFull.cs +++ b/products/ASC.People/Server/Models/EmployeeWraperFull.cs @@ -124,16 +124,10 @@ namespace ASC.Web.Api.Models { } - public EmployeeWraperFull(UserInfo userInfo) - : this(userInfo, null) - { - } - public EmployeeWraperFull(UserInfo userInfo, ApiContext context) : base(userInfo, context) { UserName = userInfo.UserName; - IsVisitor = userInfo.IsVisitor(); FirstName = userInfo.FirstName; LastName = userInfo.LastName; Birthday = (ApiDateTime)userInfo.BirthDate; @@ -174,9 +168,11 @@ namespace ASC.Web.Api.Models if (context.Check("groups") || context.Check("department")) { - var groups = CoreContext.UserManager.GetUserGroups(userInfo.ID).Select(x => new GroupWrapperSummary(x)).ToList(); + var groups = CoreContext.UserManager.GetUserGroups(context.Tenant, userInfo.ID) + .Select(x => new GroupWrapperSummary(x, context)) + .ToList(); - if (groups.Any()) + if (groups.Count > 0) { Groups = groups; Department = string.Join(", ", Groups.Select(d => d.Name.HtmlEncode())); @@ -191,31 +187,30 @@ namespace ASC.Web.Api.Models if (context.Check("avatarMax")) { - AvatarMax = UserPhotoManager.GetMaxPhotoURL(userInfo.ID, out var isdef) + (isdef ? "": $"?_={userInfoLM}"); + AvatarMax = UserPhotoManager.GetMaxPhotoURL(context.Tenant.TenantId, userInfo.ID, out var isdef) + (isdef ? "": $"?_={userInfoLM}"); } if (context.Check("avatarMedium")) { - AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + AvatarMedium = UserPhotoManager.GetMediumPhotoURL(context.Tenant.TenantId, userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); } if (context.Check("avatar")) { - Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + Avatar = UserPhotoManager.GetBigPhotoURL(context.Tenant.TenantId, userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); } - IsAdmin = userInfo.IsAdmin(); - if (context.Check("listAdminModules")) { - var listAdminModules = userInfo.GetListAdminModules(); + var listAdminModules = userInfo.GetListAdminModules(context.Tenant); if (listAdminModules.Any()) ListAdminModules = listAdminModules; } - IsOwner = userInfo.IsOwner(); - + IsVisitor = userInfo.IsVisitor(context.Tenant); + IsAdmin = userInfo.IsAdmin(context.Tenant); + IsOwner = userInfo.IsOwner(context.Tenant); IsLDAP = userInfo.IsLDAP(); IsSSO = userInfo.IsSSO(); } @@ -237,22 +232,22 @@ namespace ASC.Web.Api.Models } } - public static EmployeeWraperFull GetFull(Guid userId) + public static EmployeeWraperFull GetFull(Guid userId, ApiContext context) { try { - return GetFull(CoreContext.UserManager.GetUsers(userId)); + return GetFull(CoreContext.UserManager.GetUsers(userId), context); } catch (Exception) { - return GetFull(ASC.Core.Users.Constants.LostUser); + return GetFull(ASC.Core.Users.Constants.LostUser, context); } } - public static EmployeeWraperFull GetFull(UserInfo userInfo) + public static EmployeeWraperFull GetFull(UserInfo userInfo, ApiContext context) { - return new EmployeeWraperFull(userInfo); + return new EmployeeWraperFull(userInfo, context); } public new static EmployeeWraperFull GetSample() diff --git a/products/ASC.People/Server/Models/GroupWrapperFull.cs b/products/ASC.People/Server/Models/GroupWrapperFull.cs index a8550ff076..348659dffc 100644 --- a/products/ASC.People/Server/Models/GroupWrapperFull.cs +++ b/products/ASC.People/Server/Models/GroupWrapperFull.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; +using ASC.Api.Core; using ASC.Core; using ASC.Core.Users; @@ -36,17 +37,17 @@ namespace ASC.Web.Api.Models [DataContract(Name = "group", Namespace = "")] public class GroupWrapperFull { - public GroupWrapperFull(GroupInfo group, bool includeMembers) + public GroupWrapperFull(GroupInfo group, bool includeMembers, ApiContext context) { Id = group.ID; Category = group.CategoryID; Parent = group.Parent != null ? group.Parent.ID : Guid.Empty; Name = group.Name; - Manager = EmployeeWraper.Get(CoreContext.UserManager.GetUsers(CoreContext.UserManager.GetDepartmentManager(group.ID))); + Manager = EmployeeWraper.Get(CoreContext.UserManager.GetUsers(CoreContext.UserManager.GetDepartmentManager(context.Tenant.TenantId, group.ID)), context); if (includeMembers) { - Members = new List(CoreContext.UserManager.GetUsersByGroup(group.ID).Select(EmployeeWraper.Get)); + Members = new List(CoreContext.UserManager.GetUsersByGroup(context.Tenant, group.ID).Select(r=> EmployeeWraper.Get(r, context))); } } diff --git a/products/ASC.People/Server/Models/GroupWrapperSummary.cs b/products/ASC.People/Server/Models/GroupWrapperSummary.cs index e1373fbfde..bbccf7ffc6 100644 --- a/products/ASC.People/Server/Models/GroupWrapperSummary.cs +++ b/products/ASC.People/Server/Models/GroupWrapperSummary.cs @@ -26,6 +26,7 @@ using System; using System.Runtime.Serialization; +using ASC.Api.Core; using ASC.Core; using ASC.Core.Users; @@ -34,11 +35,11 @@ namespace ASC.Web.Api.Models [DataContract(Name = "group", Namespace = "")] public class GroupWrapperSummary { - public GroupWrapperSummary(GroupInfo group) + public GroupWrapperSummary(GroupInfo group, ApiContext context) { Id = group.ID; Name = group.Name; - Manager = CoreContext.UserManager.GetUsers(CoreContext.UserManager.GetDepartmentManager(group.ID)).UserName; + Manager = CoreContext.UserManager.GetUsers(CoreContext.UserManager.GetDepartmentManager(context.Tenant.TenantId, group.ID)).UserName; } protected GroupWrapperSummary() diff --git a/products/ASC.People/Server/Models/ThumbnailsDataWrapper.cs b/products/ASC.People/Server/Models/ThumbnailsDataWrapper.cs index 5e93fbaadb..56c07580b6 100644 --- a/products/ASC.People/Server/Models/ThumbnailsDataWrapper.cs +++ b/products/ASC.People/Server/Models/ThumbnailsDataWrapper.cs @@ -26,6 +26,7 @@ using System; using System.Runtime.Serialization; +using ASC.Core.Tenants; using ASC.Web.Core.Users; namespace ASC.Web.Api.Models @@ -33,14 +34,14 @@ namespace ASC.Web.Api.Models [DataContract] public class ThumbnailsDataWrapper { - public ThumbnailsDataWrapper(Guid userId) + public ThumbnailsDataWrapper(Tenant tenant, Guid userId) { - Original = UserPhotoManager.GetPhotoAbsoluteWebPath(userId); - Retina = UserPhotoManager.GetRetinaPhotoURL(userId); - Max = UserPhotoManager.GetMaxPhotoURL(userId); - Big = UserPhotoManager.GetBigPhotoURL(userId); - Medium = UserPhotoManager.GetMediumPhotoURL(userId); - Small = UserPhotoManager.GetSmallPhotoURL(userId); + Original = UserPhotoManager.GetPhotoAbsoluteWebPath(tenant, userId); + Retina = UserPhotoManager.GetRetinaPhotoURL(tenant.TenantId, userId); + Max = UserPhotoManager.GetMaxPhotoURL(tenant.TenantId, userId); + Big = UserPhotoManager.GetBigPhotoURL(tenant.TenantId, userId); + Medium = UserPhotoManager.GetMediumPhotoURL(tenant.TenantId, userId); + Small = UserPhotoManager.GetSmallPhotoURL(tenant.TenantId, userId); } private ThumbnailsDataWrapper() diff --git a/web/ASC.Web.Api/Controllers/AuthenticationController.cs b/web/ASC.Web.Api/Controllers/AuthenticationController.cs index 9899b109a3..4d7b225d0e 100644 --- a/web/ASC.Web.Api/Controllers/AuthenticationController.cs +++ b/web/ASC.Web.Api/Controllers/AuthenticationController.cs @@ -18,13 +18,13 @@ namespace ASC.Web.Api.Controllers [Create(false)] public AuthenticationTokenData AuthenticateMe([FromBody]AuthModel auth) { - var user = GetUser(auth.UserName, auth.Password); + var tenant = CoreContext.TenantManager.GetCurrentTenant(); + var user = GetUser(tenant.TenantId, auth.UserName, auth.Password); try { var token = SecurityContext.AuthenticateMe(user.ID); - var tenant = CoreContext.TenantManager.GetCurrentTenant().TenantId; - var expires = TenantCookieSettings.GetExpiresTime(tenant); + var expires = TenantCookieSettings.GetExpiresTime(tenant.TenantId); return new AuthenticationTokenData { @@ -38,14 +38,14 @@ namespace ASC.Web.Api.Controllers } } - private static UserInfo GetUser(string userName, string password) + private static UserInfo GetUser(int tenantId, string userName, string password) { var user = CoreContext.UserManager.GetUsers( - CoreContext.TenantManager.GetCurrentTenant().TenantId, + tenantId, userName, Hasher.Base64Hash(password, HashAlg.SHA256)); - if (user == null || !CoreContext.UserManager.UserExists(user.ID)) + if (user == null || !CoreContext.UserManager.UserExists(user.ID, tenantId)) { throw new Exception("user not found"); } diff --git a/web/ASC.Web.Api/Controllers/ModulesController.cs b/web/ASC.Web.Api/Controllers/ModulesController.cs index 138784f3c9..d5dc1076ba 100644 --- a/web/ASC.Web.Api/Controllers/ModulesController.cs +++ b/web/ASC.Web.Api/Controllers/ModulesController.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using ASC.Core; using ASC.Web.Api.Routing; using ASC.Web.Core; using ASC.Web.Core.WebZones; @@ -15,7 +16,7 @@ namespace ASC.Web.Api.Controllers { var result = new List(); - foreach (var a in WebItemManager.Instance.GetItems(WebZoneType.StartProductList)) + foreach (var a in WebItemManager.Instance.GetItems(CoreContext.TenantManager.GetCurrentTenant(), WebZoneType.StartProductList)) { result.Add(a.ApiURL); } diff --git a/web/ASC.Web.Core/Calendars/CalendarManager.cs b/web/ASC.Web.Core/Calendars/CalendarManager.cs index 8becdb1b7c..d8f7429e0f 100644 --- a/web/ASC.Web.Core/Calendars/CalendarManager.cs +++ b/web/ASC.Web.Core/Calendars/CalendarManager.cs @@ -26,6 +26,7 @@ using System; using System.Collections.Generic; +using ASC.Core.Tenants; namespace ASC.Web.Core.Calendars { @@ -87,22 +88,22 @@ namespace ASC.Web.Core.Calendars } } - public BaseCalendar GetCalendarForUser(Guid userId, string calendarId) + public BaseCalendar GetCalendarForUser(Tenant tenant, Guid userId, string calendarId) { - return GetCalendarsForUser(userId).Find(c=> String.Equals(c.Id, calendarId, StringComparison.InvariantCultureIgnoreCase)); + return GetCalendarsForUser(tenant, userId).Find(c=> String.Equals(c.Id, calendarId, StringComparison.InvariantCultureIgnoreCase)); } - public List GetCalendarsForUser(Guid userId) + public List GetCalendarsForUser(Tenant tenant, Guid userId) { var cals = new List(); foreach (var h in _calendarProviders) { var list = h(userId); if(list!=null) - cals.AddRange(list.FindAll(c => c.SharingOptions.PublicForItem(userId))); + cals.AddRange(list.FindAll(c => c.SharingOptions.PublicForItem(tenant, userId))); } - cals.AddRange(_calendars.FindAll(c => c.SharingOptions.PublicForItem(userId))); + cals.AddRange(_calendars.FindAll(c => c.SharingOptions.PublicForItem(tenant, userId))); return cals; } diff --git a/web/ASC.Web.Core/Calendars/SharingOptions.cs b/web/ASC.Web.Core/Calendars/SharingOptions.cs index 780ecb13fc..5108771266 100644 --- a/web/ASC.Web.Core/Calendars/SharingOptions.cs +++ b/web/ASC.Web.Core/Calendars/SharingOptions.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.Runtime.Serialization; using ASC.Core; +using ASC.Core.Tenants; using ASC.Core.Users; namespace ASC.Web.Core.Calendars @@ -50,7 +51,7 @@ namespace ASC.Web.Core.Calendars this.PublicItems = new List(); } - public bool PublicForItem(Guid itemId) + public bool PublicForItem(Tenant tenant, Guid itemId) { if (SharedForAll) return true; @@ -61,8 +62,8 @@ namespace ASC.Web.Core.Calendars var u = CoreContext.UserManager.GetUsers(itemId); if(u!=null && u.ID!= ASC.Core.Users.Constants.LostUser.ID) { - var userGroups = new List(CoreContext.UserManager.GetUserGroups(itemId)); - userGroups.AddRange(CoreContext.UserManager.GetUserGroups(itemId, Constants.SysGroupCategoryId)); + var userGroups = new List(CoreContext.UserManager.GetUserGroups(tenant, itemId)); + userGroups.AddRange(CoreContext.UserManager.GetUserGroups(tenant, itemId, Constants.SysGroupCategoryId)); return userGroups.Exists(g => PublicItems.Exists(i => i.Id.Equals(g.ID))); } diff --git a/web/ASC.Web.Core/CookiesManager.cs b/web/ASC.Web.Core/CookiesManager.cs index f077a98cd2..8b7c69c2ba 100644 --- a/web/ASC.Web.Core/CookiesManager.cs +++ b/web/ASC.Web.Core/CookiesManager.cs @@ -150,13 +150,13 @@ namespace ASC.Web.Core public static void SetLifeTime(this HttpContext httpContext, int lifeTime) { - if (!CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID)) + var tenant = CoreContext.TenantManager.GetCurrentTenant(); + if (!CoreContext.UserManager.IsUserInGroup(tenant, SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID)) { throw new SecurityException(); } - var tenant = TenantProvider.CurrentTenantID; - var settings = TenantCookieSettings.GetForTenant(tenant); + var settings = TenantCookieSettings.GetForTenant(tenant.TenantId); if (lifeTime > 0) { @@ -168,7 +168,7 @@ namespace ASC.Web.Core settings.LifeTime = 0; } - TenantCookieSettings.SetForTenant(tenant, settings); + TenantCookieSettings.SetForTenant(tenant.TenantId, settings); var cookie = SecurityContext.AuthenticateMe(SecurityContext.CurrentAccount.ID); @@ -196,15 +196,16 @@ namespace ASC.Web.Core public static void ResetTenantCookie(this HttpContext httpContext) { - if (!CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID)) + var tenant = CoreContext.TenantManager.GetCurrentTenant(); + + if (!CoreContext.UserManager.IsUserInGroup(tenant, SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID)) { throw new SecurityException(); } - var tenant = TenantProvider.CurrentTenantID; - var settings = TenantCookieSettings.GetForTenant(tenant); + var settings = TenantCookieSettings.GetForTenant(tenant.TenantId); settings.Index = settings.Index + 1; - TenantCookieSettings.SetForTenant(tenant, settings); + TenantCookieSettings.SetForTenant(tenant.TenantId, settings); var cookie = SecurityContext.AuthenticateMe(SecurityContext.CurrentAccount.ID); httpContext.SetCookies(CookiesType.AuthKey, cookie); diff --git a/web/ASC.Web.Core/Extensions/UserInfoExtension.cs b/web/ASC.Web.Core/Extensions/UserInfoExtension.cs index b3d721cf73..a3703a8a7b 100644 --- a/web/ASC.Web.Core/Extensions/UserInfoExtension.cs +++ b/web/ASC.Web.Core/Extensions/UserInfoExtension.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Text; +using ASC.Core.Tenants; using ASC.Web.Core.Users; using ASC.Web.Studio.Utility; @@ -54,52 +55,52 @@ namespace ASC.Core.Users return users; } - public static bool HasAvatar(this UserInfo userInfo) + public static bool HasAvatar(this UserInfo userInfo, Tenant tenant) { - return UserPhotoManager.UserHasAvatar(userInfo.ID); + return UserPhotoManager.UserHasAvatar(tenant, userInfo.ID); } - public static Size GetPhotoSize(this UserInfo userInfo) + public static Size GetPhotoSize(this UserInfo userInfo, Tenant tenant) { - return UserPhotoManager.GetPhotoSize(userInfo.ID); + return UserPhotoManager.GetPhotoSize(tenant, userInfo.ID); } - public static string GetPhotoURL(this UserInfo userInfo) + public static string GetPhotoURL(this UserInfo userInfo, Tenant tenant) { - return UserPhotoManager.GetPhotoAbsoluteWebPath(userInfo.ID); + return UserPhotoManager.GetPhotoAbsoluteWebPath(tenant, userInfo.ID); } - public static string GetRetinaPhotoURL(this UserInfo userInfo) + public static string GetRetinaPhotoURL(this UserInfo userInfo, int tenantId) { - return UserPhotoManager.GetRetinaPhotoURL(userInfo.ID); + return UserPhotoManager.GetRetinaPhotoURL(tenantId, userInfo.ID); } - public static string GetMaxPhotoURL(this UserInfo userInfo) + public static string GetMaxPhotoURL(this UserInfo userInfo, int tenantId) { - return UserPhotoManager.GetMaxPhotoURL(userInfo.ID); + return UserPhotoManager.GetMaxPhotoURL(tenantId, userInfo.ID); } - public static string GetBigPhotoURL(this UserInfo userInfo) + public static string GetBigPhotoURL(this UserInfo userInfo, int tenantId) { - return UserPhotoManager.GetBigPhotoURL(userInfo.ID); + return UserPhotoManager.GetBigPhotoURL(tenantId, userInfo.ID); } - public static string GetMediumPhotoURL(this UserInfo userInfo) + public static string GetMediumPhotoURL(this UserInfo userInfo, int tenantId) { - return UserPhotoManager.GetMediumPhotoURL(userInfo.ID); + return UserPhotoManager.GetMediumPhotoURL(tenantId, userInfo.ID); } - public static string GetSmallPhotoURL(this UserInfo userInfo) + public static string GetSmallPhotoURL(this UserInfo userInfo, int tenantId) { - return UserPhotoManager.GetSmallPhotoURL(userInfo.ID); + return UserPhotoManager.GetSmallPhotoURL(tenantId, userInfo.ID); } - public static string RenderProfileLinkBase(this UserInfo userInfo) + public static string RenderProfileLinkBase(this UserInfo userInfo, Tenant tenant) { var sb = new StringBuilder(); //check for removed users - if (userInfo == null || !CoreContext.UserManager.UserExists(userInfo.ID)) + if (userInfo == null || !CoreContext.UserManager.UserExists(userInfo.ID, tenant.TenantId)) { sb.Append("profile removed"); } diff --git a/web/ASC.Web.Core/Extensions/WebItemExtension.cs b/web/ASC.Web.Core/Extensions/WebItemExtension.cs index 19e8917745..314a7dd1d3 100644 --- a/web/ASC.Web.Core/Extensions/WebItemExtension.cs +++ b/web/ASC.Web.Core/Extensions/WebItemExtension.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.Linq; using ASC.Core; +using ASC.Core.Tenants; using ASC.Web.Core.Utility.Skins; namespace ASC.Web.Core @@ -111,14 +112,14 @@ namespace ASC.Web.Core } - public static bool IsDisabled(this IWebItem item) + public static bool IsDisabled(this IWebItem item, Tenant tenant) { - return IsDisabled(item, SecurityContext.CurrentAccount.ID); + return item.IsDisabled(tenant, SecurityContext.CurrentAccount.ID); } - public static bool IsDisabled(this IWebItem item, Guid userID) + public static bool IsDisabled(this IWebItem item, Tenant tenant, Guid userID) { - return item != null && (!WebItemSecurity.IsAvailableForUser(item.ID, userID) || !item.Visible); + return item != null && (!WebItemSecurity.IsAvailableForUser(tenant, item.ID, userID) || !item.Visible); } public static bool IsSubItem(this IWebItem item) diff --git a/web/ASC.Web.Core/Helpers/AuthorizationHelper.cs b/web/ASC.Web.Core/Helpers/AuthorizationHelper.cs index a9c6792e15..11410b389a 100644 --- a/web/ASC.Web.Core/Helpers/AuthorizationHelper.cs +++ b/web/ASC.Web.Core/Helpers/AuthorizationHelper.cs @@ -57,7 +57,7 @@ namespace ASC.Web.Core.Helpers 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); + var u = CoreContext.UserManager.GetUserByEmail(CoreContext.TenantManager.GetCurrentTenant().TenantId, username); if (u != null && u.ID != ASC.Core.Users.Constants.LostUser.ID) { authCookie = SecurityContext.AuthenticateMe(u.Email, password); diff --git a/web/ASC.Web.Core/Mail/MailServiceHelper.cs b/web/ASC.Web.Core/Mail/MailServiceHelper.cs index 9a7258c63c..f790922fa3 100644 --- a/web/ASC.Web.Core/Mail/MailServiceHelper.cs +++ b/web/ASC.Web.Core/Mail/MailServiceHelper.cs @@ -90,7 +90,7 @@ namespace ASC.Web.Core.Mail if (!CoreContext.Configuration.Standalone) throw new NotSupportedException("Method for server edition only."); - if (!CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID)) + if (!CoreContext.UserManager.IsUserInGroup(CoreContext.TenantManager.GetCurrentTenant(), SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID)) throw new SecurityException(); } diff --git a/web/ASC.Web.Core/Notify/NotifyConfiguration.cs b/web/ASC.Web.Core/Notify/NotifyConfiguration.cs index e8900f1a17..bc7caf6159 100644 --- a/web/ASC.Web.Core/Notify/NotifyConfiguration.cs +++ b/web/ASC.Web.Core/Notify/NotifyConfiguration.cs @@ -124,6 +124,7 @@ namespace ASC.Web.Studio.Core.Notify { // culture var u = Constants.LostUser; + var tenant = CoreContext.TenantManager.GetCurrentTenant(); if (32 <= r.Recipient.ID.Length) { @@ -135,25 +136,25 @@ namespace ASC.Web.Studio.Core.Notify catch (FormatException) { } catch (OverflowException) { } - if (guid != default(Guid)) + if (guid != default) { - u = CoreContext.UserManager.GetUsers(guid); + u = CoreContext.UserManager.GetUsers(guid, tenant.TenantId); } } if (Constants.LostUser.Equals(u)) { - u = CoreContext.UserManager.GetUserByEmail(r.Recipient.ID); + u = CoreContext.UserManager.GetUserByEmail(tenant.TenantId, r.Recipient.ID); } if (Constants.LostUser.Equals(u)) { - u = CoreContext.UserManager.GetUserByUserName(r.Recipient.ID); + u = CoreContext.UserManager.GetUserByUserName(tenant.TenantId, r.Recipient.ID); } if (!Constants.LostUser.Equals(u)) { - var culture = !string.IsNullOrEmpty(u.CultureName) ? u.GetCulture() : CoreContext.TenantManager.GetCurrentTenant().GetCulture(); + var culture = !string.IsNullOrEmpty(u.CultureName) ? u.GetCulture() : tenant.GetCulture(); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; @@ -171,7 +172,7 @@ namespace ASC.Web.Studio.Core.Notify } if (productId != Guid.Empty && productId != new Guid("f4d98afdd336433287783c6945c81ea0") /* ignore people product */) { - return !WebItemSecurity.IsAvailableForUser(productId, u.ID); + return !WebItemSecurity.IsAvailableForUser(tenant, productId, u.ID); } } @@ -230,10 +231,12 @@ namespace ASC.Web.Studio.Core.Notify { var aid = Guid.Empty; var aname = string.Empty; + var tenant = CoreContext.TenantManager.GetCurrentTenant(); + if (SecurityContext.IsAuthenticated) { aid = SecurityContext.CurrentAccount.ID; - if (CoreContext.UserManager.UserExists(aid)) + if (CoreContext.UserManager.UserExists(aid, tenant.TenantId)) { aname = CoreContext.UserManager.GetUsers(aid).DisplayUserName(false) .Replace(">", ">") @@ -244,7 +247,7 @@ namespace ASC.Web.Studio.Core.Notify IProduct product; IModule module; //TODOL httpContext - CommonLinkUtility.GetLocationByRequest(out product, out module, null); + CommonLinkUtility.GetLocationByRequest(tenant, out product, out module, null); if (product == null && CallContext.GetData("asc.web.product_id") != null) { product = WebItemManager.Instance[(Guid)CallContext.GetData("asc.web.product_id")] as IProduct; diff --git a/web/ASC.Web.Core/Notify/StudioNotifyHelper.cs b/web/ASC.Web.Core/Notify/StudioNotifyHelper.cs index 5d05f1ebcf..a2c38689b0 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyHelper.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyHelper.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.Linq; using ASC.Core; +using ASC.Core.Tenants; using ASC.Core.Users; using ASC.Notify.Model; using ASC.Notify.Recipients; @@ -55,45 +56,45 @@ namespace ASC.Web.Studio.Core.Notify } - public static IEnumerable GetRecipients(bool toadmins, bool tousers, bool toguests) + public static IEnumerable GetRecipients(Tenant tenant, bool toadmins, bool tousers, bool toguests) { if (toadmins) { if (tousers) { if (toguests) - return CoreContext.UserManager.GetUsers(); + return CoreContext.UserManager.GetUsers(tenant); - return CoreContext.UserManager.GetUsers(EmployeeStatus.Default, EmployeeType.User); + return CoreContext.UserManager.GetUsers(tenant, EmployeeStatus.Default, EmployeeType.User); } if (toguests) return - CoreContext.UserManager.GetUsersByGroup(Constants.GroupAdmin.ID) - .Concat(CoreContext.UserManager.GetUsers(EmployeeStatus.Default, EmployeeType.Visitor)); + CoreContext.UserManager.GetUsersByGroup(tenant, Constants.GroupAdmin.ID) + .Concat(CoreContext.UserManager.GetUsers(tenant, EmployeeStatus.Default, EmployeeType.Visitor)); - return CoreContext.UserManager.GetUsersByGroup(Constants.GroupAdmin.ID); + return CoreContext.UserManager.GetUsersByGroup(tenant, Constants.GroupAdmin.ID); } if (tousers) { if (toguests) - return CoreContext.UserManager.GetUsers() - .Where(u => !CoreContext.UserManager.IsUserInGroup(u.ID, Constants.GroupAdmin.ID)); + return CoreContext.UserManager.GetUsers(tenant) + .Where(u => !CoreContext.UserManager.IsUserInGroup(tenant, u.ID, Constants.GroupAdmin.ID)); - return CoreContext.UserManager.GetUsers(EmployeeStatus.Default, EmployeeType.User) - .Where(u => !CoreContext.UserManager.IsUserInGroup(u.ID, Constants.GroupAdmin.ID)); + return CoreContext.UserManager.GetUsers(tenant, EmployeeStatus.Default, EmployeeType.User) + .Where(u => !CoreContext.UserManager.IsUserInGroup(tenant, u.ID, Constants.GroupAdmin.ID)); } if (toguests) - return CoreContext.UserManager.GetUsers(EmployeeStatus.Default, EmployeeType.Visitor); + return CoreContext.UserManager.GetUsers(tenant, EmployeeStatus.Default, EmployeeType.Visitor); return new List(); } - public static IRecipient ToRecipient(Guid userId) + public static IRecipient ToRecipient(int tenantId, Guid userId) { - return RecipientsProvider.GetRecipient(userId.ToString()); + return RecipientsProvider.GetRecipient(tenantId, userId.ToString()); } public static IRecipient[] RecipientFromEmail(string email, bool checkActivation) @@ -136,19 +137,19 @@ namespace ASC.Web.Studio.Core.Notify } - public static bool IsSubscribedToNotify(Guid userId, INotifyAction notifyAction) + public static bool IsSubscribedToNotify(Tenant tenant, Guid userId, INotifyAction notifyAction) { - return IsSubscribedToNotify(ToRecipient(userId), notifyAction); + return IsSubscribedToNotify(tenant, ToRecipient(tenant.TenantId, userId), notifyAction); } - public static bool IsSubscribedToNotify(IRecipient recipient, INotifyAction notifyAction) + public static bool IsSubscribedToNotify(Tenant tenant, IRecipient recipient, INotifyAction notifyAction) { - return recipient != null && SubscriptionProvider.IsSubscribed(notifyAction, recipient, null); + return recipient != null && SubscriptionProvider.IsSubscribed(tenant, notifyAction, recipient, null); } - public static void SubscribeToNotify(Guid userId, INotifyAction notifyAction, bool subscribe) + public static void SubscribeToNotify(int tenantId, Guid userId, INotifyAction notifyAction, bool subscribe) { - SubscribeToNotify(ToRecipient(userId), notifyAction, subscribe); + SubscribeToNotify(ToRecipient(tenantId, userId), notifyAction, subscribe); } public static void SubscribeToNotify(IRecipient recipient, INotifyAction notifyAction, bool subscribe) diff --git a/web/ASC.Web.Core/Notify/StudioNotifyService.cs b/web/ASC.Web.Core/Notify/StudioNotifyService.cs index a841b8c3fa..0dd92e23a6 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyService.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyService.cs @@ -58,14 +58,14 @@ namespace ASC.Web.Studio.Core.Notify client = new StudioNotifyServiceHelper(); } - public void SendMsgToAdminAboutProfileUpdated() + public void SendMsgToAdminAboutProfileUpdated(int tenantId) { - client.SendNoticeAsync(Actions.SelfProfileUpdated, null); + client.SendNoticeAsync(tenantId, Actions.SelfProfileUpdated, null); } - public void SendMsgToAdminFromNotAuthUser(string email, string message) + public void SendMsgToAdminFromNotAuthUser(int tenantId, string email, string message) { - client.SendNoticeAsync(Actions.UserMessageToAdmin, null, new TagValue(Tags.Body, message), new TagValue(Tags.UserEmail, email)); + client.SendNoticeAsync(tenantId, Actions.UserMessageToAdmin, null, new TagValue(Tags.Body, message), new TagValue(Tags.UserEmail, email)); } public void SendRequestTariff(bool license, string fname, string lname, string title, string email, string phone, string ctitle, string csize, string site, string message) @@ -107,14 +107,14 @@ namespace ASC.Web.Studio.Core.Notify #region Voip - public void SendToAdminVoipWarning(double balance) + public void SendToAdminVoipWarning(int tenantId, double balance) { - client.SendNoticeAsync(Actions.VoipWarning, null, new TagValue(Tags.Body, balance)); + client.SendNoticeAsync(tenantId, Actions.VoipWarning, null, new TagValue(Tags.Body, balance)); } - public void SendToAdminVoipBlocked() + public void SendToAdminVoipBlocked(int tenantId) { - client.SendNoticeAsync(Actions.VoipBlocked, null); + client.SendNoticeAsync(tenantId, Actions.VoipBlocked, null); } #endregion @@ -263,9 +263,9 @@ namespace ASC.Web.Studio.Core.Notify } - public void UserHasJoin() + public void UserHasJoin(int tenantId) { - client.SendNoticeAsync(Actions.UserHasJoin, null); + client.SendNoticeAsync(tenantId, Actions.UserHasJoin, null); } public void SendJoinMsg(string email, EmployeeType emplType) @@ -284,9 +284,9 @@ namespace ASC.Web.Studio.Core.Notify TagValues.SendFrom()); } - public void UserInfoAddedAfterInvite(UserInfo newUserInfo) + public void UserInfoAddedAfterInvite(int tenantId, UserInfo newUserInfo) { - if (!CoreContext.UserManager.UserExists(newUserInfo.ID)) return; + if (!CoreContext.UserManager.UserExists(newUserInfo.ID, tenantId)) return; INotifyAction notifyAction; var footer = "social"; @@ -338,9 +338,9 @@ namespace ASC.Web.Studio.Core.Notify new TagValue(CommonTags.Analytics, analytics)); } - public void GuestInfoAddedAfterInvite(UserInfo newUserInfo) + public void GuestInfoAddedAfterInvite(int tenantId, UserInfo newUserInfo) { - if (!CoreContext.UserManager.UserExists(newUserInfo.ID)) return; + if (!CoreContext.UserManager.UserExists(newUserInfo.ID, tenantId)) return; INotifyAction notifyAction; var analytics = string.Empty; @@ -466,11 +466,11 @@ namespace ASC.Web.Studio.Core.Notify new TagValue(CommonTags.Culture, user.GetCulture().Name)); } - public void SendMsgReassignsCompleted(Guid recipientId, UserInfo fromUser, UserInfo toUser) + public void SendMsgReassignsCompleted(int tenantId, Guid recipientId, UserInfo fromUser, UserInfo toUser) { client.SendNoticeToAsync( Actions.ReassignsCompleted, - new[] { StudioNotifyHelper.ToRecipient(recipientId) }, + new[] { StudioNotifyHelper.ToRecipient(tenantId, recipientId) }, new[] { EMailSenderName }, new TagValue(Tags.UserName, DisplayUserSettings.GetFullUserName(recipientId)), new TagValue(Tags.FromUserName, fromUser.DisplayUserName()), @@ -479,11 +479,11 @@ namespace ASC.Web.Studio.Core.Notify new TagValue(Tags.ToUserLink, GetUserProfileLink(toUser.ID))); } - public void SendMsgReassignsFailed(Guid recipientId, UserInfo fromUser, UserInfo toUser, string message) + public void SendMsgReassignsFailed(int tenantId, Guid recipientId, UserInfo fromUser, UserInfo toUser, string message) { client.SendNoticeToAsync( Actions.ReassignsFailed, - new[] { StudioNotifyHelper.ToRecipient(recipientId) }, + new[] { StudioNotifyHelper.ToRecipient(tenantId, recipientId) }, new[] { EMailSenderName }, new TagValue(Tags.UserName, DisplayUserSettings.GetFullUserName(recipientId)), new TagValue(Tags.FromUserName, fromUser.DisplayUserName()), @@ -493,11 +493,11 @@ namespace ASC.Web.Studio.Core.Notify new TagValue(Tags.Message, message)); } - public void SendMsgRemoveUserDataCompleted(Guid recipientId, Guid fromUserId, string fromUserName, long docsSpace, long crmSpace, long mailSpace, long talkSpace) + public void SendMsgRemoveUserDataCompleted(int tenantId, Guid recipientId, Guid fromUserId, string fromUserName, long docsSpace, long crmSpace, long mailSpace, long talkSpace) { client.SendNoticeToAsync( CoreContext.Configuration.CustomMode ? Actions.RemoveUserDataCompletedCustomMode : Actions.RemoveUserDataCompleted, - new[] { StudioNotifyHelper.ToRecipient(recipientId) }, + new[] { StudioNotifyHelper.ToRecipient(tenantId, recipientId) }, new[] { EMailSenderName }, new TagValue(Tags.UserName, DisplayUserSettings.GetFullUserName(recipientId)), new TagValue(Tags.FromUserName, fromUserName.HtmlEncode()), @@ -508,11 +508,11 @@ namespace ASC.Web.Studio.Core.Notify new TagValue("TalkSpace", FileSizeComment.FilesSizeToString(talkSpace))); } - public void SendMsgRemoveUserDataFailed(Guid recipientId, Guid fromUserId, string fromUserName, string message) + public void SendMsgRemoveUserDataFailed(int tenantId, Guid recipientId, Guid fromUserId, string fromUserName, string message) { client.SendNoticeToAsync( Actions.RemoveUserDataFailed, - new[] { StudioNotifyHelper.ToRecipient(recipientId) }, + new[] { StudioNotifyHelper.ToRecipient(tenantId, recipientId) }, new[] { EMailSenderName }, new TagValue(Tags.UserName, DisplayUserSettings.GetFullUserName(recipientId)), new TagValue(Tags.FromUserName, fromUserName.HtmlEncode()), @@ -520,9 +520,9 @@ namespace ASC.Web.Studio.Core.Notify new TagValue(Tags.Message, message)); } - public void SendAdminWelcome(UserInfo newUserInfo) + public void SendAdminWelcome(UserInfo newUserInfo, int tenantId) { - if (!CoreContext.UserManager.UserExists(newUserInfo.ID)) return; + if (!CoreContext.UserManager.UserExists(newUserInfo.ID, tenantId)) return; if (!newUserInfo.IsActive) throw new ArgumentException("User is not activated yet!"); @@ -572,21 +572,21 @@ namespace ASC.Web.Studio.Core.Notify #region Backup & Restore - public void SendMsgBackupCompleted(Guid userId, string link) + public void SendMsgBackupCompleted(int tenantId, Guid userId, string link) { client.SendNoticeToAsync( Actions.BackupCreated, - new[] { StudioNotifyHelper.ToRecipient(userId) }, + new[] { StudioNotifyHelper.ToRecipient(tenantId, userId) }, new[] {EMailSenderName}, new TagValue(Tags.OwnerName, CoreContext.UserManager.GetUsers(userId).DisplayUserName())); } - public void SendMsgRestoreStarted(bool notifyAllUsers) + public void SendMsgRestoreStarted(Tenant tenant, bool notifyAllUsers) { - var owner = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId); + var owner = CoreContext.UserManager.GetUsers(tenant.OwnerId); var users = notifyAllUsers - ? StudioNotifyHelper.RecipientFromEmail(CoreContext.UserManager.GetUsers(EmployeeStatus.Active).Where(r => r.ActivationStatus == EmployeeActivationStatus.Activated).Select(u => u.Email).ToArray(), false) + ? StudioNotifyHelper.RecipientFromEmail(CoreContext.UserManager.GetUsers(tenant, EmployeeStatus.Active).Where(r => r.ActivationStatus == EmployeeActivationStatus.Activated).Select(u => u.Email).ToArray(), false) : owner.ActivationStatus == EmployeeActivationStatus.Activated ? StudioNotifyHelper.RecipientFromEmail(owner.Email, false) : new IDirectRecipient[0]; client.SendNoticeToAsync( @@ -595,14 +595,14 @@ namespace ASC.Web.Studio.Core.Notify new[] { EMailSenderName }); } - public void SendMsgRestoreCompleted(bool notifyAllUsers) + public void SendMsgRestoreCompleted(Tenant tenant, bool notifyAllUsers) { var owner = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId); var users = notifyAllUsers - ? CoreContext.UserManager.GetUsers(EmployeeStatus.Active).Select(u => StudioNotifyHelper.ToRecipient(u.ID)).ToArray() - : new[] { StudioNotifyHelper.ToRecipient(owner.ID) }; + ? CoreContext.UserManager.GetUsers(tenant, EmployeeStatus.Active).Select(u => StudioNotifyHelper.ToRecipient(tenant.TenantId, u.ID)).ToArray() + : new[] { StudioNotifyHelper.ToRecipient(tenant.TenantId, owner.ID) }; client.SendNoticeToAsync( Actions.RestoreCompleted, @@ -741,10 +741,10 @@ namespace ASC.Web.Studio.Core.Notify #region Personal - public void SendInvitePersonal(string email, string additionalMember = "", bool analytics = true) + public void SendInvitePersonal(int tenantId, string email, string additionalMember = "", bool analytics = true) { - var newUserInfo = CoreContext.UserManager.GetUserByEmail(email); - if (CoreContext.UserManager.UserExists(newUserInfo.ID)) return; + var newUserInfo = CoreContext.UserManager.GetUserByEmail(tenantId, email); + if (CoreContext.UserManager.UserExists(newUserInfo.ID, tenantId)) return; var lang = CoreContext.Configuration.CustomMode ? "ru-RU" @@ -780,26 +780,26 @@ namespace ASC.Web.Studio.Core.Notify #region Migration Portal - public void MigrationPortalStart(string region, bool notify) + public void MigrationPortalStart(Tenant tenant, string region, bool notify) { - MigrationNotify(Actions.MigrationPortalStart, region, string.Empty, notify); + MigrationNotify(tenant, Actions.MigrationPortalStart, region, string.Empty, notify); } - public void MigrationPortalSuccess(string region, string url, bool notify) + public void MigrationPortalSuccess(Tenant tenant, string region, string url, bool notify) { - MigrationNotify(Actions.MigrationPortalSuccess, region, url, notify); + MigrationNotify(tenant, Actions.MigrationPortalSuccess, region, url, notify); } - public void MigrationPortalError(string region, string url, bool notify) + public void MigrationPortalError(Tenant tenant, string region, string url, bool notify) { - MigrationNotify(!string.IsNullOrEmpty(region) ? Actions.MigrationPortalError : Actions.MigrationPortalServerFailure, region, url, notify); + MigrationNotify(tenant, !string.IsNullOrEmpty(region) ? Actions.MigrationPortalError : Actions.MigrationPortalServerFailure, region, url, notify); } - private void MigrationNotify(INotifyAction action, string region, string url, bool notify) + private void MigrationNotify(Tenant tenant, INotifyAction action, string region, string url, bool notify) { - var users = CoreContext.UserManager.GetUsers() - .Where(u => notify ? u.ActivationStatus.HasFlag(EmployeeActivationStatus.Activated) : u.IsOwner()) - .Select(u => StudioNotifyHelper.ToRecipient(u.ID)) + var users = CoreContext.UserManager.GetUsers(tenant) + .Where(u => notify ? u.ActivationStatus.HasFlag(EmployeeActivationStatus.Activated) : u.IsOwner(tenant)) + .Select(u => StudioNotifyHelper.ToRecipient(tenant.TenantId, u.ID)) .ToArray(); if (users.Any()) @@ -813,18 +813,16 @@ namespace ASC.Web.Studio.Core.Notify } } - public void PortalRenameNotify(String oldVirtualRootPath) + public void PortalRenameNotify(Tenant tenant, String oldVirtualRootPath) { - var tenant = CoreContext.TenantManager.GetCurrentTenant(); - - var users = CoreContext.UserManager.GetUsers() + var users = CoreContext.UserManager.GetUsers(tenant) .Where(u => u.ActivationStatus.HasFlag(EmployeeActivationStatus.Activated)); ThreadPool.QueueUserWorkItem(_ => { try { - CoreContext.TenantManager.SetCurrentTenant(tenant); + CoreContext.TenantManager.SetCurrentTenant(tenant); foreach (var u in users) { @@ -834,7 +832,7 @@ namespace ASC.Web.Studio.Core.Notify client.SendNoticeToAsync( Actions.PortalRename, - new[] { StudioNotifyHelper.ToRecipient(u.ID) }, + new[] { StudioNotifyHelper.ToRecipient(tenant.TenantId, u.ID) }, new[] { EMailSenderName }, new TagValue(Tags.PortalUrl, oldVirtualRootPath), new TagValue(Tags.UserDisplayName, u.DisplayUserName())); diff --git a/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs b/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs index 8fefbd902b..bb992a4b2f 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs @@ -43,10 +43,10 @@ namespace ASC.Web.Core.Notify SendNoticeToAsync(action, objectID, new[] { recipient }, null, false, args); } - public void SendNoticeAsync(INotifyAction action, string objectID, params ITagValue[] args) + public void SendNoticeAsync(int tenantId, INotifyAction action, string objectID, params ITagValue[] args) { var subscriptionSource = StudioNotifyHelper.NotifySource.GetSubscriptionProvider(); - var recipients = subscriptionSource.GetRecipients(action, objectID); + var recipients = subscriptionSource.GetRecipients(tenantId, action, objectID); SendNoticeToAsync(action, objectID, recipients, null, false, args); } diff --git a/web/ASC.Web.Core/Notify/StudioNotifySource.cs b/web/ASC.Web.Core/Notify/StudioNotifySource.cs index cf76f03405..e2cc184551 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifySource.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifySource.cs @@ -25,6 +25,7 @@ using ASC.Core.Notify; +using ASC.Core.Tenants; using ASC.Notify.Model; using ASC.Notify.Patterns; using ASC.Notify.Recipients; @@ -181,14 +182,14 @@ namespace ASC.Web.Studio.Core.Notify this.provider = provider; } - public object GetSubscriptionRecord(INotifyAction action, IRecipient recipient, string objectID) + public object GetSubscriptionRecord(Tenant tenant, INotifyAction action, IRecipient recipient, string objectID) { - return provider.GetSubscriptionRecord(GetAdminAction(action), recipient, objectID); + return provider.GetSubscriptionRecord(tenant, GetAdminAction(action), recipient, objectID); } - public string[] GetSubscriptions(INotifyAction action, IRecipient recipient, bool checkSubscription = true) + public string[] GetSubscriptions(Tenant tenant, INotifyAction action, IRecipient recipient, bool checkSubscription = true) { - return provider.GetSubscriptions(GetAdminAction(action), recipient, checkSubscription); + return provider.GetSubscriptions(tenant, GetAdminAction(action), recipient, checkSubscription); } public void Subscribe(INotifyAction action, string objectID, IRecipient recipient) @@ -196,9 +197,9 @@ namespace ASC.Web.Studio.Core.Notify provider.Subscribe(GetAdminAction(action), objectID, recipient); } - public void UnSubscribe(INotifyAction action, IRecipient recipient) + public void UnSubscribe(Tenant tenant, INotifyAction action, IRecipient recipient) { - provider.UnSubscribe(GetAdminAction(action), recipient); + provider.UnSubscribe(tenant, GetAdminAction(action), recipient); } public void UnSubscribe(INotifyAction action) @@ -221,14 +222,14 @@ namespace ASC.Web.Studio.Core.Notify provider.UpdateSubscriptionMethod(GetAdminAction(action), recipient, senderNames); } - public IRecipient[] GetRecipients(INotifyAction action, string objectID) + public IRecipient[] GetRecipients(int tenantId, INotifyAction action, string objectID) { - return provider.GetRecipients(GetAdminAction(action), objectID); + return provider.GetRecipients(tenantId, GetAdminAction(action), objectID); } - public string[] GetSubscriptionMethod(INotifyAction action, IRecipient recipient) + public string[] GetSubscriptionMethod(Tenant tenant, INotifyAction action, IRecipient recipient) { - return provider.GetSubscriptionMethod(GetAdminAction(action), recipient); + return provider.GetSubscriptionMethod(tenant, GetAdminAction(action), recipient); } public bool IsUnsubscribe(IDirectRecipient recipient, INotifyAction action, string objectID) diff --git a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs index eb0e8e29be..46ca7ab832 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -151,7 +151,7 @@ namespace ASC.Web.Studio.Core.Notify #region 3 days after registration to admins SAAS TRIAL + only 1 user - if (tenant.CreatedDateTime.Date.AddDays(3) == now && CoreContext.UserManager.GetUsers().Count() == 1) + if (tenant.CreatedDateTime.Date.AddDays(3) == now && CoreContext.UserManager.GetUsers(tenant).Count() == 1) { action = Actions.SaasAdminInviteTeammatesV10; paymentMessage = false; @@ -327,7 +327,7 @@ namespace ASC.Web.Studio.Core.Notify #region 30 days after SAAS TRIAL expired + only 1 user - else if (duedate != DateTime.MaxValue && duedate.AddDays(30) == now && CoreContext.UserManager.GetUsers().Count() == 1) + else if (duedate != DateTime.MaxValue && duedate.AddDays(30) == now && CoreContext.UserManager.GetUsers(tenant).Count() == 1) { action = Actions.SaasAdminTrialWarningAfter30V10; toadmins = true; @@ -447,26 +447,26 @@ namespace ASC.Web.Studio.Core.Notify if (action == null) continue; var users = toowner - ? new List { CoreContext.UserManager.GetUsers(tenant.OwnerId) } - : StudioNotifyHelper.GetRecipients(toadmins, tousers, false); + ? new List { CoreContext.UserManager.GetUsers(tenant.OwnerId, tenant.TenantId) } + : StudioNotifyHelper.GetRecipients(tenant, toadmins, tousers, false); var analytics = StudioNotifyHelper.GetNotifyAnalytics(tenant.TenantId, action, toowner, toadmins, tousers, false); - foreach (var u in users.Where(u => paymentMessage || StudioNotifyHelper.IsSubscribedToNotify(u, Actions.PeriodicNotify))) + foreach (var u in users.Where(u => paymentMessage || StudioNotifyHelper.IsSubscribedToNotify(tenant, u, Actions.PeriodicNotify))) { var culture = string.IsNullOrEmpty(u.CultureName) ? tenant.GetCulture() : u.GetCulture(); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; - var rquota = TenantExtra.GetRightQuota() ?? TenantQuota.Default; + var rquota = TenantExtra.GetRightQuota(tenant) ?? TenantQuota.Default; client.SendNoticeToAsync( action, - new[] { StudioNotifyHelper.ToRecipient(u.ID) }, + new[] { StudioNotifyHelper.ToRecipient(tenant.TenantId, u.ID) }, new[] { senderName }, new TagValue(Tags.UserName, u.FirstName.HtmlEncode()), new TagValue(Tags.PricingPage, CommonLinkUtility.GetFullAbsolutePath("~/tariffs.aspx")), - new TagValue(Tags.ActiveUsers, CoreContext.UserManager.GetUsers().Count()), + new TagValue(Tags.ActiveUsers, CoreContext.UserManager.GetUsers(tenant).Count()), new TagValue(Tags.Price, rquota.Price), new TagValue(Tags.PricePeriod, rquota.Year3 ? UserControlsCommonResource.TariffPerYear3 : rquota.Year ? UserControlsCommonResource.TariffPerYear : UserControlsCommonResource.TariffPerMonth), new TagValue(Tags.DueDate, duedate.ToLongDateString()), @@ -482,7 +482,7 @@ namespace ASC.Web.Studio.Core.Notify TagValues.TableItem(6, tableItemText6, tableItemUrl6, tableItemImg6, tableItemComment6, tableItemLearnMoreText6, tableItemLearnMoreUrl6), TagValues.TableItem(7, tableItemText7, tableItemUrl7, tableItemImg7, tableItemComment7, tableItemLearnMoreText7, tableItemLearnMoreUrl7), TagValues.TableBottom(), - new TagValue(CommonTags.Footer, u.IsAdmin() ? "common" : "social"), + new TagValue(CommonTags.Footer, u.IsAdmin(tenant) ? "common" : "social"), new TagValue(CommonTags.Analytics, analytics), new TagValue(Tags.Coupon, coupon)); } @@ -625,7 +625,7 @@ namespace ASC.Web.Studio.Core.Notify #region 4 days after registration to admins ENTERPRISE TRIAL + only 1 user + defaultRebranding - else if (tenant.CreatedDateTime.Date.AddDays(4) == now && CoreContext.UserManager.GetUsers().Count() == 1) + else if (tenant.CreatedDateTime.Date.AddDays(4) == now && CoreContext.UserManager.GetUsers(tenant).Count() == 1) { action = Actions.EnterpriseAdminInviteTeammatesV10; paymentMessage = false; @@ -833,23 +833,23 @@ namespace ASC.Web.Studio.Core.Notify if (action == null) continue; - var users = StudioNotifyHelper.GetRecipients(toadmins, tousers, false); + var users = StudioNotifyHelper.GetRecipients(tenant, toadmins, tousers, false); - foreach (var u in users.Where(u => paymentMessage || StudioNotifyHelper.IsSubscribedToNotify(u, Actions.PeriodicNotify))) + foreach (var u in users.Where(u => paymentMessage || StudioNotifyHelper.IsSubscribedToNotify(tenant, u, Actions.PeriodicNotify))) { var culture = string.IsNullOrEmpty(u.CultureName) ? tenant.GetCulture() : u.GetCulture(); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; - var rquota = TenantExtra.GetRightQuota() ?? TenantQuota.Default; + var rquota = TenantExtra.GetRightQuota(tenant) ?? TenantQuota.Default; client.SendNoticeToAsync( action, - new[] { StudioNotifyHelper.ToRecipient(u.ID) }, + new[] { StudioNotifyHelper.ToRecipient(tenant.TenantId, u.ID) }, new[] { senderName }, new TagValue(Tags.UserName, u.FirstName.HtmlEncode()), new TagValue(Tags.PricingPage, CommonLinkUtility.GetFullAbsolutePath("~/tariffs.aspx")), - new TagValue(Tags.ActiveUsers, CoreContext.UserManager.GetUsers().Count()), + new TagValue(Tags.ActiveUsers, CoreContext.UserManager.GetUsers(tenant).Count()), new TagValue(Tags.Price, rquota.Price), new TagValue(Tags.PricePeriod, rquota.Year3 ? UserControlsCommonResource.TariffPerYear3 : rquota.Year ? UserControlsCommonResource.TariffPerYear : UserControlsCommonResource.TariffPerMonth), new TagValue(Tags.DueDate, duedate.ToLongDateString()), @@ -1014,9 +1014,9 @@ namespace ASC.Web.Studio.Core.Notify if (action == null) continue; - var users = StudioNotifyHelper.GetRecipients(true, false, false); + var users = StudioNotifyHelper.GetRecipients(tenant, true, false, false); - foreach (var u in users.Where(u => StudioNotifyHelper.IsSubscribedToNotify(u, Actions.PeriodicNotify))) + foreach (var u in users.Where(u => StudioNotifyHelper.IsSubscribedToNotify(tenant, u, Actions.PeriodicNotify))) { var culture = string.IsNullOrEmpty(u.CultureName) ? tenant.GetCulture() : u.GetCulture(); Thread.CurrentThread.CurrentCulture = culture; @@ -1024,7 +1024,7 @@ namespace ASC.Web.Studio.Core.Notify client.SendNoticeToAsync( action, - new[] { StudioNotifyHelper.ToRecipient(u.ID) }, + new[] { StudioNotifyHelper.ToRecipient(tenant.TenantId, u.ID) }, new[] { senderName }, new TagValue(Tags.UserName, u.DisplayUserName()), TagValues.GreenButton(greenButtonText, greenButtonUrl), @@ -1068,9 +1068,9 @@ namespace ASC.Web.Studio.Core.Notify log.InfoFormat("Current tenant: {0}", tenant.TenantId); - var users = CoreContext.UserManager.GetUsers(EmployeeStatus.Active); + var users = CoreContext.UserManager.GetUsers(tenant, EmployeeStatus.Active); - foreach (var user in users.Where(u => StudioNotifyHelper.IsSubscribedToNotify(u, Actions.PeriodicNotify))) + foreach (var user in users.Where(u => StudioNotifyHelper.IsSubscribedToNotify(tenant, u, Actions.PeriodicNotify))) { INotifyAction action; @@ -1159,11 +1159,11 @@ namespace ASC.Web.Studio.Core.Notify log.Info("End SendLettersPersonal."); } - public static bool ChangeSubscription(Guid userId) + public static bool ChangeSubscription(Tenant tenant, Guid userId) { - var recipient = StudioNotifyHelper.ToRecipient(userId); + var recipient = StudioNotifyHelper.ToRecipient(tenant.TenantId, userId); - var isSubscribe = StudioNotifyHelper.IsSubscribedToNotify(recipient, Actions.PeriodicNotify); + var isSubscribe = StudioNotifyHelper.IsSubscribedToNotify(tenant, recipient, Actions.PeriodicNotify); StudioNotifyHelper.SubscribeToNotify(recipient, Actions.PeriodicNotify, !isSubscribe); diff --git a/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs b/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs index d8cde6f3ff..93de06e210 100644 --- a/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs @@ -77,9 +77,9 @@ namespace ASC.Web.Studio.Core.Notify CoreContext.TenantManager.SetCurrentTenant(tenant); log.InfoFormat("Start send whats new in {0} ({1}).", tenant.TenantDomain, tenantid); - foreach (var user in CoreContext.UserManager.GetUsers()) + foreach (var user in CoreContext.UserManager.GetUsers(tenant)) { - if (!StudioNotifyHelper.IsSubscribedToNotify(user, Actions.SendWhatsNew)) + if (!StudioNotifyHelper.IsSubscribedToNotify(tenant, user, Actions.SendWhatsNew)) { continue; } diff --git a/web/ASC.Web.Core/Users/DisplayUserSettings.cs b/web/ASC.Web.Core/Users/DisplayUserSettings.cs index 73507ea0cd..f46dd760b6 100644 --- a/web/ASC.Web.Core/Users/DisplayUserSettings.cs +++ b/web/ASC.Web.Core/Users/DisplayUserSettings.cs @@ -69,7 +69,7 @@ namespace ASC.Web.Core.Users { return string.Empty; } - if (!userInfo.ID.Equals(Guid.Empty) && !CoreContext.UserManager.UserExists(userInfo.ID)) + if (!userInfo.ID.Equals(Guid.Empty) && !CoreContext.UserManager.UserExists(userInfo.ID, userInfo.Tenant)) { return "profile removed"; } diff --git a/web/ASC.Web.Core/Users/UserInfoExtension.cs b/web/ASC.Web.Core/Users/UserInfoExtension.cs index ca56271eae..c419b5fcb8 100644 --- a/web/ASC.Web.Core/Users/UserInfoExtension.cs +++ b/web/ASC.Web.Core/Users/UserInfoExtension.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using ASC.Core.Tenants; using ASC.Web.Core; using ASC.Web.Core.PublicResources; using ASC.Web.Studio.Utility; @@ -41,11 +42,11 @@ namespace ASC.Core.Users return userInfo == null ? "" : CommonLinkUtility.GetUserProfile(userInfo.ID); } - public static string RenderProfileLink(this UserInfo userInfo, Guid productID) + public static string RenderProfileLink(this UserInfo userInfo, Guid productID, int tenantId) { var sb = new StringBuilder(); - if (userInfo == null || !CoreContext.UserManager.UserExists(userInfo.ID)) + if (userInfo == null || !CoreContext.UserManager.UserExists(userInfo.ID, tenantId)) { sb.Append(""); sb.Append(Resource.ProfileRemoved); @@ -66,13 +67,13 @@ namespace ASC.Core.Users return sb.ToString(); } - public static string RenderCustomProfileLink(this UserInfo userInfo, String containerCssClass, String linkCssClass) + public static string RenderCustomProfileLink(this UserInfo userInfo, String containerCssClass, String linkCssClass, int tenantId) { var containerCss = string.IsNullOrEmpty(containerCssClass) ? "userLink" : "userLink " + containerCssClass; var linkCss = string.IsNullOrEmpty(linkCssClass) ? "" : linkCssClass; var sb = new StringBuilder(); - if (userInfo == null || !CoreContext.UserManager.UserExists(userInfo.ID)) + if (userInfo == null || !CoreContext.UserManager.UserExists(userInfo.ID, tenantId)) { sb.AppendFormat("", containerCss); sb.Append(Resource.ProfileRemoved); @@ -93,11 +94,11 @@ namespace ASC.Core.Users return sb.ToString(); } - public static List GetListAdminModules(this UserInfo ui) + public static List GetListAdminModules(this UserInfo ui, Tenant tenant) { var products = WebItemManager.Instance.GetItemsAll().Where(i => i is IProduct || i.ID == WebItemManager.MailProductID); - return (from product in products where WebItemSecurity.IsProductAdministrator(product.ID, ui.ID) select product.ProductClassName).ToList(); + return (from product in products where WebItemSecurity.IsProductAdministrator(tenant, product.ID, ui.ID) select product.ProductClassName).ToList(); } } } \ No newline at end of file diff --git a/web/ASC.Web.Core/Users/UserManagerWrapper.cs b/web/ASC.Web.Core/Users/UserManagerWrapper.cs index a8647b48ef..132c3a478a 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -53,14 +53,14 @@ namespace ASC.Web.Core.Users StudioNotifyService = studioNotifyService; } - private static bool TestUniqueUserName(string uniqueName) + private static bool TestUniqueUserName(string uniqueName, int tenantId) { if (String.IsNullOrEmpty(uniqueName)) return false; - return Equals(CoreContext.UserManager.GetUserByUserName(uniqueName), Constants.LostUser); + return Equals(CoreContext.UserManager.GetUserByUserName(tenantId, uniqueName), Constants.LostUser); } - private static string MakeUniqueName(UserInfo userInfo) + private static string MakeUniqueName(int tenantId, UserInfo userInfo) { if (string.IsNullOrEmpty(userInfo.Email)) throw new ArgumentException(Resource.ErrorEmailEmpty, "userInfo"); @@ -68,20 +68,20 @@ namespace ASC.Web.Core.Users var uniqueName = new MailAddress(userInfo.Email).User; var startUniqueName = uniqueName; var i = 0; - while (!TestUniqueUserName(uniqueName)) + while (!TestUniqueUserName(uniqueName, tenantId)) { uniqueName = string.Format("{0}{1}", startUniqueName, (++i).ToString(CultureInfo.InvariantCulture)); } return uniqueName; } - public static bool CheckUniqueEmail(Guid userId, string email) + public static bool CheckUniqueEmail(int tenantId, Guid userId, string email) { - var foundUser = CoreContext.UserManager.GetUserByEmail(email); + var foundUser = CoreContext.UserManager.GetUserByEmail(tenantId, email); return Equals(foundUser, Constants.LostUser) || foundUser.ID == userId; } - public UserInfo AddUser(UserInfo userInfo, string password, bool afterInvite = false, bool notify = true, bool isVisitor = false, bool fromInviteLink = false, bool makeUniqueName = true) + public UserInfo AddUser(Tenant tenant, UserInfo userInfo, string password, bool afterInvite = false, bool notify = true, bool isVisitor = false, bool fromInviteLink = false, bool makeUniqueName = true) { if (userInfo == null) throw new ArgumentNullException("userInfo"); @@ -90,11 +90,11 @@ namespace ASC.Web.Core.Users CheckPasswordPolicy(password); - if (!CheckUniqueEmail(userInfo.ID, userInfo.Email)) + if (!CheckUniqueEmail(tenant.TenantId, userInfo.ID, userInfo.Email)) throw new Exception(CustomNamingPeople.Substitute("ErrorEmailAlreadyExists")); if (makeUniqueName) { - userInfo.UserName = MakeUniqueName(userInfo); + userInfo.UserName = MakeUniqueName(tenant.TenantId, userInfo); } if (!userInfo.WorkFromDate.HasValue) { @@ -106,7 +106,7 @@ namespace ASC.Web.Core.Users userInfo.ActivationStatus = !afterInvite ? EmployeeActivationStatus.Pending : EmployeeActivationStatus.Activated; } - var newUserInfo = CoreContext.UserManager.SaveUserInfo(userInfo, isVisitor); + var newUserInfo = CoreContext.UserManager.SaveUserInfo(tenant, userInfo, isVisitor); SecurityContext.SetUserPassword(newUserInfo.ID, password); if (CoreContext.Configuration.Personal) @@ -122,11 +122,11 @@ namespace ASC.Web.Core.Users { if (isVisitor) { - StudioNotifyService.GuestInfoAddedAfterInvite(newUserInfo); + StudioNotifyService.GuestInfoAddedAfterInvite(tenant.TenantId, newUserInfo); } else { - StudioNotifyService.UserInfoAddedAfterInvite(newUserInfo); + StudioNotifyService.UserInfoAddedAfterInvite(tenant.TenantId, newUserInfo); } if (fromInviteLink) @@ -151,7 +151,7 @@ namespace ASC.Web.Core.Users if (isVisitor) { - CoreContext.UserManager.AddUserIntoGroup(newUserInfo.ID, Constants.GroupVisitor.ID); + CoreContext.UserManager.AddUserIntoGroup(tenant, newUserInfo.ID, Constants.GroupVisitor.ID); } return newUserInfo; @@ -170,7 +170,7 @@ namespace ASC.Web.Core.Users throw new Exception(GenerateErrorMessage(passwordSettingsObj)); } - public UserInfo SendUserPassword(string email, MessageService messageService, HttpContext context) + public UserInfo SendUserPassword(int tenantId, string email, MessageService messageService, HttpContext context) { email = (email ?? "").Trim(); if (!email.TestEmailRegex()) throw new ArgumentNullException("email", Resource.ErrorNotCorrectEmail); @@ -182,8 +182,8 @@ namespace ASC.Web.Core.Users throw new Exception(Resource.ErrorAccessRestricted); } - var userInfo = CoreContext.UserManager.GetUserByEmail(email); - if (!CoreContext.UserManager.UserExists(userInfo.ID) || string.IsNullOrEmpty(userInfo.Email)) + var userInfo = CoreContext.UserManager.GetUserByEmail(tenantId, email); + if (!CoreContext.UserManager.UserExists(userInfo.ID, tenantId) || string.IsNullOrEmpty(userInfo.Email)) { throw new Exception(string.Format(Resource.ErrorUserNotFoundByEmail, email)); } diff --git a/web/ASC.Web.Core/Users/UserPhotoManager.cs b/web/ASC.Web.Core/Users/UserPhotoManager.cs index c657806ec2..ec31e7ab77 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -37,6 +37,7 @@ using ASC.Common.Caching; using ASC.Common.Logging; using ASC.Common.Threading.Workers; using ASC.Core; +using ASC.Core.Tenants; using ASC.Data.Storage; using ASC.Web.Core.Utility.Skins; using ASC.Web.Studio.Utility; @@ -178,60 +179,60 @@ namespace ASC.Web.Core.Users return WebImageSupplier.GetAbsoluteWebPath(_defaultAvatar); } - public static string GetRetinaPhotoURL(Guid userID) + public static string GetRetinaPhotoURL(int tenantId, Guid userID) { - return GetRetinaPhotoURL(userID, out _); + return GetRetinaPhotoURL(tenantId, userID, out _); } - public static string GetRetinaPhotoURL(Guid userID, out bool isdef) + public static string GetRetinaPhotoURL(int tenantId, Guid userID, out bool isdef) { - return GetSizedPhotoAbsoluteWebPath(userID, RetinaFotoSize, out isdef); + return GetSizedPhotoAbsoluteWebPath(tenantId, userID, RetinaFotoSize, out isdef); } - public static string GetMaxPhotoURL(Guid userID) + public static string GetMaxPhotoURL(int tenantId, Guid userID) { - return GetMaxPhotoURL(userID, out _); + return GetMaxPhotoURL(tenantId, userID, out _); } - public static string GetMaxPhotoURL(Guid userID, out bool isdef) + public static string GetMaxPhotoURL(int tenantId, Guid userID, out bool isdef) { - return GetSizedPhotoAbsoluteWebPath(userID, MaxFotoSize, out isdef); + return GetSizedPhotoAbsoluteWebPath(tenantId, userID, MaxFotoSize, out isdef); } - public static string GetBigPhotoURL(Guid userID) + public static string GetBigPhotoURL(int tenantId, Guid userID) { - return GetBigPhotoURL(userID, out _); + return GetBigPhotoURL(tenantId, userID, out _); } - public static string GetBigPhotoURL(Guid userID, out bool isdef) + public static string GetBigPhotoURL(int tenantId, Guid userID, out bool isdef) { - return GetSizedPhotoAbsoluteWebPath(userID, BigFotoSize, out isdef); + return GetSizedPhotoAbsoluteWebPath(tenantId, userID, BigFotoSize, out isdef); } - public static string GetMediumPhotoURL(Guid userID) + public static string GetMediumPhotoURL(int tenantId, Guid userID) { - return GetMediumPhotoURL(userID, out _); + return GetMediumPhotoURL(tenantId, userID, out _); } - public static string GetMediumPhotoURL(Guid userID, out bool isdef) + public static string GetMediumPhotoURL(int tenantId, Guid userID, out bool isdef) { - return GetSizedPhotoAbsoluteWebPath(userID, MediumFotoSize, out isdef); + return GetSizedPhotoAbsoluteWebPath(tenantId, userID, MediumFotoSize, out isdef); } - public static string GetSmallPhotoURL(Guid userID) + public static string GetSmallPhotoURL(int tenantId, Guid userID) { - return GetSmallPhotoURL(userID, out _); + return GetSmallPhotoURL(tenantId, userID, out _); } - public static string GetSmallPhotoURL(Guid userID, out bool isdef) + public static string GetSmallPhotoURL(int tenantId, Guid userID, out bool isdef) { - return GetSizedPhotoAbsoluteWebPath(userID, SmallFotoSize, out isdef); + return GetSizedPhotoAbsoluteWebPath(tenantId, userID, SmallFotoSize, out isdef); } - public static string GetSizedPhotoUrl(Guid userId, int width, int height) + public static string GetSizedPhotoUrl(int tenantId, Guid userId, int width, int height) { - return GetSizedPhotoAbsoluteWebPath(userId, new Size(width, height)); + return GetSizedPhotoAbsoluteWebPath(tenantId, userId, new Size(width, height)); } @@ -300,21 +301,21 @@ namespace ASC.Web.Core.Users private static string _tempDomainName = "temp"; - public static bool UserHasAvatar(Guid userID) + public static bool UserHasAvatar(Tenant tenant, Guid userID) { - var path = GetPhotoAbsoluteWebPath(userID); + var path = GetPhotoAbsoluteWebPath(tenant, userID); var fileName = Path.GetFileName(path); return fileName != _defaultAvatar; } - public static string GetPhotoAbsoluteWebPath(Guid userID) + public static string GetPhotoAbsoluteWebPath(Tenant tenant, Guid userID) { var path = SearchInCache(userID, Size.Empty, out _); if (!string.IsNullOrEmpty(path)) return path; try { - var data = CoreContext.UserManager.GetUserPhoto(userID); + var data = CoreContext.UserManager.GetUserPhoto(tenant.TenantId, userID); string photoUrl; string fileName; if (data == null || data.Length == 0) @@ -324,7 +325,7 @@ namespace ASC.Web.Core.Users } else { - photoUrl = SaveOrUpdatePhoto(userID, data, -1, new Size(-1, -1), false, out fileName); + photoUrl = SaveOrUpdatePhoto(tenant, userID, data, -1, new Size(-1, -1), false, out fileName); } AddToCache(userID, Size.Empty, fileName); @@ -336,9 +337,9 @@ namespace ASC.Web.Core.Users return GetDefaultPhotoAbsoluteWebPath(); } - internal static Size GetPhotoSize(Guid userID) + internal static Size GetPhotoSize(Tenant tenant, Guid userID) { - var virtualPath = GetPhotoAbsoluteWebPath(userID); + var virtualPath = GetPhotoAbsoluteWebPath(tenant, userID); if (virtualPath == null) return Size.Empty; try @@ -354,19 +355,19 @@ namespace ASC.Web.Core.Users } } - private static string GetSizedPhotoAbsoluteWebPath(Guid userID, Size size) + private static string GetSizedPhotoAbsoluteWebPath(int tenantId, Guid userID, Size size) { - return GetSizedPhotoAbsoluteWebPath(userID, size, out _); + return GetSizedPhotoAbsoluteWebPath(tenantId, userID, size, out _); } - private static string GetSizedPhotoAbsoluteWebPath(Guid userID, Size size, out bool isdef) + private static string GetSizedPhotoAbsoluteWebPath(int tenantId, Guid userID, Size size, out bool isdef) { var res = SearchInCache(userID, size, out isdef); if (!string.IsNullOrEmpty(res)) return res; try { - var data = CoreContext.UserManager.GetUserPhoto(userID); + var data = CoreContext.UserManager.GetUserPhoto(tenantId, userID); if (data == null || data.Length == 0) { @@ -379,7 +380,7 @@ namespace ASC.Web.Core.Users } //Enqueue for sizing - SizePhoto(userID, data, -1, size); + SizePhoto(tenantId, userID, data, -1, size); } catch { } @@ -513,19 +514,19 @@ namespace ASC.Web.Core.Users thumbSettings.SaveForUser(userId); } - public static string SaveOrUpdatePhoto(Guid userID, byte[] data) + public static string SaveOrUpdatePhoto(Tenant tenant, Guid userID, byte[] data) { string fileName; - return SaveOrUpdatePhoto(userID, data, -1, OriginalFotoSize, true, out fileName); + return SaveOrUpdatePhoto(tenant, userID, data, -1, OriginalFotoSize, true, out fileName); } - public static void RemovePhoto(Guid idUser) + public static void RemovePhoto(Tenant tenant, Guid idUser) { - CoreContext.UserManager.SaveUserPhoto(idUser, null); + CoreContext.UserManager.SaveUserPhoto(tenant, idUser, null); ClearCache(idUser); } - private static string SaveOrUpdatePhoto(Guid userID, byte[] data, long maxFileSize, Size size, bool saveInCoreContext, out string fileName) + private static string SaveOrUpdatePhoto(Tenant tenant, Guid userID, byte[] data, long maxFileSize, Size size, bool saveInCoreContext, out string fileName) { ImageFormat imgFormat; int width; @@ -537,7 +538,7 @@ namespace ASC.Web.Core.Users if (saveInCoreContext) { - CoreContext.UserManager.SaveUserPhoto(userID, data); + CoreContext.UserManager.SaveUserPhoto(tenant, userID, data); SetUserPhotoThumbnailSettings(userID, width, height); ClearCache(userID); } @@ -552,11 +553,11 @@ namespace ASC.Web.Core.Users photoUrl = store.Save(fileName, stream).ToString(); } //Queue resizing - SizePhoto(userID, data, -1, SmallFotoSize, true); - SizePhoto(userID, data, -1, MediumFotoSize, true); - SizePhoto(userID, data, -1, BigFotoSize, true); - SizePhoto(userID, data, -1, MaxFotoSize, true); - SizePhoto(userID, data, -1, RetinaFotoSize, true); + SizePhoto(tenant.TenantId, userID, data, -1, SmallFotoSize, true); + SizePhoto(tenant.TenantId, userID, data, -1, MediumFotoSize, true); + SizePhoto(tenant.TenantId, userID, data, -1, BigFotoSize, true); + SizePhoto(tenant.TenantId, userID, data, -1, MaxFotoSize, true); + SizePhoto(tenant.TenantId, userID, data, -1, RetinaFotoSize, true); } return photoUrl; } @@ -657,12 +658,12 @@ namespace ASC.Web.Core.Users //note: using auto stop queue private static readonly WorkerQueue ResizeQueue = new WorkerQueue(2, TimeSpan.FromSeconds(30), 1, true);//TODO: configure - private static string SizePhoto(Guid userID, byte[] data, long maxFileSize, Size size) + private static string SizePhoto(int tenantId, Guid userID, byte[] data, long maxFileSize, Size size) { - return SizePhoto(userID, data, maxFileSize, size, false); + return SizePhoto(tenantId, userID, data, maxFileSize, size, false); } - private static string SizePhoto(Guid userID, byte[] data, long maxFileSize, Size size, bool now) + private static string SizePhoto(int tenantId, Guid userID, byte[] data, long maxFileSize, Size size, bool now) { if (data == null || data.Length <= 0) throw new UnknownImageFormatException(); if (maxFileSize != -1 && data.Length > maxFileSize) throw new ImageWeightLimitException(); @@ -673,7 +674,7 @@ namespace ASC.Web.Core.Users { //Resize synchronously ResizeImage(resizeTask); - return GetSizedPhotoAbsoluteWebPath(userID, size); + return GetSizedPhotoAbsoluteWebPath(tenantId, userID, size); } else { @@ -817,11 +818,11 @@ namespace ASC.Web.Core.Users } - public static Bitmap GetPhotoBitmap(Guid userID) + public static Bitmap GetPhotoBitmap(int tenantId, Guid userID) { try { - var data = CoreContext.UserManager.GetUserPhoto(userID); + var data = CoreContext.UserManager.GetUserPhoto(tenantId, userID); if (data != null) { using (var s = new MemoryStream(data)) diff --git a/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs b/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs index 30dbda0d8c..38f31d24ba 100644 --- a/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs @@ -27,22 +27,23 @@ using System; using System.Collections.Generic; using System.Drawing; - +using ASC.Core.Tenants; + namespace ASC.Web.Core.Users { public class UserPhotoThumbnailManager { - public static List SaveThumbnails(int x, int y, int width, int height, Guid userId) + public static List SaveThumbnails(int tenantId, int x, int y, int width, int height, Guid userId) { - return SaveThumbnails(new UserPhotoThumbnailSettings(x, y, width, height), userId); + return SaveThumbnails(tenantId, new UserPhotoThumbnailSettings(x, y, width, height), userId); } - public static List SaveThumbnails(Point point, Size size, Guid userId) + public static List SaveThumbnails(int tenantId, Point point, Size size, Guid userId) { - return SaveThumbnails(new UserPhotoThumbnailSettings(point, size), userId); + return SaveThumbnails(tenantId, new UserPhotoThumbnailSettings(point, size), userId); } - public static List SaveThumbnails(UserPhotoThumbnailSettings thumbnailSettings, Guid userId) + public static List SaveThumbnails(int tenantId, UserPhotoThumbnailSettings thumbnailSettings, Guid userId) { if (thumbnailSettings.Size.IsEmpty) return null; @@ -50,22 +51,22 @@ namespace ASC.Web.Core.Users var resultBitmaps = new List(); - var img = thumbnailsData.MainImgBitmap; + var img = thumbnailsData.MainImgBitmap(tenantId); if (img == null) return null; - foreach (var thumbnail in thumbnailsData.ThumbnailList) + foreach (var thumbnail in thumbnailsData.ThumbnailList(tenantId)) { thumbnail.Bitmap = GetBitmap(img, thumbnail.Size, thumbnailSettings); resultBitmaps.Add(thumbnail); } - thumbnailsData.Save(resultBitmaps); + thumbnailsData.Save(tenantId, resultBitmaps); thumbnailSettings.SaveForUser(userId); - return thumbnailsData.ThumbnailList; + return thumbnailsData.ThumbnailList(tenantId); } public static Bitmap GetBitmap(Image mainImg, Size size, UserPhotoThumbnailSettings thumbnailSettings) @@ -114,55 +115,52 @@ namespace ASC.Web.Core.Users UserId = userId; } - public Bitmap MainImgBitmap + public Bitmap MainImgBitmap(int tenantId) { - get { return UserPhotoManager.GetPhotoBitmap(UserId); } + return UserPhotoManager.GetPhotoBitmap(tenantId, UserId); } - public string MainImgUrl + public string MainImgUrl(Tenant tenant) { - get { return UserPhotoManager.GetPhotoAbsoluteWebPath(UserId); } + return UserPhotoManager.GetPhotoAbsoluteWebPath(tenant, UserId); } - public List ThumbnailList - { - get - { - return new List - { - new ThumbnailItem - { - Size = UserPhotoManager.RetinaFotoSize, - ImgUrl = UserPhotoManager.GetRetinaPhotoURL(UserId) - }, - new ThumbnailItem - { - Size = UserPhotoManager.MaxFotoSize, - ImgUrl = UserPhotoManager.GetMaxPhotoURL(UserId) - }, - new ThumbnailItem - { - Size = UserPhotoManager.BigFotoSize, - ImgUrl = UserPhotoManager.GetBigPhotoURL(UserId) - }, - new ThumbnailItem - { - Size = UserPhotoManager.MediumFotoSize, - ImgUrl = UserPhotoManager.GetMediumPhotoURL(UserId) - }, - new ThumbnailItem - { - Size = UserPhotoManager.SmallFotoSize, - ImgUrl = UserPhotoManager.GetSmallPhotoURL(UserId) - } - }; - } + public List ThumbnailList(int tenantId) + { + return new List + { + new ThumbnailItem + { + Size = UserPhotoManager.RetinaFotoSize, + ImgUrl = UserPhotoManager.GetRetinaPhotoURL(tenantId, UserId) + }, + new ThumbnailItem + { + Size = UserPhotoManager.MaxFotoSize, + ImgUrl = UserPhotoManager.GetMaxPhotoURL(tenantId, UserId) + }, + new ThumbnailItem + { + Size = UserPhotoManager.BigFotoSize, + ImgUrl = UserPhotoManager.GetBigPhotoURL(tenantId, UserId) + }, + new ThumbnailItem + { + Size = UserPhotoManager.MediumFotoSize, + ImgUrl = UserPhotoManager.GetMediumPhotoURL(tenantId, UserId) + }, + new ThumbnailItem + { + Size = UserPhotoManager.SmallFotoSize, + ImgUrl = UserPhotoManager.GetSmallPhotoURL(tenantId, UserId) + } + }; } - public void Save(List bitmaps) + public void Save(int tenantId, List bitmaps) { foreach (var item in bitmaps) - UserPhotoManager.SaveThumbnail(UserId, item.Bitmap, MainImgBitmap.RawFormat); + UserPhotoManager.SaveThumbnail(UserId, item.Bitmap, MainImgBitmap(tenantId).RawFormat); } } } \ No newline at end of file diff --git a/web/ASC.Web.Core/Utility/CommonLinkUtility.cs b/web/ASC.Web.Core/Utility/CommonLinkUtility.cs index f25ab96f0f..4025c804fc 100644 --- a/web/ASC.Web.Core/Utility/CommonLinkUtility.cs +++ b/web/ASC.Web.Core/Utility/CommonLinkUtility.cs @@ -31,6 +31,7 @@ using System.Text.RegularExpressions; using System.Web; using ASC.Core; using ASC.Core.Common; +using ASC.Core.Tenants; using ASC.Core.Users; using ASC.Security.Cryptography; using ASC.Web.Core; @@ -109,14 +110,18 @@ namespace ASC.Web.Studio.Utility get { return BaseCommonLinkUtility.VirtualRoot; } } - public static string ServerRootPath + public static string ServerRootPath(HttpContext context) { - get { return BaseCommonLinkUtility.ServerRootPath; } + return BaseCommonLinkUtility.ServerRootPath(context); } public static string GetFullAbsolutePath(string virtualPath) { - return BaseCommonLinkUtility.GetFullAbsolutePath(virtualPath); + return GetFullAbsolutePath(ASC.Common.HttpContext.Current,virtualPath); + } + public static string GetFullAbsolutePath(HttpContext context, string virtualPath) + { + return BaseCommonLinkUtility.GetFullAbsolutePath(context, virtualPath); } public static string ToAbsolute(string virtualPath) @@ -159,23 +164,27 @@ namespace ASC.Web.Studio.Utility public static string GetUserProfile() { - return GetUserProfile(null); + return GetUserProfile(CoreContext.TenantManager.GetCurrentTenant().TenantId); + } + public static string GetUserProfile(int tenantId) + { + return GetUserProfile(null, tenantId); } public static string GetUserProfile(Guid userID) { - if (!CoreContext.UserManager.UserExists(userID)) + return GetUserProfile(userID, CoreContext.TenantManager.GetCurrentTenant().TenantId); + } + + public static string GetUserProfile(Guid userID, int tenantId) + { + if (!CoreContext.UserManager.UserExists(userID, tenantId)) return GetEmployees(); - return GetUserProfile(userID.ToString()); + return GetUserProfile(userID.ToString(), tenantId); } - public static string GetUserProfile(string user) - { - return GetUserProfile(user, true); - } - - public static string GetUserProfile(string user, bool absolute) + public static string GetUserProfile(string user, int tenantId, bool absolute = true) { var queryParams = ""; @@ -193,7 +202,7 @@ namespace ASC.Web.Studio.Utility } } - queryParams = guid != Guid.Empty ? GetUserParamsPair(guid) : ParamName_UserUserName + "=" + HttpUtility.UrlEncode(user); + queryParams = guid != Guid.Empty ? GetUserParamsPair(guid, tenantId) : ParamName_UserUserName + "=" + HttpUtility.UrlEncode(user); } var url = absolute ? ToAbsolute("~/products/people/") : "/products/people/"; @@ -202,23 +211,33 @@ namespace ASC.Web.Studio.Utility return url; } + public static string GetUserProfile(Guid user, int tenantId, bool absolute = true) + { + var queryParams = GetUserParamsPair(user, tenantId); + + var url = absolute ? ToAbsolute("~/products/people/") : "/products/people/"; + url += "profile.aspx?"; + url += queryParams; + + return url; + } #endregion - public static Guid GetProductID(HttpContext context) + public static Guid GetProductID(Tenant tenant, HttpContext context) { var productID = Guid.Empty; if (context != null) { - GetLocationByRequest(out var product, out var module, context); + GetLocationByRequest(tenant, out var product, out var module, context); if (product != null) productID = product.ID; } return productID; } - public static void GetLocationByRequest(out IProduct currentProduct, out IModule currentModule, HttpContext context) + public static void GetLocationByRequest(Tenant tenant, out IProduct currentProduct, out IModule currentModule, HttpContext context) { var currentURL = string.Empty; if (context != null && context.Request != null) @@ -233,7 +252,7 @@ namespace ASC.Web.Studio.Utility //} } - GetLocationByUrl(currentURL, out currentProduct, out currentModule); + GetLocationByUrl(tenant, currentURL, out currentProduct, out currentModule); } public static IWebItem GetWebItemByUrl(string currentURL) @@ -277,7 +296,7 @@ namespace ASC.Web.Studio.Utility return null; } - public static void GetLocationByUrl(string currentURL, out IProduct currentProduct, out IModule currentModule) + public static void GetLocationByUrl(Tenant tenant, string currentURL, out IProduct currentProduct, out IModule currentModule) { currentProduct = null; currentModule = null; @@ -316,7 +335,7 @@ namespace ASC.Web.Studio.Utility if (!String.IsNullOrEmpty(moduleName)) { - foreach (var module in WebItemManager.Instance.GetSubItems(product.ID).OfType()) + foreach (var module in WebItemManager.Instance.GetSubItems(tenant, product.ID).OfType()) { var _moduleName = GetModuleNameFromUrl(module.StartURL); if (!string.IsNullOrEmpty(_moduleName)) @@ -331,7 +350,7 @@ namespace ASC.Web.Studio.Utility } else { - foreach (var module in WebItemManager.Instance.GetSubItems(product.ID).OfType()) + foreach (var module in WebItemManager.Instance.GetSubItems(tenant, product.ID).OfType()) { if (!module.StartURL.Equals(product.StartURL) && currentURL.Contains(RegFilePathTrim.Replace(module.StartURL, string.Empty))) { @@ -433,11 +452,11 @@ namespace ASC.Web.Studio.Utility return result; } - public static string GetUserParamsPair(Guid userID) + public static string GetUserParamsPair(Guid userID, int tenantId) { return - CoreContext.UserManager.UserExists(userID) - ? GetUserParamsPair(CoreContext.UserManager.GetUsers(userID)) + CoreContext.UserManager.UserExists(userID, tenantId) + ? GetUserParamsPair(CoreContext.UserManager.GetUsers(userID, tenantId)) : ""; } diff --git a/web/ASC.Web.Core/Utility/TenantExtra.cs b/web/ASC.Web.Core/Utility/TenantExtra.cs index 776c8fcd76..ab17f86086 100644 --- a/web/ASC.Web.Core/Utility/TenantExtra.cs +++ b/web/ASC.Web.Core/Utility/TenantExtra.cs @@ -75,7 +75,10 @@ namespace ASC.Web.Studio.Utility public static bool EnableControlPanel { - get { return Enterprise && GetTenantQuota().ControlPanel && GetCurrentTariff().State < TariffState.NotPaid && CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin(); } + get { return Enterprise && + GetTenantQuota().ControlPanel && + GetCurrentTariff().State < TariffState.NotPaid && + CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsAdmin(CoreContext.TenantManager.GetCurrentTenant()); } } public static bool EnableDocbuilder @@ -133,16 +136,16 @@ namespace ASC.Web.Studio.Utility return prevQuota.ActiveUsers + 1; } - public static int GetRightQuotaId() + public static int GetRightQuotaId(Tenant tenant) { - var q = GetRightQuota(); + var q = GetRightQuota(tenant); return q != null ? q.Id : 0; } - public static TenantQuota GetRightQuota() + public static TenantQuota GetRightQuota(Tenant tenant) { var usedSpace = TenantStatisticsProvider.GetUsedSize(); - var needUsersCount = TenantStatisticsProvider.GetUsersCount(); + var needUsersCount = TenantStatisticsProvider.GetUsersCount(tenant); var quotas = GetTenantQuotas(); return quotas.OrderBy(q => q.ActiveUsers) @@ -161,9 +164,9 @@ namespace ASC.Web.Studio.Utility CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID)); } - public static int GetRemainingCountUsers() + public static int GetRemainingCountUsers(Tenant tenant) { - return GetTenantQuota().ActiveUsers - TenantStatisticsProvider.GetUsersCount(); + return GetTenantQuota().ActiveUsers - TenantStatisticsProvider.GetUsersCount(tenant); } public static bool UpdatedWithoutLicense diff --git a/web/ASC.Web.Core/Utility/TenantStatisticsProvider.cs b/web/ASC.Web.Core/Utility/TenantStatisticsProvider.cs index 1a3ba53425..854bed5e15 100644 --- a/web/ASC.Web.Core/Utility/TenantStatisticsProvider.cs +++ b/web/ASC.Web.Core/Utility/TenantStatisticsProvider.cs @@ -45,9 +45,9 @@ namespace ASC.Web.Studio.UserControls.Statistics || TenantExtra.Enterprise && !TenantExtra.EnterprisePaid && tariff.LicenseDate == DateTime.MaxValue); } - public static int GetUsersCount() + public static int GetUsersCount(Tenant tenant) { - return CoreContext.UserManager.GetUsersByGroup(Constants.GroupUser.ID).Length; + return CoreContext.UserManager.GetUsersByGroup(tenant, Constants.GroupUser.ID).Length; } public static long GetUsedSize() diff --git a/web/ASC.Web.Core/WebItemManager.cs b/web/ASC.Web.Core/WebItemManager.cs index 5b9fc599ab..5682c125f2 100644 --- a/web/ASC.Web.Core/WebItemManager.cs +++ b/web/ASC.Web.Core/WebItemManager.cs @@ -31,6 +31,7 @@ using System.Linq; using ASC.Common.DependencyInjection; using ASC.Common.Logging; using ASC.Common.Utils; +using ASC.Core.Tenants; using ASC.Web.Core.WebZones; using Autofac; @@ -191,17 +192,17 @@ namespace ASC.Web.Core } } - public List GetItems(WebZoneType webZone) + public List GetItems(Tenant tenant, WebZoneType webZone) { - return GetItems(webZone, ItemAvailableState.Normal); + return GetItems(tenant, webZone, ItemAvailableState.Normal); } - public List GetItems(WebZoneType webZone, ItemAvailableState avaliableState) + public List GetItems(Tenant tenant, WebZoneType webZone, ItemAvailableState avaliableState) { var copy = items.Values.ToList(); var list = copy.Where(item => { - if ((avaliableState & ItemAvailableState.Disabled) != ItemAvailableState.Disabled && item.IsDisabled()) + if ((avaliableState & ItemAvailableState.Disabled) != ItemAvailableState.Disabled && item.IsDisabled(tenant)) { return false; } @@ -213,14 +214,14 @@ namespace ASC.Web.Core return list; } - public List GetSubItems(Guid parentItemID) + public List GetSubItems(Tenant tenant, Guid parentItemID) { - return GetSubItems(parentItemID, ItemAvailableState.Normal); + return GetSubItems(tenant, parentItemID, ItemAvailableState.Normal); } - public List GetSubItems(Guid parentItemID, ItemAvailableState avaliableState) + public List GetSubItems(Tenant tenant, Guid parentItemID, ItemAvailableState avaliableState) { - return GetItems(WebZoneType.All, avaliableState).OfType() + return GetItems(tenant, WebZoneType.All, avaliableState).OfType() .Where(p => p.ProjectId == parentItemID) .Cast() .ToList(); diff --git a/web/ASC.Web.Core/WebItemSecurity.cs b/web/ASC.Web.Core/WebItemSecurity.cs index 0ea4d6d9a7..5cbc2b9981 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -28,6 +28,7 @@ using ASC.Common.Caching; using ASC.Common.Security; using ASC.Common.Security.Authorizing; using ASC.Core; +using ASC.Core.Tenants; using ASC.Core.Users; using ASC.Web.Core.Utility.Settings; using ASC.Web.Studio.Utility; @@ -63,12 +64,12 @@ namespace ASC.Web.Core } } - public static bool IsAvailableForMe(Guid id) + public static bool IsAvailableForMe(Tenant tenant, Guid id) { - return IsAvailableForUser(id, SecurityContext.CurrentAccount.ID); + return IsAvailableForUser(tenant, id, SecurityContext.CurrentAccount.ID); } - public static bool IsAvailableForUser(Guid itemId, Guid @for) + public static bool IsAvailableForUser(Tenant tenant, Guid itemId, Guid @for) { var id = itemId.ToString(); var result = false; @@ -108,28 +109,28 @@ namespace ASC.Web.Core webitem.ID == WebItemManager.PeopleProductID || webitem.ID == WebItemManager.BirthdaysProductID || webitem.ID == WebItemManager.MailProductID) && - CoreContext.UserManager.GetUsers(@for).IsVisitor()) + CoreContext.UserManager.GetUsers(@for).IsVisitor(tenant)) { // hack: crm, people, birtthday and mail products not visible for collaborators result = false; } else if ((webitem.ID == WebItemManager.CalendarProductID || webitem.ID == WebItemManager.TalkProductID) && - CoreContext.UserManager.GetUsers(@for).IsOutsider()) + CoreContext.UserManager.GetUsers(@for).IsOutsider(tenant)) { // hack: calendar and talk products not visible for outsider result = false; } else if (webitem is IModule) { - result = SecurityContext.PermissionResolver.Check(CoreContext.Authentication.GetAccountByID(@for), securityObj, null, Read) && - IsAvailableForUser(WebItemManager.Instance.GetParentItemID(webitem.ID), @for); + result = SecurityContext.PermissionResolver.Check(tenant, CoreContext.Authentication.GetAccountByID(@for), securityObj, null, Read) && + IsAvailableForUser(tenant, WebItemManager.Instance.GetParentItemID(webitem.ID), @for); } else { var hasUsers = CoreContext.AuthorizationManager.GetAces(Guid.Empty, Read.ID, securityObj).Any(a => a.SubjectId != ASC.Core.Users.Constants.GroupEveryone.ID); - result = SecurityContext.PermissionResolver.Check(CoreContext.Authentication.GetAccountByID(@for), securityObj, null, Read) || - (hasUsers && IsProductAdministrator(securityObj.WebItemId, @for)); + result = SecurityContext.PermissionResolver.Check(tenant, CoreContext.Authentication.GetAccountByID(@for), securityObj, null, Read) || + (hasUsers && IsProductAdministrator(tenant, securityObj.WebItemId, @for)); } } else @@ -180,7 +181,7 @@ namespace ASC.Web.Core cacheNotify.Publish(new WebItemSecurityNotifier(), CacheNotifyAction.Any); } - public static WebItemSecurityInfo GetSecurityInfo(string id) + public static WebItemSecurityInfo GetSecurityInfo(int tenantId, string id) { var info = GetSecurity(id).ToList(); var module = WebItemManager.Instance.GetParentItemID(new Guid(id)) != Guid.Empty; @@ -195,7 +196,7 @@ namespace ASC.Web.Core .Where(u => u.ID != ASC.Core.Users.Constants.LostUser.ID), Groups = info - .Select(i => CoreContext.UserManager.GetGroupInfo(i.Item1)) + .Select(i => CoreContext.UserManager.GetGroupInfo(tenantId, i.Item1)) .Where(g => g.ID != ASC.Core.Users.Constants.LostGroupInfo.ID && g.CategoryID != ASC.Core.Users.Constants.SysGroupCategoryId) }; } @@ -215,7 +216,7 @@ namespace ASC.Web.Core return result; } - public static void SetProductAdministrator(Guid productid, Guid userid, bool administrator) + public static void SetProductAdministrator(Tenant tenant, Guid productid, Guid userid, bool administrator) { if (productid == Guid.Empty) { @@ -223,7 +224,7 @@ namespace ASC.Web.Core } if (administrator) { - if (CoreContext.UserManager.IsUserInGroup(userid, ASC.Core.Users.Constants.GroupVisitor.ID)) + if (CoreContext.UserManager.IsUserInGroup(tenant, userid, ASC.Core.Users.Constants.GroupVisitor.ID)) { throw new SecurityException("Collaborator can not be an administrator"); } @@ -236,7 +237,7 @@ namespace ASC.Web.Core } } - CoreContext.UserManager.AddUserIntoGroup(userid, productid); + CoreContext.UserManager.AddUserIntoGroup(tenant, userid, productid); } else { @@ -247,7 +248,7 @@ namespace ASC.Web.Core foreach (var id in groups) { - CoreContext.UserManager.RemoveUserFromGroup(userid, id); + CoreContext.UserManager.RemoveUserFromGroup(tenant, userid, id); } } @@ -259,19 +260,19 @@ namespace ASC.Web.Core } } - CoreContext.UserManager.RemoveUserFromGroup(userid, productid); + CoreContext.UserManager.RemoveUserFromGroup(tenant, userid, productid); } cacheNotify.Publish(new WebItemSecurityNotifier(), CacheNotifyAction.Any); } - public static bool IsProductAdministrator(Guid productid, Guid userid) + public static bool IsProductAdministrator(Tenant tenant, Guid productid, Guid userid) { - return CoreContext.UserManager.IsUserInGroup(userid, ASC.Core.Users.Constants.GroupAdmin.ID) || - CoreContext.UserManager.IsUserInGroup(userid, productid); + return CoreContext.UserManager.IsUserInGroup(tenant, userid, ASC.Core.Users.Constants.GroupAdmin.ID) || + CoreContext.UserManager.IsUserInGroup(tenant, userid, productid); } - public static IEnumerable GetProductAdministrators(Guid productid) + public static IEnumerable GetProductAdministrators(Tenant tenant, Guid productid) { var groups = new List(); if (productid == Guid.Empty) @@ -288,7 +289,7 @@ namespace ASC.Web.Core var users = Enumerable.Empty(); foreach (var id in groups) { - users = users.Union(CoreContext.UserManager.GetUsersByGroup(id)); + users = users.Union(CoreContext.UserManager.GetUsersByGroup(tenant, id)); } return users.ToList(); } From ecb9c4ea1260e36bf44bc26ae70df28a562fc307 Mon Sep 17 00:00:00 2001 From: NikolayRechkin Date: Thu, 8 Aug 2019 12:45:00 +0300 Subject: [PATCH 4/5] web: components: upgraded SearchInput and FilterInput components --- .../src/components/filter-input/index.js | 139 ++++++++----- .../components/search-input/hide-filter.js | 16 +- .../src/components/search-input/index.js | 183 +++++++++++++++--- .../stories/filter/README.md | 8 +- .../filter/base/base.filter.stories.js | 82 +++++--- .../stories/input/search/README.md | 1 + .../stories/input/search/index.stories.js | 55 ++++-- 7 files changed, 359 insertions(+), 125 deletions(-) diff --git a/web/ASC.Web.Components/src/components/filter-input/index.js b/web/ASC.Web.Components/src/components/filter-input/index.js index 884bcf37f6..fac14d821f 100644 --- a/web/ASC.Web.Components/src/components/filter-input/index.js +++ b/web/ASC.Web.Components/src/components/filter-input/index.js @@ -5,7 +5,6 @@ import SearchInput from '../search-input'; import ComboBox from '../combobox' import IconButton from '../icon-button'; - const StyledFilterInput = styled.div` min-width: 380px; `; @@ -27,35 +26,27 @@ const StyledComboBox = styled(ComboBox)` class FilterInput extends React.Component { constructor(props) { super(props); - - function getDefaultFilterData(){ - let filterData = props.getFilterData(); - let defaultFilterItems = []; - props.defaultFilterData.filterValue.forEach(defaultfilterValue => { - let filterValue = filterData.find(x => (x.key === defaultfilterValue.value && x.group === defaultfilterValue.key)); - if(filterValue != undefined){ - defaultfilterValue.label = filterValue.label; - defaultfilterValue.groupLabel = filterData.find(x => (x.key === defaultfilterValue.key)).label; - defaultFilterItems.push(defaultfilterValue); - } - }); - return defaultFilterItems; - } this.state = { - sortDirection: props.defaultFilterData ? props.defaultFilterData.sortDirection == "asc" ? true : false : false, - sortId: props.defaultFilterData ? - this.props.getSortData().findIndex(x => x.id === props.defaultFilterData.sortId) != -1 ? props.defaultFilterData.sortId : "" : - this.props.getSortData().length > 0 ? this.props.getSortData()[0].id : "", + sortDirection: props.selectedFilterData ? props.selectedFilterData.sortDirection == "asc" ? true : false : false, + sortId: props.selectedFilterData ? + this.props.getSortData().findIndex(x => x.key === props.selectedFilterData.sortId) != -1 ? props.selectedFilterData.sortId : "" : + this.props.getSortData().length > 0 ? this.props.getSortData()[0].key : "", - filterValue: props.defaultFilterData ? - getDefaultFilterData() : - [], - searchText: props.defaultFilterData ? props.defaultFilterData.inputValue : this.props.value + filterValue: props.selectedFilterData ? props.selectedFilterData.filterValue : [], + searchText: props.selectedFilterData ? props.selectedFilterData.inputValue : this.props.value }; this.timerId = null; + this.isNew = true; + this.isNeedUpdate = false; + + this.updatedProps = { + sortDirection: false, + sortId: false, + filterValue: false, + searchText: false + }; - this.getSortData = this.getSortData.bind(this); this.onClickSortItem = this.onClickSortItem.bind(this); this.onSortDirectionClick = this.onSortDirectionClick.bind(this); this.onSearch = this.onSearch.bind(this); @@ -66,33 +57,25 @@ class FilterInput extends React.Component { } getDefaultSelectedIndex(){ - const sortData = this.getSortData(); + const sortData = this.props.getSortData(); if(sortData.length > 0){ - let defaultIndex = sortData.findIndex(x => x.id === this.state.sortId); + let defaultIndex = sortData.findIndex(x => x.key === this.state.sortId); return defaultIndex != -1 ? defaultIndex : 0; } return 0; } - getSortData() { - let _this = this; - let d = this.props.getSortData(); - d.map(function (item) { - item.key = item.id; - return item; - }); - return d; - } onClickSortItem(item) { - this.setState({ sortId: item.id }); - this.onFilter(this.state.filterValue, item.id, this.state.sortDirection ? "asc" : "desc"); + this.setState({ sortId: item.key }); + this.onFilter(this.state.filterValue, item.key, this.state.sortDirection ? "asc" : "desc"); } onSortDirectionClick(e) { - this.onFilter(this.state.filterValue, this.state.sortId, !this.state.sortDirection ? "asc" : "desc") + this.isNeedUpdate = true; + this.onFilter(this.state.filterValue, this.state.sortId, !this.state.sortDirection ? "asc" : "desc"); this.setState({ sortDirection: !this.state.sortDirection }); } onSearch(result) { this.setState({ filterValue: result.filterValue }); - this.onFilter(result.filterValue, this.state.sortId, this.state.sortDirection ? "asc" : "desc") + this.onFilter(result.filterValue, this.state.sortId, this.state.sortDirection ? "asc" : "desc"); } onFilter(filterValue, sortId, sortDirection) { @@ -101,7 +84,7 @@ class FilterInput extends React.Component { filterValue: filterValue, sortId: sortId, sortDirection: sortDirection - } + }; this.props.onFilter(result); } @@ -116,11 +99,73 @@ class FilterInput extends React.Component { } onSearchChanged(e) { - this.setState({ searchText: e.target.value }) + this.isNeedUpdate = true; + this.setState({ searchText: e.target.value }); if (this.props.autoRefresh) this.setFilterTimer(); } + componentDidUpdate(){ + if(this.isNeedUpdate){ + this.setState( + { + sortDirection: this.updatedProps.sortDirection ? this.props.selectedFilterData.sortDirection == "asc" ? true : false : this.state.sortDirection, + sortId: this.updatedProps.sortId ? this.props.getSortData().findIndex(x => x.key === this.props.selectedFilterData.sortId) != -1 ? this.props.selectedFilterData.sortId : "" : this.state.sortId, + filterValue: this.updatedProps.filterValue ? this.props.selectedFilterData.filterValue ? this.props.selectedFilterData.filterValue : [] : this.state.filterValue, + searchText: this.updatedProps.searchText ? this.props.selectedFilterData.inputValue ? this.props.selectedFilterData.inputValue : this.props.value : this.state.searchText + } + ); + this.updatedProps={ + sortDirection: false, + sortId: false, + filterValue: false, + searchText: false + } + } + } + shouldComponentUpdate(nextProps, nextState){ + if(!this.isNeedUpdate){ + for (let propsKey in this.props) { + if(typeof this.props[propsKey] != "function" && typeof this.props[propsKey] != "object" && this.props[propsKey] != nextProps[propsKey]){ + this.isNeedUpdate = true; + break; + } + } + if(nextProps.selectedFilterData && this.props.selectedFilterData){ + if(this.props.selectedFilterData.filterValue.length != nextProps.selectedFilterData.filterValue.length){ + this.updatedProps.filterValue = true; + this.isNeedUpdate = true; + }else{ + let newFilterItems = nextProps.selectedFilterData.filterValue; + let oldFilterItems = this.props.selectedFilterData.filterValue; + + for(let i = 0; i < newFilterItems.length; i++){ + if(oldFilterItems.find(x => (x.key === newFilterItems[i].key && x.group === newFilterItems[i].group)) == undefined){ + this.updatedProps.filterValue = true; + this.isNeedUpdate = true; + break; + } + } + } + } + if(nextProps.selectedFilterData.inputValue != this.props.selectedFilterData.inputValue){ + this.updatedProps.searchText = true; + this.isNeedUpdate = true; + } + if(nextProps.selectedFilterData.sortDirection != this.props.selectedFilterData.sortDirection){ + this.updatedProps.sortDirection = true; + this.isNeedUpdate = true; + } + if(nextProps.selectedFilterData.sortId != this.props.selectedFilterData.sortId){ + this.updatedProps.sortId = true; + this.isNeedUpdate = true; + } + if(!this.isNeedUpdate) return false; + else return true; + } + this.isNeedUpdate = false; + return true; + } render() { //console.log("FilterInput render"); @@ -138,16 +183,16 @@ class FilterInput extends React.Component { onSearchClick={this.onSearch} onChangeFilter={this.onSearch} value={this.state.searchText} - defaultFilterData={this.state.filterValue} + selectedFilterData={this.state.filterValue} onChange={this.onSearchChanged} /> props.isDisabled ? 'default' : 'pointer'}; font-family: Open Sans; font-style: normal; :hover{ - border-color: #A3A9AE; + border-color: ${props => props.isDisabled ? '#ECEEF1' : '#A3A9AE'}; } :active{ - background-color: #ECEEF1; + background-color: ${props => props.isDisabled ? '#F8F9F9' : '#ECEEF1'}; } `; const StyledHideFilter = styled.div` @@ -52,16 +52,18 @@ class HideFilter extends React.Component { } toggle() { - this.setState({ - popoverOpen: !this.state.popoverOpen - }); + if(!this.props.isDisabled){ + this.setState({ + popoverOpen: !this.state.popoverOpen + }); + } } render() { //console.log("HideFilter render"); return ( - {this.props.count} + {this.props.count} props.block ? 'block' : 'inline-block'}; margin-bottom: ${props => props.block ? '3px' : '0'}; @@ -37,7 +36,6 @@ const StyledFilterItem = styled.div` margin-bottom: 0; } `; - const StyledCloseButtonBlock = styled.div` display: flex; align-items: center; @@ -49,7 +47,6 @@ const StyledCloseButtonBlock = styled.div` top: 0; `; - const FilterItem = props => { //console.log("FilterItem render"); const { groupLabel, id, label, block } = props; @@ -66,18 +63,51 @@ const FilterItem = props => { ); }; +const cloneProperty = function(props){ + var newProps = []; + props.forEach(item=> { + let cloneItem = {}; + for (var key in item) { + cloneItem[key] = item[key]; + } + newProps.push(cloneItem); + }); + return newProps; +} + class SearchInput extends React.Component { constructor(props) { super(props); + function getDefaultFilterData(){ + let filterData = props.getFilterData(); + let filterItems = []; + let selectedFilterData = cloneProperty(props.selectedFilterData); + selectedFilterData.forEach(defaultfilterValue => { + let filterValue = filterData.find(x => ((x.key === defaultfilterValue.key.replace(defaultfilterValue.group + "_",'')) && x.group === defaultfilterValue.group)); + if(filterValue != undefined){ + defaultfilterValue.key = defaultfilterValue.group + "_" + defaultfilterValue.key; + defaultfilterValue.label = filterValue.label; + defaultfilterValue.groupLabel = filterData.find(x => (x.key === defaultfilterValue.group)).label; + filterItems.push(defaultfilterValue); + } + }); + return filterItems; + } + this.minWidth = 190; this.isUpdateFilter = true; + this.isResizeUpdate = false; + this.isNewProps = false; + this.isUpdatedHiddenItems = false; + + this.isNew = true; + this.state = { - filterItems: props.defaultFilterData ? props.defaultFilterData : [], + filterItems: props.selectedFilterData ? getDefaultFilterData() : [], openFilterItems: [], hideFilterItems: [] }; - this.searchWrapper = React.createRef(); this.filterWrapper = React.createRef(); @@ -88,30 +118,37 @@ class SearchInput extends React.Component { this.getFilterItems = this.getFilterItems.bind(this); this.updateFilter = this.updateFilter.bind(this); this.resize = this.resize.bind(this); - } +} onClickDropDownItem(event, filterItem){ - - let curentFilterItems = this.state.filterItems.slice(); - let filterItems = this.getData() - let indexFilterItem = curentFilterItems.findIndex(x => x.key === filterItem.group); + let curentFilterItems = cloneProperty(this.state.filterItems); + let filterItems = this.getData(); + + let indexFilterItem = curentFilterItems.findIndex(x => x.group === filterItem.group); if(indexFilterItem != -1){ curentFilterItems.splice(indexFilterItem, 1); } - + let selectFilterItem = { - key: filterItem.group, - value: filterItem.key, + key: filterItem.key, + group: filterItem.group, label: filterItem.label, groupLabel: filterItems.find(x => x.key === filterItem.group).label }; curentFilterItems.push(selectFilterItem); + this.setState({ filterItems: curentFilterItems}); - this.setState({ filterItems: curentFilterItems}); + let clone = cloneProperty(curentFilterItems); + clone.map(function(item){ + item.key = item.key.replace(item.group + "_" ,''); + return item; + }) if(typeof this.props.onChangeFilter === "function") this.props.onChangeFilter({ inputValue: this.props.value, - filterValue: this.props.isNeedFilter ? curentFilterItems : null + filterValue: this.props.isNeedFilter ? + clone : + null }); this.isUpdateFilter = false; } @@ -121,6 +158,7 @@ class SearchInput extends React.Component { let d = this.props.getFilterData(); d.map(function(item){ item.onClick = !item.isSeparator && !item.isHeader && !item.disabled ? ((e) => _this.onClickDropDownItem(e, item)) : undefined; + item.key = item.group != item.key ? item.group +"_"+ item.key : item.key; return item; }); return d; @@ -129,7 +167,10 @@ class SearchInput extends React.Component { onSearchClick(e, value){ let searchResult = { inputValue: value, - filterValue: this.props.isNeedFilter ? this.state.filterItems : null + filterValue: this.props.isNeedFilter ? this.state.filterItems.map(function(item){ + item.key = item.key.replace(item.group + "_",''); + return item; + }) : null }; if(typeof this.props.onSearchClick === "function") this.props.onSearchClick(searchResult); @@ -147,7 +188,11 @@ class SearchInput extends React.Component { if(typeof this.props.onChangeFilter === "function") this.props.onChangeFilter({ inputValue: this.props.value, - filterValue: this.props.isNeedFilter ? curentFilterItems : null + filterValue: this.props.isNeedFilter ? + curentFilterItems.map(function(item){ + item.key = item.key.replace(item.group + "_",''); + return item; + }) : null }); this.isUpdateFilter = false; } @@ -162,7 +207,7 @@ class SearchInput extends React.Component { return @@ -171,7 +216,7 @@ class SearchInput extends React.Component { } if(this.state.hideFilterItems.length > 0 && this.isUpdateFilter){ hideItems.push( - + { this.state.hideFilterItems.map(function(item) { return { openFilterWidth = openFilterWidth + element.getBoundingClientRect().width; if(openFilterWidth < fullWidth/3){ - newOpenFilterItems.push(this.state.filterItems.find(x => x.value === element.getAttribute('id'))); + newOpenFilterItems.push(this.state.filterItems.find(x => x.key === element.getAttribute('id'))); }else{ - newHideFilterItems.push(this.state.filterItems.find(x => x.value === element.getAttribute('id'))); + newHideFilterItems.push(this.state.filterItems.find(x => x.key === element.getAttribute('id'))); } }); this.setState({ openFilterItems: newOpenFilterItems}); this.setState({ hideFilterItems: newHideFilterItems}); - }else{ this.setState({ openFilterItems: this.state.filterItems.slice()}); this.setState({ hideFilterItems: []}); + } + this.isUpdatedHiddenItems = true; this.isUpdateFilter = true; } + resize(){ + this.isResizeUpdate = true; this.isUpdateFilter = false; this.forceUpdate(); } componentDidUpdate(){ - if(!this.isUpdateFilter) this.updateFilter(); + if(!this.isUpdateFilter){ + this.updateFilter(); + }else if(this.isNewProps && this.props.isNeedFilter){ + let filterData = this.props.getFilterData(); + let filterItems = []; + + let curentFilterItems = cloneProperty(this.props.selectedFilterData); + + for(let i=0; i < curentFilterItems.length; i++){ + let filterValue = filterData.find(x => ((x.key === curentFilterItems[i].key.replace(curentFilterItems[i].group + "_",'')) && x.group === curentFilterItems[i].group)); + if(filterValue != undefined){ + curentFilterItems[i].key = curentFilterItems[i].group + "_" + curentFilterItems[i].key; + curentFilterItems[i].label = filterValue.label; + curentFilterItems[i].groupLabel = filterData.find(x => (x.group === curentFilterItems[i].group)).label; + filterItems.push(curentFilterItems[i]); + } + } + this.isNewProps= false; + this.isUpdateFilter = false; + this.setState({ filterItems: filterItems}); + } } - componentDidMount() { window.addEventListener('resize', _.throttle(this.resize), 100); this.isUpdateFilter = false; this.updateFilter(); @@ -253,8 +318,66 @@ class SearchInput extends React.Component { componentWillUnmount() { window.removeEventListener('resize', this.resize()); } + shouldComponentUpdate(nextProps, nextState){ + if(!this.isNew){ + let isNeedUpdate = false; + + if(nextProps.selectedFilterData && this.props.selectedFilterData && this.props.isNeedFilter){ + if(this.props.selectedFilterData.length != nextProps.selectedFilterData.length){ + this.isNewProps = true; + isNeedUpdate = true; + }else{ + let newFilterItems = nextProps.selectedFilterData; + let oldFilterItems = this.props.selectedFilterData; + + for(let i = 0; i < newFilterItems.length; i++){ + if(oldFilterItems.find(x => (x.key === newFilterItems[i].key && x.group === newFilterItems[i].group)) == undefined){ + this.isNewProps = true; + isNeedUpdate = true; + break; + } + } + } + } + if(!isNeedUpdate){ + for (let propsKey in this.props) { + if(typeof this.props[propsKey] != "function" && typeof this.props[propsKey] != "object" && this.props[propsKey] != nextProps[propsKey]){ + isNeedUpdate = true; + break; + } + } + } + if(!isNeedUpdate){ + for (let key in this.state) { + if(this.state[key].length != nextState[key].length){ + isNeedUpdate = true; + }else{ + for(let i = 0; i < this.state[key].length; i++){ + if(nextState[key].find(x => (x.key === this.state[key][i].key && x.group === this.state[key][i].group)) == undefined){ + isNeedUpdate = true; + break; + } + } + } + } + } + if(!isNeedUpdate && !this.isResizeUpdate){ + if(nextProps.value == this.props.value){ + if(!this.isUpdatedHiddenItems){ + this.isUpdatedHiddenItems = false; + return false; + } + } + }else if(this.isResizeUpdate){ + this.isResizeUpdate = false + } + } + this.isNew = false; + return true; + } render() { + //console.log("Search input render"); let _this = this; let iconSize = 32; switch (this.props.size) { @@ -309,7 +432,8 @@ SearchInput.propTypes = { onChange: PropTypes.func, getFilterData:PropTypes.func, isNeedFilter: PropTypes.bool, - isDisabled: PropTypes.bool + isDisabled: PropTypes.bool, + selectedFilterData: PropTypes.array }; SearchInput.defaultProps = { @@ -317,7 +441,8 @@ SearchInput.defaultProps = { value: '', scale: false, isNeedFilter: false, - isDisabled: false + isDisabled: false, + selectedFilterData: [] }; export default SearchInput; \ No newline at end of file diff --git a/web/ASC.Web.Storybook/stories/filter/README.md b/web/ASC.Web.Storybook/stories/filter/README.md index 5797bfb09f..df68e13eae 100644 --- a/web/ASC.Web.Storybook/stories/filter/README.md +++ b/web/ASC.Web.Storybook/stories/filter/README.md @@ -15,10 +15,10 @@ FilterInput description ```js [ { key: 'filter-example', group: 'filter-example', label: 'example group', isHeader: true }, - { key: 'filter-example-test', group: 'filter-example', label: 'Test' }] + { key: '0', group: 'filter-example', label: 'Test' }] } - getSortData={() => [ { id: 'name', label: 'Name' }, - { id: 'surname', label: 'Surname'] + getSortData={() => [ { key: 'name', label: 'Name' }, + { key: 'surname', label: 'Surname'] onFilter={(result) => {console.log(result)}} /> ``` @@ -33,6 +33,6 @@ FilterInput description | `placeholder` | `string` | - | - | - | Placeholder text for the input | | `size` | `string` | | `base`, `middle`, `big`, `huge`| `base` | Supported size of the input fields. | | `scale` | `bool` | - | - | - | Indicates the input field has scale | -| `defaultFilterData` | `object` | - | - | - | Default filter data | +| `selectedFilterData` | `object` | - | - | - | Selected filter data | diff --git a/web/ASC.Web.Storybook/stories/filter/base/base.filter.stories.js b/web/ASC.Web.Storybook/stories/filter/base/base.filter.stories.js index 8fe7db5f9e..3504f7e9e4 100644 --- a/web/ASC.Web.Storybook/stories/filter/base/base.filter.stories.js +++ b/web/ASC.Web.Storybook/stories/filter/base/base.filter.stories.js @@ -5,45 +5,59 @@ import { StringValue } from 'react-values'; import { withKnobs, boolean, text, select, number } from '@storybook/addon-knobs/react'; import withReadme from 'storybook-readme/with-readme'; import Readme from '../README.md'; -import { FilterInput } from 'asc-web-components'; +import { FilterInput, Button } from 'asc-web-components'; import Section from '../../../.storybook/decorators/section'; const sizeOptions = ['base', 'middle', 'big', 'huge']; -const defaultFilterData = { - filterValue: [ - {key: "filter-status", value: "filter-status-disabled"} - ], - sortDirection: "desc", - sortId: "name", - inputValue: "text" -}; - function getData() { return [ { key: 'filter-status', group: 'filter-status', label: 'Status', isHeader: true }, - { key: 'filter-status-active', group: 'filter-status', label: 'Active' }, - { key: 'filter-status-disabled', group: 'filter-status', label: 'Disabled' }, + { key: '0', group: 'filter-status', label: 'Active' }, + { key: '1', group: 'filter-status', label: 'Disabled' }, { key: 'filter-type', group: 'filter-type', label: 'Type', isHeader: true }, - { key: 'filter-type-administrator', group: 'filter-type', label: 'Folders' }, - { key: 'filter-type-employee', group: 'filter-type', label: 'Employee' }, + { key: '0', group: 'filter-type', label: 'Folders' }, + { key: '1', group: 'filter-type', label: 'Employee' }, ]; } function getSortData() { return [ - { - id: 'name', label: 'Name' - }, - { - id: 'surname', label: 'Surname' - } + {key: 'name', label: 'Name'}, + {key: 'surname', label: 'Surname'} ]; } -storiesOf('Components|Filter', module) - .addDecorator(withKnobs) - .addDecorator(withReadme(Readme)) - .add('base', () => ( -
+ +class FilterStory extends React.Component { + constructor(props) { + super(props); + this.state = { + selectedFilterData: { + filterValue: [ + {key: "1", group: "filter-status"} + ], + sortDirection: "desc", + sortId: "name", + inputValue: "text" + } + }; + this.buttonClick = this.buttonClick.bind(this); + } + buttonClick(){ + this.setState({ + selectedFilterData: { + filterValue: [ + {key: "0", group: "filter-status"}, + {key: "1", group: "filter-type"} + ], + sortDirection: "asc", + sortId: "surname", + inputValue: "text 123" + } + }); + } + render(){ + return( +
{ action('onChange')(e); @@ -52,19 +66,24 @@ storiesOf('Components|Filter', module) > {({ value, set }) => (
+
+
{console.log(result)}} value={value} - defaultFilterData={defaultFilterData} + selectedFilterData={this.state.selectedFilterData} onChange={e => { set(e.target.value); }} @@ -74,4 +93,13 @@ storiesOf('Components|Filter', module) )}
+ ) + } +} + +storiesOf('Components|Filter', module) + .addDecorator(withKnobs) + .addDecorator(withReadme(Readme)) + .add('base', () => ( + )); \ No newline at end of file diff --git a/web/ASC.Web.Storybook/stories/input/search/README.md b/web/ASC.Web.Storybook/stories/input/search/README.md index 129111a02d..a536a1f0c6 100644 --- a/web/ASC.Web.Storybook/stories/input/search/README.md +++ b/web/ASC.Web.Storybook/stories/input/search/README.md @@ -34,4 +34,5 @@ SearchInput description | `size` | `string` | | `base`, `middle`, `big`, `huge`| `base` | Supported size of the input fields. | | `scale` | `bool` | - | - | - | Indicates the input field has scale | | `isNeedFilter` | `bool` | | | `false` | Determines if filter is needed | +| `selectedFilterData` | `array` | - | | | Selected filter data | diff --git a/web/ASC.Web.Storybook/stories/input/search/index.stories.js b/web/ASC.Web.Storybook/stories/input/search/index.stories.js index f7e4f2a2c2..efa4c3f477 100644 --- a/web/ASC.Web.Storybook/stories/input/search/index.stories.js +++ b/web/ASC.Web.Storybook/stories/input/search/index.stories.js @@ -5,26 +5,41 @@ import { StringValue } from 'react-values'; import { withKnobs, boolean, text, select, number } from '@storybook/addon-knobs/react'; import withReadme from 'storybook-readme/with-readme'; import Readme from './README.md'; -import { SearchInput } from 'asc-web-components'; +import { SearchInput, Button } from 'asc-web-components'; import Section from '../../../.storybook/decorators/section'; const sizeOptions = ['base', 'middle', 'big', 'huge']; + function getData() { return [ { key: 'filter-status', group: 'filter-status', label: 'Status', isHeader: true }, - { key: 'filter-status-active', group: 'filter-status', label: 'Active' }, - { key: 'filter-status-disabled', group: 'filter-status', label: 'Disabled' }, + { key: '0', group: 'filter-status', label: 'Active' }, + { key: '1', group: 'filter-status', label: 'Disabled' }, { key: 'filter-type', group: 'filter-type', label: 'Type', isHeader: true }, - { key: 'filter-type-administrator', group: 'filter-type', label: 'Folders' }, - { key: 'filter-type-employee', group: 'filter-type', label: 'Employee' }, + { key: '0', group: 'filter-type', label: 'Folders' }, + { key: '1', group: 'filter-type', label: 'Employee' }, ]; +} +class SearchStory extends React.Component { + constructor(props) { + super(props); + this.state = { + selectedFilterData: [ + {key: "0", group: "filter-status"} + ] + }; + this.buttonClick = this.buttonClick.bind(this); } - -storiesOf('Components|Input', module) - .addDecorator(withKnobs) - .addDecorator(withReadme(Readme)) - .add('search', () => ( -
+ buttonClick(){ + this.setState({ selectedFilterData:[ + {key: "1", group: "filter-status"}, + {key: "1", group: "filter-type"} + ] + }); + } + render(){ + return( +
{ action('onChange')(e); @@ -33,6 +48,12 @@ storiesOf('Components|Input', module) > {({ value, set }) => (
+
+
{console.log(result)}} onChangeFilter={(result) => {console.log(result)}} @@ -51,5 +73,14 @@ storiesOf('Components|Input', module)
)}
-
+
+ ) + } +} + +storiesOf('Components|Input', module) + .addDecorator(withKnobs) + .addDecorator(withReadme(Readme)) + .add('search', () => ( + )); \ No newline at end of file From bd308070e82cc0c6f9b1a93b9611486ff956c92f Mon Sep 17 00:00:00 2001 From: NikolayRechkin Date: Thu, 8 Aug 2019 12:45:55 +0300 Subject: [PATCH 5/5] web: components: fixed IconButton component --- .../src/components/icon-button/index.js | 68 +++++++++++-------- 1 file changed, 38 insertions(+), 30 deletions(-) diff --git a/web/ASC.Web.Components/src/components/icon-button/index.js b/web/ASC.Web.Components/src/components/icon-button/index.js index c51ab741d5..ed08ed1e5f 100644 --- a/web/ASC.Web.Components/src/components/icon-button/index.js +++ b/web/ASC.Web.Components/src/components/icon-button/index.js @@ -24,42 +24,50 @@ class IconButton extends React.Component{ onMouseEnter(e){ - this.setState({ - currentIconName: this.props.iconHoverName ? this.props.iconHoverName : this.props.iconName, - currentIconColor: this.props.hoverColor ? this.props.hoverColor : this.props.color - }); - this.props.onMouseEnter && this.props.onMouseEnter(e); + if(!this.props.isDisabled){ + this.setState({ + currentIconName: this.props.iconHoverName ? this.props.iconHoverName : this.props.iconName, + currentIconColor: this.props.hoverColor ? this.props.hoverColor : this.props.color + }); + this.props.onMouseEnter && this.props.onMouseEnter(e); + } } onMouseLeave(e){ - this.setState({ - currentIconName: this.props.iconName, - currentIconColor: this.props.color - }); - this.props.onMouseDown && this.props.onMouseDown(e); + if(!this.props.isDisabled){ + this.setState({ + currentIconName: this.props.iconName, + currentIconColor: this.props.color + }); + this.props.onMouseDown && this.props.onMouseDown(e); + } } onMouseDown(e){ - this.setState({ - currentIconName: this.props.iconClickName ? this.props.iconClickName : this.props.iconName, - currentIconColor: this.props.clickColor ? this.props.clickColor : this.props.color - }); - this.props.onMouseDown && this.props.onMouseDown(e); + if(!this.props.isDisabled){ + this.setState({ + currentIconName: this.props.iconClickName ? this.props.iconClickName : this.props.iconName, + currentIconColor: this.props.clickColor ? this.props.clickColor : this.props.color + }); + this.props.onMouseDown && this.props.onMouseDown(e); + } } onMouseUp(e){ - switch (e.nativeEvent.which) { - case 1: //Left click - this.setState({ - currentIconName: this.props.iconHoverName ? this.props.iconHoverName : this.props.iconName, - currentIconColor: this.props.iconHoverName ? this.props.iconHoverName : this.props.color - }); - this.props.onClick && this.props.onClick(e); - this.props.onMouseUp && this.props.onMouseUp(e); - break; - case 3://Right click - this.props.onMouseUp && this.props.onMouseUp(e); - break; - - default: - break; + if(!this.props.isDisabled){ + switch (e.nativeEvent.which) { + case 1: //Left click + this.setState({ + currentIconName: this.props.iconHoverName ? this.props.iconHoverName : this.props.iconName, + currentIconColor: this.props.iconHoverName ? this.props.iconHoverName : this.props.color + }); + this.props.onClick && this.props.onClick(e); + this.props.onMouseUp && this.props.onMouseUp(e); + break; + case 3://Right click + this.props.onMouseUp && this.props.onMouseUp(e); + break; + + default: + break; + } } } render(){