DocSpace-buildtools/web/ASC.Web.Api/Api/AuthenticationController.cs

593 lines
23 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 AuthenticationException = System.Security.Authentication.AuthenticationException;
2022-02-28 15:31:03 +00:00
using Constants = ASC.Core.Users.Constants;
2022-03-01 10:58:02 +00:00
namespace ASC.Web.Api.Controllers;
[Scope]
[DefaultRoute]
[ApiController]
[AllowAnonymous]
public class AuthenticationController : ControllerBase
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
private readonly UserManager _userManager;
private readonly TenantManager _tenantManager;
private readonly SecurityContext _securityContext;
private readonly TenantCookieSettingsHelper _tenantCookieSettingsHelper;
private readonly CookiesManager _cookiesManager;
private readonly PasswordHasher _passwordHasher;
private readonly EmailValidationKeyModelHelper _emailValidationKeyModelHelper;
private readonly ICache _cache;
private readonly SetupInfo _setupInfo;
private readonly MessageService _messageService;
private readonly ProviderManager _providerManager;
private readonly IOptionsSnapshot<AccountLinker> _accountLinker;
private readonly CoreBaseSettings _coreBaseSettings;
private readonly PersonalSettingsHelper _personalSettingsHelper;
private readonly StudioNotifyService _studioNotifyService;
private readonly UserHelpTourHelper _userHelpTourHelper;
private readonly Signature _signature;
private readonly InstanceCrypto _instanceCrypto;
private readonly DisplayUserSettingsHelper _displayUserSettingsHelper;
private readonly MessageTarget _messageTarget;
private readonly StudioSmsNotificationSettingsHelper _studioSmsNotificationSettingsHelper;
private readonly SettingsManager _settingsManager;
private readonly SmsManager _smsManager;
private readonly TfaManager _tfaManager;
private readonly TimeZoneConverter _timeZoneConverter;
private readonly SmsKeyStorage _smsKeyStorage;
private readonly CommonLinkUtility _commonLinkUtility;
private readonly ApiContext _apiContext;
2022-06-14 08:11:41 +00:00
private readonly AuthContext _authContext;
private readonly CookieStorage _cookieStorage;
private readonly DbLoginEventsManager _dbLoginEventsManager;
2022-03-01 10:58:02 +00:00
private readonly UserManagerWrapper _userManagerWrapper;
public AuthenticationController(
UserManager userManager,
TenantManager tenantManager,
SecurityContext securityContext,
TenantCookieSettingsHelper tenantCookieSettingsHelper,
CookiesManager cookiesManager,
PasswordHasher passwordHasher,
EmailValidationKeyModelHelper emailValidationKeyModelHelper,
ICache cache,
SetupInfo setupInfo,
MessageService messageService,
ProviderManager providerManager,
IOptionsSnapshot<AccountLinker> accountLinker,
CoreBaseSettings coreBaseSettings,
PersonalSettingsHelper personalSettingsHelper,
StudioNotifyService studioNotifyService,
UserManagerWrapper userManagerWrapper,
UserHelpTourHelper userHelpTourHelper,
Signature signature,
InstanceCrypto instanceCrypto,
DisplayUserSettingsHelper displayUserSettingsHelper,
MessageTarget messageTarget,
StudioSmsNotificationSettingsHelper studioSmsNotificationSettingsHelper,
SettingsManager settingsManager,
SmsManager smsManager,
TfaManager tfaManager,
TimeZoneConverter timeZoneConverter,
SmsKeyStorage smsKeyStorage,
CommonLinkUtility commonLinkUtility,
ApiContext apiContext,
2022-06-14 08:11:41 +00:00
AuthContext authContext,
CookieStorage cookieStorage,
DbLoginEventsManager dbLoginEventsManager)
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
_userManager = userManager;
_tenantManager = tenantManager;
_securityContext = securityContext;
_tenantCookieSettingsHelper = tenantCookieSettingsHelper;
_cookiesManager = cookiesManager;
_passwordHasher = passwordHasher;
_emailValidationKeyModelHelper = emailValidationKeyModelHelper;
_cache = cache;
_setupInfo = setupInfo;
_messageService = messageService;
_providerManager = providerManager;
_accountLinker = accountLinker;
_coreBaseSettings = coreBaseSettings;
_personalSettingsHelper = personalSettingsHelper;
_studioNotifyService = studioNotifyService;
_userHelpTourHelper = userHelpTourHelper;
_signature = signature;
_instanceCrypto = instanceCrypto;
_displayUserSettingsHelper = displayUserSettingsHelper;
_messageTarget = messageTarget;
_studioSmsNotificationSettingsHelper = studioSmsNotificationSettingsHelper;
_settingsManager = settingsManager;
_smsManager = smsManager;
_tfaManager = tfaManager;
_timeZoneConverter = timeZoneConverter;
_smsKeyStorage = smsKeyStorage;
_commonLinkUtility = commonLinkUtility;
_apiContext = apiContext;
2022-06-14 08:11:41 +00:00
_authContext = authContext;
_cookieStorage = cookieStorage;
_dbLoginEventsManager = dbLoginEventsManager;
2022-03-01 10:58:02 +00:00
_userManagerWrapper = userManagerWrapper;
}
2022-02-28 15:31:03 +00:00
[HttpGet]
2022-03-01 10:58:02 +00:00
public bool GetIsAuthentificated()
{
return _securityContext.IsAuthenticated;
}
[AllowNotPayment]
2022-06-29 16:43:29 +00:00
[HttpPost("{code}", Order = 1)]
public AuthenticationTokenDto AuthenticateMeFromBodyWithCode(AuthRequestsDto inDto)
2022-03-01 10:58:02 +00:00
{
var tenant = _tenantManager.GetCurrentTenant().Id;
var user = GetUser(inDto, out _);
2022-02-28 15:31:03 +00:00
var sms = false;
try
2022-03-17 15:01:39 +00:00
{
2022-06-07 18:00:08 +00:00
if (_studioSmsNotificationSettingsHelper.IsVisibleAndAvailableSettings() && _studioSmsNotificationSettingsHelper.Enable)
{
sms = true;
2022-06-07 18:00:08 +00:00
_smsManager.ValidateSmsCode(user, inDto.Code, true);
}
else if (TfaAppAuthSettings.IsVisibleSettings && _settingsManager.Load<TfaAppAuthSettings>().EnableSetting)
{
2022-06-07 18:00:08 +00:00
if (_tfaManager.ValidateAuthCode(user, inDto.Code, true, true))
{
_messageService.Send(MessageAction.UserConnectedTfaApp, _messageTarget.Create(user.Id));
}
}
else
{
throw new SecurityException("Auth code is not available");
}
2022-06-07 18:00:08 +00:00
var token = _cookiesManager.AuthenticateMeAndSetCookies(user.Tenant, user.Id, MessageAction.LoginSuccess);
var expires = _tenantCookieSettingsHelper.GetExpiresTime(tenant);
2022-03-01 10:58:02 +00:00
var result = new AuthenticationTokenDto
{
Token = token,
Expires = new ApiDateTime(_tenantManager, _timeZoneConverter, expires)
};
2022-03-01 10:58:02 +00:00
if (sms)
{
result.Sms = true;
result.PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone);
}
else
{
result.Tfa = true;
}
2022-02-28 15:31:03 +00:00
return result;
}
catch
2022-02-28 15:31:03 +00:00
{
_messageService.Send(user.DisplayUserName(false, _displayUserSettingsHelper), sms
? MessageAction.LoginFailViaApiSms
: MessageAction.LoginFailViaApiTfa,
_messageTarget.Create(user.Id));
throw new AuthenticationException("User authentication failed");
}
finally
2022-02-28 15:31:03 +00:00
{
_securityContext.Logout();
}
2022-03-01 10:58:02 +00:00
}
[AllowNotPayment]
[HttpPost]
public async Task<AuthenticationTokenDto> AuthenticateMeAsync(AuthRequestsDto inDto)
2022-03-01 10:58:02 +00:00
{
bool viaEmail;
2022-03-15 10:56:22 +00:00
var user = GetUser(inDto, out viaEmail);
2022-03-01 10:58:02 +00:00
2022-06-07 18:00:08 +00:00
if (_studioSmsNotificationSettingsHelper.IsVisibleAndAvailableSettings() && _studioSmsNotificationSettingsHelper.Enable)
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
if (string.IsNullOrEmpty(user.MobilePhone) || user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
2022-03-17 15:01:39 +00:00
{
2022-03-15 10:00:41 +00:00
return new AuthenticationTokenDto
2022-03-01 10:58:02 +00:00
{
Sms = true,
ConfirmUrl = _commonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PhoneActivation)
};
2022-03-17 15:01:39 +00:00
}
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
await _smsManager.PutAuthCodeAsync(user, false);
2022-03-15 10:00:41 +00:00
return new AuthenticationTokenDto
2022-02-28 15:31:03 +00:00
{
Sms = true,
2022-03-01 10:58:02 +00:00
PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
Expires = new ApiDateTime(_tenantManager, _timeZoneConverter, DateTime.UtcNow.Add(_smsKeyStorage.StoreInterval)),
ConfirmUrl = _commonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PhoneAuth)
2022-02-28 15:31:03 +00:00
};
}
2022-03-01 10:58:02 +00:00
if (TfaAppAuthSettings.IsVisibleSettings && _settingsManager.Load<TfaAppAuthSettings>().EnableSetting)
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
if (!TfaAppUserSettings.EnableForUser(_settingsManager, user.Id))
2022-03-17 15:01:39 +00:00
{
2022-03-15 10:00:41 +00:00
return new AuthenticationTokenDto
2022-03-01 10:58:02 +00:00
{
Tfa = true,
TfaKey = _tfaManager.GenerateSetupCode(user).ManualEntryKey,
ConfirmUrl = _commonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaActivation)
};
2022-03-17 15:01:39 +00:00
}
2022-02-28 15:31:03 +00:00
2022-03-15 10:00:41 +00:00
return new AuthenticationTokenDto
2022-03-01 10:58:02 +00:00
{
Tfa = true,
ConfirmUrl = _commonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaAuth)
};
2022-02-28 15:31:03 +00:00
}
2022-03-01 10:58:02 +00:00
try
2022-06-07 18:00:08 +00:00
{
var action = viaEmail ? MessageAction.LoginSuccessViaApi : MessageAction.LoginSuccessViaApiSocialAccount;
var token = _cookiesManager.AuthenticateMeAndSetCookies(user.Tenant, user.Id, action);
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
var tenant = _tenantManager.GetCurrentTenant().Id;
var expires = _tenantCookieSettingsHelper.GetExpiresTime(tenant);
2022-03-15 10:00:41 +00:00
return new AuthenticationTokenDto
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
Token = token,
Expires = new ApiDateTime(_tenantManager, _timeZoneConverter, expires)
2022-02-28 15:31:03 +00:00
};
}
2022-03-01 10:58:02 +00:00
catch
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
_messageService.Send(user.DisplayUserName(false, _displayUserSettingsHelper), viaEmail ? MessageAction.LoginFailViaApi : MessageAction.LoginFailViaApiSocialAccount);
throw new AuthenticationException("User authentication failed");
}
finally
{
_securityContext.Logout();
}
}
2022-02-28 15:31:03 +00:00
[HttpPost("logout")]
[HttpGet("logout")]// temp fix
2022-06-14 08:11:41 +00:00
public async Task Logout()
{
var cookie = _cookiesManager.GetCookies(CookiesType.AuthKey);
var loginEventId = _cookieStorage.GetLoginEventIdFromCookie(cookie);
await _dbLoginEventsManager.LogOutEvent(loginEventId);
var user = _userManager.GetUsers(_securityContext.CurrentAccount.ID);
var loginName = user.DisplayUserName(false, _displayUserSettingsHelper);
_messageService.Send(loginName, MessageAction.Logout);
2022-02-28 15:31:03 +00:00
_cookiesManager.ClearCookies(CookiesType.AuthKey);
2022-06-14 08:11:41 +00:00
_cookiesManager.ClearCookies(CookiesType.SocketIO);
2022-02-28 15:31:03 +00:00
_securityContext.Logout();
}
[AllowNotPayment]
[HttpPost("confirm")]
public ValidationResult CheckConfirm(EmailValidationKeyModel inDto)
{
return _emailValidationKeyModelHelper.Validate(inDto);
}
2022-03-01 10:58:02 +00:00
[AllowNotPayment]
[Authorize(AuthenticationSchemes = "confirm", Roles = "PhoneActivation")]
[HttpPost("setphone")]
public async Task<AuthenticationTokenDto> SaveMobilePhoneAsync(MobileRequestsDto inDto)
{
_apiContext.AuthByClaim();
var user = _userManager.GetUsers(_authContext.CurrentAccount.ID);
inDto.MobilePhone = await _smsManager.SaveMobilePhoneAsync(user, inDto.MobilePhone);
_messageService.Send(MessageAction.UserUpdatedMobileNumber, _messageTarget.Create(user.Id), user.DisplayUserName(false, _displayUserSettingsHelper), inDto.MobilePhone);
2022-02-28 15:31:03 +00:00
return new AuthenticationTokenDto
2022-03-01 10:58:02 +00:00
{
Sms = true,
PhoneNoise = SmsSender.BuildPhoneNoise(inDto.MobilePhone),
Expires = new ApiDateTime(_tenantManager, _timeZoneConverter, DateTime.UtcNow.Add(_smsKeyStorage.StoreInterval))
};
}
[AllowNotPayment]
[HttpPost("sendsms")]
public async Task<AuthenticationTokenDto> SendSmsCodeAsync(AuthRequestsDto inDto)
{
var user = GetUser(inDto, out _);
await _smsManager.PutAuthCodeAsync(user, true);
return new AuthenticationTokenDto
2022-02-28 15:31:03 +00:00
{
Sms = true,
PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
Expires = new ApiDateTime(_tenantManager, _timeZoneConverter, DateTime.UtcNow.Add(_smsKeyStorage.StoreInterval))
};
2022-03-01 10:58:02 +00:00
}
2022-02-28 15:31:03 +00:00
2022-03-15 10:56:22 +00:00
private UserInfo GetUser(AuthRequestsDto inDto, out bool viaEmail)
2022-03-01 10:58:02 +00:00
{
viaEmail = true;
var action = MessageAction.LoginFailViaApi;
UserInfo user;
try
{
2022-03-15 10:56:22 +00:00
if ((string.IsNullOrEmpty(inDto.Provider) && string.IsNullOrEmpty(inDto.SerializedProfile)) || inDto.Provider == "email")
2022-02-28 15:31:03 +00:00
{
2022-03-15 10:56:22 +00:00
inDto.UserName.ThrowIfNull(new ArgumentException(@"userName empty", "userName"));
if (!string.IsNullOrEmpty(inDto.Password))
2022-02-28 15:31:03 +00:00
{
2022-03-15 10:56:22 +00:00
inDto.Password.ThrowIfNull(new ArgumentException(@"password empty", "password"));
2022-02-28 15:31:03 +00:00
}
2022-03-01 10:58:02 +00:00
else
2022-02-28 15:31:03 +00:00
{
2022-03-15 10:56:22 +00:00
inDto.PasswordHash.ThrowIfNull(new ArgumentException(@"PasswordHash empty", "PasswordHash"));
2022-02-28 15:31:03 +00:00
}
2022-03-01 10:58:02 +00:00
int counter;
2022-03-15 10:56:22 +00:00
int.TryParse(_cache.Get<string>("loginsec/" + inDto.UserName), out counter);
if (++counter > _setupInfo.LoginThreshold && !SetupInfo.IsSecretEmail(inDto.UserName))
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
throw new BruteForceCredentialException();
2022-02-28 15:31:03 +00:00
}
2022-03-15 10:56:22 +00:00
_cache.Insert("loginsec/" + inDto.UserName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
2022-02-28 15:31:03 +00:00
2022-03-15 10:56:22 +00:00
inDto.PasswordHash = (inDto.PasswordHash ?? "").Trim();
2022-02-28 15:31:03 +00:00
2022-03-15 10:56:22 +00:00
if (string.IsNullOrEmpty(inDto.PasswordHash))
2022-02-28 15:31:03 +00:00
{
2022-03-15 10:56:22 +00:00
inDto.Password = (inDto.Password ?? "").Trim();
2022-02-28 15:31:03 +00:00
2022-03-15 10:56:22 +00:00
if (!string.IsNullOrEmpty(inDto.Password))
2022-03-01 10:58:02 +00:00
{
2022-03-15 10:56:22 +00:00
inDto.PasswordHash = _passwordHasher.GetClientPassword(inDto.Password);
2022-03-01 10:58:02 +00:00
}
2022-02-28 15:31:03 +00:00
}
2022-03-01 10:58:02 +00:00
user = _userManager.GetUsersByPasswordHash(
_tenantManager.GetCurrentTenant().Id,
2022-03-15 10:56:22 +00:00
inDto.UserName,
inDto.PasswordHash);
2022-03-01 10:58:02 +00:00
if (user == null || !_userManager.UserExists(user))
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
throw new Exception("user not found");
2022-02-28 15:31:03 +00:00
}
2022-03-15 10:56:22 +00:00
_cache.Insert("loginsec/" + inDto.UserName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
2022-02-28 15:31:03 +00:00
}
2022-03-01 10:58:02 +00:00
else
2022-06-07 18:00:08 +00:00
{
if (!(_coreBaseSettings.Standalone || _tenantManager.GetTenantQuota(_tenantManager.GetCurrentTenant().Id).Oauth))
{
throw new Exception(Resource.ErrorNotAllowedOption);
}
2022-03-01 10:58:02 +00:00
viaEmail = false;
action = MessageAction.LoginFailViaApiSocialAccount;
LoginProfile thirdPartyProfile;
2022-03-15 10:56:22 +00:00
if (!string.IsNullOrEmpty(inDto.SerializedProfile))
2022-02-28 15:31:03 +00:00
{
2022-03-15 10:56:22 +00:00
thirdPartyProfile = new LoginProfile(_signature, _instanceCrypto, inDto.SerializedProfile);
2022-02-28 15:31:03 +00:00
}
else
{
2022-06-07 18:00:08 +00:00
thirdPartyProfile = _providerManager.GetLoginProfile(inDto.Provider, inDto.AccessToken, inDto.CodeOAuth);
2022-03-01 10:58:02 +00:00
}
2022-02-28 15:31:03 +00:00
2022-03-15 10:56:22 +00:00
inDto.UserName = thirdPartyProfile.EMail;
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
user = GetUserByThirdParty(thirdPartyProfile);
2022-02-28 15:31:03 +00:00
}
}
2022-03-01 10:58:02 +00:00
catch (BruteForceCredentialException)
{
2022-03-15 10:56:22 +00:00
_messageService.Send(!string.IsNullOrEmpty(inDto.UserName) ? inDto.UserName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce);
2022-03-01 10:58:02 +00:00
throw new AuthenticationException("Login Fail. Too many attempts");
}
catch
{
2022-03-15 10:56:22 +00:00
_messageService.Send(!string.IsNullOrEmpty(inDto.UserName) ? inDto.UserName : AuditResource.EmailNotSpecified, action);
2022-03-01 10:58:02 +00:00
throw new AuthenticationException("User authentication failed");
}
return user;
}
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
private UserInfo GetUserByThirdParty(LoginProfile loginProfile)
{
try
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
if (!string.IsNullOrEmpty(loginProfile.AuthorizationError))
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
// ignore cancellation
if (loginProfile.AuthorizationError != "Canceled at provider")
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
throw new Exception(loginProfile.AuthorizationError);
2022-02-28 15:31:03 +00:00
}
2022-03-01 10:58:02 +00:00
return Constants.LostUser;
}
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
var userInfo = Constants.LostUser;
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
Guid userId;
if (TryGetUserByHash(loginProfile.HashId, out userId))
{
userInfo = _userManager.GetUsers(userId);
}
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
var isNew = false;
if (_coreBaseSettings.Personal)
{
if (_userManager.UserExists(userInfo.Id) && SetupInfo.IsSecretEmail(userInfo.Email))
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
try
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
_securityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem);
_userManager.DeleteUser(userInfo.Id);
userInfo = Constants.LostUser;
2022-02-28 15:31:03 +00:00
}
2022-03-01 10:58:02 +00:00
finally
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
_securityContext.Logout();
2022-02-28 15:31:03 +00:00
}
}
2022-03-01 10:58:02 +00:00
if (!_userManager.UserExists(userInfo.Id))
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
userInfo = JoinByThirdPartyAccount(loginProfile);
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
isNew = true;
}
2022-02-28 15:31:03 +00:00
}
2022-03-01 10:58:02 +00:00
if (isNew)
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
//TODO:
//var spam = HttpContext.Current.Request["spam"];
//if (spam != "on")
//{
// try
// {
// const string _databaseID = "com";
// using (var db = DbManager.FromHttpContext(_databaseID))
// {
// db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
// .InColumnValue("email", userInfo.Email.ToLowerInvariant())
// .InColumnValue("reason", "personal")
// );
// Log.Debug(string.Format("Write to template_unsubscribe {0}", userInfo.Email.ToLowerInvariant()));
// }
// }
// catch (Exception ex)
// {
// Log.Debug(string.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, userInfo.Email.ToLowerInvariant()));
// }
//}
_studioNotifyService.UserHasJoin();
_userHelpTourHelper.IsNewUser = true;
_personalSettingsHelper.IsNewUser = true;
2022-02-28 15:31:03 +00:00
}
return userInfo;
}
2022-03-01 10:58:02 +00:00
catch (Exception)
{
_cookiesManager.ClearCookies(CookiesType.AuthKey);
_cookiesManager.ClearCookies(CookiesType.SocketIO);
_securityContext.Logout();
throw;
}
}
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
private UserInfo JoinByThirdPartyAccount(LoginProfile loginProfile)
{
if (string.IsNullOrEmpty(loginProfile.EMail))
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
throw new Exception(Resource.ErrorNotCorrectEmail);
}
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
var userInfo = _userManager.GetUserByEmail(loginProfile.EMail);
if (!_userManager.UserExists(userInfo.Id))
{
var newUserInfo = ProfileToUserInfo(loginProfile);
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
try
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
_securityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem);
userInfo = _userManagerWrapper.AddUser(newUserInfo, UserManagerWrapper.GeneratePassword());
}
finally
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
_securityContext.Logout();
2022-02-28 15:31:03 +00:00
}
}
2022-03-01 10:58:02 +00:00
var linker = _accountLinker.Get("webstudio");
linker.AddLink(userInfo.Id.ToString(), loginProfile);
return userInfo;
2022-02-28 15:31:03 +00:00
}
2022-03-01 10:58:02 +00:00
private UserInfo ProfileToUserInfo(LoginProfile loginProfile)
2022-02-28 15:31:03 +00:00
{
2022-03-17 15:01:39 +00:00
if (string.IsNullOrEmpty(loginProfile.EMail))
{
throw new Exception(Resource.ErrorNotCorrectEmail);
}
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
var firstName = loginProfile.FirstName;
2022-03-17 15:01:39 +00:00
if (string.IsNullOrEmpty(firstName))
{
firstName = loginProfile.DisplayName;
}
2022-02-28 15:31:03 +00:00
2022-03-01 10:58:02 +00:00
var userInfo = new UserInfo
2022-02-28 15:31:03 +00:00
{
2022-03-01 10:58:02 +00:00
FirstName = string.IsNullOrEmpty(firstName) ? UserControlsCommonResource.UnknownFirstName : firstName,
LastName = string.IsNullOrEmpty(loginProfile.LastName) ? UserControlsCommonResource.UnknownLastName : loginProfile.LastName,
Email = loginProfile.EMail,
Title = string.Empty,
Location = string.Empty,
CultureName = _coreBaseSettings.CustomMode ? "ru-RU" : Thread.CurrentThread.CurrentUICulture.Name,
ActivationStatus = EmployeeActivationStatus.Activated,
};
var gender = loginProfile.Gender;
if (!string.IsNullOrEmpty(gender))
{
userInfo.Sex = gender == "male";
2022-02-28 15:31:03 +00:00
}
2022-03-01 10:58:02 +00:00
return userInfo;
}
private bool TryGetUserByHash(string hashId, out Guid userId)
{
userId = Guid.Empty;
2022-03-17 15:01:39 +00:00
if (string.IsNullOrEmpty(hashId))
{
return false;
}
2022-03-01 10:58:02 +00:00
var linkedProfiles = _accountLinker.Get("webstudio").GetLinkedObjectsByHashId(hashId);
var tmp = Guid.Empty;
if (linkedProfiles.Any(profileId => Guid.TryParse(profileId, out tmp) && _userManager.UserExists(tmp)))
2022-03-17 15:01:39 +00:00
{
2022-03-01 10:58:02 +00:00
userId = tmp;
2022-03-17 15:01:39 +00:00
}
2022-03-01 10:58:02 +00:00
return true;
2022-02-28 15:31:03 +00:00
}
2019-05-28 09:40:37 +00:00
}