[Create("sendcongratulations", false)] //NOTE: this method doesn't requires auth!!!
        public void SendCongratulations(Guid userid, string key)
        {
            var authInterval   = TimeSpan.FromHours(1);
            var checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(userid.ToString() + ConfirmType.Auth, key, authInterval);

            switch (checkKeyResult)
            {
            case EmailValidationKeyProvider.ValidationResult.Ok:
                var currentUser = CoreContext.UserManager.GetUsers(userid);
                StudioNotifyService.Instance.SendCongratulations(currentUser);
                FirstTimeTenantSettings.SendInstallInfo(currentUser);

                if (!SetupInfo.IsSecretEmail(currentUser.Email))
                {
                    if (SetupInfo.TfaRegistration == "sms")
                    {
                        StudioSmsNotificationSettings.Enable = true;
                    }
                    else if (SetupInfo.TfaRegistration == "code")
                    {
                        TfaAppAuthSettings.Enable = true;
                    }
                }
                break;

            default:
                throw new SecurityException("Access Denied.");
            }
        }
Ejemplo n.º 2
0
        private static void DemandPermissionsTransfer()
        {
            SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

            var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

            if (!SetupInfo.IsVisibleSettings(ManagementType.Migration.ToString()) ||
                !currentUser.IsOwner() ||
                !SetupInfo.IsSecretEmail(currentUser.Email) && !TenantExtra.GetTenantQuota().HasMigration)
            {
                throw new InvalidOperationException(Resource.ErrorNotAllowedOption);
            }
        }
        [Create(@"register", false)] //NOTE: this method doesn't requires auth!!!
        public string RegisterUserOnPersonal(string email, string lang)
        {
            if (!CoreContext.Configuration.Personal)
            {
                throw new MethodAccessException("Method is only available on personal.onlyoffice.com");
            }

            try
            {
                var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.TwoLetterISOLanguageName, lang, StringComparison.InvariantCultureIgnoreCase));
                if (cultureInfo != null)
                {
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;
                }

                email.ThrowIfNull(new ArgumentException(Resource.ErrorEmailEmpty, "email"));

                if (!email.TestEmailRegex())
                {
                    throw new ArgumentException(Resource.ErrorNotCorrectEmail, "email");
                }

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

                if (CoreContext.UserManager.UserExists(newUserInfo.ID))
                {
                    if (!SetupInfo.IsSecretEmail(email) || SecurityContext.IsAuthenticated)
                    {
                        throw new Exception(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
                    }

                    try
                    {
                        SecurityContext.AuthenticateMe(Core.Configuration.Constants.CoreSystem);
                        CoreContext.UserManager.DeleteUser(newUserInfo.ID);
                    }
                    finally
                    {
                        SecurityContext.Logout();
                    }
                }

                StudioNotifyService.Instance.SendInvitePersonal(email);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            return(string.Empty);
        }
Ejemplo n.º 4
0
        private void PersonalProcess()
        {
            if (PersonalSettings.IsNewUser)
            {
                PersonalSettings.IsNewUser = false;
                AddCustomScript            = SetupInfo.CustomScripts.Length != 0 && !SetupInfo.IsSecretEmail(CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).Email);

                Classes.Global.Logger.Info("New personal user " + SecurityContext.CurrentAccount.ID
                                           + ((string)Session["campaign"] == "personal" ? " with campaign=personal" : ""));
            }

            if (PersonalSettings.IsNotActivated)
            {
                var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

                if (user.ActivationStatus != EmployeeActivationStatus.NotActivated)
                {
                    return;
                }

                try
                {
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                    user.ActivationStatus = EmployeeActivationStatus.Activated;
                    CoreContext.UserManager.SaveUserInfo(user);
                }
                finally
                {
                    SecurityContext.Logout();
                }

                SecurityContext.AuthenticateMe(user.ID);

                PersonalSettings.IsNotActivated = false;
                Classes.Global.Logger.InfoFormat("User {0} ActivationStatus - Activated", user.ID);

                StudioNotifyService.Instance.UserHasJoin();
                StudioNotifyService.Instance.SendUserWelcomePersonal(user);
            }
        }
        private static UserInfo CreateNewUser(string firstName, string lastName, string email, string passwordHash, EmployeeType employeeType, bool fromInviteLink)
        {
            var isVisitor = employeeType == EmployeeType.Visitor;

            if (SetupInfo.IsSecretEmail(email))
            {
                fromInviteLink = false;
            }

            var userInfo = new UserInfo
            {
                FirstName = string.IsNullOrEmpty(firstName) ? UserControlsCommonResource.UnknownFirstName : firstName,
                LastName  = string.IsNullOrEmpty(lastName) ? UserControlsCommonResource.UnknownLastName : lastName,
                Email     = email,
            };

            if (CoreContext.Configuration.Personal)
            {
                userInfo.ActivationStatus = EmployeeActivationStatus.Activated;
                userInfo.CultureName      = CoreContext.Configuration.CustomMode ? "ru-RU" : Thread.CurrentThread.CurrentUICulture.Name;
            }

            return(UserManagerWrapper.AddUser(userInfo, passwordHash, true, true, isVisitor, fromInviteLink));
        }
Ejemplo n.º 6
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);
        }
        public static 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 = CoreContext.UserManager.GetUsers(userId);
                }

                var isNew = false;
                if (CoreContext.Configuration.Personal)
                {
                    if (CoreContext.UserManager.UserExists(userInfo.ID) && SetupInfo.IsSecretEmail(userInfo.Email))
                    {
                        try
                        {
                            SecurityContext.CurrentAccount = ASC.Core.Configuration.Constants.CoreSystem;
                            CoreContext.UserManager.DeleteUser(userInfo.ID);
                            userInfo = Constants.LostUser;
                        }
                        finally
                        {
                            SecurityContext.Logout();
                        }
                    }

                    if (!CoreContext.UserManager.UserExists(userInfo.ID))
                    {
                        userInfo = JoinByThirdPartyAccount(loginProfile);

                        isNew = true;
                    }
                }

                if (isNew)
                {
                    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.Instance.UserHasJoin();
                    UserHelpTourHelper.IsNewUser = true;
                    PersonalSettings.IsNewUser   = true;
                }

                return(userInfo);
            }
            catch (Exception)
            {
                Auth.ProcessLogout();
                throw;
            }
        }
        [Create(@"register", false)] //NOTE: this method doesn't requires auth!!!
        public string RegisterUserOnPersonal(string email, string lang, bool spam)
        {
            if (!CoreContext.Configuration.Personal)
            {
                throw new MethodAccessException("Method is only available on personal.onlyoffice.com");
            }

            try
            {
                var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.TwoLetterISOLanguageName, lang, StringComparison.InvariantCultureIgnoreCase));
                if (cultureInfo != null)
                {
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;
                }

                email.ThrowIfNull(new ArgumentException(Resource.ErrorEmailEmpty, "email"));

                if (!email.TestEmailRegex())
                {
                    throw new ArgumentException(Resource.ErrorNotCorrectEmail, "email");
                }

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

                if (CoreContext.UserManager.UserExists(newUserInfo.ID))
                {
                    if (!SetupInfo.IsSecretEmail(email) || SecurityContext.IsAuthenticated)
                    {
                        throw new Exception(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
                    }

                    try
                    {
                        SecurityContext.AuthenticateMe(Core.Configuration.Constants.CoreSystem);
                        CoreContext.UserManager.DeleteUser(newUserInfo.ID);
                    }
                    finally
                    {
                        SecurityContext.Logout();
                    }
                }
                if (!spam)
                {
                    try
                    {
                        const string _databaseID = "com";
                        using (var db = DbManager.FromHttpContext(_databaseID))
                        {
                            db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
                                               .InColumnValue("email", email.ToLowerInvariant())
                                               .InColumnValue("reason", "personal")
                                               );
                            log4net.LogManager.GetLogger("ASC.Web").Debug(String.Format("Write to template_unsubscribe {0}", email.ToLowerInvariant()));
                        }
                    }
                    catch (Exception ex)
                    {
                        log4net.LogManager.GetLogger("ASC.Web").Debug(String.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, email.ToLowerInvariant()));
                    }
                }
                StudioNotifyService.Instance.SendInvitePersonal(email);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            return(string.Empty);
        }
Ejemplo n.º 9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginMessage = Request["m"];

            Page.RegisterStyle("~/UserControls/Common/AuthorizeDocs/css/authorizedocs.less", "~/UserControls/Common/AuthorizeDocs/css/slick.less")
            .RegisterBodyScripts("~/UserControls/Common/AuthorizeDocs/js/authorizedocs.js", "~/UserControls/Common/Authorize/js/authorize.js", "~/js/third-party/slick.min.js");

            if (CoreContext.Configuration.CustomMode)
            {
                Page.RegisterStyle("~/UserControls/Common/AuthorizeDocs/css/custom-mode.less");
            }

            Page.Title           = CoreContext.Configuration.CustomMode ? CustomModeResource.TitlePageNewCustomMode : Resource.AuthDocsTitlePage;
            Page.MetaDescription = CoreContext.Configuration.CustomMode ? CustomModeResource.AuthDocsMetaDescriptionCustomMode.HtmlEncode() : Resource.AuthDocsMetaDescription.HtmlEncode();
            Page.MetaKeywords    = CoreContext.Configuration.CustomMode ? CustomModeResource.AuthDocsMetaKeywordsCustomMode : Resource.AuthDocsMetaKeywords;

            HelpLink = GetHelpLink();

            PersonalFooterHolder.Controls.Add(LoadControl(CoreContext.Configuration.CustomMode
                                                              ? PersonalFooter.PersonalFooter.LocationCustomMode
                                                              : PersonalFooter.PersonalFooter.Location));

            if (AccountLinkControl.IsNotEmpty)
            {
                HolderLoginWithThirdParty.Controls.Add(LoadControl(LoginWithThirdParty.Location));
                LoginSocialNetworks.Controls.Add(LoadControl(LoginWithThirdParty.Location));
            }
            pwdReminderHolder.Controls.Add(LoadControl(PwdTool.Location));

            if (IsPostBack)
            {
                var loginCounter = 0;
                ShowRecaptcha = false;
                try
                {
                    Login = Request["login"].Trim();
                    var password = Request["pwd"];

                    if (string.IsNullOrEmpty(Login) || string.IsNullOrEmpty(password))
                    {
                        if (AccountLinkControl.IsNotEmpty &&
                            (Request.Url.GetProfile() != null ||
                             Request["__EVENTTARGET"] == "thirdPartyLogin"))
                        {
                            return;
                        }
                        throw new InvalidCredentialException(Resource.InvalidUsernameOrPassword);
                    }

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

                        loginCounter++;

                        if (!RecaptchaEnable)
                        {
                            if (loginCounter > SetupInfo.LoginThreshold)
                            {
                                throw new Authorize.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) ||
                                    !Authorize.ValidateRecaptcha(recaptchaResponse, ip))
                                {
                                    throw new Authorize.RecaptchaException();
                                }
                            }
                        }

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

                    var session = string.IsNullOrEmpty(Request["remember"]);

                    var cookiesKey = SecurityContext.AuthenticateMe(Login, password);
                    CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey, session);
                    MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess);

                    cache.Insert("loginsec/" + Login, (--loginCounter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }
                catch (InvalidCredentialException ex)
                {
                    Auth.ProcessLogout();
                    MessageAction messageAction;

                    if (ex is Authorize.BruteForceCredentialException)
                    {
                        LoginMessage  = Resource.LoginWithBruteForce;
                        messageAction = MessageAction.LoginFailBruteForce;
                    }
                    else if (ex is Authorize.RecaptchaException)
                    {
                        LoginMessage  = Resource.RecaptchaInvalid;
                        messageAction = MessageAction.LoginFailRecaptcha;
                    }
                    else
                    {
                        LoginMessage  = Resource.InvalidUsernameOrPassword;
                        messageAction = MessageAction.LoginFailInvalidCombination;
                    }

                    var loginName = string.IsNullOrWhiteSpace(Login) ? AuditResource.EmailNotSpecified : Login;

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

                    return;
                }
                catch (System.Security.SecurityException)
                {
                    Auth.ProcessLogout();
                    LoginMessage = Resource.ErrorDisabledProfile;
                    MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailDisabledProfile);
                    return;
                }
                catch (Exception ex)
                {
                    Auth.ProcessLogout();
                    LoginMessage = ex.Message;
                    MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFail);
                    return;
                }

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

                var refererURL = (string)Session["refererURL"];

                if (string.IsNullOrEmpty(refererURL))
                {
                    Response.Redirect(CommonLinkUtility.GetDefault());
                }
                else
                {
                    Session["refererURL"] = null;
                    Response.Redirect(refererURL);
                }
            }
            else
            {
                var confirmedEmail = (Request.QueryString["confirmed-email"] ?? "").Trim();

                if (String.IsNullOrEmpty(confirmedEmail) || !confirmedEmail.TestEmailRegex())
                {
                    return;
                }

                Login            = confirmedEmail;
                LoginMessage     = Resource.MessageEmailConfirmed + " " + Resource.MessageAuthorize;
                LoginMessageType = 1;
            }
        }
        public static UserInfo GetUserByThirdParty(LoginProfile loginProfile)
        {
            try
            {
                if (!string.IsNullOrEmpty(loginProfile.AuthorizationError))
                {
                    // ignore cancellation
                    if (loginProfile.AuthorizationError != "Canceled at provider")
                    {
                        throw new Exception(loginProfile.AuthorizationError);
                    }
                    return(ASC.Core.Users.Constants.LostUser);
                }

                if (string.IsNullOrEmpty(loginProfile.EMail))
                {
                    throw new Exception(Resource.ErrorNotCorrectEmail);
                }

                var userInfo = new UserInfo();

                Guid userId;
                if (TryGetUserByHash(loginProfile.HashId, out userId))
                {
                    userInfo = CoreContext.UserManager.GetUsers(userId);
                }
                if (!CoreContext.UserManager.UserExists(userInfo.ID))
                {
                    userInfo = CoreContext.UserManager.GetUserByEmail(loginProfile.EMail);
                }

                var isNew = false;
                if (CoreContext.Configuration.Personal)
                {
                    if (CoreContext.UserManager.UserExists(userInfo.ID) && SetupInfo.IsSecretEmail(userInfo.Email))
                    {
                        try
                        {
                            SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                            CoreContext.UserManager.DeleteUser(userInfo.ID);
                            userInfo = ASC.Core.Users.Constants.LostUser;
                        }
                        finally
                        {
                            SecurityContext.Logout();
                        }
                    }

                    if (!CoreContext.UserManager.UserExists(userInfo.ID))
                    {
                        userInfo = JoinByThirdPartyAccount(loginProfile);

                        isNew = true;
                    }
                }

                if (isNew)
                {
                    StudioNotifyService.Instance.UserHasJoin();
                    UserHelpTourHelper.IsNewUser = true;
                    PersonalSettings.IsNewUser   = true;
                }

                return(userInfo);
            }
            catch (Exception)
            {
                Auth.ProcessLogout();
                throw;
            }
        }
        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 && !SetupInfo.IsSecretEmail(Login))
                    {
                        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);
        }
        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);
        }
Ejemplo n.º 13
0
        [Create(@"register", false)] //NOTE: This method doesn't require auth!!!
        public string RegisterUserOnPersonal(string email, string lang, bool spam, string recaptchaResponse)
        {
            if (!CoreContext.Configuration.Personal)
            {
                throw new MethodAccessException("Method is only available on personal.onlyoffice.com");
            }

            try
            {
                if (CoreContext.Configuration.CustomMode)
                {
                    lang = "ru-RU";
                }

                var cultureInfo = SetupInfo.GetPersonalCulture(lang).Value;

                if (cultureInfo != null)
                {
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;
                }

                email.ThrowIfNull(new ArgumentException(Resource.ErrorEmailEmpty, "email"));

                if (!email.TestEmailRegex())
                {
                    throw new ArgumentException(Resource.ErrorNotCorrectEmail, "email");
                }

                if (!SetupInfo.IsSecretEmail(email) &&
                    !string.IsNullOrEmpty(SetupInfo.RecaptchaPublicKey) && !string.IsNullOrEmpty(SetupInfo.RecaptchaPrivateKey))
                {
                    var ip = Request.Headers["X-Forwarded-For"] ?? Request.UserHostAddress;

                    if (String.IsNullOrEmpty(recaptchaResponse) ||
                        !Authorize.ValidateRecaptcha(recaptchaResponse, ip))
                    {
                        throw new Authorize.RecaptchaException(Resource.RecaptchaInvalid);
                    }
                }

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

                if (CoreContext.UserManager.UserExists(newUserInfo.ID))
                {
                    if (!SetupInfo.IsSecretEmail(email) || SecurityContext.IsAuthenticated)
                    {
                        throw new Exception(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
                    }

                    try
                    {
                        SecurityContext.CurrentAccount = Constants.CoreSystem;
                        CoreContext.UserManager.DeleteUser(newUserInfo.ID);
                    }
                    finally
                    {
                        SecurityContext.Logout();
                    }
                }
                if (!spam)
                {
                    try
                    {
                        const string _databaseID = "com";
                        using (var db = DbManager.FromHttpContext(_databaseID))
                        {
                            db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
                                               .InColumnValue("email", email.ToLowerInvariant())
                                               .InColumnValue("reason", "personal")
                                               );
                            Log.Debug(String.Format("Write to template_unsubscribe {0}", email.ToLowerInvariant()));
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Debug(String.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, email.ToLowerInvariant()));
                    }
                }
                StudioNotifyService.Instance.SendInvitePersonal(email);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            return(string.Empty);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var accountLink = (AccountLinkControl)LoadControl(AccountLinkControl.Location);

            accountLink.ClientCallback = "loginJoinCallback";
            accountLink.SettingsView   = false;
            ThirdPartyList.Controls.Add(accountLink);

            var thirdPartyProfile = Request.Url.GetProfile();

            if (thirdPartyProfile == null && !IsPostBack || SecurityContext.IsAuthenticated)
            {
                return;
            }

            try
            {
                if (thirdPartyProfile == null)
                {
                    if (string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) || Request["__EVENTTARGET"] != "thirdPartyLogin")
                    {
                        return;
                    }

                    thirdPartyProfile = new LoginProfile(Request["__EVENTARGUMENT"]);
                }

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

                if (string.IsNullOrEmpty(thirdPartyProfile.EMail))
                {
                    LoginMessage = Resource.ErrorNotCorrectEmail;
                    return;
                }

                var userId         = Guid.Empty;
                var linkedProfiles = accountLink.GetLinker().GetLinkedObjectsByHashId(thirdPartyProfile.HashId);
                linkedProfiles.Any(profileId => Guid.TryParse(profileId, out userId) && CoreContext.UserManager.UserExists(userId));

                var acc = CoreContext.UserManager.GetUsers(userId);

                if (!CoreContext.UserManager.UserExists(acc.ID))
                {
                    acc = CoreContext.UserManager.GetUserByEmail(thirdPartyProfile.EMail);
                }

                var isNew = false;
                if (CoreContext.Configuration.Personal)
                {
                    if (CoreContext.UserManager.UserExists(acc.ID) && SetupInfo.IsSecretEmail(acc.Email))
                    {
                        try
                        {
                            SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                            CoreContext.UserManager.DeleteUser(acc.ID);
                            acc = ASC.Core.Users.Constants.LostUser;
                        }
                        finally
                        {
                            SecurityContext.Logout();
                        }
                    }

                    if (!CoreContext.UserManager.UserExists(acc.ID))
                    {
                        acc = JoinByThirdPartyAccount(thirdPartyProfile);

                        isNew = true;
                    }
                }

                var cookiesKey = SecurityContext.AuthenticateMe(acc.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccessViaSocialAccount);

                if (isNew)
                {
                    StudioNotifyService.Instance.UserHasJoin();
                    UserHelpTourHelper.IsNewUser = true;
                    PersonalSettings.IsNewUser   = true;
                }
            }
            catch (System.Security.SecurityException)
            {
                Auth.ProcessLogout();
                LoginMessage = Resource.InvalidUsernameOrPassword;
                MessageService.Send(HttpContext.Current.Request, thirdPartyProfile != null ? thirdPartyProfile.HashId : AuditResource.EmailNotSpecified, MessageAction.LoginFailDisabledProfile);
                return;
            }
            catch (Exception exception)
            {
                Auth.ProcessLogout();
                LoginMessage = exception.Message;
                MessageService.Send(HttpContext.Current.Request, AuditResource.EmailNotSpecified, MessageAction.LoginFail);
                return;
            }

            var refererURL = (string)Session["refererURL"];

            if (String.IsNullOrEmpty(refererURL))
            {
                Response.Redirect(CommonLinkUtility.GetDefault());
            }
            else
            {
                Session["refererURL"] = null;
                Response.Redirect(refererURL);
            }
        }
        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);
                }

                var isNew = false;
                if (CoreBaseSettings.Personal)
                {
                    if (UserManager.UserExists(userInfo.ID) && SetupInfo.IsSecretEmail(userInfo.Email))
                    {
                        try
                        {
                            SecurityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem);
                            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 GetUser(AuthModel memberModel, out bool viaEmail)
        {
            viaEmail = true;
            var      action = MessageAction.LoginFailViaApi;
            UserInfo user;

            try
            {
                if ((string.IsNullOrEmpty(memberModel.Provider) && string.IsNullOrEmpty(memberModel.SerializedProfile)) || memberModel.Provider == "email")
                {
                    memberModel.UserName.ThrowIfNull(new ArgumentException(@"userName empty", "userName"));
                    if (!string.IsNullOrEmpty(memberModel.Password))
                    {
                        memberModel.Password.ThrowIfNull(new ArgumentException(@"password empty", "password"));
                    }
                    else
                    {
                        memberModel.PasswordHash.ThrowIfNull(new ArgumentException(@"PasswordHash empty", "PasswordHash"));
                    }
                    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(
                        TenantManager.GetCurrentTenant().TenantId,
                        memberModel.UserName,
                        memberModel.PasswordHash);

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

                    Cache.Insert("loginsec/" + memberModel.UserName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }
                else
                {
                    viaEmail = false;
                    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);
                    }

                    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);
        }