示例#1
0
        private static void RequestCode(HttpContext context)
        {
            var token = GetToken(context.Request["code"]);

            if (token == null)
            {
                Global.Logger.Error("BoxApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var boxUserId = context.Request["userId"];

            if (SecurityContext.IsAuthenticated)
            {
                if (!CurrentUser(boxUserId))
                {
                    Global.Logger.Debug("BoxApp: logout for " + boxUserId);
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    SecurityContext.Logout();
                }
            }

            if (!SecurityContext.IsAuthenticated)
            {
                bool isNew;
                var  userInfo = GetUserInfo(token, out isNew);

                if (userInfo == null)
                {
                    Global.Logger.Error("BoxApp: UserInfo is null");
                    throw new Exception("Profile is null");
                }

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

                if (isNew)
                {
                    UserHelpTourHelper.IsNewUser    = true;
                    PersonalSettings.IsNewUser      = true;
                    PersonalSettings.IsNotActivated = true;
                }

                if (!string.IsNullOrEmpty(boxUserId) && !CurrentUser(boxUserId))
                {
                    AddLinker(boxUserId);
                }
            }

            Token.SaveToken(token);

            var fileId = context.Request["id"];

            context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
        }
示例#2
0
        public static string SaveMobilePhone(UserInfo user, string mobilePhone)
        {
            mobilePhone = GetPhoneValueDigits(mobilePhone);

            if (user == null || Equals(user, Constants.LostUser))
            {
                throw new Exception(Resource.ErrorUserNotFound);
            }
            if (string.IsNullOrEmpty(mobilePhone))
            {
                throw new Exception(Resource.ActivateMobilePhoneEmptyPhoneNumber);
            }
            if (!string.IsNullOrEmpty(user.MobilePhone) && user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.Activated)
            {
                throw new Exception(Resource.MobilePhoneMustErase);
            }

            user.MobilePhone = mobilePhone;
            user.MobilePhoneActivationStatus = MobilePhoneActivationStatus.NotActivated;
            if (SecurityContext.IsAuthenticated)
            {
                CoreContext.UserManager.SaveUserInfo(user);
            }
            else
            {
                try
                {
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                    CoreContext.UserManager.SaveUserInfo(user);
                }
                finally
                {
                    SecurityContext.Logout();
                }
            }

            if (StudioSmsNotificationSettings.Enable)
            {
                PutAuthCode(user, false);
            }
            else
            {
                if (!SecurityContext.IsAuthenticated)
                {
                    var cookiesKey = SecurityContext.AuthenticateMe(user.ID);
                    CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                }
                if (user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
                {
                    user.MobilePhoneActivationStatus = MobilePhoneActivationStatus.Activated;
                    CoreContext.UserManager.SaveUserInfo(user);
                }
            }

            return(mobilePhone);
        }
示例#3
0
        public bool ValidateAuthCode(UserInfo user, int tenantId, string code, bool checkBackup = true)
        {
            if (!TfaAppAuthSettings.IsVisibleSettings ||
                !SettingsManager.Load <TfaAppAuthSettings>().EnableSetting)
            {
                return(false);
            }

            if (user == null || Equals(user, Constants.LostUser))
            {
                throw new Exception(Resource.ErrorUserNotFound);
            }

            code = (code ?? "").Trim();

            if (string.IsNullOrEmpty(code))
            {
                throw new Exception(Resource.ActivateTfaAppEmptyCode);
            }

            int.TryParse(Cache.Get <string>("tfa/" + user.ID), out var counter);
            if (++counter > SetupInfo.LoginThreshold)
            {
                throw new BruteForceCredentialException(Resource.TfaTooMuchError);
            }
            Cache.Insert("tfa/" + user.ID, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

            if (!Tfa.ValidateTwoFactorPIN(GenerateAccessToken(user), code))
            {
                if (checkBackup && TfaAppUserSettings.BackupCodesForUser(SettingsManager, user.ID).Any(x => x.Code == code && !x.IsUsed))
                {
                    TfaAppUserSettings.DisableCodeForUser(SettingsManager, user.ID, code);
                }
                else
                {
                    throw new ArgumentException(Resource.TfaAppAuthMessageError);
                }
            }

            Cache.Insert("tfa/" + user.ID, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

            if (!SecurityContext.IsAuthenticated)
            {
                var cookiesKey = SecurityContext.AuthenticateMe(user.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
            }

            if (!TfaAppUserSettings.EnableForUser(SettingsManager, user.ID))
            {
                GenerateBackupCodes(user);
                return(true);
            }

            return(false);
        }
示例#4
0
        private bool CheckBasicAuth(HttpContext context)
        {
            string authCookie;

            if (AuthorizationHelper.ProcessBasicAuthorization(context, out authCookie))
            {
                CookiesManager.SetCookies(CookiesType.AuthKey, authCookie);
                return(true);
            }
            return(false);
        }
示例#5
0
 private static void OutsideAuth()
 {
     var cookie = SecurityContext.AuthenticateMe(Constants.OutsideUser.ID);
     if (HttpContext.Current != null)
     {
         CookiesManager.SetCookies(CookiesType.AuthKey, cookie);
     }
     else
     {
         SecurityContext.AuthenticateMe(cookie);
     }
 }
示例#6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            cmd        = Request.Form["subCmd"];
            loginOkUrl = Request.QueryString["url"];
            AJM_WeiXinUserInfo user     = new AJM_WeiXinUserInfo();
            string             loginId  = txt_LoginID.Value;
            string             password = txt_Password.Value;

            if (!IsPostBack)
            {
                BindSelSchool();
            }

            //通过页面验证,执行登录操作
            if (cmd == "Login")
            {
                CookiesManager.RemoveCookies("userInfo");
                if (loginHandle(loginId, password, selSchool.Value))
                {
                    //若选择记住密码,则记录用户信息cookies
                    CookiesManager.SetCookies(loginId, password, UserSchoolInfo.SchoolNo);
                    if (!string.IsNullOrEmpty(loginOkUrl))
                    {
                        Response.Redirect(loginOkUrl);
                    }
                    else
                    {
                        Response.Redirect("MainFunctionPage.aspx");
                    }
                }
            }
            else
            {
                if (Request.Cookies["userInfo"] != null)//存在记录的cookies信息
                {
                    loginId  = CookiesManager.GetCookiesValue(CookiesManager.LoginID);
                    password = CookiesManager.GetCookiesValue(CookiesManager.Password);
                    string schoolId = CookiesManager.GetCookiesValue(CookiesManager.SchoolId);

                    if (loginHandle(loginId, password, schoolId))
                    {
                        if (!string.IsNullOrEmpty(loginOkUrl))
                        {
                            Response.Redirect(loginOkUrl);
                        }
                        else
                        {
                            Response.Redirect("MainFunctionPage.aspx");
                        }
                    }
                }
            }
        }
示例#7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            TenantName = CoreContext.TenantManager.GetCurrentTenant().Name;
            Page.Title = TenantName;

            if (Request.QueryString["stop"] == "true")
            {
                WarmUpController.Instance.Terminate();
            }

            if (Request.QueryString["restart"] == "true")
            {
                WarmUpController.Instance.Restart();
            }

            if (!CoreContext.Configuration.Standalone || WarmUpController.Instance.CheckCompleted())
            {
                Response.Redirect(CommonLinkUtility.GetDefault(), true);

                if (!WarmUpSettings.GetCompleted())
                {
                    WarmUpSettings.SetCompleted(true);
                }
            }

            if (!SecurityContext.IsAuthenticated)
            {
                var owner  = CoreContext.TenantManager.GetCurrentTenant();
                var cookie = SecurityContext.AuthenticateMe(owner.OwnerId);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookie);
            }

            Master.DisabledSidePanel = true;

            //top panel
            Master.TopStudioPanel.DisableProductNavigation = true;
            Master.TopStudioPanel.DisableUserInfo          = true;
            Master.TopStudioPanel.DisableSearch            = true;
            Master.TopStudioPanel.DisableSettings          = true;
            Master.TopStudioPanel.DisableTariff            = true;

            var loader = (LoaderPage)LoadControl(LoaderPage.Location);

            loader.Static = true;
            loaderHolder.Controls.Add(loader);

            AjaxPro.Utility.RegisterTypeForAjax(GetType());

            Page.RegisterStyle("~/usercontrols/common/startup/css/startup.less")
            .RegisterBodyScripts("~/usercontrols/common/startup/js/startup.js")
            .RegisterInlineScript(string.Format("ProgressStartUpManager.init({0});", WarmUpController.Instance.GetSerializedProgress()));
        }
        public static void SetUserPassword(Guid userID, string password)
        {
            CheckPasswordPolicy(password);

            var cookie = SecurityContext.SetUserPassword(userID, password);

            StudioNotifyService.Instance.UserPasswordChanged(userID, password);

            if (cookie != null)
            {
                CookiesManager.SetCookies(CookiesType.AuthKey, cookie);
            }
        }
        public object SaveData(string email, string pwd, string header)
        {
            try
            {
                var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

                if (!currentUser.IsOwner())
                {
                    return(new { Status = 0, Message = Resources.Resource.EmailAndPasswordNotOwner });
                }

                if (!UserManagerWrapper.ValidateEmail(email))
                {
                    return(new { Status = 0, Message = Resources.Resource.EmailAndPasswordIncorrectEmail });
                }

                UserManagerWrapper.SetUserPassword(currentUser.ID, pwd);

                if (currentUser.Email != email)
                {
                    currentUser.Email            = email;
                    currentUser.ActivationStatus = EmployeeActivationStatus.NotActivated;
                }
                CoreContext.UserManager.SaveUserInfo(currentUser);

                if (currentUser.ActivationStatus == EmployeeActivationStatus.NotActivated)
                {
                    StudioNotifyService.Instance.SendEmailActivationInstructions(currentUser, email);
                }

                var newCookie = SecurityContext.AuthenticateMe(email, CoreContext.Authentication.GetUserPasswordHash(currentUser.ID));
                CookiesManager.SetCookies(CookiesType.AuthKey, newCookie);

                var wizardSettings =
                    SettingsManager.Instance.LoadSettings <WizardSettings>(TenantProvider.CurrentTenantID);
                wizardSettings.Completed = true;
                SettingsManager.Instance.SaveSettings(wizardSettings, TenantProvider.CurrentTenantID);

                var currentTenant = CoreContext.TenantManager.GetCurrentTenant();
                currentTenant.Name = header;
                CoreContext.TenantManager.SaveTenant(currentTenant);

                SendInstallInfo(currentUser);

                return(new { Status = 1, Message = Resources.Resource.EmailAndPasswordSaved });
            }
            catch (Exception ex)
            {
                return(new { Status = 0, Message = ex.Message });
            }
        }
示例#10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            UserSchoolInfo = null;
            if (!IsPostBack)
            {
                BindSelSchool();
                if (Request.QueryString["WXID"] != null)
                {
                    BindStuData(Request.QueryString["WXID"]);
                }
            }
            if (Request.QueryString["WXID"] == null)
            {
                divcontent.Style.Add("display", "block");
                divstuInfo.Style.Add("display", "none");
                divSuccess.Style.Add("display", "none");
                return;
            }

            cmd = Request.Form["subCmd"];
            //通过页面验证,执行登录操作
            if (cmd == "Login")
            {
                WeiXinUsers user     = new WeiXinUsers();
                UserInfo    users    = new UserInfo();
                string      schoolId = selSchool.Items[selSchool.SelectedIndex].Value;
                if (schoolId == "-1")
                {
                    spanWarmInfo.Visible   = true;
                    spanWarmInfo.InnerText = "请选择学校";
                }
                users.LoginId  = txt_LoginID.Value;
                users.Password = txt_Password.Value;
                if (loginHandle(users, schoolId))
                {
                    user.WeixinID   = Request.QueryString["WXID"];
                    user.CardNo     = txt_LoginID.Value;
                    user.SchoolInfo = new AMS_School {
                        Id = Convert.ToInt32(schoolId)
                    };

                    spanWarmInfo.Visible   = true;
                    spanWarmInfo.InnerText = WeiXinProxy.BindUserInfo(user);

                    AMS_School school = AMS_SchoolProxy.GetSchoolById(int.Parse(schoolId));
                    CookiesManager.SetCookies(user.CardNo, txt_Password.Value, schoolId);
                }
            }
        }
示例#11
0
        private void AddUser(SamlResponse samlResponse, UserInfo userInfo)
        {
            try
            {
                _log.DebugFormat("Adding or updating user in database, userId={0}", userInfo.ID);
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                if (!string.IsNullOrEmpty(userInfo.MobilePhone))
                {
                    userInfo.MobilePhone = SmsManager.GetPhoneValueDigits(userInfo.MobilePhone);
                }
                if (string.IsNullOrEmpty(userInfo.UserName))
                {
                    if (string.IsNullOrWhiteSpace(userInfo.FirstName))
                    {
                        userInfo.FirstName = Resource.FirstName;
                    }
                    if (string.IsNullOrWhiteSpace(userInfo.LastName))
                    {
                        userInfo.LastName = Resource.LastName;
                    }
                    if (TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers)
                    {
                        userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), true, false);
                    }
                    else
                    {
                        userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), true, false, true);
                    }
                }
                else
                {
                    CoreContext.UserManager.SaveUserInfo(userInfo);
                }
                var photoUrl = samlResponse.GetRemotePhotoUrl();
                if (!string.IsNullOrEmpty(photoUrl))
                {
                    var photoLoader = new UserPhotoLoader();
                    photoLoader.SaveOrUpdatePhoto(photoUrl, userInfo.ID);
                }
            }
            finally
            {
                SecurityContext.Logout();
            }
            var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);

            CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
        }
示例#12
0
        public static void ValidateSmsCode(UserInfo user, string code)
        {
            if (!StudioSmsNotificationSettings.IsVisibleSettings ||
                !StudioSmsNotificationSettings.Enable)
            {
                return;
            }

            if (user == null || Equals(user, Constants.LostUser))
            {
                throw new Exception(Resource.ErrorUserNotFound);
            }

            code = (code ?? "").Trim();

            if (string.IsNullOrEmpty(code))
            {
                throw new Exception(Resource.ActivateMobilePhoneEmptyCode);
            }

            int counter;

            int.TryParse(CodeCache.Get <String>("loginsec/" + user.ID), out counter);

            if (++counter % 5 == 0)
            {
                Thread.Sleep(TimeSpan.FromSeconds(10));
            }
            CodeCache.Insert("loginsec/" + user.ID, counter.ToString(), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

            if (!SmsKeyStorage.ValidateKey(user.MobilePhone, code))
            {
                throw new ArgumentException(Resource.SmsAuthenticationMessageError);
            }

            if (!SecurityContext.IsAuthenticated)
            {
                var cookiesKey = SecurityContext.AuthenticateMe(user.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
            }

            if (user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
            {
                user.MobilePhoneActivationStatus = MobilePhoneActivationStatus.Activated;
                CoreContext.UserManager.SaveUserInfo(user);
            }
        }
        public static void ValidateSmsCode(UserInfo user, string code)
        {
            if (!StudioSmsNotificationSettings.IsVisibleSettings ||
                !StudioSmsNotificationSettings.Enable)
            {
                return;
            }

            if (user == null || Equals(user, Constants.LostUser))
            {
                throw new Exception(Resource.ErrorUserNotFound);
            }

            var valid = SmsKeyStorage.ValidateKey(user.MobilePhone, code);

            switch (valid)
            {
            case SmsKeyStorage.Result.Empty:
                throw new Exception(Resource.ActivateMobilePhoneEmptyCode);

            case SmsKeyStorage.Result.TooMuch:
                throw new Authorize.BruteForceCredentialException(Resource.SmsTooMuchError);

            case SmsKeyStorage.Result.Timeout:
                throw new TimeoutException(Resource.SmsAuthenticationTimeout);

            case SmsKeyStorage.Result.Invalide:
                throw new ArgumentException(Resource.SmsAuthenticationMessageError);
            }
            if (valid != SmsKeyStorage.Result.Ok)
            {
                throw new Exception("Error: " + valid);
            }

            if (!SecurityContext.IsAuthenticated)
            {
                var cookiesKey = SecurityContext.AuthenticateMe(user.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
            }

            if (user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
            {
                user.MobilePhoneActivationStatus = MobilePhoneActivationStatus.Activated;
                CoreContext.UserManager.SaveUserInfo(user);
            }
        }
示例#14
0
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            if (!SecurityContext.IsAuthenticated)
            {
                if (CoreContext.Configuration.Personal)
                {
                    if (CoreContext.Configuration.Standalone)
                    {
                        var admin  = CoreContext.UserManager.GetUserByUserName("administrator");
                        var cookie = SecurityContext.AuthenticateMe(admin.ID);
                        CookiesManager.SetCookies(CookiesType.AuthKey, cookie);
                        Response.Redirect(CommonLinkUtility.GetDefault(), true);
                    }

                    if (Request["campaign"] == "personal")
                    {
                        Session["campaign"] = "personal";
                    }
                    CheckSocialMedia();

                    SetLanguage(abTesting: true);
                }

                return;
            }

            if (IsLogout)
            {
                var loginName = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).DisplayUserName(false);
                ProcessLogout();
                MessageService.Send(HttpContext.Current.Request, loginName, MessageAction.Logout);

                // slo redirect
                if (SsoImporter.SloIsEnable && HttpContext.Current != null)
                {
                    HttpContext.Current.Response.Redirect(SsoImporter.SloEndPoint, true);
                }
                Response.Redirect("~/auth.aspx", true);
            }
            else
            {
                Response.Redirect(CommonLinkUtility.GetDefault(), true);
            }
        }
示例#15
0
        public static bool Authenticate()
        {
            if (SecurityContext.IsAuthenticated)
            {
                return(true);
            }

            var authenticated = false;
            var tenant        = CoreContext.TenantManager.GetCurrentTenant(false);

            if (tenant != null)
            {
                if (HttpContext.Current != null)
                {
                    string cookie;
                    if (AuthorizationHelper.ProcessBasicAuthorization(HttpContext.Current, out cookie))
                    {
                        CookiesManager.SetCookies(CookiesType.AuthKey, cookie);
                        authenticated = true;
                    }
                }
                if (!authenticated)
                {
                    var cookie = CookiesManager.GetCookies(CookiesType.AuthKey);
                    if (!string.IsNullOrEmpty(cookie))
                    {
                        authenticated = SecurityContext.AuthenticateMe(cookie);

                        if (!authenticated)
                        {
                            Auth.ProcessLogout();
                            return(false);
                        }
                    }
                }

                var accessSettings = TenantAccessSettings.Load();
                if (authenticated && SecurityContext.CurrentAccount.ID == ASC.Core.Users.Constants.OutsideUser.ID && !accessSettings.Anyone)
                {
                    Auth.ProcessLogout();
                    authenticated = false;
                }
            }
            return(authenticated);
        }
示例#16
0
        private static void UserAuth(UserInfo user, HttpContext context)
        {
            if (SecurityContext.IsAuthenticated)
            {
                return;
            }

            if (StudioSmsNotificationSettings.IsVisibleSettings && StudioSmsNotificationSettings.Enable)
            {
                context.Session["refererURL"] = context.Request.Url.AbsoluteUri;
                context.Response.Redirect(Confirm.SmsConfirmUrl(user), true);
                return;
            }

            var cookiesKey = SecurityContext.AuthenticateMe(user.ID);

            CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
            MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess);
        }
示例#17
0
        private void ActivateUser(UserInfo user, string newPwd)
        {
            try
            {
                //Set status to activated
                user.ActivationStatus = EmployeeActivationStatus.Activated;
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                CoreContext.UserManager.SaveUserInfo(user);
                if (!string.IsNullOrEmpty(newPwd))
                {
                    //set password if it's specified
                    SecurityContext.SetUserPassword(user.ID, newPwd);
                }
            }
            catch (Exception ex)
            {
                ShowError(ex.Message);
            }
            finally
            {
                SecurityContext.Logout(); //Logout from core system
            }
            //Login user
            try
            {
                var cookiesKey = SecurityContext.AuthenticateMe(user.ID.ToString(),
                                                                CoreContext.Authentication.GetUserPasswordHash(user.ID));

                CookiesManager.SetCookies(CookiesType.UserID, user.ID.ToString());
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
            }
            catch (Exception exception)
            {
                ShowError(exception.Message);
                return;
            }
            UserOnlineManager.Instance.RegistryOnlineUser(SecurityContext.CurrentAccount.ID);
            WebItemManager.Instance.ItemGlobalHandlers.Login(SecurityContext.CurrentAccount.ID);
        }
        public AuthenticationTokenData AuthenticateMe([FromBody] AuthModel auth)
        {
            var tenant = TenantManager.GetCurrentTenant();
            var user   = GetUser(tenant.TenantId, auth);

            try
            {
                var token = SecurityContext.AuthenticateMe(user.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, token);
                var expires = TenantCookieSettingsHelper.GetExpiresTime(tenant.TenantId);

                return(new AuthenticationTokenData
                {
                    Token = token,
                    Expires = expires
                });
            }
            catch
            {
                throw new Exception("User authentication failed");
            }
        }
        private void ActivateUser(UserInfo user, string newPwd)
        {
            try
            {
                //Set status to activated
                user.ActivationStatus = EmployeeActivationStatus.Activated;
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                CoreContext.UserManager.SaveUserInfo(user);
                if (!string.IsNullOrEmpty(newPwd))
                {
                    //set password if it's specified
                    SecurityContext.SetUserPassword(user.ID, newPwd);
                }
            }
            catch (Exception ex)
            {
                ShowError(ex.Message);
            }
            finally
            {
                SecurityContext.Logout(); //Logout from core system
            }
            //Login user
            try
            {
                var cookiesKey = SecurityContext.AuthenticateMe(user.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);

                if (newPwd != null)
                {
                    MessageService.Send(HttpContext.Current.Request, MessageAction.UserUpdatedPassword);
                    MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess, user.DisplayUserName(false));
                }
            }
            catch (Exception exception)
            {
                ShowError(exception.Message);
            }
        }
示例#20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!CoreContext.Configuration.Standalone || WarmUp.Instance.Completed)
            {
                Response.Redirect(CommonLinkUtility.GetDefault(), true);
            }

            if (!SecurityContext.IsAuthenticated)
            {
                var owner  = CoreContext.TenantManager.GetCurrentTenant();
                var cookie = SecurityContext.AuthenticateMe(owner.OwnerId);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookie);
            }

            Master.DisabledSidePanel = true;

            //top panel
            Master.TopStudioPanel.DisableProductNavigation = true;
            Master.TopStudioPanel.DisableUserInfo          = true;
            Master.TopStudioPanel.DisableSearch            = true;
            Master.TopStudioPanel.DisableSettings          = true;
            Master.TopStudioPanel.DisableTariff            = true;

            loaderHolder.Controls.Add(LoadControl(LoaderPage.Location));

            AjaxPro.Utility.RegisterTypeForAjax(GetType());

            Page.RegisterStyleControl(VirtualPathUtility.ToAbsolute("~/usercontrols/common/startup/css/startup.less"));
            Page.RegisterBodyScripts(ResolveUrl("~/usercontrols/common/startup/js/startup.js"));
            Page.RegisterInlineScript(string.Format("ProgressStartUpManager.init({0});", WarmUp.Instance.Progress.ProgressPercent));

            if (Request.QueryString["sync"] == "true")
            {
                WarmUp.Instance.StartSync();
            }
        }
示例#21
0
        public object SaveData(string email, string pwd, string lng, bool populateDemoData, string promocode)
        {
            try
            {
                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = SettingsManager.Instance.LoadSettings <WizardSettings>(tenant.TenantId);
                if (settings.Completed)
                {
                    return(new { Status = 0, Message = "Wizard passed." });
                }

                if (tenant.OwnerId == Guid.Empty)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(6)); // wait cache interval
                    tenant = CoreContext.TenantManager.GetTenant(tenant.TenantId);
                    if (tenant.OwnerId == Guid.Empty)
                    {
                        LogManager.GetLogger("ASC.Web.FirstTime").Error(tenant.TenantId + ": owner id is empty.");
                    }
                }
                var currentUser = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId);

                if (!currentUser.IsOwner())
                {
                    return(new { Status = 0, Message = Resources.Resource.EmailAndPasswordNotOwner });
                }
                if (!UserManagerWrapper.ValidateEmail(email))
                {
                    return(new { Status = 0, Message = Resources.Resource.EmailAndPasswordIncorrectEmail });
                }

                SecurityContext.AuthenticateMe(currentUser.ID);
                UserManagerWrapper.SetUserPassword(currentUser.ID, pwd);

                email = email.Trim();
                if (currentUser.Email != email)
                {
                    currentUser.Email            = email;
                    currentUser.ActivationStatus = EmployeeActivationStatus.NotActivated;
                }
                CoreContext.UserManager.SaveUserInfo(currentUser);

                var cookie = SecurityContext.AuthenticateMe(currentUser.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookie);

                if (!string.IsNullOrWhiteSpace(promocode))
                {
                    try
                    {
                        CoreContext.PaymentManager.ActivateKey(promocode);
                    }
                    catch (Exception err)
                    {
                        LogManager.GetLogger("ASC.Web.FirstTime").ErrorFormat("Incorrect Promo: {0}\r\n{1}", promocode, err);
                        return(new { Status = 0, Message = Resources.Resource.EmailAndPasswordIncorrectPromocode });
                    }
                }

                settings.Completed = true;
                SettingsManager.Instance.SaveSettings(settings, tenant.TenantId);

                TrySetLanguage(tenant, lng);
                FirstTimeTenantSettings.SetDefaultTenantSettings();
                FirstTimeTenantSettings.SendInstallInfo(currentUser);
                if (populateDemoData)
                {
                    FirstTimeTenantSettings.SetTenantData(lng);
                }

                return(new { Status = 1, Message = Resources.Resource.EmailAndPasswordSaved });
            }
            catch (Exception ex)
            {
                return(new { Status = 0, Message = ex.Message });
            }
        }
示例#22
0
        private bool CheckValidationKey()
        {
            var key      = Request["key"] ?? "";
            var emplType = Request["emplType"] ?? "";

            var validInterval = SetupInfo.ValidEamilKeyInterval;
            var authInterval  = TimeSpan.FromHours(1);

            EmailValidationKeyProvider.ValidationResult checkKeyResult;
            switch (_type)
            {
            case ConfirmType.PortalContinue:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key);
                break;

            case ConfirmType.PhoneActivation:
            case ConfirmType.PhoneAuth:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key, authInterval);
                break;

            case ConfirmType.Auth:
            {
                var first  = Request["first"] ?? "";
                var module = Request["module"];

                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + first + module, key, authInterval);

                if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    var user = _email.Contains("@")
                                           ? CoreContext.UserManager.GetUserByEmail(_email)
                                           : CoreContext.UserManager.GetUsers(new Guid(_email));

                    if (SecurityContext.IsAuthenticated && SecurityContext.CurrentAccount.ID != user.ID)
                    {
                        Auth.ProcessLogout();
                    }

                    if (!SecurityContext.IsAuthenticated)
                    {
                        if (StudioSmsNotificationSettings.IsVisibleSettings && StudioSmsNotificationSettings.Enable)
                        {
                            Response.Redirect(SmsConfirmUrl(user), true);
                        }

                        var authCookie = SecurityContext.AuthenticateMe(user.ID);
                        CookiesManager.SetCookies(CookiesType.AuthKey, authCookie);
                        MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess, user.DisplayUserName(false));
                    }

                    AuthRedirect(user, first.ToLower() == "true", module, Request[FilesLinkUtility.FileUri]);
                }
            }
            break;

            case ConfirmType.DnsChange:
            {
                var dnsChangeKey = string.Join(string.Empty, new[] { _email, _type.ToString(), Request["dns"], Request["alias"] });
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(dnsChangeKey, key, validInterval);
            }
            break;

            case ConfirmType.PortalOwnerChange:
            {
                Guid uid;
                try
                {
                    uid = new Guid(Request["uid"]);
                }
                catch
                {
                    uid = Guid.Empty;
                }
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + uid, key, validInterval);
            }
            break;

            case ConfirmType.EmpInvite:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + emplType, key, validInterval);
                break;

            case ConfirmType.LinkInvite:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_type + emplType, key, validInterval);
                break;

            case ConfirmType.PasswordChange:

                var userHash = !String.IsNullOrEmpty(Request["p"]) && Request["p"] == "1";

                String hash = String.Empty;

                if (userHash)
                {
                    hash = CoreContext.Authentication.GetUserPasswordHash(CoreContext.UserManager.GetUserByEmail(_email).ID);
                }

                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + (string.IsNullOrEmpty(hash) ? string.Empty : Hasher.Base64Hash(hash)), key, validInterval);
                break;

            default:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key, validInterval);
                break;
            }

            if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Expired)
            {
                ShowError(Resource.ErrorExpiredActivationLink);
                return(false);
            }

            if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Invalid)
            {
                ShowError(_type == ConfirmType.LinkInvite
                              ? Resource.ErrorInvalidActivationLink
                              : Resource.ErrorConfirmURLError);
                return(false);
            }

            if (!string.IsNullOrEmpty(_email) && !_email.TestEmailRegex())
            {
                ShowError(Resource.ErrorNotCorrectEmail);
                return(false);
            }

            return(true);
        }
示例#23
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);
        }
示例#24
0
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            if (!SecurityContext.IsAuthenticated)
            {
                if (CoreContext.Configuration.Personal)
                {
                    if (Request["campaign"] == "personal")
                    {
                        Session["campaign"] = "personal";
                    }
                    CheckSocialMedia();

                    SetLanguage(abTesting: true);
                }

                var token = Request["asc_auth_key"];
                if (SecurityContext.AuthenticateMe(token))
                {
                    CookiesManager.SetCookies(CookiesType.AuthKey, token);

                    var refererURL = Request["refererURL"];
                    if (string.IsNullOrEmpty(refererURL))
                    {
                        refererURL = "~/auth.aspx";
                    }

                    Response.Redirect(refererURL, true);
                }

                return;
            }

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

                var loginName = user.DisplayUserName(false);
                ProcessLogout();
                MessageService.Send(HttpContext.Current.Request, loginName, MessageAction.Logout);

                if (!string.IsNullOrEmpty(user.SsoNameId))
                {
                    var settings = SsoSettingsV2.Load();

                    if (settings.EnableSso && !string.IsNullOrEmpty(settings.IdpSettings.SloUrl))
                    {
                        var logoutSsoUserData = Signature.Create(new LogoutSsoUserData
                        {
                            NameId    = user.SsoNameId,
                            SessionId = user.SsoSessionId
                        });

                        HttpContext.Current.Response.Redirect(SetupInfo.SsoSamlLogoutUrl + "?data=" + HttpUtility.UrlEncode(logoutSsoUserData), true);
                    }
                }

                Response.Redirect("~/auth.aspx", true);
            }
            else
            {
                Response.Redirect(CommonLinkUtility.GetDefault(), 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());
        }
示例#26
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;
            }
        }
示例#27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.RegisterStyleControl(VirtualPathUtility.ToAbsolute("~/usercontrols/common/authorize/css/authorize.less"));

            Login    = "";
            Password = "";
            HashId   = "";

            //Account link control
            AccountLinkControl accountLink = null;

            if (SetupInfo.ThirdPartyAuthEnabled && AccountLinkControl.IsNotEmpty)
            {
                accountLink                = (AccountLinkControl)LoadControl(AccountLinkControl.Location);
                accountLink.Visible        = true;
                accountLink.ClientCallback = "authCallback";
                accountLink.SettingsView   = false;
                signInPlaceholder.Controls.Add(accountLink);
            }

            //top panel
            var master = Page.Master as BaseTemplate;

            if (master != null)
            {
                master.TopStudioPanel.DisableProductNavigation = true;
                master.TopStudioPanel.DisableSearch            = true;
                master.TopStudioPanel.DisableVideo             = true;
            }

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

            pwdReminderHolder.Controls.Add(LoadControl(PwdTool.Location));

            var msg = Request["m"];

            if (!string.IsNullOrEmpty(msg))
            {
                ErrorMessage = msg;
            }

            if (IsPostBack && !SecurityContext.IsAuthenticated)
            {
                var tryByHash   = false;
                var smsLoginUrl = string.Empty;
                try
                {
                    if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) && Request["__EVENTTARGET"] == "signInLogin" && accountLink != null)
                    {
                        HashId = Request["__EVENTARGUMENT"];
                    }

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

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


                    var counter = (int)(cache.Get("loginsec/" + Login) ?? 0);
                    if (++counter % 5 == 0)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(10));
                    }
                    cache.Insert("loginsec/" + Login, counter, DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

                    smsLoginUrl = SmsLoginUrl(accountLink);
                    if (string.IsNullOrEmpty(smsLoginUrl))
                    {
                        if (string.IsNullOrEmpty(HashId))
                        {
                            var cookiesKey = SecurityContext.AuthenticateMe(Login, Password);
                            CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                        }
                        else
                        {
                            Guid userId;
                            tryByHash = TryByHashId(accountLink, HashId, out userId);
                            var cookiesKey = SecurityContext.AuthenticateMe(userId);
                            CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                        }
                    }
                }
                catch (InvalidCredentialException)
                {
                    Auth.ProcessLogout();
                    ErrorMessage = tryByHash ? Resource.LoginWithAccountNotFound : Resource.InvalidUsernameOrPassword;
                    return;
                }
                catch (System.Security.SecurityException)
                {
                    Auth.ProcessLogout();
                    ErrorMessage = Resource.ErrorDisabledProfile;
                    return;
                }
                catch (Exception ex)
                {
                    Auth.ProcessLogout();
                    ErrorMessage = ex.Message;
                    return;
                }

                if (!string.IsNullOrEmpty(smsLoginUrl))
                {
                    Response.Redirect(smsLoginUrl);
                }

                var refererURL = (string)Session["refererURL"];
                if (string.IsNullOrEmpty(refererURL))
                {
                    Response.Redirect("~/");
                }
                else
                {
                    Session["refererURL"] = null;
                    Response.Redirect(refererURL);
                }
            }

            ProcessConfirmedEmailCondition();
        }
示例#28
0
        private static void RequestCode(HttpContext context)
        {
            var state = context.Request["state"];

            Global.Logger.Debug("GoogleDriveApp: state - " + state);
            if (string.IsNullOrEmpty(state))
            {
                Global.Logger.Error("GoogleDriveApp: empty state");
                throw new Exception("Empty state");
            }

            var token = GetToken(context.Request["code"]);

            if (token == null)
            {
                Global.Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var stateJson = JObject.Parse(state);

            var googleUserId = stateJson.Value <string>("userId");

            if (SecurityContext.IsAuthenticated)
            {
                if (!CurrentUser(googleUserId))
                {
                    Global.Logger.Debug("GoogleDriveApp: logout for " + googleUserId);
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    SecurityContext.Logout();
                }
            }

            if (!SecurityContext.IsAuthenticated)
            {
                bool isNew;
                var  userInfo = GetUserInfo(token, out isNew);

                if (userInfo == null)
                {
                    Global.Logger.Error("GoogleDriveApp: UserInfo is null");
                    throw new Exception("Profile is null");
                }

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

                if (isNew)
                {
                    UserHelpTourHelper.IsNewUser    = true;
                    PersonalSettings.IsNewUser      = true;
                    PersonalSettings.IsNotActivated = true;
                }

                if (!string.IsNullOrEmpty(googleUserId) && !CurrentUser(googleUserId))
                {
                    AddLinker(googleUserId);
                }
            }

            Token.SaveToken(token);

            var action = stateJson.Value <string>("action");

            switch (action)
            {
            case "create":
                var folderId = stateJson.Value <string>("folderId");

                context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FolderId + "=" + HttpUtility.UrlEncode(folderId), true);
                return;

            case "open":
                var idsArray = stateJson.Value <JArray>("ids") ?? stateJson.Value <JArray>("exportIds");
                if (idsArray == null)
                {
                    Global.Logger.Error("GoogleDriveApp: ids is empty");
                    throw new Exception("File id is null");
                }
                var fileId = idsArray.ToObject <List <string> >().FirstOrDefault();

                var driveFile = GetDriveFile(fileId, token);
                if (driveFile == null)
                {
                    Global.Logger.Error("GoogleDriveApp: file is null");
                    throw new Exception("File not found");
                }

                var jsonFile = JObject.Parse(driveFile);
                var ext      = GetCorrectExt(jsonFile);
                if (FileUtility.ExtsMustConvert.Contains(ext) ||
                    GoogleLoginProvider.GoogleDriveExt.Contains(ext))
                {
                    Global.Logger.Debug("GoogleDriveApp: file must be converted");
                    if (FilesSettings.ConvertNotify)
                    {
                        context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId), true);
                        return;
                    }

                    fileId = CreateConvertedFile(driveFile, token);
                }

                context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
                return;
            }
            Global.Logger.Error("GoogleDriveApp: Action not identified");
            throw new Exception("Action not identified");
        }
        public object SaveData(string email, string pwd, string lng, string promocode, string amiid, bool analytics)
        {
            try
            {
                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = WizardSettings.Load();
                if (settings.Completed)
                {
                    throw new Exception("Wizard passed.");
                }

                if (IsAmi && IncorrectAmiId(amiid))
                {
                    throw new Exception(Resource.EmailAndPasswordIncorrectAmiId);
                }

                if (tenant.OwnerId == Guid.Empty)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(6)); // wait cache interval
                    tenant = CoreContext.TenantManager.GetTenant(tenant.TenantId);
                    if (tenant.OwnerId == Guid.Empty)
                    {
                        LogManager.GetLogger("ASC.Web.FirstTime").Error(tenant.TenantId + ": owner id is empty.");
                    }
                }

                var currentUser = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId);
                var cookie      = SecurityContext.AuthenticateMe(currentUser.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookie);

                if (!UserManagerWrapper.ValidateEmail(email))
                {
                    throw new Exception(Resource.EmailAndPasswordIncorrectEmail);
                }

                UserManagerWrapper.CheckPasswordPolicy(pwd);
                SecurityContext.SetUserPassword(currentUser.ID, pwd);

                email = email.Trim();
                if (currentUser.Email != email)
                {
                    currentUser.Email            = email;
                    currentUser.ActivationStatus = EmployeeActivationStatus.NotActivated;
                }
                CoreContext.UserManager.SaveUserInfo(currentUser);

                if (!string.IsNullOrWhiteSpace(promocode))
                {
                    try
                    {
                        CoreContext.PaymentManager.ActivateKey(promocode);
                    }
                    catch (Exception err)
                    {
                        LogManager.GetLogger("ASC.Web.FirstTime").Error("Incorrect Promo: " + promocode, err);
                        throw new Exception(Resource.EmailAndPasswordIncorrectPromocode);
                    }
                }

                if (RequestLicense)
                {
                    TariffSettings.LicenseAccept = true;
                    MessageService.Send(HttpContext.Current.Request, MessageAction.LicenseKeyUploaded);

                    LicenseReader.RefreshLicense();
                }

                if (TenantExtra.Opensource)
                {
                    settings.Analytics = analytics;
                }
                settings.Completed = true;
                settings.Save();

                TrySetLanguage(tenant, lng);

                StudioNotifyService.Instance.SendCongratulations(currentUser);
                FirstTimeTenantSettings.SendInstallInfo(currentUser);

                return(new { Status = 1, Message = Resource.EmailAndPasswordSaved });
            }
            catch (BillingNotFoundException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseKeyNotFound });
            }
            catch (BillingNotConfiguredException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseKeyNotCorrect });
            }
            catch (BillingException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseException });
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("ASC.Web.FirstTime").Error(ex);
                return(new { Status = 0, Message = ex.Message });
            }
        }
        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 loginProfile = Request.Url.GetProfile();

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

            string cookiesKey;

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

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

                var userInfo = GetUserByThirdParty(loginProfile);
                if (!CoreContext.UserManager.UserExists(userInfo.ID))
                {
                    return;
                }

                cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccessViaSocialAccount);
            }
            catch (System.Security.SecurityException)
            {
                LoginMessage = Resource.InvalidUsernameOrPassword;
                MessageService.Send(HttpContext.Current.Request, loginProfile != null ? loginProfile.EMail : AuditResource.EmailNotSpecified, MessageAction.LoginFailDisabledProfile);
                return;
            }
            catch (Exception exception)
            {
                LoginMessage = exception.Message;
                MessageService.Send(HttpContext.Current.Request, AuditResource.EmailNotSpecified, MessageAction.LoginFail);
                return;
            }

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

            if (String.IsNullOrEmpty(refererURL))
            {
                refererURL = CommonLinkUtility.GetDefault();
            }
            if (Request.DesktopApp())
            {
                refererURL += (refererURL.Contains("?") ? "&" : "?") + "token=" + HttpUtility.HtmlEncode(cookiesKey);
            }

            Session["refererURL"] = null;
            Response.Redirect(refererURL);
        }