DocSpace-buildtools/web/ASC.Web.Core/CookiesManager.cs

335 lines
11 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
2019-06-07 08:59:07 +00:00
2022-06-14 08:11:41 +00:00
using ASC.Core.Data;
2022-11-18 10:20:50 +00:00
using Microsoft.Net.Http.Headers;
using Constants = ASC.Core.Users.Constants;
2019-06-07 08:59:07 +00:00
2022-03-17 15:13:38 +00:00
namespace ASC.Web.Core;
public enum CookiesType
{
AuthKey,
SocketIO
}
[Scope]
public class CookiesManager
2019-06-07 08:59:07 +00:00
{
2022-03-25 16:26:06 +00:00
private const string AuthCookiesName = "asc_auth_key";
private const string SocketIOCookiesName = "socketio.sid";
2022-03-17 15:13:38 +00:00
2022-04-15 09:08:06 +00:00
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly UserManager _userManager;
private readonly SecurityContext _securityContext;
private readonly TenantCookieSettingsHelper _tenantCookieSettingsHelper;
private readonly TenantManager _tenantManager;
private readonly CoreBaseSettings _coreBaseSettings;
2022-06-14 08:11:41 +00:00
private readonly DbLoginEventsManager _dbLoginEventsManager;
private readonly MessageService _messageService;
2022-11-18 12:12:36 +00:00
private readonly ILogger<CookiesManager> _logger;
2022-03-17 15:13:38 +00:00
public CookiesManager(
IHttpContextAccessor httpContextAccessor,
UserManager userManager,
SecurityContext securityContext,
TenantCookieSettingsHelper tenantCookieSettingsHelper,
TenantManager tenantManager,
2022-06-14 08:11:41 +00:00
CoreBaseSettings coreBaseSettings,
DbLoginEventsManager dbLoginEventsManager,
2022-11-18 12:12:36 +00:00
MessageService messageService,
ILogger<CookiesManager> logger)
2019-06-07 08:59:07 +00:00
{
2022-04-15 09:08:06 +00:00
_httpContextAccessor = httpContextAccessor;
_userManager = userManager;
_securityContext = securityContext;
_tenantCookieSettingsHelper = tenantCookieSettingsHelper;
_tenantManager = tenantManager;
_coreBaseSettings = coreBaseSettings;
2022-06-14 08:11:41 +00:00
_dbLoginEventsManager = dbLoginEventsManager;
_messageService = messageService;
2022-11-18 12:12:36 +00:00
_logger = logger;
2019-06-07 08:59:07 +00:00
}
2022-03-17 15:13:38 +00:00
public void SetCookies(CookiesType type, string value, bool session = false)
{
2022-04-15 09:08:06 +00:00
if (_httpContextAccessor?.HttpContext == null)
2022-03-17 15:13:38 +00:00
{
return;
2019-06-07 08:59:07 +00:00
}
2022-03-17 15:13:38 +00:00
var options = new CookieOptions
2019-06-07 08:59:07 +00:00
{
2022-03-17 15:13:38 +00:00
Expires = GetExpiresDate(session)
};
2019-06-07 08:59:07 +00:00
2022-03-17 15:13:38 +00:00
if (type == CookiesType.AuthKey)
{
options.HttpOnly = true;
2019-06-07 08:59:07 +00:00
2022-11-18 10:20:50 +00:00
var urlRewriter = _httpContextAccessor.HttpContext.Request.GetUrlRewriter();
if (urlRewriter.Scheme == "https")
{
2022-03-17 15:13:38 +00:00
options.Secure = true;
}
2019-06-07 08:59:07 +00:00
2022-11-18 10:20:50 +00:00
if (FromCors())
{
2022-11-18 10:20:50 +00:00
options.Domain = $".{_coreBaseSettings.Basedomain}";
}
2019-06-07 08:59:07 +00:00
}
2022-04-15 09:08:06 +00:00
_httpContextAccessor.HttpContext.Response.Cookies.Append(GetCookiesName(type), value, options);
2022-03-17 15:13:38 +00:00
}
2019-06-07 08:59:07 +00:00
2022-03-17 15:13:38 +00:00
public string GetCookies(CookiesType type)
{
2022-04-15 09:08:06 +00:00
if (_httpContextAccessor?.HttpContext != null)
2019-06-07 08:59:07 +00:00
{
2022-03-17 15:13:38 +00:00
var cookieName = GetCookiesName(type);
2019-06-07 08:59:07 +00:00
2022-04-15 09:08:06 +00:00
if (_httpContextAccessor.HttpContext.Request.Cookies.ContainsKey(cookieName))
{
2022-04-15 09:08:06 +00:00
return _httpContextAccessor.HttpContext.Request.Cookies[cookieName] ?? "";
}
2019-06-07 08:59:07 +00:00
}
2022-03-17 15:13:38 +00:00
return "";
}
2019-06-07 08:59:07 +00:00
2022-03-17 15:13:38 +00:00
public void ClearCookies(CookiesType type)
{
2022-04-15 09:08:06 +00:00
if (_httpContextAccessor?.HttpContext == null)
2019-06-07 08:59:07 +00:00
{
2022-03-17 15:13:38 +00:00
return;
2019-06-07 08:59:07 +00:00
}
2022-04-15 09:08:06 +00:00
if (_httpContextAccessor.HttpContext.Request.Cookies.ContainsKey(GetCookiesName(type)))
2019-06-07 08:59:07 +00:00
{
2022-04-15 09:08:06 +00:00
_httpContextAccessor.HttpContext.Response.Cookies.Delete(GetCookiesName(type), new CookieOptions() { Expires = DateTime.Now.AddDays(-3) });
2022-03-17 15:13:38 +00:00
}
}
2019-06-07 08:59:07 +00:00
2022-03-17 15:13:38 +00:00
private DateTime? GetExpiresDate(bool session)
{
DateTime? expires = null;
2019-06-07 08:59:07 +00:00
2022-03-17 15:13:38 +00:00
if (!session)
{
2022-04-15 09:08:06 +00:00
var tenant = _tenantManager.GetCurrentTenant().Id;
expires = _tenantCookieSettingsHelper.GetExpiresTime(tenant);
2019-06-07 08:59:07 +00:00
}
2022-03-17 15:13:38 +00:00
return expires;
}
2022-06-14 08:11:41 +00:00
public async Task SetLifeTime(int lifeTime)
2022-03-17 15:13:38 +00:00
{
2022-04-15 09:08:06 +00:00
var tenant = _tenantManager.GetCurrentTenant();
if (!_userManager.IsUserInGroup(_securityContext.CurrentAccount.ID, Constants.GroupAdmin.ID))
2019-06-07 08:59:07 +00:00
{
2022-03-17 15:13:38 +00:00
throw new SecurityException();
2019-06-07 08:59:07 +00:00
}
2022-04-15 09:08:06 +00:00
var settings = _tenantCookieSettingsHelper.GetForTenant(tenant.Id);
2022-03-17 15:13:38 +00:00
if (lifeTime > 0)
2019-06-07 08:59:07 +00:00
{
2019-08-15 14:48:55 +00:00
settings.Index += 1;
2022-03-17 15:13:38 +00:00
settings.LifeTime = lifeTime;
}
else
{
settings.LifeTime = 0;
}
2019-06-07 08:59:07 +00:00
2022-04-15 09:08:06 +00:00
_tenantCookieSettingsHelper.SetForTenant(tenant.Id, settings);
2019-06-07 08:59:07 +00:00
2022-06-14 08:11:41 +00:00
if (lifeTime > 0)
{
await _dbLoginEventsManager.LogOutAllActiveConnectionsForTenant(tenant.Id);
}
2019-06-07 08:59:07 +00:00
2022-06-14 08:11:41 +00:00
AuthenticateMeAndSetCookies(tenant.Id, _securityContext.CurrentAccount.ID, MessageAction.LoginSuccess);
2022-03-17 15:13:38 +00:00
}
2019-08-08 09:26:58 +00:00
2022-03-17 15:13:38 +00:00
public int GetLifeTime(int tenantId)
{
2022-04-15 09:08:06 +00:00
return _tenantCookieSettingsHelper.GetForTenant(tenantId).LifeTime;
2022-03-17 15:13:38 +00:00
}
2019-06-07 08:59:07 +00:00
2022-06-14 08:11:41 +00:00
public async Task ResetUserCookie(Guid? userId = null)
2022-03-17 15:13:38 +00:00
{
2022-06-14 08:11:41 +00:00
var currentUserId = _securityContext.CurrentAccount.ID;
var tenant = _tenantManager.GetCurrentTenant().Id;
var settings = _tenantCookieSettingsHelper.GetForUser(userId ?? currentUserId);
settings.Index = settings.Index + 1;
_tenantCookieSettingsHelper.SetForUser(userId ?? currentUserId, settings);
await _dbLoginEventsManager.LogOutAllActiveConnections(tenant, userId ?? currentUserId);
2019-06-07 08:59:07 +00:00
2022-03-17 15:13:38 +00:00
if (!userId.HasValue)
{
2022-06-14 08:11:41 +00:00
AuthenticateMeAndSetCookies(tenant, currentUserId, MessageAction.LoginSuccess);
2019-06-07 08:59:07 +00:00
}
}
2022-03-17 15:13:38 +00:00
2022-06-14 08:11:41 +00:00
public async Task ResetTenantCookie()
2022-03-17 15:13:38 +00:00
{
2022-04-15 09:08:06 +00:00
var tenant = _tenantManager.GetCurrentTenant();
2022-03-17 15:13:38 +00:00
2022-04-15 09:08:06 +00:00
if (!_userManager.IsUserInGroup(_securityContext.CurrentAccount.ID, Constants.GroupAdmin.ID))
2022-03-17 15:13:38 +00:00
{
throw new SecurityException();
}
2022-04-15 09:08:06 +00:00
var settings = _tenantCookieSettingsHelper.GetForTenant(tenant.Id);
2022-03-17 15:13:38 +00:00
settings.Index += 1;
2022-04-15 09:08:06 +00:00
_tenantCookieSettingsHelper.SetForTenant(tenant.Id, settings);
2022-03-17 15:13:38 +00:00
2022-06-14 08:11:41 +00:00
await _dbLoginEventsManager.LogOutAllActiveConnectionsForTenant(tenant.Id);
}
public string AuthenticateMeAndSetCookies(int tenantId, Guid userId, MessageAction action, bool session = false)
{
var isSuccess = true;
var cookies = string.Empty;
Func<int> funcLoginEvent = () => { return GetLoginEventId(action); };
try
{
cookies = _securityContext.AuthenticateMe(userId, funcLoginEvent);
}
catch (Exception)
{
isSuccess = false;
throw;
}
finally
{
if (isSuccess)
{
SetCookies(CookiesType.AuthKey, cookies, session);
_dbLoginEventsManager.ResetCache(tenantId, userId);
}
}
return cookies;
}
public void AuthenticateMeAndSetCookies(string login, string passwordHash, MessageAction action, bool session = false)
{
var isSuccess = true;
var cookies = string.Empty;
Func<int> funcLoginEvent = () => { return GetLoginEventId(action); };
try
{
cookies = _securityContext.AuthenticateMe(login, passwordHash, funcLoginEvent);
}
catch (Exception)
{
isSuccess = false;
throw;
}
finally
{
if (isSuccess)
{
SetCookies(CookiesType.AuthKey, cookies, session);
_dbLoginEventsManager.ResetCache();
}
}
}
public int GetLoginEventId(MessageAction action)
{
var tenantId = _tenantManager.GetCurrentTenant().Id;
var userId = _securityContext.CurrentAccount.ID;
var data = new MessageUserData(tenantId, userId);
return _messageService.SendLoginMessage(data, action);
2022-03-17 15:13:38 +00:00
}
2022-11-18 10:20:50 +00:00
private string GetCookiesName(CookiesType type)
{
var result = type switch
{
CookiesType.AuthKey => AuthCookiesName,
CookiesType.SocketIO => SocketIOCookiesName,
_ => string.Empty,
};
if (FromCors())
{
var origin = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Origin].FirstOrDefault();
if (!string.IsNullOrEmpty(origin))
{
var originUri = new Uri(origin);
result = $"{result}_{originUri.Host.Replace('.', '_')}";
}
}
return result;
}
private bool FromCors()
{
var urlRewriter = _httpContextAccessor.HttpContext.Request.GetUrlRewriter();
var origin = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Origin].FirstOrDefault();
var baseDomain = _coreBaseSettings.Basedomain;
try
{
2022-11-18 12:12:36 +00:00
_logger.Debug($"baseDomain:{baseDomain}");
_logger.Debug($"origin:{origin}");
2022-11-18 10:20:50 +00:00
if (!string.IsNullOrEmpty(origin))
{
var originUri = new Uri(origin);
2022-11-18 12:12:36 +00:00
_logger.Debug($"originHost:{originUri.Host}");
_logger.Debug($"urlRewriter:{urlRewriter.Host}");
2022-11-18 10:20:50 +00:00
if (!string.IsNullOrEmpty(baseDomain) &&
urlRewriter.Host != originUri.Host &&
originUri.Host.EndsWith(baseDomain))
{
return true;
}
}
}
catch (Exception)
{
}
return false;
}
2022-03-17 15:13:38 +00:00
}