private static UserInfo GetUser(string userName, string password, string provider, string accessToken, out bool viaEmail)
        {
            viaEmail = true;
            var      action = MessageAction.LoginFailViaApi;
            UserInfo user;

            try
            {
                if (string.IsNullOrEmpty(provider) || provider == "email")
                {
                    userName.ThrowIfNull(new ArgumentException(@"userName empty", "userName"));
                    password.ThrowIfNull(new ArgumentException(@"password empty", "password"));


                    var localization    = new LdapLocalization(Resource.ResourceManager);
                    var ldapUserManager = new LdapUserManager(localization);

                    if (!ldapUserManager.TryGetAndSyncLdapUserInfo(userName, password, out user))
                    {
                        user = CoreContext.UserManager.GetUsers(
                            CoreContext.TenantManager.GetCurrentTenant().TenantId,
                            userName,
                            Hasher.Base64Hash(password, HashAlg.SHA256));
                    }

                    if (user == null || !CoreContext.UserManager.UserExists(user.ID))
                    {
                        throw new Exception("user not found");
                    }
                }
                else
                {
                    viaEmail = false;

                    action = MessageAction.LoginFailViaApiSocialAccount;
                    var thirdPartyProfile = ProviderManager.GetLoginProfile(provider, accessToken);
                    userName = thirdPartyProfile.EMail;

                    user = LoginWithThirdParty.GetUserByThirdParty(thirdPartyProfile);
                }
            }
            catch
            {
                MessageService.Send(Request, string.IsNullOrEmpty(userName) ? userName : AuditResource.EmailNotSpecified, action);
                throw new AuthenticationException("User authentication failed");
            }

            var tenant   = CoreContext.TenantManager.GetCurrentTenant();
            var settings = IPRestrictionsSettings.Load();

            if (settings.Enable && user.ID != tenant.OwnerId && !IPSecurity.IPSecurity.Verify(tenant))
            {
                throw new IPSecurityException();
            }

            return(user);
        }
예제 #2
0
        public static UserInfo SendUserPassword(string email)
        {
            email = (email ?? "").Trim();
            if (!email.TestEmailRegex())
            {
                throw new ArgumentNullException("email", Resource.ErrorNotCorrectEmail);
            }

            var tenant   = CoreContext.TenantManager.GetCurrentTenant();
            var settings = IPRestrictionsSettings.Load();

            if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant))
            {
                throw new Exception(Resource.ErrorAccessRestricted);
            }

            var userInfo = CoreContext.UserManager.GetUserByEmail(email);

            if (!CoreContext.UserManager.UserExists(userInfo.ID) || string.IsNullOrEmpty(userInfo.Email))
            {
                throw new Exception(String.Format(Resource.ErrorUserNotFoundByEmail, email));
            }
            if (userInfo.Status == EmployeeStatus.Terminated)
            {
                throw new Exception(Resource.ErrorDisabledProfile);
            }
            if (userInfo.IsLDAP())
            {
                throw new Exception(Resource.CouldNotRecoverPasswordForLdapUser);
            }
            if (userInfo.IsSSO())
            {
                throw new Exception(Resource.CouldNotRecoverPasswordForSsoUser);
            }

            StudioNotifyService.Instance.UserPasswordChange(userInfo);

            var displayUserName = userInfo.DisplayUserName(false);

            MessageService.Send(HttpContext.Current.Request, MessageAction.UserSentPasswordChangeInstructions, displayUserName);

            return(userInfo);
        }
        public object SendJoinInviteMail(string email)
        {
            try
            {
                if (!EnabledJoin)
                {
                    throw new MethodAccessException("Method not available");
                }

                if (!email.TestEmailRegex())
                {
                    throw new Exception(Resource.ErrorNotCorrectEmail);
                }

                var user = CoreContext.UserManager.GetUserByEmail(email);
                if (!user.ID.Equals(Constants.LostUser.ID))
                {
                    throw new Exception(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
                }

                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = IPRestrictionsSettings.Load();

                if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant))
                {
                    throw new Exception(Resource.ErrorAccessRestricted);
                }

                var trustedDomainSettings = StudioTrustedDomainSettings.Load();
                var emplType          = trustedDomainSettings.InviteUsersAsVisitors ? EmployeeType.Visitor : EmployeeType.User;
                var enableInviteUsers = TenantStatisticsProvider.GetUsersCount() <
                                        TenantExtra.GetTenantQuota().ActiveUsers;

                if (!enableInviteUsers)
                {
                    emplType = EmployeeType.Visitor;
                }

                switch (tenant.TrustedDomainsType)
                {
                case TenantTrustedDomainsType.Custom:
                {
                    var address = new MailAddress(email);
                    if (
                        tenant.TrustedDomains.Any(
                            d => address.Address.EndsWith("@" + d, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        StudioNotifyService.Instance.SendJoinMsg(email, emplType);
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System,
                                            MessageAction.SentInviteInstructions, email);
                        return(new { Status = 1, Message = Resource.FinishInviteJoinEmailMessage });
                    }

                    throw new Exception(Resource.ErrorEmailDomainNotAllowed);
                }

                case TenantTrustedDomainsType.All:
                {
                    StudioNotifyService.Instance.SendJoinMsg(email, emplType);
                    MessageService.Send(HttpContext.Current.Request, MessageInitiator.System,
                                        MessageAction.SentInviteInstructions, email);
                    return(new { Status = 1, Message = Resource.FinishInviteJoinEmailMessage });
                }

                default:
                    throw new Exception(Resource.ErrorNotCorrectEmail);
                }
            }
            catch (FormatException)
            {
                return(new { Status = 0, Message = Resource.ErrorNotCorrectEmail });
            }
            catch (Exception e)
            {
                return(new { Status = 0, Message = e.Message.HtmlEncode() });
            }
        }
예제 #4
0
        private bool AuthProcess(LoginProfile thirdPartyProfile, bool withAccountLink)
        {
            var authMethod   = AuthMethod.Login;
            var tfaLoginUrl  = string.Empty;
            var loginCounter = 0;

            ShowRecaptcha = false;
            try
            {
                if (thirdPartyProfile != null)
                {
                    if (string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError))
                    {
                        HashId = thirdPartyProfile.HashId;
                        Login  = thirdPartyProfile.EMail;
                    }
                    else
                    {
                        // ignore cancellation
                        if (thirdPartyProfile.AuthorizationError != "Canceled at provider")
                        {
                            ErrorMessage = thirdPartyProfile.AuthorizationError;
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) && Request["__EVENTTARGET"] == "signInLogin" && withAccountLink)
                    {
                        HashId = ASC.Common.Utils.Signature.Read <string>(Request["__EVENTARGUMENT"]);
                    }
                }

                if (!string.IsNullOrEmpty(Request["login"]))
                {
                    Login = Request["login"].Trim();
                }
                else if (string.IsNullOrEmpty(HashId))
                {
                    IsLoginInvalid = true;
                    throw new InvalidCredentialException("login");
                }

                if (!string.IsNullOrEmpty(Request["passwordHash"]))
                {
                    PasswordHash = Request["passwordHash"];
                }
                else if (string.IsNullOrEmpty(HashId))
                {
                    IsPasswordInvalid = true;
                    throw new InvalidCredentialException("password");
                }

                if (string.IsNullOrEmpty(HashId) && !SetupInfo.IsSecretEmail(Login))
                {
                    int.TryParse(cache.Get <String>("loginsec/" + Login), out loginCounter);

                    loginCounter++;

                    if (!RecaptchaEnable)
                    {
                        if (loginCounter > SetupInfo.LoginThreshold)
                        {
                            throw new BruteForceCredentialException();
                        }
                    }
                    else
                    {
                        if (loginCounter > SetupInfo.LoginThreshold - 1)
                        {
                            ShowRecaptcha = true;
                        }
                        if (loginCounter > SetupInfo.LoginThreshold)
                        {
                            var ip = Request.Headers["X-Forwarded-For"] ?? Request.UserHostAddress;

                            var recaptchaResponse = Request["g-recaptcha-response"];
                            if (String.IsNullOrEmpty(recaptchaResponse) ||
                                !ValidateRecaptcha(recaptchaResponse, ip))
                            {
                                throw new RecaptchaException();
                            }
                        }
                    }

                    cache.Insert("loginsec/" + Login, loginCounter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }

                var userInfo = GetUser(out authMethod);
                if (!CoreContext.UserManager.UserExists(userInfo.ID) || userInfo.Status != EmployeeStatus.Active)
                {
                    IsLoginInvalid    = true;
                    IsPasswordInvalid = true;
                    throw new InvalidCredentialException();
                }

                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = IPRestrictionsSettings.Load();
                if (settings.Enable && userInfo.ID != tenant.OwnerId && !IPSecurity.IPSecurity.Verify(tenant))
                {
                    throw new IPSecurityException();
                }

                if (StudioSmsNotificationSettings.IsVisibleAndAvailableSettings &&
                    StudioSmsNotificationSettings.Enable)
                {
                    tfaLoginUrl = Studio.Confirm.SmsConfirmUrl(userInfo);
                }
                else if (TfaAppAuthSettings.IsVisibleSettings &&
                         TfaAppAuthSettings.Enable)
                {
                    tfaLoginUrl = Studio.Confirm.TfaConfirmUrl(userInfo);
                }
                else
                {
                    var session = EnableSession && string.IsNullOrEmpty(Request["remember"]);

                    var action = authMethod == AuthMethod.ThirdParty ? MessageAction.LoginSuccessViaSocialAccount : MessageAction.LoginSuccess;
                    CookiesManager.AuthenticateMeAndSetCookies(userInfo.Tenant, userInfo.ID, action, session);
                }
            }
            catch (InvalidCredentialException ex)
            {
                Auth.MessageKey messageKey;
                MessageAction   messageAction;

                if (ex is BruteForceCredentialException)
                {
                    messageKey    = Auth.MessageKey.LoginWithBruteForce;
                    messageAction = MessageAction.LoginFailBruteForce;
                }
                else if (ex is RecaptchaException)
                {
                    messageKey    = Auth.MessageKey.RecaptchaInvalid;
                    messageAction = MessageAction.LoginFailRecaptcha;
                }
                else if (authMethod == AuthMethod.ThirdParty)
                {
                    messageKey    = Auth.MessageKey.LoginWithAccountNotFound;
                    messageAction = MessageAction.LoginFailSocialAccountNotFound;
                }
                else
                {
                    messageKey    = Auth.MessageKey.InvalidUsernameOrPassword;
                    messageAction = MessageAction.LoginFailInvalidCombination;
                }

                var loginName = !string.IsNullOrWhiteSpace(Login)
                                    ? Login
                                    : authMethod == AuthMethod.ThirdParty && !string.IsNullOrWhiteSpace(HashId)
                                          ? HashId
                                          : AuditResource.EmailNotSpecified;

                MessageService.Send(HttpContext.Current.Request, loginName, messageAction);

                Auth.ProcessLogout();

                if (authMethod == AuthMethod.ThirdParty && thirdPartyProfile != null)
                {
                    Response.Redirect("~/Auth.aspx?am=" + (int)messageKey + (Request.DesktopApp() ? "&desktop=true" : ""), true);
                }
                else
                {
                    ErrorMessage = Auth.GetAuthMessage(messageKey);
                }

                return(false);
            }
            catch (SecurityException)
            {
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailDisabledProfile);
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorDisabledProfile;
                return(false);
            }
            catch (IPSecurityException)
            {
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailIpSecurity);
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorIpSecurity;
                return(false);
            }
            catch (Exception ex)
            {
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFail);
                Auth.ProcessLogout();
                ErrorMessage = ex.Message;
                return(false);
            }

            if (loginCounter > 0)
            {
                cache.Insert("loginsec/" + Login, (--loginCounter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
            }

            if (!string.IsNullOrEmpty(tfaLoginUrl))
            {
                if (Request.DesktopApp())
                {
                    tfaLoginUrl += "&desktop=true";
                }

                Response.Redirect(tfaLoginUrl, true);
            }

            return(true);
        }
예제 #5
0
        private bool AuthProcess(LoginProfile thirdPartyProfile, bool withAccountLink)
        {
            var authMethod   = AuthMethod.Login;
            var tfaLoginUrl  = string.Empty;
            var loginCounter = 0;

            try
            {
                if (thirdPartyProfile != null)
                {
                    if (string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError))
                    {
                        HashId = thirdPartyProfile.HashId;
                        Login  = thirdPartyProfile.EMail;
                    }
                    else
                    {
                        // ignore cancellation
                        if (thirdPartyProfile.AuthorizationError != "Canceled at provider")
                        {
                            ErrorMessage = thirdPartyProfile.AuthorizationError;
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) && Request["__EVENTTARGET"] == "signInLogin" && withAccountLink)
                    {
                        HashId = ASC.Common.Utils.Signature.Read <string>(Request["__EVENTARGUMENT"]);
                    }
                }

                if (!string.IsNullOrEmpty(Request["login"]))
                {
                    Login = Request["login"].Trim();
                }
                else if (string.IsNullOrEmpty(HashId))
                {
                    IsLoginInvalid = true;
                    throw new InvalidCredentialException("login");
                }

                if (!string.IsNullOrEmpty(Request["pwd"]))
                {
                    Password = Request["pwd"];
                }
                else if (string.IsNullOrEmpty(HashId))
                {
                    IsPasswordInvalid = true;
                    throw new InvalidCredentialException("password");
                }

                if (string.IsNullOrEmpty(HashId))
                {
                    int.TryParse(cache.Get <String>("loginsec/" + Login), out loginCounter);
                    if (++loginCounter > 5)
                    {
                        throw new BruteForceCredentialException();
                    }
                    cache.Insert("loginsec/" + Login, loginCounter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }

                var userInfo = GetUser(out authMethod);
                if (!CoreContext.UserManager.UserExists(userInfo.ID) || userInfo.Status != EmployeeStatus.Active)
                {
                    IsLoginInvalid    = true;
                    IsPasswordInvalid = true;
                    throw new InvalidCredentialException();
                }

                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = IPRestrictionsSettings.Load();
                if (settings.Enable && userInfo.ID != tenant.OwnerId && !IPSecurity.IPSecurity.Verify(tenant))
                {
                    throw new IPSecurityException();
                }

                if (StudioSmsNotificationSettings.IsVisibleSettings &&
                    StudioSmsNotificationSettings.Enable)
                {
                    tfaLoginUrl = Studio.Confirm.SmsConfirmUrl(userInfo);
                }
                else if (TfaAppAuthSettings.IsVisibleSettings &&
                         TfaAppAuthSettings.Enable)
                {
                    tfaLoginUrl = Studio.Confirm.TfaConfirmUrl(userInfo);
                }
                else
                {
                    var session = EnableSession && string.IsNullOrEmpty(Request["remember"]);

                    var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                    CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey, session);
                    MessageService.Send(HttpContext.Current.Request,
                                        authMethod == AuthMethod.ThirdParty
                                            ? MessageAction.LoginSuccessViaSocialAccount
                                            : MessageAction.LoginSuccess
                                        );
                }
            }
            catch (InvalidCredentialException ex)
            {
                Auth.ProcessLogout();
                var isBruteForce = (ex is BruteForceCredentialException);

                ErrorMessage = isBruteForce
                                   ? Resource.LoginWithBruteForce
                                   : authMethod == AuthMethod.ThirdParty ? Resource.LoginWithAccountNotFound : Resource.InvalidUsernameOrPassword;

                var loginName = !string.IsNullOrWhiteSpace(Login)
                                    ? Login
                                    : authMethod == AuthMethod.ThirdParty && !string.IsNullOrWhiteSpace(HashId)
                                          ? HashId
                                          : AuditResource.EmailNotSpecified;

                var messageAction = isBruteForce
                                        ? MessageAction.LoginFailBruteForce
                                        : authMethod == AuthMethod.ThirdParty
                                              ? MessageAction.LoginFailSocialAccountNotFound
                                              : MessageAction.LoginFailInvalidCombination;

                MessageService.Send(HttpContext.Current.Request, loginName, messageAction);

                if (authMethod == AuthMethod.ThirdParty && thirdPartyProfile != null)
                {
                    Response.Redirect("~/auth.aspx?m=" + HttpUtility.UrlEncode(_errorMessage), true);
                }
                return(false);
            }
            catch (SecurityException)
            {
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorDisabledProfile;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailDisabledProfile);
                return(false);
            }
            catch (IPSecurityException)
            {
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorIpSecurity;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailIpSecurity);
                return(false);
            }
            catch (Exception ex)
            {
                Auth.ProcessLogout();
                ErrorMessage = ex.Message;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFail);
                return(false);
            }

            if (loginCounter > 0)
            {
                cache.Insert("loginsec/" + Login, (--loginCounter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
            }

            if (!string.IsNullOrEmpty(tfaLoginUrl))
            {
                Response.Redirect(tfaLoginUrl, true);
            }
            return(true);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.RegisterBodyScripts("~/js/third-party/xregexp.js", "~/UserControls/Management/ConfirmInviteActivation/js/confirm_invite_activation.js")
            .RegisterStyle("~/UserControls/Management/ConfirmInviteActivation/css/confirm_invite_activation.less");

            var uid = Guid.Empty;

            try
            {
                uid = new Guid(Request["uid"]);
            }
            catch
            {
            }

            var email = GetEmailAddress();

            if (_type != ConfirmType.Activation && AccountLinkControl.IsNotEmpty && !CoreContext.Configuration.Personal)
            {
                var thrd = (AccountLinkControl)LoadControl(AccountLinkControl.Location);
                thrd.InviteView     = true;
                thrd.ClientCallback = "loginJoinCallback";
                thrdParty.Visible   = true;
                thrdParty.Controls.Add(thrd);
            }

            Page.Title = HeaderStringHelper.GetPageTitle(Resource.Authorization);

            UserInfo user;

            try
            {
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);

                user = CoreContext.UserManager.GetUserByEmail(email);
                var usr = CoreContext.UserManager.GetUsers(uid);
                if (usr.ID.Equals(Constants.LostUser.ID) || usr.ID.Equals(ASC.Core.Configuration.Constants.Guest.ID))
                {
                    usr = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId);
                }

                var photoData = UserPhotoManager.GetUserPhotoData(usr.ID, UserPhotoManager.MediumFotoSize);

                _userAvatar = photoData == null?usr.GetMediumPhotoURL() : "data:image/png;base64," + Convert.ToBase64String(photoData);

                _userName = usr.DisplayUserName(true);
                _userPost = (usr.Title ?? "").HtmlEncode();
            }
            finally
            {
                SecurityContext.Logout();
            }

            if (_type == ConfirmType.LinkInvite || _type == ConfirmType.EmpInvite)
            {
                if (TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers&& _employeeType == EmployeeType.User)
                {
                    ShowError(UserControlsCommonResource.TariffUserLimitReason);
                    return;
                }

                if (!user.ID.Equals(Constants.LostUser.ID))
                {
                    ShowError(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
                    return;
                }
            }

            else if (_type == ConfirmType.Activation)
            {
                if (user.IsActive)
                {
                    Response.Redirect(CommonLinkUtility.GetDefault());
                    return;
                }

                if (user.ID.Equals(Constants.LostUser.ID) || user.Status == EmployeeStatus.Terminated)
                {
                    ShowError(string.Format(Resource.ErrorUserNotFoundByEmail, email));
                    return;
                }
            }

            var tenant = CoreContext.TenantManager.GetCurrentTenant();

            if (tenant != null)
            {
                var settings = IPRestrictionsSettings.Load();
                if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant))
                {
                    ShowError(Resource.ErrorAccessRestricted);
                    return;
                }
            }

            if (!IsPostBack)
            {
                return;
            }

            var firstName = GetFirstName();
            var lastName  = GetLastName();

            var          passwordHash       = (Request["passwordHash"] ?? "").Trim();
            var          analytics          = (Request["analytics"] ?? "").Trim() == "True";
            var          mustChangePassword = false;
            LoginProfile thirdPartyProfile;

            //thirdPartyLogin confirmInvite
            if (Request["__EVENTTARGET"] == "thirdPartyLogin")
            {
                var valueRequest = Request["__EVENTARGUMENT"];
                thirdPartyProfile = new LoginProfile(valueRequest);

                if (!string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError))
                {
                    // ignore cancellation
                    if (thirdPartyProfile.AuthorizationError != "Canceled at provider")
                    {
                        ShowError(HttpUtility.HtmlEncode(thirdPartyProfile.AuthorizationError));
                    }
                    return;
                }

                if (string.IsNullOrEmpty(thirdPartyProfile.EMail))
                {
                    ShowError(HttpUtility.HtmlEncode(Resource.ErrorNotCorrectEmail));
                    return;
                }
            }

            if (Request["__EVENTTARGET"] == "confirmInvite")
            {
                if (String.IsNullOrEmpty(email))
                {
                    _errorMessage = Resource.ErrorEmptyUserEmail;
                    return;
                }

                if (!email.TestEmailRegex())
                {
                    _errorMessage = Resource.ErrorNotCorrectEmail;
                    return;
                }

                if (String.IsNullOrEmpty(firstName))
                {
                    _errorMessage = Resource.ErrorEmptyUserFirstName;
                    return;
                }

                if (String.IsNullOrEmpty(lastName))
                {
                    _errorMessage = Resource.ErrorEmptyUserLastName;
                    return;
                }

                if (String.IsNullOrEmpty(passwordHash))
                {
                    _errorMessage = Resource.ErrorPasswordEmpty;
                    return;
                }
            }
            var userID = Guid.Empty;

            try
            {
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                if (_type == ConfirmType.EmpInvite || _type == ConfirmType.LinkInvite)
                {
                    if (TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers&& _employeeType == EmployeeType.User)
                    {
                        ShowError(UserControlsCommonResource.TariffUserLimitReason);
                        return;
                    }

                    UserInfo newUser;
                    if (Request["__EVENTTARGET"] == "confirmInvite")
                    {
                        var fromInviteLink = _type == ConfirmType.LinkInvite;
                        newUser = CreateNewUser(firstName, lastName, email, passwordHash, _employeeType, fromInviteLink);

                        var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite;
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, MessageTarget.Create(newUser.ID), newUser.DisplayUserName(false));

                        userID = newUser.ID;

                        var settings = TenantAnalyticsSettings.LoadForCurrentUser();
                        settings.Analytics = analytics;

                        settings.SaveForCurrentUser();
                    }

                    if (Request["__EVENTTARGET"] == "thirdPartyLogin")
                    {
                        if (String.IsNullOrEmpty(passwordHash))
                        {
                            passwordHash       = UserManagerWrapper.GeneratePassword();
                            mustChangePassword = true;
                        }

                        var valueRequest = Request["__EVENTARGUMENT"];
                        thirdPartyProfile = new LoginProfile(valueRequest);
                        newUser           = CreateNewUser(GetFirstName(thirdPartyProfile), GetLastName(thirdPartyProfile), GetEmailAddress(thirdPartyProfile), passwordHash, _employeeType, false);

                        var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite;
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, MessageTarget.Create(newUser.ID), newUser.DisplayUserName(false));

                        userID = newUser.ID;
                        if (!String.IsNullOrEmpty(thirdPartyProfile.Avatar))
                        {
                            SaveContactImage(userID, thirdPartyProfile.Avatar);
                        }

                        var linker = new AccountLinker("webstudio");
                        linker.AddLink(userID.ToString(), thirdPartyProfile);
                    }
                }
                else if (_type == ConfirmType.Activation)
                {
                    if (!UserFormatter.IsValidUserName(firstName, lastName))
                    {
                        throw new Exception(Resource.ErrorIncorrectUserName);
                    }

                    SecurityContext.SetUserPasswordHash(user.ID, passwordHash);

                    user.ActivationStatus = EmployeeActivationStatus.Activated;
                    user.FirstName        = firstName;
                    user.LastName         = lastName;
                    CoreContext.UserManager.SaveUserInfo(user);

                    userID = user.ID;

                    //notify
                    if (user.IsVisitor())
                    {
                        StudioNotifyService.Instance.GuestInfoAddedAfterInvite(user);
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.GuestActivated, MessageTarget.Create(user.ID), user.DisplayUserName(false));
                    }
                    else
                    {
                        StudioNotifyService.Instance.UserInfoAddedAfterInvite(user);
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.UserActivated, MessageTarget.Create(user.ID), user.DisplayUserName(false));
                    }
                }
            }
            catch (SecurityContext.PasswordException)
            {
                _errorMessage = HttpUtility.HtmlEncode(Resource.ErrorPasswordRechange);
                return;
            }
            catch (Exception exception)
            {
                _errorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }
            finally
            {
                SecurityContext.Logout();
            }

            user = CoreContext.UserManager.GetUsers(userID);
            try
            {
                var cookiesKey = SecurityContext.AuthenticateMe(user.Email, passwordHash);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess);
                StudioNotifyService.Instance.UserHasJoin();

                if (mustChangePassword)
                {
                    StudioNotifyService.Instance.UserPasswordChange(user);
                }
            }
            catch (Exception exception)
            {
                (Page as Confirm).ErrorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }

            UserHelpTourHelper.IsNewUser = true;
            if (CoreContext.Configuration.Personal)
            {
                PersonalSettings.IsNewUser = true;
            }
            Response.Redirect(CommonLinkUtility.GetDefault());
        }
        private static UserInfo GetUser(string userName, string password, string provider, string accessToken, out bool viaEmail)
        {
            viaEmail = true;
            var      action = MessageAction.LoginFailViaApi;
            UserInfo user;

            try
            {
                if (string.IsNullOrEmpty(provider) || provider == "email")
                {
                    userName.ThrowIfNull(new ArgumentException(@"userName empty", "userName"));
                    password.ThrowIfNull(new ArgumentException(@"password empty", "password"));

                    int counter;
                    int.TryParse(Cache.Get <String>("loginsec/" + userName), out counter);
                    if (++counter > 5 && !SetupInfo.IsSecretEmail(userName))
                    {
                        throw new Authorize.BruteForceCredentialException();
                    }
                    Cache.Insert("loginsec/" + userName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

                    var localization    = new LdapLocalization(Resource.ResourceManager);
                    var ldapUserManager = new LdapUserManager(localization);

                    if (!ldapUserManager.TryGetAndSyncLdapUserInfo(userName, password, out user))
                    {
                        user = CoreContext.UserManager.GetUsers(
                            CoreContext.TenantManager.GetCurrentTenant().TenantId,
                            userName,
                            Hasher.Base64Hash(password, HashAlg.SHA256));
                    }

                    if (user == null || !CoreContext.UserManager.UserExists(user.ID))
                    {
                        throw new Exception("user not found");
                    }

                    Cache.Insert("loginsec/" + userName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }
                else
                {
                    viaEmail = false;

                    action = MessageAction.LoginFailViaApiSocialAccount;
                    var thirdPartyProfile = ProviderManager.GetLoginProfile(provider, accessToken);
                    userName = thirdPartyProfile.EMail;

                    user = LoginWithThirdParty.GetUserByThirdParty(thirdPartyProfile);
                }
            }
            catch (Authorize.BruteForceCredentialException)
            {
                MessageService.Send(Request, !string.IsNullOrEmpty(userName) ? userName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce);
                throw new AuthenticationException("Login Fail. Too many attempts");
            }
            catch
            {
                MessageService.Send(Request, !string.IsNullOrEmpty(userName) ? userName : AuditResource.EmailNotSpecified, action);
                throw new AuthenticationException("User authentication failed");
            }

            var tenant   = CoreContext.TenantManager.GetCurrentTenant();
            var settings = IPRestrictionsSettings.Load();

            if (settings.Enable && user.ID != tenant.OwnerId && !IPSecurity.IPSecurity.Verify(tenant))
            {
                throw new IPSecurityException();
            }

            return(user);
        }
        public AjaxResponse SendJoinInviteMail(string email)
        {
            email = (email ?? "").Trim();
            var resp = new AjaxResponse {
                rs1 = "0"
            };

            try
            {
                if (String.IsNullOrEmpty(email))
                {
                    resp.rs2 = Resource.ErrorNotCorrectEmail;
                    return(resp);
                }

                if (!email.TestEmailRegex())
                {
                    resp.rs2 = Resource.ErrorNotCorrectEmail;
                }

                var user = CoreContext.UserManager.GetUserByEmail(email);
                if (!user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID))
                {
                    resp.rs1 = "0";
                    resp.rs2 = CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists").HtmlEncode();
                    return(resp);
                }

                var tenant = CoreContext.TenantManager.GetCurrentTenant();
                if (tenant != null)
                {
                    var settings = IPRestrictionsSettings.Load();
                    if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant))
                    {
                        resp.rs2 = Resource.ErrorAccessRestricted;
                        return(resp);
                    }
                }


                var trustedDomainSettings = StudioTrustedDomainSettings.Load();
                var emplType          = trustedDomainSettings.InviteUsersAsVisitors ? EmployeeType.Visitor : EmployeeType.User;
                var enableInviteUsers = TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers;

                if (!enableInviteUsers)
                {
                    emplType = EmployeeType.Visitor;
                }

                switch (tenant.TrustedDomainsType)
                {
                case TenantTrustedDomainsType.Custom:
                {
                    var address = new MailAddress(email);
                    if (tenant.TrustedDomains.Any(d => address.Address.EndsWith("@" + d, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        StudioNotifyService.Instance.InviteUsers(email, "", true, emplType);
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.SentInviteInstructions, email);
                        resp.rs1 = "1";
                        resp.rs2 = Resource.FinishInviteJoinEmailMessage;
                        return(resp);
                    }
                    else
                    {
                        resp.rs2 = Resource.ErrorEmailDomainNotAllowed;
                    }
                }
                break;

                case TenantTrustedDomainsType.All:
                    StudioNotifyService.Instance.InviteUsers(email, "", true, emplType);
                    MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.SentInviteInstructions, email);
                    resp.rs1 = "1";
                    resp.rs2 = Resource.FinishInviteJoinEmailMessage;
                    return(resp);

                default:
                    resp.rs2 = Resource.ErrorNotCorrectEmail;
                    break;
                }
            }
            catch (FormatException)
            {
                resp.rs2 = Resource.ErrorNotCorrectEmail;
            }
            catch (Exception e)
            {
                resp.rs2 = HttpUtility.HtmlEncode(e.Message);
            }

            return(resp);
        }