DocSpace-buildtools/common/ASC.Core.Common/Context/Impl/UserManager.cs

922 lines
31 KiB
C#
Raw Normal View History

2022-03-15 18:00:53 +00:00
// (c) Copyright Ascensio System SIA 2010-2022
//
// This program is a free software product.
// You can redistribute it and/or modify it under the terms
// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software
// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended
// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of
// any third-party rights.
//
// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see
// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
//
// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021.
//
// The interactive user interfaces in modified source and object code versions of the Program must
// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3.
//
// Pursuant to Section 7(b) of the License you must retain the original Product logo when
// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under
// trademark law for use of our trademarks.
//
// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing
// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
using Constants = ASC.Core.Users.Constants;
2019-08-30 12:40:57 +00:00
2022-02-15 11:52:43 +00:00
namespace ASC.Core;
[Singletone]
public class UserManagerConstants
2020-10-18 16:03:14 +00:00
{
2022-02-15 11:52:43 +00:00
public IDictionary<Guid, UserInfo> SystemUsers { get; }
internal Constants Constants { get; }
public UserManagerConstants(Constants constants)
{
SystemUsers = Configuration.Constants.SystemAccounts.ToDictionary(a => a.ID, a => new UserInfo { Id = a.ID, LastName = a.Name });
SystemUsers[Constants.LostUser.Id] = Constants.LostUser;
SystemUsers[Constants.OutsideUser.Id] = Constants.OutsideUser;
SystemUsers[constants.NamingPoster.Id] = constants.NamingPoster;
Constants = constants;
}
}
[Scope]
public class UserManager
{
private IDictionary<Guid, UserInfo> SystemUsers => _userManagerConstants.SystemUsers;
private readonly IHttpContextAccessor _accessor;
private readonly IUserService _userService;
private readonly TenantManager _tenantManager;
private readonly PermissionContext _permissionContext;
private readonly UserManagerConstants _userManagerConstants;
private readonly CoreBaseSettings _coreBaseSettings;
2022-06-01 14:07:08 +00:00
private readonly CoreSettings _coreSettings;
private readonly InstanceCrypto _instanceCrypto;
private readonly RadicaleClient _radicaleClient;
private readonly CardDavAddressbook _cardDavAddressbook;
private readonly ILogger<UserManager> _log;
private readonly ICache _cache;
2022-11-15 10:28:25 +00:00
private readonly TenantQuotaFeatureCheckerCount<CountRoomAdminFeature> _countRoomAdminChecker;
2022-10-18 18:37:16 +00:00
private readonly TenantQuotaFeatureCheckerCount<CountUserFeature> _activeUsersFeatureChecker;
2022-02-15 11:52:43 +00:00
private readonly Constants _constants;
private readonly UserFormatter _userFormatter;
2022-02-15 11:52:43 +00:00
private Tenant _tenant;
private Tenant Tenant => _tenant ??= _tenantManager.GetCurrentTenant();
public UserManager()
{
}
public UserManager(
IUserService service,
TenantManager tenantManager,
PermissionContext permissionContext,
UserManagerConstants userManagerConstants,
2022-06-01 14:07:08 +00:00
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
InstanceCrypto instanceCrypto,
RadicaleClient radicaleClient,
CardDavAddressbook cardDavAddressbook,
ILogger<UserManager> log,
2022-09-19 14:56:45 +00:00
ICache cache,
2022-11-15 10:28:25 +00:00
TenantQuotaFeatureCheckerCount<CountRoomAdminFeature> countRoomAdrminChecker,
TenantQuotaFeatureCheckerCount<CountUserFeature> activeUsersFeatureChecker,
UserFormatter userFormatter
2022-09-19 14:56:45 +00:00
)
2022-02-15 11:52:43 +00:00
{
_userService = service;
_tenantManager = tenantManager;
_permissionContext = permissionContext;
_userManagerConstants = userManagerConstants;
_coreBaseSettings = coreBaseSettings;
2022-06-01 14:07:08 +00:00
_coreSettings = coreSettings;
_instanceCrypto = instanceCrypto;
_radicaleClient = radicaleClient;
_cardDavAddressbook = cardDavAddressbook;
_log = log;
_cache = cache;
2022-11-15 10:28:25 +00:00
_countRoomAdminChecker = countRoomAdrminChecker;
2022-09-19 14:56:45 +00:00
_activeUsersFeatureChecker = activeUsersFeatureChecker;
2022-02-15 11:52:43 +00:00
_constants = _userManagerConstants.Constants;
_userFormatter = userFormatter;
2022-02-15 11:52:43 +00:00
}
public UserManager(
IUserService service,
TenantManager tenantManager,
PermissionContext permissionContext,
UserManagerConstants userManagerConstants,
CoreBaseSettings coreBaseSettings,
2022-06-01 14:07:08 +00:00
CoreSettings coreSettings,
InstanceCrypto instanceCrypto,
RadicaleClient radicaleClient,
CardDavAddressbook cardDavAddressbook,
ILogger<UserManager> log,
ICache cache,
TenantQuotaFeatureCheckerCount<CountRoomAdminFeature> tenantQuotaFeatureChecker,
2022-10-18 18:37:16 +00:00
TenantQuotaFeatureCheckerCount<CountUserFeature> activeUsersFeatureChecker,
IHttpContextAccessor httpContextAccessor,
UserFormatter userFormatter)
: this(service, tenantManager, permissionContext, userManagerConstants, coreBaseSettings, coreSettings, instanceCrypto, radicaleClient, cardDavAddressbook, log, cache, tenantQuotaFeatureChecker, activeUsersFeatureChecker, userFormatter)
2022-02-15 11:52:43 +00:00
{
_accessor = httpContextAccessor;
}
public void ClearCache()
{
if (_userService is ICachedService service)
2021-08-06 14:30:51 +00:00
{
2022-02-15 11:52:43 +00:00
service.InvalidateCache();
}
}
#region Users
2022-02-15 11:52:43 +00:00
public UserInfo[] GetUsers()
{
return GetUsers(EmployeeStatus.Default);
}
public UserInfo[] GetUsers(EmployeeStatus status)
{
return GetUsers(status, EmployeeType.All);
}
public UserInfo[] GetUsers(EmployeeStatus status, EmployeeType type)
{
var users = GetUsersInternal().Where(u => (u.Status & status) == u.Status);
switch (type)
{
2022-10-18 11:22:02 +00:00
case EmployeeType.RoomAdmin:
users = users.Where(u => !this.IsUser(u));
2022-02-15 11:52:43 +00:00
break;
2022-10-18 11:22:02 +00:00
case EmployeeType.User:
users = users.Where(u => this.IsUser(u));
2022-02-15 11:52:43 +00:00
break;
2021-11-23 12:25:34 +00:00
}
2022-02-15 11:52:43 +00:00
return users.ToArray();
}
public IQueryable<UserInfo> GetUsers(
2022-10-18 11:22:02 +00:00
bool isDocSpaceAdmin,
2022-02-15 11:52:43 +00:00
EmployeeStatus? employeeStatus,
List<List<Guid>> includeGroups,
List<Guid> excludeGroups,
EmployeeActivationStatus? activationStatus,
string text,
string sortBy,
bool sortOrderAsc,
long limit,
long offset,
out int total,
out int count)
{
2022-10-18 11:22:02 +00:00
return _userService.GetUsers(Tenant.Id, isDocSpaceAdmin, employeeStatus, includeGroups, excludeGroups, activationStatus, text, sortBy, sortOrderAsc, limit, offset, out total, out count);
2022-02-15 11:52:43 +00:00
}
public string[] GetUserNames(EmployeeStatus status)
{
return GetUsers(status)
.Select(u => u.UserName)
.Where(s => !string.IsNullOrEmpty(s))
.ToArray();
}
public UserInfo GetUserByUserName(string username)
{
var u = _userService.GetUserByUserName(_tenantManager.GetCurrentTenant().Id, username);
return u ?? Constants.LostUser;
}
public UserInfo GetUserBySid(string sid)
{
return GetUsersInternal()
.FirstOrDefault(u => u.Sid != null && string.Equals(u.Sid, sid, StringComparison.CurrentCultureIgnoreCase)) ?? Constants.LostUser;
2022-02-15 11:52:43 +00:00
}
public UserInfo GetSsoUserByNameId(string nameId)
{
return GetUsersInternal()
.FirstOrDefault(u => !string.IsNullOrEmpty(u.SsoNameId) && string.Equals(u.SsoNameId, nameId, StringComparison.CurrentCultureIgnoreCase)) ?? Constants.LostUser;
}
public bool IsUserNameExists(string username)
{
return GetUserNames(EmployeeStatus.All)
.Contains(username, StringComparer.CurrentCultureIgnoreCase);
}
public UserInfo GetUsers(Guid id)
{
if (IsSystemUser(id))
{
2022-02-15 11:52:43 +00:00
return SystemUsers[id];
}
2022-02-15 11:52:43 +00:00
var u = _userService.GetUser(Tenant.Id, id);
2020-12-28 13:22:08 +00:00
2022-02-15 11:52:43 +00:00
return u != null && !u.Removed ? u : Constants.LostUser;
}
2022-02-15 11:52:43 +00:00
public UserInfo GetUser(Guid id, Expression<Func<User, UserInfo>> exp)
{
if (IsSystemUser(id))
{
return SystemUsers[id];
}
2022-02-15 11:52:43 +00:00
var u = _userService.GetUser(Tenant.Id, id, exp);
return u != null && !u.Removed ? u : Constants.LostUser;
}
public UserInfo GetUsersByPasswordHash(int tenant, string login, string passwordHash)
{
var u = _userService.GetUserByPasswordHash(tenant, login, passwordHash);
return u != null && !u.Removed ? u : Constants.LostUser;
}
public bool UserExists(Guid id)
{
return UserExists(GetUsers(id));
}
public bool UserExists(UserInfo user)
{
return !user.Equals(Constants.LostUser);
}
public bool IsSystemUser(Guid id)
{
return SystemUsers.ContainsKey(id);
}
public UserInfo GetUserByEmail(string email)
{
if (string.IsNullOrEmpty(email))
{
return Constants.LostUser;
}
var u = _userService.GetUser(Tenant.Id, email);
return u != null && !u.Removed ? u : Constants.LostUser;
}
public UserInfo[] Search(string text, EmployeeStatus status)
{
return Search(text, status, Guid.Empty);
}
public UserInfo[] Search(string text, EmployeeStatus status, Guid groupId)
{
if (text == null || text.Trim().Length == 0)
{
return new UserInfo[0];
}
var words = text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (words.Length == 0)
{
return Array.Empty<UserInfo>();
}
var users = groupId == Guid.Empty ?
GetUsers(status) :
GetUsersByGroup(groupId).Where(u => (u.Status & status) == status);
var findUsers = new List<UserInfo>();
foreach (var user in users)
{
var properties = new string[]
{
user.LastName ?? string.Empty,
user.FirstName ?? string.Empty,
user.Title ?? string.Empty,
user.Location ?? string.Empty,
2022-02-15 11:52:43 +00:00
user.Email ?? string.Empty,
};
if (IsPropertiesContainsWords(properties, words))
{
findUsers.Add(user);
}
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
return findUsers.ToArray();
}
2022-10-25 15:27:56 +00:00
public UserInfo UpdateUserInfo(UserInfo u)
2022-02-15 11:52:43 +00:00
{
if (IsSystemUser(u.Id))
2021-05-17 11:35:00 +00:00
{
2022-02-15 11:52:43 +00:00
return SystemUsers[u.Id];
}
2022-10-24 15:30:17 +00:00
_permissionContext.DemandPermissions(new UserSecurityProvider(u.Id), Constants.Action_EditUser);
if (u.Status == EmployeeStatus.Terminated && u.Id == _tenantManager.GetCurrentTenant().OwnerId)
2022-02-15 11:52:43 +00:00
{
2022-10-24 15:30:17 +00:00
throw new InvalidOperationException("Can not disable tenant owner.");
2022-02-15 11:52:43 +00:00
}
2022-10-24 15:30:17 +00:00
var oldUserData = _userService.GetUserByUserName(_tenantManager.GetCurrentTenant().Id, u.UserName);
if (oldUserData == null || Equals(oldUserData, Constants.LostUser))
{
throw new InvalidOperationException("User not found.");
}
2022-10-25 15:27:56 +00:00
return _userService.SaveUser(_tenantManager.GetCurrentTenant().Id, u);
}
public async Task<UserInfo> UpdateUserInfoWithSyncCardDavAsync(UserInfo u)
{
var oldUserData = _userService.GetUserByUserName(_tenantManager.GetCurrentTenant().Id, u.UserName);
var newUser = UpdateUserInfo(u);
2022-12-14 11:38:40 +00:00
if (_coreBaseSettings.DisableDocSpace)
{
await SyncCardDavAsync(u, oldUserData, newUser);
}
2022-10-24 15:30:17 +00:00
return newUser;
}
public async Task<UserInfo> SaveUserInfo(UserInfo u, bool isVisitor = false, bool syncCardDav = false)
2022-10-24 15:30:17 +00:00
{
if (IsSystemUser(u.Id))
{
return SystemUsers[u.Id];
}
_permissionContext.DemandPermissions(new UserSecurityProvider(u.Id, isVisitor ? EmployeeType.User : EmployeeType.RoomAdmin),
Constants.Action_AddRemoveUser);
2022-02-15 11:52:43 +00:00
if (!_coreBaseSettings.Personal)
{
if (_constants.MaxEveryoneCount <= GetUsersByGroup(Constants.GroupEveryone.ID).Length)
{
2022-02-15 11:52:43 +00:00
throw new TenantQuotaException("Maximum number of users exceeded");
}
2022-02-15 11:52:43 +00:00
}
2021-05-17 11:35:00 +00:00
2022-10-24 15:30:17 +00:00
var oldUserData = _userService.GetUserByUserName(_tenantManager.GetCurrentTenant().Id, u.UserName);
if (oldUserData != null && !Equals(oldUserData, Constants.LostUser))
2022-02-15 11:52:43 +00:00
{
2022-10-24 15:30:17 +00:00
throw new InvalidOperationException("User already exist.");
2022-02-15 11:52:43 +00:00
}
2022-10-24 15:30:17 +00:00
if (isVisitor)
2022-10-19 09:48:23 +00:00
{
2022-10-25 15:27:56 +00:00
await _activeUsersFeatureChecker.CheckAppend();
2022-10-24 15:30:17 +00:00
}
else
{
2022-11-15 10:28:25 +00:00
await _countRoomAdminChecker.CheckAppend();
2022-10-19 09:48:23 +00:00
}
2022-02-15 11:52:43 +00:00
var newUser = _userService.SaveUser(_tenantManager.GetCurrentTenant().Id, u);
2022-06-01 14:07:08 +00:00
if (syncCardDav)
{
2022-10-25 15:27:56 +00:00
await SyncCardDavAsync(u, oldUserData, newUser);
2022-10-24 15:30:17 +00:00
}
2022-06-01 14:07:08 +00:00
2022-10-24 15:30:17 +00:00
return newUser;
}
2022-10-25 15:27:56 +00:00
private async Task SyncCardDavAsync(UserInfo u, UserInfo oldUserData, UserInfo newUser)
2022-10-24 15:30:17 +00:00
{
var tenant = _tenantManager.GetCurrentTenant();
var myUri = (_accessor?.HttpContext != null) ? _accessor.HttpContext.Request.GetUrlRewriter().ToString() :
(_cache.Get<string>("REWRITE_URL" + tenant.Id) != null) ?
new Uri(_cache.Get<string>("REWRITE_URL" + tenant.Id)).ToString() : tenant.GetTenantDomain(_coreSettings);
var rootAuthorization = _cardDavAddressbook.GetSystemAuthorization();
var allUserEmails = GetDavUserEmails().ToList();
2022-06-01 14:07:08 +00:00
2022-10-24 15:30:17 +00:00
if (oldUserData != null && oldUserData.Status != newUser.Status && newUser.Status == EmployeeStatus.Terminated)
{
var userAuthorization = oldUserData.Email.ToLower() + ":" + _instanceCrypto.Encrypt(oldUserData.Email);
var requestUrlBook = _cardDavAddressbook.GetRadicaleUrl(myUri, newUser.Email.ToLower(), true, true);
2022-10-27 10:49:42 +00:00
var collection = await _cardDavAddressbook.GetCollection(requestUrlBook, userAuthorization, myUri.ToString());
2022-10-24 15:30:17 +00:00
if (collection.Completed && collection.StatusCode != 404)
2022-06-01 14:07:08 +00:00
{
2022-11-15 10:28:25 +00:00
await _cardDavAddressbook.Delete(myUri, newUser.Id, newUser.Email, tenant.Id);
2022-10-24 15:30:17 +00:00
}
foreach (var email in allUserEmails)
{
var requestUrlItem = _cardDavAddressbook.GetRadicaleUrl(myUri.ToString(), email.ToLower(), true, true, itemID: newUser.Id.ToString());
try
2022-06-01 14:07:08 +00:00
{
2022-10-24 15:30:17 +00:00
var davItemRequest = new DavRequest()
{
Url = requestUrlItem,
Authorization = rootAuthorization,
Header = myUri
};
2022-10-25 15:27:56 +00:00
await _radicaleClient.RemoveAsync(davItemRequest).ConfigureAwait(false);
2022-06-01 14:07:08 +00:00
}
2022-10-24 15:30:17 +00:00
catch (Exception ex)
2022-06-01 14:07:08 +00:00
{
2022-10-24 15:30:17 +00:00
_log.ErrorWithException(ex);
2022-06-01 14:07:08 +00:00
}
}
2022-10-24 15:30:17 +00:00
}
else
{
try
2022-06-01 14:07:08 +00:00
{
2022-10-24 15:30:17 +00:00
var cardDavUser = new CardDavItem(u.Id, u.FirstName, u.LastName, u.UserName, u.BirthDate, u.Sex, u.Title, u.Email, u.ContactsList, u.MobilePhone);
2022-06-01 14:07:08 +00:00
try
{
2022-11-15 10:28:25 +00:00
await _cardDavAddressbook.UpdateItemForAllAddBooks(allUserEmails, myUri, cardDavUser, _tenantManager.GetCurrentTenant().Id, oldUserData != null && oldUserData.Email != newUser.Email ? oldUserData.Email : null);
2022-06-01 14:07:08 +00:00
}
catch (Exception ex)
{
_log.ErrorWithException(ex);
}
}
2022-10-24 15:30:17 +00:00
catch (Exception ex)
{
_log.ErrorWithException(ex);
}
2022-06-01 14:07:08 +00:00
}
2022-02-15 11:52:43 +00:00
}
2022-10-24 15:30:17 +00:00
2022-06-01 14:07:08 +00:00
public IEnumerable<string> GetDavUserEmails()
{
return _userService.GetDavUserEmails(_tenantManager.GetCurrentTenant().Id);
}
2021-05-17 11:35:00 +00:00
public IEnumerable<int> GetTenantsWithFeeds(DateTime from)
{
return _userService.GetTenantsWithFeeds(from);
}
2022-10-27 11:06:37 +00:00
public async Task DeleteUser(Guid id)
2022-02-15 11:52:43 +00:00
{
if (IsSystemUser(id))
{
return;
2021-05-17 11:35:00 +00:00
}
2022-02-15 11:52:43 +00:00
_permissionContext.DemandPermissions(Constants.Action_AddRemoveUser);
if (id == Tenant.OwnerId)
{
throw new InvalidOperationException("Can not remove tenant owner.");
}
2022-06-01 14:07:08 +00:00
var delUser = GetUsers(id);
2022-02-15 11:52:43 +00:00
_userService.RemoveUser(Tenant.Id, id);
2022-06-01 14:07:08 +00:00
var tenant = _tenantManager.GetCurrentTenant();
try
{
var curreMail = delUser.Email.ToLower();
var currentAccountPaswd = _instanceCrypto.Encrypt(curreMail);
var userAuthorization = curreMail + ":" + currentAccountPaswd;
var rootAuthorization = _cardDavAddressbook.GetSystemAuthorization();
var myUri = (_accessor?.HttpContext != null) ? _accessor.HttpContext.Request.GetUrlRewriter().ToString() :
(_cache.Get<string>("REWRITE_URL" + tenant.Id) != null) ?
new Uri(_cache.Get<string>("REWRITE_URL" + tenant.Id)).ToString() : tenant.GetTenantDomain(_coreSettings);
var davUsersEmails = GetDavUserEmails();
var requestUrlBook = _cardDavAddressbook.GetRadicaleUrl(myUri, delUser.Email.ToLower(), true, true);
2022-10-27 10:49:42 +00:00
var addBookCollection = await _cardDavAddressbook.GetCollection(requestUrlBook, userAuthorization, myUri.ToString());
2022-06-01 14:07:08 +00:00
if (addBookCollection.Completed && addBookCollection.StatusCode != 404)
{
var davbookRequest = new DavRequest()
{
Url = requestUrlBook,
Authorization = rootAuthorization,
Header = myUri
};
2022-10-27 10:49:42 +00:00
await _radicaleClient.RemoveAsync(davbookRequest).ConfigureAwait(false);
2022-06-01 14:07:08 +00:00
}
foreach (var email in davUsersEmails)
{
var requestUrlItem = _cardDavAddressbook.GetRadicaleUrl(myUri.ToString(), email.ToLower(), true, true, itemID: delUser.Id.ToString());
try
{
var davItemRequest = new DavRequest()
{
Url = requestUrlItem,
Authorization = rootAuthorization,
Header = myUri
};
2022-10-27 10:49:42 +00:00
await _radicaleClient.RemoveAsync(davItemRequest).ConfigureAwait(false);
2022-06-01 14:07:08 +00:00
}
catch (Exception ex)
{
_log.ErrorWithException(ex);
}
}
}
catch (Exception ex)
{
_log.ErrorWithException(ex);
}
2022-02-15 11:52:43 +00:00
}
2022-02-15 11:52:43 +00:00
public void SaveUserPhoto(Guid id, byte[] photo)
{
if (IsSystemUser(id))
2021-08-06 14:30:51 +00:00
{
2022-02-15 11:52:43 +00:00
return;
}
2021-05-18 15:50:48 +00:00
2022-02-15 11:52:43 +00:00
_permissionContext.DemandPermissions(new UserSecurityProvider(id), Constants.Action_EditUser);
2021-05-18 15:50:48 +00:00
2022-02-15 11:52:43 +00:00
_userService.SetUserPhoto(Tenant.Id, id, photo);
}
2022-02-15 11:52:43 +00:00
public byte[] GetUserPhoto(Guid id)
{
if (IsSystemUser(id))
{
return null;
}
2021-09-28 17:30:02 +00:00
2022-02-15 11:52:43 +00:00
return _userService.GetUserPhoto(Tenant.Id, id);
}
2021-09-28 17:30:02 +00:00
2022-02-15 11:52:43 +00:00
public List<GroupInfo> GetUserGroups(Guid id)
{
return GetUserGroups(id, IncludeType.Distinct, Guid.Empty);
}
public List<GroupInfo> GetUserGroups(Guid id, Guid categoryID)
{
return GetUserGroups(id, IncludeType.Distinct, categoryID);
}
public List<GroupInfo> GetUserGroups(Guid userID, IncludeType includeType)
{
return GetUserGroups(userID, includeType, null);
}
internal List<GroupInfo> GetUserGroups(Guid userID, IncludeType includeType, Guid? categoryId)
{
if (_coreBaseSettings.Personal)
2021-09-28 17:30:02 +00:00
{
2022-09-19 14:56:45 +00:00
return new List<GroupInfo> { Constants.GroupManager, Constants.GroupEveryone };
2022-02-15 11:52:43 +00:00
}
2021-09-28 17:30:02 +00:00
2022-02-15 11:52:43 +00:00
var httpRequestDictionary = new HttpRequestDictionary<List<GroupInfo>>(_accessor?.HttpContext, "GroupInfo");
var result = httpRequestDictionary.Get(userID.ToString());
2022-12-08 11:55:05 +00:00
if (result != null && result.Count > 0)
2022-02-15 11:52:43 +00:00
{
if (categoryId.HasValue)
{
2022-02-15 11:52:43 +00:00
result = result.Where(r => r.CategoryID.Equals(categoryId.Value)).ToList();
}
2022-02-15 11:52:43 +00:00
return result;
}
2022-02-15 11:52:43 +00:00
result = new List<GroupInfo>();
var distinctUserGroups = new List<GroupInfo>();
var refs = GetRefsInternal();
IEnumerable<UserGroupRef> userRefs = null;
if (refs is UserGroupRefStore store)
{
userRefs = store.GetRefsByUser(userID);
}
2022-02-15 11:52:43 +00:00
var userRefsContainsNotRemoved = userRefs?.Where(r => !r.Removed && r.RefType == UserGroupRefType.Contains).ToList();
foreach (var g in GetGroupsInternal().Where(g => !categoryId.HasValue || g.CategoryID == categoryId))
{
if (((g.CategoryID == Constants.SysGroupCategoryId || userRefs == null) && IsUserInGroupInternal(userID, g.ID, refs)) ||
(userRefsContainsNotRemoved != null && userRefsContainsNotRemoved.Any(r => r.GroupId == g.ID)))
{
2022-02-15 11:52:43 +00:00
distinctUserGroups.Add(g);
}
2022-02-15 11:52:43 +00:00
}
2022-02-15 11:52:43 +00:00
if (IncludeType.Distinct == (includeType & IncludeType.Distinct))
{
result.AddRange(distinctUserGroups);
}
result.Sort((group1, group2) => string.Compare(group1.Name, group2.Name, StringComparison.Ordinal));
httpRequestDictionary.Add(userID.ToString(), result);
if (categoryId.HasValue)
{
result = result.Where(r => r.CategoryID.Equals(categoryId.Value)).ToList();
}
return result;
}
public bool IsUserInGroup(Guid userId, Guid groupId)
{
return IsUserInGroupInternal(userId, groupId, GetRefsInternal());
}
public UserInfo[] GetUsersByGroup(Guid groupId, EmployeeStatus employeeStatus = EmployeeStatus.Default)
{
var refs = GetRefsInternal();
return GetUsers(employeeStatus).Where(u => IsUserInGroupInternal(u.Id, groupId, refs)).ToArray();
}
public async Task AddUserIntoGroup(Guid userId, Guid groupId, bool dontClearAddressBook = false)
2022-02-15 11:52:43 +00:00
{
if (Constants.LostUser.Id == userId || Constants.LostGroupInfo.ID == groupId)
{
return;
}
var user = GetUsers(userId);
_permissionContext.DemandPermissions(new UserGroupObject(new UserAccount(user, _tenantManager.GetCurrentTenant().Id, _userFormatter), groupId),
Constants.Action_EditGroups);
2022-02-15 11:52:43 +00:00
_userService.SaveUserGroupRef(Tenant.Id, new UserGroupRef(userId, groupId, UserGroupRefType.Contains));
ResetGroupCache(userId);
2022-09-19 14:56:45 +00:00
if (groupId == Constants.GroupUser.ID)
2022-06-01 14:07:08 +00:00
{
var tenant = _tenantManager.GetCurrentTenant();
var myUri = (_accessor?.HttpContext != null) ? _accessor.HttpContext.Request.GetUrlRewriter().ToString() :
(_cache.Get<string>("REWRITE_URL" + tenant.Id) != null) ?
new Uri(_cache.Get<string>("REWRITE_URL" + tenant.Id)).ToString() : tenant.GetTenantDomain(_coreSettings);
2022-11-15 10:28:25 +00:00
if (!dontClearAddressBook)
{
await _cardDavAddressbook.Delete(myUri, user.Id, user.Email, tenant.Id);
}
2022-06-01 14:07:08 +00:00
}
2022-02-15 11:52:43 +00:00
}
public void RemoveUserFromGroup(Guid userId, Guid groupId)
2022-02-15 11:52:43 +00:00
{
if (Constants.LostUser.Id == userId || Constants.LostGroupInfo.ID == groupId)
{
return;
}
var user = GetUsers(userId);
_permissionContext.DemandPermissions(new UserGroupObject(new UserAccount(user, _tenantManager.GetCurrentTenant().Id, _userFormatter), groupId),
Constants.Action_EditGroups);
2022-02-15 11:52:43 +00:00
_userService.RemoveUserGroupRef(Tenant.Id, userId, groupId, UserGroupRefType.Contains);
ResetGroupCache(userId);
}
internal void ResetGroupCache(Guid userID)
{
new HttpRequestDictionary<List<GroupInfo>>(_accessor?.HttpContext, "GroupInfo").Reset(userID.ToString());
new HttpRequestDictionary<List<Guid>>(_accessor?.HttpContext, "GroupInfoID").Reset(userID.ToString());
}
#endregion Users
2022-02-15 11:52:43 +00:00
#region Company
2022-02-15 11:52:43 +00:00
public GroupInfo[] GetDepartments()
{
return GetGroups();
}
public Guid GetDepartmentManager(Guid deparmentID)
{
var groupRef = _userService.GetUserGroupRef(Tenant.Id, deparmentID, UserGroupRefType.Manager);
if (groupRef == null)
{
return Guid.Empty;
}
return groupRef.UserId;
}
public void SetDepartmentManager(Guid deparmentID, Guid userID)
{
var managerId = GetDepartmentManager(deparmentID);
if (managerId != Guid.Empty)
{
_userService.RemoveUserGroupRef(
Tenant.Id,
managerId, deparmentID, UserGroupRefType.Manager);
}
if (userID != Guid.Empty)
{
_userService.SaveUserGroupRef(
Tenant.Id,
new UserGroupRef(userID, deparmentID, UserGroupRefType.Manager));
}
}
public UserInfo GetCompanyCEO()
{
var id = GetDepartmentManager(Guid.Empty);
return id != Guid.Empty ? GetUsers(id) : null;
}
public void SetCompanyCEO(Guid userId)
{
SetDepartmentManager(Guid.Empty, userId);
}
#endregion Company
2022-02-15 11:52:43 +00:00
#region Groups
2022-02-15 11:52:43 +00:00
public GroupInfo[] GetGroups()
{
return GetGroups(Guid.Empty);
}
public GroupInfo[] GetGroups(Guid categoryID)
{
return GetGroupsInternal()
.Where(g => g.CategoryID == categoryID)
.ToArray();
}
public GroupInfo GetGroupInfo(Guid groupID)
{
var group = _userService.GetGroup(Tenant.Id, groupID);
if (group == null)
{
2022-09-14 11:21:25 +00:00
group = ToGroup(Constants.BuildinGroups.FirstOrDefault(r => r.ID == groupID) ?? Constants.LostGroupInfo);
}
if (group == null)
{
return Constants.LostGroupInfo;
}
2022-02-15 11:52:43 +00:00
return new GroupInfo
{
ID = group.Id,
CategoryID = group.CategoryId,
Name = group.Name,
Sid = group.Sid
};
}
public GroupInfo GetGroupInfoBySid(string sid)
{
return GetGroupsInternal()
.SingleOrDefault(g => g.Sid == sid) ?? Constants.LostGroupInfo;
}
public GroupInfo SaveGroupInfo(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);
}
_permissionContext.DemandPermissions(Constants.Action_EditGroups);
var newGroup = _userService.SaveGroup(Tenant.Id, ToGroup(g));
return new GroupInfo(newGroup.CategoryId) { ID = newGroup.Id, Name = newGroup.Name, Sid = newGroup.Sid };
}
public void DeleteGroup(Guid id)
{
if (Constants.LostGroupInfo.Equals(id))
{
return;
}
if (Constants.BuildinGroups.Any(b => b.ID == id))
{
return;
}
_permissionContext.DemandPermissions(Constants.Action_EditGroups);
_userService.RemoveGroup(Tenant.Id, id);
}
#endregion Groups
2022-02-15 11:52:43 +00:00
private bool IsPropertiesContainsWords(IEnumerable<string> properties, IEnumerable<string> words)
{
foreach (var w in words)
{
var find = false;
foreach (var p in properties)
{
find = (2 <= w.Length) && (0 <= p.IndexOf(w, StringComparison.CurrentCultureIgnoreCase));
if (find)
{
2022-02-15 11:52:43 +00:00
break;
}
}
2022-02-15 11:52:43 +00:00
if (!find)
{
return false;
}
2022-02-15 11:52:43 +00:00
}
return true;
}
private IEnumerable<UserInfo> GetUsersInternal()
{
return _userService.GetUsers(Tenant.Id)
.Where(u => !u.Removed);
}
private IEnumerable<GroupInfo> GetGroupsInternal()
{
return _userService.GetGroups(Tenant.Id)
.Where(g => !g.Removed)
.Select(g => new GroupInfo(g.CategoryId) { ID = g.Id, Name = g.Name, Sid = g.Sid })
.Concat(Constants.BuildinGroups)
.ToList();
}
private IDictionary<string, UserGroupRef> GetRefsInternal()
{
return _userService.GetUserGroupRefs(Tenant.Id);
}
private bool IsUserInGroupInternal(Guid userId, Guid groupId, IDictionary<string, UserGroupRef> refs)
{
if (groupId == Constants.GroupEveryone.ID)
{
return true;
}
if (groupId == Constants.GroupAdmin.ID && (Tenant.OwnerId == userId || userId == Configuration.Constants.CoreSystem.ID || userId == _constants.NamingPoster.Id))
{
return true;
}
2022-09-19 14:56:45 +00:00
if (groupId == Constants.GroupUser.ID && userId == Constants.OutsideUser.Id)
2022-02-15 11:52:43 +00:00
{
return true;
}
UserGroupRef r;
2022-09-19 14:56:45 +00:00
if (groupId == Constants.GroupManager.ID || groupId == Constants.GroupUser.ID)
2022-02-15 11:52:43 +00:00
{
2022-10-18 11:22:02 +00:00
var user = refs.TryGetValue(UserGroupRef.CreateKey(Tenant.Id, userId, Constants.GroupUser.ID, UserGroupRefType.Contains), out r) && !r.Removed;
2022-09-19 14:56:45 +00:00
if (groupId == Constants.GroupUser.ID)
{
2022-10-18 11:22:02 +00:00
return user;
}
2022-09-19 14:56:45 +00:00
if (groupId == Constants.GroupManager.ID)
2022-02-15 11:52:43 +00:00
{
2022-10-18 11:22:02 +00:00
return !user;
2022-02-15 11:52:43 +00:00
}
}
2022-02-15 11:52:43 +00:00
return refs.TryGetValue(UserGroupRef.CreateKey(Tenant.Id, userId, groupId, UserGroupRefType.Contains), out r) && !r.Removed;
}
private Group ToGroup(GroupInfo g)
{
if (g == null)
{
return null;
}
return new Group
{
Id = g.ID,
Name = g.Name,
ParentId = g.Parent != null ? g.Parent.ID : Guid.Empty,
CategoryId = g.CategoryID,
Sid = g.Sid
};
}
}