DocSpace-client/common/ASC.Core.Common/Context/SecurityContext.cs

372 lines
13 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
2022-02-15 11:52:43 +00:00
namespace ASC.Core;
[Scope]
public class SecurityContext
{
2022-02-15 11:52:43 +00:00
private readonly ILog _logger;
public IAccount CurrentAccount => _authContext.CurrentAccount;
public bool IsAuthenticated => _authContext.IsAuthenticated;
private readonly UserManager _userManager;
private readonly AuthManager _authentication;
private readonly AuthContext _authContext;
private readonly TenantManager _tenantManager;
private readonly UserFormatter _userFormatter;
private readonly CookieStorage _cookieStorage;
private readonly TenantCookieSettingsHelper _tenantCookieSettingsHelper;
private readonly IHttpContextAccessor _httpContextAccessor;
public SecurityContext(
UserManager userManager,
AuthManager authentication,
AuthContext authContext,
TenantManager tenantManager,
UserFormatter userFormatter,
CookieStorage cookieStorage,
TenantCookieSettingsHelper tenantCookieSettingsHelper,
IOptionsMonitor<ILog> options
)
{
_logger = options.CurrentValue;
_userManager = userManager;
_authentication = authentication;
_authContext = authContext;
_tenantManager = tenantManager;
_userFormatter = userFormatter;
_cookieStorage = cookieStorage;
_tenantCookieSettingsHelper = tenantCookieSettingsHelper;
}
public SecurityContext(
IHttpContextAccessor httpContextAccessor,
UserManager userManager,
AuthManager authentication,
AuthContext authContext,
TenantManager tenantManager,
UserFormatter userFormatter,
CookieStorage cookieStorage,
TenantCookieSettingsHelper tenantCookieSettingsHelper,
IOptionsMonitor<ILog> options
) : this(userManager, authentication, authContext, tenantManager, userFormatter, cookieStorage, tenantCookieSettingsHelper, options)
{
2022-02-15 11:52:43 +00:00
_httpContextAccessor = httpContextAccessor;
}
public string AuthenticateMe(string login, string passwordHash)
{
2022-03-09 17:15:51 +00:00
ArgumentNullException.ThrowIfNull(login);
ArgumentNullException.ThrowIfNull(passwordHash);
2022-02-15 11:52:43 +00:00
var tenantid = _tenantManager.GetCurrentTenant().Id;
var u = _userManager.GetUsersByPasswordHash(tenantid, login, passwordHash);
2022-02-15 11:52:43 +00:00
return AuthenticateMe(new UserAccount(u, tenantid, _userFormatter));
}
public bool AuthenticateMe(string cookie)
{
if (!string.IsNullOrEmpty(cookie))
{
2022-02-15 11:52:43 +00:00
if (cookie.Equals("Bearer", StringComparison.InvariantCulture))
{
2022-02-15 11:52:43 +00:00
var ipFrom = string.Empty;
var address = string.Empty;
if (_httpContextAccessor?.HttpContext != null)
{
var request = _httpContextAccessor?.HttpContext.Request;
2022-03-09 17:15:51 +00:00
ArgumentNullException.ThrowIfNull(request);
2022-02-15 11:52:43 +00:00
ipFrom = "from " + (request.Headers["X-Forwarded-For"].ToString() ?? request.GetUserHostAddress());
address = "for " + request.GetUrlRewriter();
}
_logger.InfoFormat("Empty Bearer cookie: {0} {1}", ipFrom, address);
}
else if (_cookieStorage.DecryptCookie(cookie, out var tenant, out var userid, out var indexTenant, out var expire, out var indexUser))
{
2022-02-15 11:52:43 +00:00
if (tenant != _tenantManager.GetCurrentTenant().Id)
{
2022-02-15 11:52:43 +00:00
return false;
}
2022-02-15 11:52:43 +00:00
var settingsTenant = _tenantCookieSettingsHelper.GetForTenant(tenant);
if (indexTenant != settingsTenant.Index)
{
2022-02-15 11:52:43 +00:00
return false;
}
2022-02-15 11:52:43 +00:00
if (expire != DateTime.MaxValue && expire < DateTime.UtcNow)
{
return false;
}
2022-02-15 11:52:43 +00:00
try
{
var settingsUser = _tenantCookieSettingsHelper.GetForUser(userid);
if (indexUser != settingsUser.Index)
{
return false;
}
2022-02-15 11:52:43 +00:00
AuthenticateMeWithoutCookie(new UserAccount(new UserInfo { Id = userid }, tenant, _userFormatter));
2022-02-15 11:52:43 +00:00
return true;
}
2022-02-15 11:52:43 +00:00
catch (InvalidCredentialException ice)
{
2022-02-15 11:52:43 +00:00
_logger.DebugFormat("{0}: cookie {1}, tenant {2}, userid {3}", ice.Message, cookie, tenant, userid);
}
catch (SecurityException se)
{
_logger.DebugFormat("{0}: cookie {1}, tenant {2}, userid {3}", se.Message, cookie, tenant, userid);
}
catch (Exception err)
{
_logger.ErrorFormat("Authenticate error: cookie {0}, tenant {1}, userid {2}, : {3}", cookie, tenant, userid, err);
}
}
else
{
var ipFrom = string.Empty;
var address = string.Empty;
if (_httpContextAccessor?.HttpContext != null)
{
var request = _httpContextAccessor?.HttpContext.Request;
2021-12-30 10:23:01 +00:00
2022-03-09 17:15:51 +00:00
ArgumentNullException.ThrowIfNull(request);
2022-02-15 11:52:43 +00:00
address = "for " + request.GetUrlRewriter();
ipFrom = "from " + (request.Headers["X-Forwarded-For"].ToString() ?? request.GetUserHostAddress());
}
2022-02-15 11:52:43 +00:00
_logger.WarnFormat("Can not decrypt cookie: {0} {1} {2}", cookie, ipFrom, address);
}
2022-02-15 11:52:43 +00:00
}
return false;
}
2022-02-15 11:52:43 +00:00
public string AuthenticateMe(IAccount account, List<Claim> additionalClaims = null)
{
AuthenticateMeWithoutCookie(account, additionalClaims);
string cookie = null;
if (account is IUserAccount)
{
cookie = _cookieStorage.EncryptCookie(_tenantManager.GetCurrentTenant().Id, account.ID);
}
2022-02-15 11:52:43 +00:00
return cookie;
}
public void AuthenticateMeWithoutCookie(IAccount account, List<Claim> additionalClaims = null)
{
if (account == null || account.Equals(Configuration.Constants.Guest))
2021-08-18 14:04:16 +00:00
{
2022-02-15 11:52:43 +00:00
throw new InvalidCredentialException("account");
}
2021-08-18 14:04:16 +00:00
2022-02-15 11:52:43 +00:00
var roles = new List<string> { Role.Everyone };
2021-08-18 14:04:16 +00:00
2022-02-15 11:52:43 +00:00
if (account is ISystemAccount && account.ID == Configuration.Constants.CoreSystem.ID)
{
roles.Add(Role.System);
2021-08-18 14:04:16 +00:00
}
2022-02-15 11:52:43 +00:00
if (account is IUserAccount)
{
2022-02-15 11:52:43 +00:00
var tenant = _tenantManager.GetCurrentTenant();
2022-02-15 11:52:43 +00:00
var u = _userManager.GetUsers(account.ID);
2022-02-15 11:52:43 +00:00
if (u.Id == Users.Constants.LostUser.Id)
{
2022-02-15 11:52:43 +00:00
throw new InvalidCredentialException("Invalid username or password.");
}
2022-02-15 11:52:43 +00:00
if (u.Status != EmployeeStatus.Active)
{
2022-02-15 11:52:43 +00:00
throw new SecurityException("Account disabled.");
}
2019-08-09 12:28:19 +00:00
2022-02-15 11:52:43 +00:00
// for LDAP users only
if (u.Sid != null)
{
if (!_tenantManager.GetTenantQuota(tenant.Id).Ldap)
{
2022-02-15 11:52:43 +00:00
throw new BillingException("Your tariff plan does not support this option.", "Ldap");
}
2022-02-15 11:52:43 +00:00
}
2022-02-15 11:52:43 +00:00
if (_userManager.IsUserInGroup(u.Id, Users.Constants.GroupAdmin.ID))
{
roles.Add(Role.Administrators);
}
2022-02-15 11:52:43 +00:00
roles.Add(Role.Users);
2022-02-15 11:52:43 +00:00
account = new UserAccount(u, _tenantManager.GetCurrentTenant().Id, _userFormatter);
}
2022-02-15 11:52:43 +00:00
var claims = new List<Claim>
2019-09-16 09:21:10 +00:00
{
new Claim(ClaimTypes.Sid, account.ID.ToString()),
new Claim(ClaimTypes.Name, account.Name)
};
2022-02-15 11:52:43 +00:00
claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r)));
2019-09-16 09:21:10 +00:00
2022-02-15 11:52:43 +00:00
if (additionalClaims != null)
{
2022-02-15 11:52:43 +00:00
claims.AddRange(additionalClaims);
}
2022-02-15 11:52:43 +00:00
_authContext.Principal = new CustomClaimsPrincipal(new ClaimsIdentity(account, claims), account);
}
2022-02-15 11:52:43 +00:00
public string AuthenticateMe(Guid userId, List<Claim> additionalClaims = null)
{
var account = _authentication.GetAccountByID(_tenantManager.GetCurrentTenant().Id, userId);
2021-08-18 14:04:16 +00:00
2022-02-15 11:52:43 +00:00
return AuthenticateMe(account, additionalClaims);
}
2022-02-15 11:52:43 +00:00
public void AuthenticateMeWithoutCookie(Guid userId, List<Claim> additionalClaims = null)
{
var account = _authentication.GetAccountByID(_tenantManager.GetCurrentTenant().Id, userId);
2022-02-15 11:52:43 +00:00
AuthenticateMeWithoutCookie(account, additionalClaims);
}
public void Logout()
{
_authContext.Logout();
}
2022-02-15 11:52:43 +00:00
public void SetUserPasswordHash(Guid userID, string passwordHash)
{
var tenantid = _tenantManager.GetCurrentTenant().Id;
var u = _userManager.GetUsersByPasswordHash(tenantid, userID.ToString(), passwordHash);
if (!Equals(u, Users.Constants.LostUser))
{
2022-02-15 11:52:43 +00:00
throw new PasswordException("A new password must be used");
}
2022-02-15 11:52:43 +00:00
_authentication.SetUserPasswordHash(userID, passwordHash);
2019-09-09 12:56:33 +00:00
}
2022-02-15 11:52:43 +00:00
public class PasswordException : Exception
2019-09-09 12:56:33 +00:00
{
2022-02-15 11:52:43 +00:00
public PasswordException(string message) : base(message) { }
}
}
2022-02-15 11:52:43 +00:00
[Scope]
public class PermissionContext
{
public IPermissionResolver PermissionResolver { get; set; }
private AuthContext AuthContext { get; }
2022-02-15 11:52:43 +00:00
public PermissionContext(IPermissionResolver permissionResolver, AuthContext authContext)
{
PermissionResolver = permissionResolver;
AuthContext = authContext;
}
2019-09-09 12:56:33 +00:00
2022-02-15 11:52:43 +00:00
public bool CheckPermissions(params IAction[] actions)
{
return PermissionResolver.Check(AuthContext.CurrentAccount, actions);
}
2022-02-15 11:52:43 +00:00
public bool CheckPermissions(ISecurityObject securityObject, params IAction[] actions)
{
return CheckPermissions(securityObject, null, actions);
}
2022-02-15 11:52:43 +00:00
public bool CheckPermissions(ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions)
{
return PermissionResolver.Check(AuthContext.CurrentAccount, objectId, securityObjProvider, actions);
}
2022-02-15 11:52:43 +00:00
public void DemandPermissions(params IAction[] actions)
{
PermissionResolver.Demand(AuthContext.CurrentAccount, actions);
}
2022-02-15 11:52:43 +00:00
public void DemandPermissions(ISecurityObject securityObject, params IAction[] actions)
{
DemandPermissions(securityObject, null, actions);
2019-09-09 12:56:33 +00:00
}
2022-02-15 11:52:43 +00:00
public void DemandPermissions(ISecurityObjectId objectId, ISecurityObjectProvider securityObjProvider, params IAction[] actions)
2019-09-09 12:56:33 +00:00
{
2022-02-15 11:52:43 +00:00
PermissionResolver.Demand(AuthContext.CurrentAccount, objectId, securityObjProvider, actions);
}
}
2019-10-22 16:08:37 +00:00
2022-02-15 11:52:43 +00:00
[Scope]
public class AuthContext
{
private IHttpContextAccessor HttpContextAccessor { get; }
2020-02-27 08:44:55 +00:00
2022-02-15 11:52:43 +00:00
public AuthContext()
{
2020-02-27 08:44:55 +00:00
2022-02-15 11:52:43 +00:00
}
public AuthContext(IHttpContextAccessor httpContextAccessor)
{
HttpContextAccessor = httpContextAccessor;
}
2019-09-09 12:56:33 +00:00
2022-02-15 11:52:43 +00:00
public IAccount CurrentAccount => Principal?.Identity is IAccount ? (IAccount)Principal.Identity : Configuration.Constants.Guest;
2019-09-09 12:56:33 +00:00
2022-02-15 11:52:43 +00:00
public bool IsAuthenticated => CurrentAccount.IsAuthenticated;
2022-02-15 11:52:43 +00:00
public void Logout()
{
Principal = null;
}
2020-02-03 10:41:24 +00:00
2022-02-15 11:52:43 +00:00
internal ClaimsPrincipal Principal
{
get => Thread.CurrentPrincipal as ClaimsPrincipal ?? HttpContextAccessor?.HttpContext?.User;
set
{
2022-02-15 11:52:43 +00:00
Thread.CurrentPrincipal = value;
2022-02-15 11:52:43 +00:00
if (HttpContextAccessor?.HttpContext != null)
{
HttpContextAccessor.HttpContext.User = value;
}
}
}
2022-02-15 11:52:43 +00:00
}