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

975 lines
34 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;
2023-02-20 08:15:18 +00:00
private readonly TenantQuotaFeatureCheckerCount<CountPaidUserFeature> _countPaidUserChecker;
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,
2023-02-20 08:15:18 +00:00
TenantQuotaFeatureCheckerCount<CountPaidUserFeature> countPaidUserChecker,
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;
2023-02-20 08:15:18 +00:00
_countPaidUserChecker = countPaidUserChecker;
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,
2023-02-20 08:15:18 +00:00
TenantQuotaFeatureCheckerCount<CountPaidUserFeature> 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
2023-03-24 07:53:49 +00:00
public async Task<UserInfo[]> GetUsersAsync()
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return await GetUsersAsync(EmployeeStatus.Default);
2022-02-15 11:52:43 +00:00
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo[]> GetUsersAsync(EmployeeStatus status)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return await GetUsersAsync(status, EmployeeType.All);
2022-02-15 11:52:43 +00:00
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo[]> GetUsersAsync(EmployeeStatus status, EmployeeType type)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
var users = (await GetUsersInternalAsync()).Where(u => (u.Status & status) == u.Status).ToAsyncEnumerable();
2022-02-15 11:52:43 +00:00
switch (type)
{
2022-10-18 11:22:02 +00:00
case EmployeeType.RoomAdmin:
2023-03-24 07:53:49 +00:00
users = users.WhereAwait(async u => !await this.IsUserAsync(u) && !await this.IsCollaboratorAsync(u) && !await this.IsDocSpaceAdminAsync(u));
2023-02-17 14:53:18 +00:00
break;
case EmployeeType.DocSpaceAdmin:
2023-03-24 07:53:49 +00:00
users = users.WhereAwait(async u => await this.IsDocSpaceAdminAsync(u));
2023-02-17 14:53:18 +00:00
break;
case EmployeeType.Collaborator:
2023-03-24 07:53:49 +00:00
users = users.WhereAwait(async u => await this.IsCollaboratorAsync(u));
2022-02-15 11:52:43 +00:00
break;
2022-10-18 11:22:02 +00:00
case EmployeeType.User:
2023-03-24 07:53:49 +00:00
users = users.WhereAwait(async u => await this.IsUserAsync(u));
2022-02-15 11:52:43 +00:00
break;
2021-11-23 12:25:34 +00:00
}
2023-03-24 07:53:49 +00:00
return await users.ToArrayAsync();
2022-02-15 11:52:43 +00:00
}
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
}
2023-03-24 07:53:49 +00:00
public async Task<string[]> GetUserNamesAsyncAsync(EmployeeStatus status)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return (await GetUsersAsync(status))
2022-02-15 11:52:43 +00:00
.Select(u => u.UserName)
.Where(s => !string.IsNullOrEmpty(s))
.ToArray();
}
2023-03-20 16:16:00 +00:00
public async Task<UserInfo> GetUserByUserNameAsync(string username)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
var u = await _userService.GetUserByUserName((await _tenantManager.GetCurrentTenantAsync()).Id, username);
2022-02-15 11:52:43 +00:00
return u ?? Constants.LostUser;
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo> GetUserBySidAsync(string sid)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return (await GetUsersInternalAsync())
.FirstOrDefault(u => u.Sid != null && string.Equals(u.Sid, sid, StringComparison.CurrentCultureIgnoreCase)) ?? Constants.LostUser;
2022-02-15 11:52:43 +00:00
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo> GetSsoUserByNameIdAsync(string nameId)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return (await GetUsersInternalAsync())
2022-02-15 11:52:43 +00:00
.FirstOrDefault(u => !string.IsNullOrEmpty(u.SsoNameId) && string.Equals(u.SsoNameId, nameId, StringComparison.CurrentCultureIgnoreCase)) ?? Constants.LostUser;
}
2023-03-24 07:53:49 +00:00
public async Task<bool> IsUserNameExistsAsync(string username)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return (await GetUserNamesAsyncAsync(EmployeeStatus.All))
2022-02-15 11:52:43 +00:00
.Contains(username, StringComparer.CurrentCultureIgnoreCase);
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo> GetUsersAsync(Guid id)
{
if (IsSystemUser(id))
{
return SystemUsers[id];
}
var u = await _userService.GetUserAsync(Tenant.Id, id);
return u != null && !u.Removed ? u : Constants.LostUser;
}
2022-02-15 11:52:43 +00:00
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;
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo> GetUserAsync(Guid id, Expression<Func<User, UserInfo>> exp)
2022-02-15 11:52:43 +00:00
{
if (IsSystemUser(id))
{
return SystemUsers[id];
}
2023-03-24 07:53:49 +00:00
var u = await _userService.GetUserAsync(Tenant.Id, id, exp);
2022-02-15 11:52:43 +00:00
return u != null && !u.Removed ? u : Constants.LostUser;
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo> GetUsersByPasswordHashAsync(int tenant, string login, string passwordHash)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
var u = await _userService.GetUserByPasswordHashAsync(tenant, login, passwordHash);
2022-02-15 11:52:43 +00:00
return u != null && !u.Removed ? u : Constants.LostUser;
}
2023-03-24 07:53:49 +00:00
public async Task<bool> UserExistsAsync(Guid id)
{
return UserExists(await GetUsersAsync(id));
}
2022-02-15 11:52:43 +00:00
public bool UserExists(Guid id)
{
2023-03-24 07:53:49 +00:00
return UserExists (GetUsers(id));
2022-02-15 11:52:43 +00:00
}
public bool UserExists(UserInfo user)
{
return !user.Equals(Constants.LostUser);
}
public bool IsSystemUser(Guid id)
{
return SystemUsers.ContainsKey(id);
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo> GetUserByEmailAsync(string email)
2022-02-15 11:52:43 +00:00
{
if (string.IsNullOrEmpty(email))
{
return Constants.LostUser;
}
2023-03-24 07:53:49 +00:00
var u = await _userService.GetUserAsync(Tenant.Id, email);
2022-02-15 11:52:43 +00:00
return u != null && !u.Removed ? u : Constants.LostUser;
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo[]> SearchAsync(string text, EmployeeStatus status)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return await SearchAsync(text, status, Guid.Empty);
2022-02-15 11:52:43 +00:00
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo[]> SearchAsync(string text, EmployeeStatus status, Guid groupId)
2022-02-15 11:52:43 +00:00
{
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 ?
2023-03-24 07:53:49 +00:00
await GetUsersAsync(status) :
(await GetUsersByGroupAsync(groupId)).Where(u => (u.Status & status) == status);
2022-02-15 11:52:43 +00:00
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();
}
2023-03-20 16:16:00 +00:00
public async Task<UserInfo> UpdateUserInfoAsync(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];
}
2023-03-20 16:16:00 +00:00
await _permissionContext.DemandPermissionsAsync(new UserSecurityProvider(u.Id), Constants.Action_EditUser);
2022-10-24 15:30:17 +00:00
2023-03-20 16:16:00 +00:00
var tenant = await _tenantManager.GetCurrentTenantAsync();
if (u.Status == EmployeeStatus.Terminated && u.Id == tenant.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
2023-03-24 07:53:49 +00:00
var oldUserData = await _userService.GetUserByUserName(tenant.Id, u.UserName);
2022-10-24 15:30:17 +00:00
if (oldUserData == null || Equals(oldUserData, Constants.LostUser))
{
throw new InvalidOperationException("User not found.");
}
2023-03-24 07:53:49 +00:00
return await _userService.SaveUserAsync(tenant.Id, u);
2022-10-25 15:27:56 +00:00
}
public async Task<UserInfo> UpdateUserInfoWithSyncCardDavAsync(UserInfo u)
{
2023-03-24 07:53:49 +00:00
var oldUserData = await _userService.GetUserByUserName((await _tenantManager.GetCurrentTenantAsync()).Id, u.UserName);
2022-10-25 15:27:56 +00:00
2023-03-20 16:16:00 +00:00
var newUser = await UpdateUserInfoAsync(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;
}
2023-02-21 16:00:25 +00:00
public async Task<UserInfo> SaveUserInfo(UserInfo u, EmployeeType type = EmployeeType.RoomAdmin, bool syncCardDav = false, bool paidUserQuotaCheck = true)
2022-10-24 15:30:17 +00:00
{
if (IsSystemUser(u.Id))
{
return SystemUsers[u.Id];
}
2023-03-20 16:16:00 +00:00
await _permissionContext.DemandPermissionsAsync(new UserSecurityProvider(u.Id, type), Constants.Action_AddRemoveUser);
2022-02-15 11:52:43 +00:00
if (!_coreBaseSettings.Personal)
{
2023-03-24 07:53:49 +00:00
if (_constants.MaxEveryoneCount <= (await GetUsersByGroupAsync(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
2023-03-24 07:53:49 +00:00
var oldUserData = await _userService.GetUserByUserName((await _tenantManager.GetCurrentTenantAsync()).Id, u.UserName);
2022-10-24 15:30:17 +00:00
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
}
2023-02-17 14:53:18 +00:00
if (type is EmployeeType.User)
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
}
2023-02-21 16:00:25 +00:00
else if (paidUserQuotaCheck)
2022-10-24 15:30:17 +00:00
{
2023-02-20 08:15:18 +00:00
await _countPaidUserChecker.CheckAppend();
2022-10-19 09:48:23 +00:00
}
2023-03-24 07:53:49 +00:00
var newUser = await _userService.SaveUserAsync((await _tenantManager.GetCurrentTenantAsync()).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
{
2023-03-20 16:16:00 +00:00
var tenant = await _tenantManager.GetCurrentTenantAsync();
2022-10-24 15:30:17 +00:00
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();
2023-03-20 16:16:00 +00:00
var allUserEmails = (await GetDavUserEmailsAsync()).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
{
2023-03-20 16:16:00 +00:00
await _cardDavAddressbook.UpdateItemForAllAddBooks(allUserEmails, myUri, cardDavUser, (await _tenantManager.GetCurrentTenantAsync()).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
2023-03-20 16:16:00 +00:00
public async Task<IEnumerable<string>> GetDavUserEmailsAsync()
2022-06-01 14:07:08 +00:00
{
2023-03-24 07:53:49 +00:00
return await _userService.GetDavUserEmailsAsync((await _tenantManager.GetCurrentTenantAsync()).Id);
2022-06-01 14:07:08 +00:00
}
2021-05-17 11:35:00 +00:00
2023-03-24 07:53:49 +00:00
public async Task<IEnumerable<int>> GetTenantsWithFeedsAsync(DateTime from)
{
2023-03-24 07:53:49 +00:00
return await _userService.GetTenantsWithFeedsAsync(from);
}
2023-03-20 16:16:00 +00:00
public async Task DeleteUserAsync(Guid id)
2022-02-15 11:52:43 +00:00
{
if (IsSystemUser(id))
{
return;
2021-05-17 11:35:00 +00:00
}
2023-03-20 16:16:00 +00:00
await _permissionContext.DemandPermissionsAsync(Constants.Action_AddRemoveUser);
2022-02-15 11:52:43 +00:00
if (id == Tenant.OwnerId)
{
throw new InvalidOperationException("Can not remove tenant owner.");
}
2023-03-24 07:53:49 +00:00
var delUser = await GetUsersAsync(id);
await _userService.RemoveUserAsync(Tenant.Id, id);
2023-03-20 16:16:00 +00:00
var tenant = await _tenantManager.GetCurrentTenantAsync();
2022-06-01 14:07:08 +00:00
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);
2023-03-20 16:16:00 +00:00
var davUsersEmails = await GetDavUserEmailsAsync();
2022-06-01 14:07:08 +00:00
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
}
2023-03-20 16:16:00 +00:00
public async Task SaveUserPhotoAsync(Guid id, byte[] photo)
2022-02-15 11:52:43 +00:00
{
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
2023-03-20 16:16:00 +00:00
await _permissionContext.DemandPermissionsAsync(new UserSecurityProvider(id), Constants.Action_EditUser);
2021-05-18 15:50:48 +00:00
2023-03-24 07:53:49 +00:00
await _userService.SetUserPhotoAsync(Tenant.Id, id, photo);
2022-02-15 11:52:43 +00:00
}
2023-03-24 07:53:49 +00:00
public async Task<byte[]> GetUserPhotoAsync(Guid id)
2022-02-15 11:52:43 +00:00
{
if (IsSystemUser(id))
{
return null;
}
2021-09-28 17:30:02 +00:00
2023-03-24 07:53:49 +00:00
return await _userService.GetUserPhotoAsync(Tenant.Id, id);
2022-02-15 11:52:43 +00:00
}
2021-09-28 17:30:02 +00:00
2023-03-24 07:53:49 +00:00
public async Task<List<GroupInfo>> GetUserGroupsAsync(Guid id)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return await GetUserGroupsAsync(id, IncludeType.Distinct, Guid.Empty);
2022-02-15 11:52:43 +00:00
}
2023-03-24 07:53:49 +00:00
public async Task<List<GroupInfo>> GetUserGroupsAsync(Guid id, Guid categoryID)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return await GetUserGroupsAsync(id, IncludeType.Distinct, categoryID);
2022-02-15 11:52:43 +00:00
}
2023-03-24 07:53:49 +00:00
public async Task<List<GroupInfo>> GetUserGroupsAsync(Guid userID, IncludeType includeType)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return await GetUserGroupsAsync(userID, includeType, null);
2022-02-15 11:52:43 +00:00
}
2023-03-24 07:53:49 +00:00
internal async Task<List<GroupInfo>> GetUserGroupsAsync(Guid userID, IncludeType includeType, Guid? categoryId)
2022-02-15 11:52:43 +00:00
{
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>();
2023-03-24 07:53:49 +00:00
var refs = await GetRefsInternalAsync();
2022-02-15 11:52:43 +00:00
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();
2023-03-24 07:53:49 +00:00
foreach (var g in (await GetGroupsInternalAsync()).Where(g => !categoryId.HasValue || g.CategoryID == categoryId))
2022-02-15 11:52:43 +00:00
{
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;
}
2023-03-24 07:53:49 +00:00
public async Task<bool> IsUserInGroupAsync(Guid userId, Guid groupId)
{
return IsUserInGroupInternal(userId, groupId, await GetRefsInternalAsync());
}
2022-02-15 11:52:43 +00:00
public bool IsUserInGroup(Guid userId, Guid groupId)
{
return IsUserInGroupInternal(userId, groupId, GetRefsInternal());
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo[]> GetUsersByGroupAsync(Guid groupId, EmployeeStatus employeeStatus = EmployeeStatus.Default)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
var refs = await GetRefsInternalAsync();
2022-02-15 11:52:43 +00:00
2023-03-24 07:53:49 +00:00
return (await GetUsersAsync(employeeStatus)).Where(u => IsUserInGroupInternal(u.Id, groupId, refs)).ToArray();
2022-02-15 11:52:43 +00:00
}
2023-03-20 16:16:00 +00:00
public async Task AddUserIntoGroupAsync(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;
}
2023-03-24 07:53:49 +00:00
var user = await GetUsersAsync(userId);
2023-03-20 16:16:00 +00:00
await _permissionContext.DemandPermissionsAsync(new UserGroupObject(new UserAccount(user, (await _tenantManager.GetCurrentTenantAsync()).Id, _userFormatter), groupId),
Constants.Action_EditGroups);
2022-02-15 11:52:43 +00:00
2023-03-24 07:53:49 +00:00
await _userService.SaveUserGroupRefAsync(Tenant.Id, new UserGroupRef(userId, groupId, UserGroupRefType.Contains));
2022-02-15 11:52:43 +00:00
ResetGroupCache(userId);
2022-09-19 14:56:45 +00:00
if (groupId == Constants.GroupUser.ID)
2022-06-01 14:07:08 +00:00
{
2023-03-20 16:16:00 +00:00
var tenant = await _tenantManager.GetCurrentTenantAsync();
2022-06-01 14:07:08 +00:00
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
}
2023-03-20 16:16:00 +00:00
public async Task RemoveUserFromGroupAsync(Guid userId, Guid groupId)
2022-02-15 11:52:43 +00:00
{
if (Constants.LostUser.Id == userId || Constants.LostGroupInfo.ID == groupId)
{
return;
}
2023-03-24 07:53:49 +00:00
var user = await GetUsersAsync(userId);
2023-03-20 16:16:00 +00:00
await _permissionContext.DemandPermissionsAsync(new UserGroupObject(new UserAccount(user, (await _tenantManager.GetCurrentTenantAsync()).Id, _userFormatter), groupId),
Constants.Action_EditGroups);
2022-02-15 11:52:43 +00:00
2023-03-24 07:53:49 +00:00
await _userService.RemoveUserGroupRefAsync(Tenant.Id, userId, groupId, UserGroupRefType.Contains);
2022-02-15 11:52:43 +00:00
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
2023-03-24 07:53:49 +00:00
public async Task<GroupInfo[]> GetDepartmentsAsync()
{
return await GetGroupsAsync();
}
public async Task<Guid> GetDepartmentManagerAsync(Guid deparmentID)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
var groupRef = await _userService.GetUserGroupRefAsync(Tenant.Id, deparmentID, UserGroupRefType.Manager);
if (groupRef == null)
{
return Guid.Empty;
}
return groupRef.UserId;
2022-02-15 11:52:43 +00:00
}
public Guid GetDepartmentManager(Guid deparmentID)
{
var groupRef = _userService.GetUserGroupRef(Tenant.Id, deparmentID, UserGroupRefType.Manager);
if (groupRef == null)
{
return Guid.Empty;
}
return groupRef.UserId;
}
2023-03-24 07:53:49 +00:00
public async Task SetDepartmentManagerAsync(Guid deparmentID, Guid userID)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
var managerId = await GetDepartmentManagerAsync(deparmentID);
2022-02-15 11:52:43 +00:00
if (managerId != Guid.Empty)
{
2023-03-24 07:53:49 +00:00
await _userService.RemoveUserGroupRefAsync(
2022-02-15 11:52:43 +00:00
Tenant.Id,
managerId, deparmentID, UserGroupRefType.Manager);
}
if (userID != Guid.Empty)
{
2023-03-24 07:53:49 +00:00
await _userService.SaveUserGroupRefAsync(
2022-02-15 11:52:43 +00:00
Tenant.Id,
new UserGroupRef(userID, deparmentID, UserGroupRefType.Manager));
}
}
2023-03-24 07:53:49 +00:00
public async Task<UserInfo> GetCompanyCEOAsync()
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
var id = await GetDepartmentManagerAsync(Guid.Empty);
2022-02-15 11:52:43 +00:00
2023-03-24 07:53:49 +00:00
return id != Guid.Empty ? await GetUsersAsync(id) : null;
2022-02-15 11:52:43 +00:00
}
2023-03-24 07:53:49 +00:00
public async Task SetCompanyCEOAsync(Guid userId)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
await SetDepartmentManagerAsync(Guid.Empty, userId);
2022-02-15 11:52:43 +00:00
}
#endregion Company
2022-02-15 11:52:43 +00:00
#region Groups
2022-02-15 11:52:43 +00:00
2023-03-24 07:53:49 +00:00
public async Task<GroupInfo[]> GetGroupsAsync()
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return await GetGroupsAsync(Guid.Empty);
2022-02-15 11:52:43 +00:00
}
2023-03-24 07:53:49 +00:00
public async Task<GroupInfo[]> GetGroupsAsync(Guid categoryID)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return (await GetGroupsInternalAsync())
2022-02-15 11:52:43 +00:00
.Where(g => g.CategoryID == categoryID)
.ToArray();
}
2023-03-24 07:53:49 +00:00
public async Task<GroupInfo> GetGroupInfoAsync(Guid groupID)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
var group = await _userService.GetGroupAsync(Tenant.Id, groupID);
2022-02-15 11:52:43 +00:00
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
};
}
2023-03-24 07:53:49 +00:00
public async Task<GroupInfo> GetGroupInfoBySidAsync(string sid)
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return (await GetGroupsInternalAsync())
2022-02-15 11:52:43 +00:00
.SingleOrDefault(g => g.Sid == sid) ?? Constants.LostGroupInfo;
}
2023-03-20 16:16:00 +00:00
public async Task<GroupInfo> SaveGroupInfoAsync(GroupInfo g)
2022-02-15 11:52:43 +00:00
{
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);
}
2023-03-20 16:16:00 +00:00
await _permissionContext.DemandPermissionsAsync(Constants.Action_EditGroups);
2022-02-15 11:52:43 +00:00
2023-03-24 07:53:49 +00:00
var newGroup = await _userService.SaveGroupAsync(Tenant.Id, ToGroup(g));
2022-02-15 11:52:43 +00:00
return new GroupInfo(newGroup.CategoryId) { ID = newGroup.Id, Name = newGroup.Name, Sid = newGroup.Sid };
}
2023-03-20 16:16:00 +00:00
public async Task DeleteGroupAsync(Guid id)
2022-02-15 11:52:43 +00:00
{
if (Constants.LostGroupInfo.Equals(id))
{
return;
}
if (Constants.BuildinGroups.Any(b => b.ID == id))
{
return;
}
2023-03-20 16:16:00 +00:00
await _permissionContext.DemandPermissionsAsync(Constants.Action_EditGroups);
2022-02-15 11:52:43 +00:00
2023-03-24 07:53:49 +00:00
await _userService.RemoveGroupAsync(Tenant.Id, id);
2022-02-15 11:52:43 +00:00
}
#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;
}
2023-03-24 07:53:49 +00:00
private async Task<IEnumerable<UserInfo>> GetUsersInternalAsync()
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return (await _userService.GetUsersAsync(Tenant.Id))
2022-02-15 11:52:43 +00:00
.Where(u => !u.Removed);
}
2023-03-24 07:53:49 +00:00
private async Task<IEnumerable<GroupInfo>> GetGroupsInternalAsync()
2022-02-15 11:52:43 +00:00
{
2023-03-24 07:53:49 +00:00
return (await _userService.GetGroupsAsync(Tenant.Id))
2022-02-15 11:52:43 +00:00
.Where(g => !g.Removed)
.Select(g => new GroupInfo(g.CategoryId) { ID = g.Id, Name = g.Name, Sid = g.Sid })
.Concat(Constants.BuildinGroups)
.ToList();
}
2023-03-24 07:53:49 +00:00
private async Task<IDictionary<string, UserGroupRef>> GetRefsInternalAsync()
{
return await _userService.GetUserGroupRefsAsync(Tenant.Id);
}
2022-02-15 11:52:43 +00:00
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;
if (groupId == Constants.GroupManager.ID || groupId == Constants.GroupUser.ID || groupId == Constants.GroupCollaborator.ID)
2022-02-15 11:52:43 +00:00
{
2023-02-17 15:11:02 +00:00
var isUser = 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)
{
2023-02-17 15:11:02 +00:00
return isUser;
}
2023-02-17 15:11:02 +00:00
var isCollaborator = refs.TryGetValue(UserGroupRef.CreateKey(Tenant.Id, userId, Constants.GroupCollaborator.ID, UserGroupRefType.Contains), out r) && !r.Removed;
if (groupId == Constants.GroupCollaborator.ID)
{
2023-02-17 15:11:02 +00:00
return isCollaborator;
}
2022-09-19 14:56:45 +00:00
if (groupId == Constants.GroupManager.ID)
2022-02-15 11:52:43 +00:00
{
2023-02-17 15:11:02 +00:00
return !isUser && !isCollaborator;
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
};
}
}