DocSpace-client/web/ASC.Web.Api/Controllers/AuthenticationController.cs

658 lines
26 KiB
C#
Raw Normal View History

2019-05-28 09:40:37 +00:00
using System;
2021-02-19 16:16:08 +00:00
using System.Globalization;
using System.Linq;
using System.Security.Authentication;
using System.Threading;
2020-02-17 08:58:14 +00:00
2021-04-26 11:56:38 +00:00
using ASC.Api.Core;
2021-02-19 16:16:08 +00:00
using ASC.Api.Utils;
2020-02-17 08:58:14 +00:00
using ASC.Common;
2021-02-19 16:16:08 +00:00
using ASC.Common.Caching;
using ASC.Common.Utils;
2019-05-28 09:40:37 +00:00
using ASC.Core;
2021-02-19 16:16:08 +00:00
using ASC.Core.Common.Security;
2021-04-26 11:56:38 +00:00
using ASC.Core.Common.Settings;
2019-05-28 09:40:37 +00:00
using ASC.Core.Tenants;
using ASC.Core.Users;
2021-02-19 16:16:08 +00:00
using ASC.FederatedLogin;
using ASC.FederatedLogin.LoginProviders;
using ASC.FederatedLogin.Profile;
using ASC.MessagingSystem;
2019-05-28 09:40:37 +00:00
using ASC.Security.Cryptography;
2021-02-19 16:16:08 +00:00
using ASC.Web.Api.Core;
2019-05-28 09:40:37 +00:00
using ASC.Web.Api.Models;
using ASC.Web.Api.Routing;
2019-11-12 11:32:05 +00:00
using ASC.Web.Core;
2021-02-19 16:16:08 +00:00
using ASC.Web.Core.PublicResources;
2021-04-26 11:56:38 +00:00
using ASC.Web.Core.Sms;
2021-02-19 16:16:08 +00:00
using ASC.Web.Core.Users;
using ASC.Web.Studio.Core;
using ASC.Web.Studio.Core.Notify;
2021-04-26 11:56:38 +00:00
using ASC.Web.Studio.Core.SMS;
using ASC.Web.Studio.Core.TFA;
2021-04-27 10:40:25 +00:00
using ASC.Web.Studio.Utility;
2020-02-17 08:58:14 +00:00
2019-05-28 09:40:37 +00:00
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
2021-02-19 16:16:08 +00:00
using Microsoft.Extensions.Options;
2020-02-17 08:58:14 +00:00
2019-09-26 13:36:53 +00:00
using static ASC.Security.Cryptography.EmailValidationKeyProvider;
2019-05-28 09:40:37 +00:00
namespace ASC.Web.Api.Controllers
{
2020-10-19 15:53:15 +00:00
[Scope]
2019-05-28 09:40:37 +00:00
[DefaultRoute]
[ApiController]
2020-12-01 13:40:38 +00:00
[AllowAnonymous]
2019-05-28 09:40:37 +00:00
public class AuthenticationController : ControllerBase
{
2020-08-12 09:58:08 +00:00
private UserManager UserManager { get; }
private TenantManager TenantManager { get; }
private SecurityContext SecurityContext { get; }
private TenantCookieSettingsHelper TenantCookieSettingsHelper { get; }
private CookiesManager CookiesManager { get; }
2021-02-19 16:16:08 +00:00
private PasswordHasher PasswordHasher { get; }
private EmailValidationKeyModelHelper EmailValidationKeyModelHelper { get; }
private ICache Cache { get; }
private SetupInfo SetupInfo { get; }
private MessageService MessageService { get; }
private ProviderManager ProviderManager { get; }
private IOptionsSnapshot<AccountLinker> AccountLinker { get; }
private CoreBaseSettings CoreBaseSettings { get; }
private PersonalSettingsHelper PersonalSettingsHelper { get; }
private StudioNotifyService StudioNotifyService { get; }
private UserHelpTourHelper UserHelpTourHelper { get; }
2021-04-26 11:56:38 +00:00
private Signature Signature { get; }
private InstanceCrypto InstanceCrypto { get; }
private DisplayUserSettingsHelper DisplayUserSettingsHelper { get; }
private MessageTarget MessageTarget { get; }
private StudioSmsNotificationSettingsHelper StudioSmsNotificationSettingsHelper { get; }
private SettingsManager SettingsManager { get; }
private SmsManager SmsManager { get; }
private TfaManager TfaManager { get; }
private TimeZoneConverter TimeZoneConverter { get; }
private SmsKeyStorage SmsKeyStorage { get; }
2021-05-05 12:57:12 +00:00
private CommonLinkUtility CommonLinkUtility { get; }
private ApiContext ApiContext { get; }
private AuthContext AuthContext { get; }
2021-02-19 16:16:08 +00:00
private UserManagerWrapper UserManagerWrapper { get; }
2019-09-09 12:56:33 +00:00
public AuthenticationController(
UserManager userManager,
TenantManager tenantManager,
2019-09-13 11:18:27 +00:00
SecurityContext securityContext,
TenantCookieSettingsHelper tenantCookieSettingsHelper,
2020-09-17 12:04:28 +00:00
CookiesManager cookiesManager,
2020-10-07 10:45:53 +00:00
PasswordHasher passwordHasher,
2021-02-19 16:16:08 +00:00
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,
2021-04-26 11:56:38 +00:00
InstanceCrypto instanceCrypto,
DisplayUserSettingsHelper displayUserSettingsHelper,
MessageTarget messageTarget,
StudioSmsNotificationSettingsHelper studioSmsNotificationSettingsHelper,
SettingsManager settingsManager,
SmsManager smsManager,
TfaManager tfaManager,
TimeZoneConverter timeZoneConverter,
2021-04-27 10:40:25 +00:00
SmsKeyStorage smsKeyStorage,
CommonLinkUtility commonLinkUtility,
ApiContext apiContext,
AuthContext authContext)
2019-09-09 12:56:33 +00:00
{
UserManager = userManager;
TenantManager = tenantManager;
SecurityContext = securityContext;
TenantCookieSettingsHelper = tenantCookieSettingsHelper;
2019-11-12 11:32:05 +00:00
CookiesManager = cookiesManager;
2020-09-17 12:04:28 +00:00
PasswordHasher = passwordHasher;
2020-10-07 10:45:53 +00:00
EmailValidationKeyModelHelper = emailValidationKeyModelHelper;
2021-02-19 16:16:08 +00:00
Cache = cache;
SetupInfo = setupInfo;
MessageService = messageService;
ProviderManager = providerManager;
AccountLinker = accountLinker;
CoreBaseSettings = coreBaseSettings;
PersonalSettingsHelper = personalSettingsHelper;
StudioNotifyService = studioNotifyService;
UserHelpTourHelper = userHelpTourHelper;
Signature = signature;
InstanceCrypto = instanceCrypto;
2021-04-26 11:56:38 +00:00
DisplayUserSettingsHelper = displayUserSettingsHelper;
MessageTarget = messageTarget;
StudioSmsNotificationSettingsHelper = studioSmsNotificationSettingsHelper;
SettingsManager = settingsManager;
SmsManager = smsManager;
TfaManager = tfaManager;
TimeZoneConverter = timeZoneConverter;
SmsKeyStorage = smsKeyStorage;
2021-04-27 10:40:25 +00:00
CommonLinkUtility = commonLinkUtility;
ApiContext = apiContext;
AuthContext = authContext;
2021-02-19 16:16:08 +00:00
UserManagerWrapper = userManagerWrapper;
2019-09-09 12:56:33 +00:00
}
2020-12-01 08:22:10 +00:00
[Read]
public bool GetIsAuthentificated()
{
return SecurityContext.IsAuthenticated;
}
2021-05-13 11:02:33 +00:00
[Create("{code}", false, order: int.MaxValue)]
2021-04-26 11:56:38 +00:00
public AuthenticationTokenData AuthenticateMeFromBodyWithCode([FromBody] AuthModel auth)
{
return AuthenticateMeWithCode(auth);
}
2021-05-13 11:02:33 +00:00
[Create("{code}", false, order: int.MaxValue)]
2021-04-26 11:56:38 +00:00
[Consumes("application/x-www-form-urlencoded")]
public AuthenticationTokenData AuthenticateMeFromFormWithCode([FromForm] AuthModel auth)
{
return AuthenticateMeWithCode(auth);
}
2019-06-25 10:46:10 +00:00
[Create(false)]
public AuthenticationTokenData AuthenticateMeFromBody([FromBody] AuthModel auth)
{
return AuthenticateMe(auth);
}
[Create(false)]
[Consumes("application/x-www-form-urlencoded")]
public AuthenticationTokenData AuthenticateMeFromForm([FromForm] AuthModel auth)
{
return AuthenticateMe(auth);
}
2020-12-01 08:22:10 +00:00
[Create("logout")]
2021-10-28 17:14:20 +00:00
[Read("logout")]// temp fix
2020-12-01 08:22:10 +00:00
public void Logout()
{
2021-11-16 17:40:15 +00:00
if (SecurityContext.IsAuthenticated)
CookiesManager.ResetUserCookie(SecurityContext.CurrentAccount.ID);
2020-12-01 08:22:10 +00:00
CookiesManager.ClearCookies(CookiesType.AuthKey);
CookiesManager.ClearCookies(CookiesType.SocketIO);
2021-11-16 17:40:15 +00:00
SecurityContext.Logout();
2020-12-01 08:22:10 +00:00
}
[Create("confirm", false)]
public ValidationResult CheckConfirmFromBody([FromBody] EmailValidationKeyModel model)
{
return EmailValidationKeyModelHelper.Validate(model);
}
[Create("confirm", false)]
[Consumes("application/x-www-form-urlencoded")]
public ValidationResult CheckConfirmFromForm([FromForm] EmailValidationKeyModel model)
{
return EmailValidationKeyModelHelper.Validate(model);
}
[Authorize(AuthenticationSchemes = "confirm", Roles = "PhoneActivation")]
2021-06-16 17:46:24 +00:00
[Create("setphone", false)]
public AuthenticationTokenData SaveMobilePhoneFromBody([FromBody] MobileModel model)
2019-05-28 09:40:37 +00:00
{
2021-06-16 17:46:24 +00:00
return SaveMobilePhone(model);
}
[Authorize(AuthenticationSchemes = "confirm", Roles = "PhoneActivation")]
2021-06-16 17:46:24 +00:00
[Create("setphone", false)]
[Consumes("application/x-www-form-urlencoded")]
public AuthenticationTokenData SaveMobilePhoneFromForm([FromForm] MobileModel model)
2021-06-16 17:46:24 +00:00
{
return SaveMobilePhone(model);
}
2021-04-26 11:56:38 +00:00
private AuthenticationTokenData SaveMobilePhone(MobileModel model)
2021-06-16 17:46:24 +00:00
{
ApiContext.AuthByClaim();
var user = UserManager.GetUsers(AuthContext.CurrentAccount.ID);
2021-06-16 17:46:24 +00:00
model.MobilePhone = SmsManager.SaveMobilePhone(user, model.MobilePhone);
MessageService.Send(MessageAction.UserUpdatedMobileNumber, MessageTarget.Create(user.ID), user.DisplayUserName(false, DisplayUserSettingsHelper), model.MobilePhone);
return new AuthenticationTokenData
{
Sms = true,
PhoneNoise = SmsSender.BuildPhoneNoise(model.MobilePhone),
Expires = new ApiDateTime(TenantManager, TimeZoneConverter, DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval))
};
}
[Create(@"sendsms", false)]
2021-10-28 17:14:20 +00:00
public AuthenticationTokenData SendSmsCodeFromBody([FromBody] AuthModel model)
2021-06-16 17:46:24 +00:00
{
return SendSmsCode(model);
}
[Create(@"sendsms", false)]
[Consumes("application/x-www-form-urlencoded")]
2021-10-28 17:14:20 +00:00
public AuthenticationTokenData SendSmsCodeFromForm([FromForm] AuthModel model)
2021-06-16 17:46:24 +00:00
{
return SendSmsCode(model);
}
private AuthenticationTokenData SendSmsCode(AuthModel model)
{
var user = GetUser(model, out _);
SmsManager.PutAuthCode(user, true);
return new AuthenticationTokenData
{
Sms = true,
PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
Expires = new ApiDateTime(TenantManager, TimeZoneConverter, DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval))
};
}
private AuthenticationTokenData AuthenticateMe(AuthModel auth)
{
2021-04-26 11:56:38 +00:00
bool viaEmail;
2021-06-16 17:46:24 +00:00
var user = GetUser(auth, out viaEmail);
2021-04-26 11:56:38 +00:00
if (StudioSmsNotificationSettingsHelper.IsVisibleSettings() && StudioSmsNotificationSettingsHelper.Enable)
{
if (string.IsNullOrEmpty(user.MobilePhone) || user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
return new AuthenticationTokenData
{
2021-04-27 10:40:25 +00:00
Sms = true,
ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PhoneActivation)
2021-04-26 11:56:38 +00:00
};
SmsManager.PutAuthCode(user, false);
return new AuthenticationTokenData
{
Sms = true,
PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
2021-04-27 10:40:25 +00:00
Expires = new ApiDateTime(TenantManager, TimeZoneConverter, DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval)),
ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PhoneAuth)
2021-04-26 11:56:38 +00:00
};
}
if (TfaAppAuthSettings.IsVisibleSettings && SettingsManager.Load<TfaAppAuthSettings>().EnableSetting)
{
if (!TfaAppUserSettings.EnableForUser(SettingsManager, user.ID))
return new AuthenticationTokenData
{
Tfa = true,
2021-06-08 08:34:14 +00:00
TfaKey = TfaManager.GenerateSetupCode(user).ManualEntryKey,
2021-04-27 10:40:25 +00:00
ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaActivation)
2021-04-26 11:56:38 +00:00
};
return new AuthenticationTokenData
{
2021-04-27 10:40:25 +00:00
Tfa = true,
ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaAuth)
2021-04-26 11:56:38 +00:00
};
}
2019-05-28 09:40:37 +00:00
try
{
2019-09-20 15:53:27 +00:00
var token = SecurityContext.AuthenticateMe(user.ID);
2021-05-05 12:57:12 +00:00
CookiesManager.SetCookies(CookiesType.AuthKey, token);
2021-04-26 11:56:38 +00:00
MessageService.Send(viaEmail ? MessageAction.LoginSuccessViaApi : MessageAction.LoginSuccessViaApiSocialAccount);
2021-10-28 17:14:20 +00:00
2021-06-16 17:46:24 +00:00
var tenant = TenantManager.GetCurrentTenant().TenantId;
2021-04-26 11:56:38 +00:00
var expires = TenantCookieSettingsHelper.GetExpiresTime(tenant);
2019-05-28 09:40:37 +00:00
return new AuthenticationTokenData
{
Token = token,
2021-04-26 11:56:38 +00:00
Expires = new ApiDateTime(TenantManager, TimeZoneConverter, expires)
};
}
catch
{
MessageService.Send(user.DisplayUserName(false, DisplayUserSettingsHelper), viaEmail ? MessageAction.LoginFailViaApi : MessageAction.LoginFailViaApiSocialAccount);
throw new AuthenticationException("User authentication failed");
}
finally
{
SecurityContext.Logout();
}
}
private AuthenticationTokenData AuthenticateMeWithCode(AuthModel auth)
{
var tenant = TenantManager.GetCurrentTenant().TenantId;
2021-06-16 17:46:24 +00:00
var user = GetUser(auth, out _);
2021-04-26 11:56:38 +00:00
var sms = false;
try
{
if (StudioSmsNotificationSettingsHelper.IsVisibleSettings() && StudioSmsNotificationSettingsHelper.Enable)
{
sms = true;
SmsManager.ValidateSmsCode(user, auth.Code);
}
else if (TfaAppAuthSettings.IsVisibleSettings && SettingsManager.Load<TfaAppAuthSettings>().EnableSetting)
{
if (TfaManager.ValidateAuthCode(user, auth.Code))
{
MessageService.Send(MessageAction.UserConnectedTfaApp, MessageTarget.Create(user.ID));
}
}
else
{
throw new System.Security.SecurityException("Auth code is not available");
}
var token = SecurityContext.AuthenticateMe(user.ID);
MessageService.Send(sms ? MessageAction.LoginSuccessViaApiSms : MessageAction.LoginSuccessViaApiTfa);
2021-10-28 17:14:20 +00:00
;
2021-04-26 11:56:38 +00:00
var expires = TenantCookieSettingsHelper.GetExpiresTime(tenant);
var result = new AuthenticationTokenData
{
Token = token,
Expires = new ApiDateTime(TenantManager, TimeZoneConverter, expires)
2019-05-28 09:40:37 +00:00
};
2021-04-26 11:56:38 +00:00
if (sms)
{
result.Sms = true;
result.PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone);
}
else
{
result.Tfa = true;
}
return result;
2019-05-28 09:40:37 +00:00
}
catch
{
2021-04-26 11:56:38 +00:00
MessageService.Send(user.DisplayUserName(false, DisplayUserSettingsHelper), sms
? MessageAction.LoginFailViaApiSms
: MessageAction.LoginFailViaApiTfa,
MessageTarget.Create(user.ID));
throw new AuthenticationException("User authentication failed");
}
finally
{
SecurityContext.Logout();
2019-05-28 09:40:37 +00:00
}
}
2021-06-16 17:46:24 +00:00
private UserInfo GetUser(AuthModel memberModel, out bool viaEmail)
2019-05-28 09:40:37 +00:00
{
2021-04-26 11:56:38 +00:00
viaEmail = true;
2021-02-19 16:16:08 +00:00
var action = MessageAction.LoginFailViaApi;
2021-04-26 11:56:38 +00:00
UserInfo user;
2021-02-19 16:16:08 +00:00
try
{
if ((string.IsNullOrEmpty(memberModel.Provider) && string.IsNullOrEmpty(memberModel.SerializedProfile)) || memberModel.Provider == "email")
{
memberModel.UserName.ThrowIfNull(new ArgumentException(@"userName empty", "userName"));
2021-02-26 19:32:03 +00:00
if (!string.IsNullOrEmpty(memberModel.Password))
{
memberModel.Password.ThrowIfNull(new ArgumentException(@"password empty", "password"));
}
else
{
memberModel.PasswordHash.ThrowIfNull(new ArgumentException(@"PasswordHash empty", "PasswordHash"));
}
2021-02-19 16:16:08 +00:00
int counter;
int.TryParse(Cache.Get<string>("loginsec/" + memberModel.UserName), out counter);
if (++counter > SetupInfo.LoginThreshold && !SetupInfo.IsSecretEmail(memberModel.UserName))
{
throw new BruteForceCredentialException();
}
Cache.Insert("loginsec/" + memberModel.UserName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
memberModel.PasswordHash = (memberModel.PasswordHash ?? "").Trim();
if (string.IsNullOrEmpty(memberModel.PasswordHash))
{
memberModel.Password = (memberModel.Password ?? "").Trim();
if (!string.IsNullOrEmpty(memberModel.Password))
{
memberModel.PasswordHash = PasswordHasher.GetClientPassword(memberModel.Password);
}
}
user = UserManager.GetUsersByPasswordHash(
2021-06-16 17:46:24 +00:00
TenantManager.GetCurrentTenant().TenantId,
2021-02-19 16:16:08 +00:00
memberModel.UserName,
memberModel.PasswordHash);
if (user == null || !UserManager.UserExists(user))
{
throw new Exception("user not found");
}
}
else
{
2021-04-26 11:56:38 +00:00
viaEmail = false;
2021-02-19 16:16:08 +00:00
action = MessageAction.LoginFailViaApiSocialAccount;
LoginProfile thirdPartyProfile;
if (!string.IsNullOrEmpty(memberModel.SerializedProfile))
{
thirdPartyProfile = new LoginProfile(Signature, InstanceCrypto, memberModel.SerializedProfile);
}
else
{
thirdPartyProfile = ProviderManager.GetLoginProfile(memberModel.Provider, memberModel.AccessToken);
}
2021-10-28 17:14:20 +00:00
2021-02-19 16:16:08 +00:00
memberModel.UserName = thirdPartyProfile.EMail;
user = GetUserByThirdParty(thirdPartyProfile);
}
}
catch (BruteForceCredentialException)
{
MessageService.Send(!string.IsNullOrEmpty(memberModel.UserName) ? memberModel.UserName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce);
throw new AuthenticationException("Login Fail. Too many attempts");
}
catch
{
MessageService.Send(!string.IsNullOrEmpty(memberModel.UserName) ? memberModel.UserName : AuditResource.EmailNotSpecified, action);
throw new AuthenticationException("User authentication failed");
}
return user;
}
private UserInfo GetUserByThirdParty(LoginProfile loginProfile)
{
try
{
if (!string.IsNullOrEmpty(loginProfile.AuthorizationError))
{
// ignore cancellation
if (loginProfile.AuthorizationError != "Canceled at provider")
{
throw new Exception(loginProfile.AuthorizationError);
}
return Constants.LostUser;
}
var userInfo = Constants.LostUser;
Guid userId;
if (TryGetUserByHash(loginProfile.HashId, out userId))
{
userInfo = UserManager.GetUsers(userId);
}
2020-09-30 14:16:48 +00:00
2021-02-19 16:16:08 +00:00
var isNew = false;
if (CoreBaseSettings.Personal)
{
if (UserManager.UserExists(userInfo.ID) && SetupInfo.IsSecretEmail(userInfo.Email))
{
try
{
2021-08-18 14:04:16 +00:00
SecurityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem);
2021-02-19 16:16:08 +00:00
UserManager.DeleteUser(userInfo.ID);
userInfo = Constants.LostUser;
}
finally
{
SecurityContext.Logout();
}
}
if (!UserManager.UserExists(userInfo.ID))
{
userInfo = JoinByThirdPartyAccount(loginProfile);
isNew = true;
}
}
if (isNew)
{
//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;
}
return userInfo;
}
catch (Exception)
{
CookiesManager.ClearCookies(CookiesType.AuthKey);
CookiesManager.ClearCookies(CookiesType.SocketIO);
SecurityContext.Logout();
throw;
}
}
private UserInfo JoinByThirdPartyAccount(LoginProfile loginProfile)
{
if (string.IsNullOrEmpty(loginProfile.EMail))
2020-09-30 14:16:48 +00:00
{
2021-02-19 16:16:08 +00:00
throw new Exception(Resource.ErrorNotCorrectEmail);
}
2020-09-30 14:16:48 +00:00
2021-02-19 16:16:08 +00:00
var userInfo = UserManager.GetUserByEmail(loginProfile.EMail);
if (!UserManager.UserExists(userInfo.ID))
{
var newUserInfo = ProfileToUserInfo(loginProfile);
try
{
2021-08-18 14:04:16 +00:00
SecurityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem);
2021-02-19 16:16:08 +00:00
userInfo = UserManagerWrapper.AddUser(newUserInfo, UserManagerWrapper.GeneratePassword());
}
finally
2020-09-30 14:16:48 +00:00
{
2021-02-19 16:16:08 +00:00
SecurityContext.Logout();
2020-09-30 14:16:48 +00:00
}
}
2021-02-19 16:16:08 +00:00
var linker = AccountLinker.Get("webstudio");
linker.AddLink(userInfo.ID.ToString(), loginProfile);
return userInfo;
}
private UserInfo ProfileToUserInfo(LoginProfile loginProfile)
{
if (string.IsNullOrEmpty(loginProfile.EMail)) throw new Exception(Resource.ErrorNotCorrectEmail);
var firstName = loginProfile.FirstName;
if (string.IsNullOrEmpty(firstName)) firstName = loginProfile.DisplayName;
2019-05-28 09:40:37 +00:00
2021-02-19 16:16:08 +00:00
var userInfo = new UserInfo
2019-05-28 09:40:37 +00:00
{
2021-02-19 16:16:08 +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";
2019-05-28 09:40:37 +00:00
}
2021-02-19 16:16:08 +00:00
return userInfo;
}
private bool TryGetUserByHash(string hashId, out Guid userId)
{
userId = Guid.Empty;
if (string.IsNullOrEmpty(hashId)) return false;
var linkedProfiles = AccountLinker.Get("webstudio").GetLinkedObjectsByHashId(hashId);
var tmp = Guid.Empty;
if (linkedProfiles.Any(profileId => Guid.TryParse(profileId, out tmp) && UserManager.UserExists(tmp)))
userId = tmp;
return true;
2019-05-28 09:40:37 +00:00
}
}
public class AuthenticationTokenData
{
public string Token { get; set; }
public DateTime Expires { get; set; }
public bool Sms { get; set; }
public string PhoneNoise { get; set; }
public bool Tfa { get; set; }
public string TfaKey { get; set; }
2021-04-27 10:40:25 +00:00
public string ConfirmUrl { get; set; }
2019-05-28 09:40:37 +00:00
public static AuthenticationTokenData GetSample()
{
return new AuthenticationTokenData
{
Expires = DateTime.UtcNow,
Token = "abcde12345",
Sms = false,
PhoneNoise = null,
Tfa = false,
TfaKey = null
};
}
}
}