예제 #1
0
        private static String GetModuleResource(String resourceClassTypeName, String resourseKey)
        {
            if (string.IsNullOrEmpty(resourseKey))
            {
                return(string.Empty);
            }
            try
            {
                var type = Type.GetType(resourceClassTypeName);

                var resManager =
                    (ResourceManager)type.InvokeMember(
                        "resourceMan",
                        BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public, null, type, null);

                //custom
                if (!SecurityContext.IsAuthenticated)
                {
                    SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey));
                }
                var u       = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
                var culture = !string.IsNullOrEmpty(u.CultureName)
                                  ? CultureInfo.GetCultureInfo(u.CultureName)
                                  : CoreContext.TenantManager.GetCurrentTenant().GetCulture();
                return(resManager.GetString(resourseKey, culture));
            }
            catch (Exception)
            {
                return(String.Empty);
            }
        }
예제 #2
0
        public int GetLoginEventIdFromCookie()
        {
            var cookie       = CookiesManager.GetCookies(CookiesType.AuthKey);
            int loginEventId = CookieStorage.GetLoginEventIdFromCookie(cookie);

            return(loginEventId);
        }
예제 #3
0
 private void CheckPermission()
 {
     if (!SecurityContext.IsAuthenticated)
     {
         try
         {
             if (!TenantExtra.GetTenantQuota().HasBackup)
             {
                 throw new Exception(Resource.ErrorNotAllowedOption);
             }
             if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
             {
                 throw GenerateException(HttpStatusCode.Unauthorized, "Unauthorized", null);
             }
             else
             {
                 if (!CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, ASC.Core.Users.Constants.GroupAdmin.ID))
                 {
                     throw GenerateException(HttpStatusCode.Unauthorized, "Permission denied", null);
                 }
             }
         }
         catch (Exception exception)
         {
             throw GenerateException(HttpStatusCode.Unauthorized, "Unauthorized", exception);
         }
     }
 }
예제 #4
0
        private static String GetModuleResource(string typeName, string key)
        {
            try
            {
                var type    = Type.GetType(typeName, true);
                var manager = (ResourceManager)type.InvokeMember(
                    "resourceMan",
                    BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public, null, type, null);

                //custom
                if (!SecurityContext.IsAuthenticated)
                {
                    SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey));
                }

                var u       = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
                var culture = !string.IsNullOrEmpty(u.CultureName) ? CultureInfo.GetCultureInfo(u.CultureName) : CoreContext.TenantManager.GetCurrentTenant().GetCulture();
                return(manager.GetString(key, culture));
            }
            catch (Exception err)
            {
                LogManager.GetLogger("ASC.Web.Template").Error(err);
                return(string.Empty);
            }
        }
예제 #5
0
        public override void OnProcessRequest(HttpContext context)
        {
            var action = context.Request[UrlConstant.Action].ToLower();

            var securityActions = new[] { "upload", "view", "download", "bulk", "save" };
            var publicActions   = new[] { "download", "view", "bulk" };

            if (securityActions.Contains(action) && !SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
            {
                if (publicActions.Contains(action) && string.IsNullOrEmpty(context.Request[UrlConstant.DocUrlKey]))
                {
                    if (!CoreContext.TenantManager.GetCurrentTenant().Public)
                    {
                        context.Response.Redirect("~/auth.aspx");
                        return;
                    }
                }
                else
                {
                    if (DocumentUtils.ParseShareLink(context.Request[UrlConstant.DocUrlKey]) == null)
                    {
                        throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                    }
                }
            }

            switch (action)
            {
            case "upload":
                UploadFile(context);
                break;

            case "view":
                DownloadFile(context, true);
                break;

            case "download":
                DownloadFile(context, false);
                break;

            case "bulk":
                BulkDownloadFile(context);
                break;

            case "save":
                SaveFile(context);
                break;

            case "stream":
                StreamFile(context);
                break;

            case "create":
                CreateFile(context);
                break;

            default:
                throw new InvalidOperationException();
            }
        }
예제 #6
0
        public void ProcessRequest(HttpContext context)
        {
            if (!SecurityContext.IsAuthenticated)
            {
                if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    context.Response.End();
                    return;
                }
            }

            context.Response.Clear();
            if (string.IsNullOrEmpty(context.Request["file"]))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.End();
                return;
            }

            var file = GetFile(context.Request["file"]);

            if (file == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.End();
                return;
            }
            if (string.IsNullOrEmpty(file.FileLocation))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.End();
                return;
            }

            var inline = context.Request["inline"] ?? string.Empty;

            var storage = StorageFactory.GetStorage(CoreContext.TenantManager.GetCurrentTenant().TenantId.ToString(), WikiSection.Section.DataStorage.ModuleName);

            if (inline.ToLowerInvariant() == "true")
            {
                context.Response.Redirect(storage.GetUri(WikiSection.Section.DataStorage.DefaultDomain, file.FileLocation).ToString());
            }
            else
            {
                context.Response.ContentType = MimeMapping.GetMimeMapping(file.FileName);
                context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", file.FileName));

                using (var stream = storage.GetReadStream(WikiSection.Section.DataStorage.DefaultDomain, file.FileLocation))
                {
                    context.Response.AddHeader("Content-Length", stream.Length.ToString());
                    stream.CopyTo(context.Response.OutputStream);
                }
            }
        }
        private static void BulkDownloadFile(HttpContext context)
        {
            if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }

            var store = Global.GetStore();
            var path  = string.Format(@"{0}\{1}.zip", SecurityContext.CurrentAccount.ID, FileConstant.DownloadTitle);

            if (!store.IsFile(FileConstant.StorageDomainTmp, path))
            {
                Global.Logger.ErrorFormat("BulkDownload file error. File is not exist on storage. UserId: {0}.", SecurityContext.CurrentAccount.ID);
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }

            if (store.IsSupportedPreSignedUri)
            {
                var url = store.GetPreSignedUri(FileConstant.StorageDomainTmp, path, TimeSpan.FromHours(1), null).ToString();
                context.Response.Redirect(url);
                return;
            }

            context.Response.Clear();

            try
            {
                bool flushed = false;
                using (var readStream = store.GetReadStream(FileConstant.StorageDomainTmp, path))
                {
                    long offset = 0;
                    long length = readStream.Length;
                    if (readStream.CanSeek)
                    {
                        length = ProcessRangeHeader(context, readStream.Length, ref offset);
                        readStream.Seek(offset, SeekOrigin.Begin);
                    }

                    SendStreamByChunks(context, length, FileConstant.DownloadTitle + ".zip", readStream, ref flushed);
                }

                context.Response.Flush();
                context.Response.SuppressContent = true;
                context.ApplicationInstance.CompleteRequest();
            }
            catch (Exception e)
            {
                Global.Logger.ErrorFormat("BulkDownloadFile failed for user {0} with error: ", SecurityContext.CurrentAccount.ID, e.Message);
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }
        }
        private void Authenticate()
        {
            var tenant = CoreContext.TenantManager.GetCurrentTenant(false);

            if (tenant != null && !SecurityContext.IsAuthenticated)
            {
                var cookie = CookiesManager.GetCookies(CookiesType.AuthKey);
                if (!string.IsNullOrEmpty(cookie))
                {
                    SecurityContext.AuthenticateMe(cookie);
                }
            }
        }
예제 #9
0
        public static bool Authenticate()
        {
            var tenant = CoreContext.TenantManager.GetCurrentTenant(false);

            if (tenant != null && !SecurityContext.IsAuthenticated)
            {
                var cookie = CookiesManager.GetCookies(CookiesType.AuthKey);
                if (!string.IsNullOrEmpty(cookie))
                {
                    return(SecurityContext.AuthenticateMe(cookie));
                }
            }
            return(false);
        }
예제 #10
0
        private static bool AuthByCookies()
        {
            var cookiesKey = CookiesManager.GetCookies(CookiesType.AuthKey);
            if (string.IsNullOrEmpty(cookiesKey)) return false;

            try
            {
                if (SecurityContext.AuthenticateMe(cookiesKey)) return true;
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("AutoAuthByCookies Error {0}", ex);
            }

            return false;
        }
예제 #11
0
        private bool AjaxCheckMethodPermissions(MethodInfo method)
        {
            var authorized = SecurityContext.IsAuthenticated;

            if (!authorized && HttpContext.Current != null)
            {
                authorized = method.GetCustomAttributes(typeof(AjaxSecurityAttribute), true)
                             .Cast <AjaxSecurityAttribute>()
                             .Any(a => a.CheckAuthorization(HttpContext.Current));
                if (!authorized)
                {
                    authorized = SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey));
                }
            }
            return(authorized);
        }
예제 #12
0
        private static void Redirect(HttpContext context)
        {
            if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }
            var urlRedirect = string.Empty;
            int id;
            var folderId = context.Request[FilesLinkUtility.FolderId];

            if (!string.IsNullOrEmpty(folderId) && int.TryParse(folderId, out id))
            {
                try
                {
                    urlRedirect = PathProvider.GetFolderUrl(id);
                }
                catch (ArgumentNullException e)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
                }
            }

            var fileId = context.Request[FilesLinkUtility.FileId];

            if (!string.IsNullOrEmpty(fileId) && int.TryParse(fileId, out id))
            {
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    var file = fileDao.GetFile(id);
                    if (file == null)
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                        return;
                    }

                    urlRedirect = FilesLinkUtility.GetFileWebPreviewUrl(file.Title, file.ID);
                }
            }

            if (string.IsNullOrEmpty(urlRedirect))
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, FilesCommonResource.ErrorMassage_BadRequest);
            }
            context.Response.Redirect(urlRedirect);
        }
예제 #13
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);
        }
예제 #14
0
        private static void BulkDownloadFile(HttpContext context)
        {
            if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
            {
                context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                return;
            }

            var store = Global.GetStore();
            var path  = string.Format(@"{0}\{1}.zip", SecurityContext.CurrentAccount.ID, FileConstant.DownloadTitle);

            if (!store.IsFile(FileConstant.StorageDomainTmp, path))
            {
                Global.Logger.ErrorFormat("BulkDownload file error. File is not exist on storage. UserId: {0}.", SecurityContext.CurrentAccount.ID);
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            }
            else
            {
                if (store is S3Storage)
                {
                    var url = store.GetPreSignedUri(FileConstant.StorageDomainTmp, path, TimeSpan.FromHours(1), null).ToString();
                    context.Response.Redirect(url);
                }
                else
                {
                    context.Response.Clear();
                    context.Response.ContentType = "application/zip";
                    context.Response.AddHeader("Content-Disposition", ContentDispositionUtil.GetHeaderValue(FileConstant.DownloadTitle + ".zip"));

                    using (var readStream = store.IronReadStream(FileConstant.StorageDomainTmp, path, 40))
                    {
                        context.Response.AddHeader("Content-Length", readStream.Length.ToString());
                        readStream.StreamCopyTo(context.Response.OutputStream);
                    }
                    try
                    {
                        context.Response.Flush();
                        context.Response.End();
                    }
                    catch (HttpException)
                    {
                    }
                }
            }
        }
예제 #15
0
        public void BeginGetResponse()
        {
            var request = (HttpWebRequest)WebRequest.Create(CommonLinkUtility.GetFullAbsolutePath(RequestUrl));

            request.Headers.Add("Authorization", CookiesManager.GetCookies(CookiesType.AuthKey));
            request.Method      = RequestMethod;
            request.ContentType = "application/x-www-form-urlencoded";

            request.ContentLength = RequestBody.Length;

            var getRequestStream = request.BeginGetRequestStream(null, null);
            var writer           = new StreamWriter(request.EndGetRequestStream(getRequestStream));

            writer.Write(RequestBody);
            writer.Close();

            request.BeginGetResponse(OnAsyncCallback, request);
        }
예제 #16
0
 private static bool ProcessAuthorization(HttpContext context)
 {
     if (!SecurityContext.IsAuthenticated)
     {
         try
         {
             var cookiesKey = CookiesManager.GetCookies(CookiesType.AuthKey);
             if (!SecurityContext.AuthenticateMe(cookiesKey))
             {
                 throw new UnauthorizedAccessException();
             }
         }
         catch (Exception)
         {
             return AuthorizationHelper.ProcessBasicAuthorization(context);
         }
     }
     return SecurityContext.IsAuthenticated;
 }
예제 #17
0
 private static bool ProcessAuthorization(HttpContext context)
 {
     if (!SecurityContext.IsAuthenticated)
     {
         //Try studio auth
         try
         {
             var cookiesKey = CookiesManager.GetCookies(CookiesType.AuthKey);
             if (!SecurityContext.AuthenticateMe(cookiesKey))
             {
                 throw new UnauthorizedAccessException();
             }
         }
         catch (Exception)
         {
         }
     }
     return(SecurityContext.IsAuthenticated);
 }
예제 #18
0
        public void ProcessRequest(HttpContext context)
        {
            if (!SecurityContext.IsAuthenticated)
            {
                if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    context.Response.End();
                    return;
                }
            }

            context.Response.Clear();
            if (string.IsNullOrEmpty(context.Request["file"]))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.End();
                return;
            }

            var file = new WikiEngine().GetFile(context.Request["file"]);

            if (file == null)
            {
                file = new WikiEngine().GetFile(context.Request["file"].Replace('_', ' '));
                if (file == null)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    context.Response.End();
                    return;
                }
            }
            if (string.IsNullOrEmpty(file.FileLocation))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.End();
                return;
            }

            var storage = StorageFactory.GetStorage(CoreContext.TenantManager.GetCurrentTenant().TenantId.ToString(), WikiSection.Section.DataStorage.ModuleName);

            context.Response.Redirect(storage.GetUri(WikiSection.Section.DataStorage.DefaultDomain, file.FileLocation).OriginalString);
        }
예제 #19
0
        private void ProcessSmsValidation(UserTransferData uData)
        {
            var smsAuthSettings = SettingsManager.Instance.LoadSettings <StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID);

            if (smsAuthSettings.Enable && SetupInfo.IsVisibleSettings <StudioSmsNotificationSettings>())
            {
                var confKey   = CookiesManager.GetCookies(CookiesType.ConfKey);
                var activated = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).MobilePhoneActivationStatus;

                if (!String.IsNullOrEmpty(confKey) && EmailValidationKeyProvider.ValidateEmailKey(CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).Email, confKey, TimeSpan.FromDays(30)) == EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    return;
                }

                uData.MobilePhoneActivationStatus = activated;
                uData.ValidationKey         = EmailValidationKeyProvider.GetEmailKey(GetEmailKey(uData, activated));
                Session["UserTransferData"] = uData;
                ProcessLogout();
                Response.Redirect(String.Format("~/Confirm.aspx?type={0}", activated == MobilePhoneActivationStatus.Activated ? ConfirmType.PhoneAuth : ConfirmType.PhoneActivation));
            }
        }
예제 #20
0
        public AjaxResponse ShowRecentActivity(Guid productId, List <Guid> moduleIds, string strFromDate, string strToDate, int type, int currentPage, Guid userOrDeptID)
        {
            if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
            {
                throw new UnauthorizedAccessException("Unauthorized");
            }

            var resp = new AjaxResponse();

            var fromDate   = Convert.ToDateTime(strFromDate);
            var toDate     = Convert.ToDateTime(strToDate);
            var actionType = UserActivityConstants.ActivityActionType;

            if (type == 0)
            {
                actionType = UserActivityConstants.AllActionType;
            }
            if (type == 1)
            {
                actionType = UserActivityConstants.ContentActionType;
            }

            var userActivity = UserActivityManager.GetUserActivities(
                TenantProvider.CurrentTenantID,
                userOrDeptID,
                productId,
                moduleIds,
                actionType,
                null,
                fromDate,
                toDate.AddDays(1));

            var activityContainer = userActivity.ConvertAll(rec => new ActivityContainer
            {
                UserProfileLink = ASC.Core.Users.StudioUserInfoExtension.RenderProfileLink(ASC.Core.CoreContext.UserManager.GetUsers(rec.UserID), rec.ProductID),
                ActionText      = rec.ActionText.ToLower(),
                URL             = CommonLinkUtility.GetFullAbsolutePath(rec.URL),
                Title           = rec.Title.HtmlEncode(),
                ModuleName      = GetModuleName(rec),
                ModuleIconUrl   = GetModuleIconUrl(rec),
                Date            = rec.Date.ToString(DateTimeExtension.DateFormatPattern),
                AgoSentence     = GetAgoSentence(rec.Date)
            });


            var CountShowOnPage = 15;

            var countTotal = activityContainer.Count;
            var amountPage = Convert.ToInt32(Math.Ceiling(countTotal / (CountShowOnPage * 1.0)));

            currentPage = currentPage > 0 ? currentPage : 1;
            if (amountPage != 0)
            {
                currentPage = currentPage <= amountPage ? currentPage : amountPage;
            }

            resp.rs10 = "5"; //CountVisiblePage
            resp.rs11 = amountPage.ToString();
            resp.rs12 = currentPage.ToString();
            resp.rs13 = Resource.BackButton;
            resp.rs14 = Resource.NextButton;

            var result = new List <ActivityContainer>();

            for (var i = (currentPage - 1) * CountShowOnPage; i < currentPage * CountShowOnPage && i < activityContainer.Count; i++)
            {
                result.Add(activityContainer[i]);
            }

            resp.rs1 = JavaScriptSerializer.Serialize(result);
            return(resp);
        }
예제 #21
0
        protected void Page_PreInit(object sender, EventArgs e)
        {
            //check if cookie from this portal
            if (SecurityContext.CurrentAccount is IUserAccount &&
                ((IUserAccount)SecurityContext.CurrentAccount).Tenant != CoreContext.TenantManager.GetCurrentTenant().TenantId)
            {
                SecurityContext.Logout();
                Response.Redirect("~/");
            }

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

            if (currentUser == Constants.LostUser || currentUser.Status != EmployeeStatus.Active)
            {
                SecurityContext.Logout();
                Response.Redirect("~/");
            }

            ProcessSecureFilter();

            var wizardSettings = SettingsManager.Instance.LoadSettings <WizardSettings>(TenantProvider.CurrentTenantID);

            if (Request["first"] == "1" && !string.IsNullOrEmpty(Request["id"]) && wizardSettings.Completed)
            {
                // wizardSettings.Completed - open source, Request["first"] - cloud
                wizardSettings.Completed = false;
                SettingsManager.Instance.SaveSettings(wizardSettings, TenantProvider.CurrentTenantID);
            }

            var smsAuthSettings = SettingsManager.Instance.LoadSettings <StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID);

            if (!wizardSettings.Completed && !(this is confirm))
            {
                var successAuth = SecurityContext.IsAuthenticated;
                if (!successAuth)
                {
                    var cookie = Request["id"] ?? CookiesManager.GetCookies(CookiesType.AuthKey);
                    if (!string.IsNullOrEmpty(cookie))
                    {
                        successAuth = AuthByCookies(cookie);
                    }
                    if (!successAuth)
                    {
                        try
                        {
                            cookie      = SecurityContext.AuthenticateMe(UserManagerWrapper.AdminID.ToString(), "admin");
                            successAuth = true;
                        }
                        catch (System.Security.SecurityException)
                        {
                        }
                    }
                    if (successAuth)
                    {
                        CookiesManager.SetCookies(CookiesType.AuthKey, cookie);
                        WebItemManager.Instance.ItemGlobalHandlers.Login(SecurityContext.CurrentAccount.ID);
                    }
                }
                if (!successAuth && !(this is Auth))
                {
                    Response.Redirect("~/auth.aspx");
                }
                if (successAuth && !(this is Wizard))
                {
                    Response.Redirect("~/wizard.aspx");
                }
            }
            else if (smsAuthSettings.Enable && Session["UserTransferData"] != null && !(this is confirm))
            {
                Response.Redirect(String.Format("~/Confirm.aspx?type={0}", ((UserTransferData)Session["UserTransferData"]).MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated ? ConfirmType.PhoneActivation : ConfirmType.PhoneAuth));
            }

            else if (!SecurityContext.IsAuthenticated && wizardSettings.Completed && !(this is confirm))
            {
                //for demo
                if (SetupInfo.WorkMode == WorkMode.Promo)
                {
                    if (AutoAuthByPromo())
                    {
                        UserOnlineManager.Instance.RegistryOnlineUser(SecurityContext.CurrentAccount.ID);

                        Response.Redirect("~/");
                        return;
                    }
                }

                if (this is Auth && Session["refererURL"] == null && !string.IsNullOrEmpty(HttpContext.Current.Request.Params["id"]))
                {
                    var authCookie = HttpContext.Current.Request.Params["id"];
                    if (AuthByCookies(authCookie))
                    {
                        CookiesManager.SetCookies(CookiesType.AuthKey, authCookie);
                        var first = Request["first"] == "1";
                        if (first)
                        {
                            try
                            {
                                var tenant = CoreContext.TenantManager.GetCurrentTenant(false);
                                tenant.Name = Resources.Resource.StudioWelcomeHeader;
                                CoreContext.TenantManager.SaveTenant(tenant);
                            }
                            catch
                            {
                            }
                        }
                        Response.Redirect(VirtualPathUtility.ToAbsolute("~/") + (first ? "?first=1" : ""));
                        return;
                    }
                }

                if (!(this is Auth))
                {
                    var refererURL = Request.Url.AbsoluteUri;
                    if (!ValidateRefererUrl(refererURL))
                    {
                        refererURL = (string)Session["refererURL"];
                    }

                    if (!AutoAuthByCookies() && !CoreContext.TenantManager.GetCurrentTenant().Public)
                    {
                        Session["refererURL"] = refererURL;
                        Response.Redirect("~/auth.aspx");
                        return;
                    }
                }
            }

            else if (SecurityContext.IsAuthenticated && this is Auth && !this.IsLogout)
            {
                Response.Redirect("~/");
                return;
            }

            else if (this is Wizard && wizardSettings.Completed)
            {
                Response.Redirect("~/");
                return;
            }

            //check disable and public
            var webitem = CommonLinkUtility.GetWebItemByUrl(Request.Url.ToString());

            if (webitem != null && webitem.IsDisabled())
            {
                Response.Redirect("~/");
                return;
            }


            if (SecurityContext.IsAuthenticated)
            {
                UserOnlineManager.Instance.RegistryOnlineUser(SecurityContext.CurrentAccount.ID);

                try
                {
                    StatisticManager.SaveUserVisit(TenantProvider.CurrentTenantID, SecurityContext.CurrentAccount.ID, CommonLinkUtility.GetProductID());
                }
                catch (Exception exc)
                {
                    Log.Error("failed save user visit", exc);
                }
            }

            CurrentSkin = WebSkin.GetUserSkin();
            Theme       = CurrentSkin.ASPTheme;


            #region Init common javascript resources

            var commonJavascriptResources = "CommonJavascriptResources";
            if (!Page.ClientScript.IsClientScriptBlockRegistered(commonJavascriptResources))
            {
                var script = string.Format(@"
var CommonJavascriptResources = {{
	CancelConfirmMessage : '{0}'
}};", Resources.Resource.CancelConfirmMessage.ReplaceSingleQuote());
                Page.ClientScript.RegisterClientScriptBlock(typeof(string), commonJavascriptResources, script, true);
            }

            #endregion

            PersonalHelper.TransferRequest(this);
        }
예제 #22
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            if (!ASC.Core.SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
            {
                return(new FileUploadResult
                {
                    Success = false,
                    Message = "Permission denied"
                });
            }

            var result = "";

            try
            {
                if (ProgressFileUploader.HasFilesToUpload(context))
                {
                    var postedFile  = new ProgressFileUploader.FileToUpload(context);
                    var fileName    = postedFile.FileName;
                    var inputStream = postedFile.InputStream;


                    var store   = Data.Storage.StorageFactory.GetStorage(TenantProvider.CurrentTenantID.ToString(), "photo");
                    var storage = StorageFactory.GetStorage();

                    var uid     = context.Request["uid"];
                    var eventID = context.Request["eventID"];

                    var albums = storage.GetAlbums(Convert.ToInt64(eventID), uid);

                    var currentAlbum = 0 < albums.Count ? albums[0] : null;

                    if (currentAlbum == null)
                    {
                        var Event = storage.GetEvent(Convert.ToInt64(eventID));

                        currentAlbum = new Album
                        {
                            Event  = Event,
                            UserID = uid
                        };

                        storage.SaveAlbum(currentAlbum);
                    }

                    if (context.Session["photo_albumid"] != null)
                    {
                        context.Session["photo_albumid"] = currentAlbum.Id;
                    }

                    var fileNamePath = PhotoConst.ImagesPath + uid + "/" + currentAlbum.Id + "/";

                    var currentImageInfo = new ImageInfo();

                    var listFiles = store.ListFilesRelative("", fileNamePath, "*.*", false);
                    context.Session["photo_listFiles"] = listFiles;

                    var fileExtension            = FileUtility.GetFileExtension(fileName);
                    var fileNameWithOutExtension = GetFileName(fileName);
                    var addSuffix = string.Empty;

                    //if file already exists
                    var i = 1;

                    while (CheckFile(listFiles, fileNameWithOutExtension + addSuffix + PhotoConst.THUMB_SUFFIX + fileExtension))
                    {
                        addSuffix = "(" + i.ToString() + ")";
                        i++;
                    }

                    var fileNameThumb   = fileNamePath + fileNameWithOutExtension + addSuffix + PhotoConst.THUMB_SUFFIX + "." + PhotoConst.jpeg_extension;
                    var fileNamePreview = fileNamePath + fileNameWithOutExtension + addSuffix + PhotoConst.PREVIEW_SUFFIX + "." + PhotoConst.jpeg_extension;

                    currentImageInfo.Name          = fileNameWithOutExtension;
                    currentImageInfo.PreviewPath   = fileNamePreview;
                    currentImageInfo.ThumbnailPath = fileNameThumb;

                    var fs = inputStream;

                    try
                    {
                        var reader = new EXIFReader(fs);
                        currentImageInfo.ActionDate = (string)reader[PropertyTagId.DateTime];
                    }
                    catch
                    {
                    }

                    ImageHelper.GenerateThumbnail(fs, fileNameThumb, ref currentImageInfo, store);
                    ImageHelper.GeneratePreview(fs, fileNamePreview, ref currentImageInfo, store);

                    fs.Dispose();

                    var image = new AlbumItem(currentAlbum)
                    {
                        Name          = currentImageInfo.Name,
                        Timestamp     = ASC.Core.Tenants.TenantUtil.DateTimeNow(),
                        UserID        = uid,
                        Location      = currentImageInfo.Name,
                        PreviewSize   = new Size(currentImageInfo.PreviewWidth, currentImageInfo.PreviewHeight),
                        ThumbnailSize = new Size(currentImageInfo.ThumbnailWidth, currentImageInfo.ThumbnailHeight)
                    };

                    storage.SaveAlbumItem(image);

                    currentAlbum.FaceItem = image;
                    storage.SaveAlbum(currentAlbum);

                    var response = image.Id.ToString();

                    var byteArray = System.Text.Encoding.UTF8.GetBytes(response);
                    result = Convert.ToBase64String(byteArray);
                }
            }
            catch (Exception ex)
            {
                return(new FileUploadResult
                {
                    Success = false,
                    Message = ex.Message,
                });
            }

            return(new FileUploadResult
            {
                Success = true,
                Data = "",
                Message = result
            });
        }
예제 #23
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            var            fileName   = string.Empty;
            MailAttachment attachment = null;

            try
            {
                if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
                {
                    throw new UnauthorizedAccessException(MailResource.AttachemntsUnauthorizedError);
                }

                if (FileToUpload.HasFilesToUpload(context))
                {
                    try
                    {
                        var streamId = context.Request["stream"];
                        var mailId   = Convert.ToInt32(context.Request["messageId"]);
                        var copyToMy = Convert.ToInt32(context.Request["copyToMy"]);

                        if (string.IsNullOrEmpty(streamId))
                        {
                            throw new AttachmentsException(AttachmentsException.Types.BadParams, "Have no stream");
                        }
                        if (mailId < 1)
                        {
                            throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "Message not yet saved!");
                        }

                        var postedFile = new FileToUpload(context);
                        fileName = context.Request["name"];

                        if (copyToMy == 1)
                        {
                            var uploadedFile = FileUploader.Exec(Global.FolderMy.ToString(), fileName, postedFile.ContentLength, postedFile.InputStream, true);
                            return(new FileUploadResult
                            {
                                Success = true,
                                FileName = uploadedFile.Title,
                                FileURL = FilesLinkUtility.GetFileWebPreviewUrl(uploadedFile.Title, uploadedFile.ID),
                                Data = new MailAttachment
                                {
                                    fileId = Convert.ToInt32(uploadedFile.ID),
                                    fileName = uploadedFile.Title,
                                    size = uploadedFile.ContentLength,
                                    contentType = uploadedFile.ConvertedType,
                                    attachedAsLink = true,
                                    tenant = TenantId,
                                    user = Username
                                }
                            });
                        }

                        attachment = new MailAttachment
                        {
                            fileId   = -1,
                            size     = postedFile.ContentLength,
                            fileName = fileName,
                            streamId = streamId,
                            tenant   = TenantId,
                            user     = Username
                        };

                        attachment = MailBoxManager.AttachFile(TenantId, Username, mailId, fileName, postedFile.InputStream, streamId);

                        return(new FileUploadResult
                        {
                            Success = true,
                            FileName = attachment.fileName,
                            FileURL = attachment.storedFileUrl,
                            Data = attachment
                        });
                    }
                    catch (AttachmentsException e)
                    {
                        string errorMessage;

                        switch (e.ErrorType)
                        {
                        case AttachmentsException.Types.BadParams:
                            errorMessage = MailScriptResource.AttachmentsBadInputParamsError;
                            break;

                        case AttachmentsException.Types.EmptyFile:
                            errorMessage = MailScriptResource.AttachmentsEmptyFileNotSupportedError;
                            break;

                        case AttachmentsException.Types.MessageNotFound:
                            errorMessage = MailScriptResource.AttachmentsMessageNotFoundError;
                            break;

                        case AttachmentsException.Types.TotalSizeExceeded:
                            errorMessage = MailScriptResource.AttachmentsTotalLimitError;
                            break;

                        case AttachmentsException.Types.DocumentNotFound:
                            errorMessage = MailScriptResource.AttachmentsDocumentNotFoundError;
                            break;

                        case AttachmentsException.Types.DocumentAccessDenied:
                            errorMessage = MailScriptResource.AttachmentsDocumentAccessDeniedError;
                            break;

                        default:
                            errorMessage = MailScriptResource.AttachmentsUnknownError;
                            break;
                        }
                        throw new Exception(errorMessage);
                    }
                    catch (ASC.Core.Tenants.TenantQuotaException)
                    {
                        throw;
                    }
                    catch (Exception)
                    {
                        throw new Exception(MailScriptResource.AttachmentsUnknownError);
                    }
                }
                throw new Exception(MailScriptResource.AttachmentsBadInputParamsError);
            }
            catch (Exception ex)
            {
                return(new FileUploadResult
                {
                    Success = false,
                    FileName = fileName,
                    Data = attachment,
                    Message = ex.Message,
                });
            }
        }
예제 #24
0
 protected static bool AutoAuthByCookies()
 {
     return(AuthByCookies(CookiesManager.GetCookies(CookiesType.AuthKey)));
 }
예제 #25
0
        public override void OnProcessRequest(HttpContext context)
        {
            var action = context.Request[CommonLinkUtility.Action];

            if (string.IsNullOrEmpty(action))
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, FilesCommonResource.ErrorMassage_BadRequest);
            }

            action = action.ToLower();

            var publicActions = new[] { "view", "download", "save", "stream" };

            if (!publicActions.Contains(action) &&
                !SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
            {
                context.Response.Redirect("~/");
                return;
            }

            if (TenantStatisticsProvider.IsNotPaid())
            {
                context.Response.Redirect(TenantExtra.GetTariffPageLink());
            }

            try
            {
                switch (action)
                {
                case "view":
                    DownloadFile(context, true);
                    break;

                case "download":
                    DownloadFile(context, false);
                    break;

                case "bulk":
                    BulkDownloadFile(context);
                    break;

                case "save":
                    SaveFile(context);
                    break;

                case "stream":
                    StreamFile(context);
                    break;

                case "create":
                    CreateFile(context);
                    break;

                case "redirect":
                    Redirect(context);
                    break;

                default:
                    throw new InvalidOperationException();
                }
            }
            catch (InvalidOperationException e)
            {
                throw new HttpException((int)HttpStatusCode.InternalServerError, FilesCommonResource.ErrorMassage_BadRequest, e);
            }
        }
예제 #26
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            var            file_name  = string.Empty;
            MailAttachment attachment = null;

            try
            {
                if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
                {
                    throw new UnauthorizedAccessException(MailResource.AttachemntsUnauthorizedError);
                }

                if (FileToUpload.HasFilesToUpload(context))
                {
                    try
                    {
                        var stream_id = context.Request["stream"];
                        var mail_id   = Convert.ToInt32(context.Request["messageId"]);

                        if (mail_id < 1)
                        {
                            throw new AttachmentsException(AttachmentsException.Types.MESSAGE_NOT_FOUND,
                                                           "Message not yet saved!");
                        }

                        if (String.IsNullOrEmpty(stream_id))
                        {
                            throw new AttachmentsException(AttachmentsException.Types.BAD_PARAMS, "Have no stream");
                        }

                        var posted_file = new FileToUpload(context);

                        file_name = context.Request["name"];

                        attachment = new MailAttachment
                        {
                            fileId   = -1,
                            size     = posted_file.ContentLength,
                            fileName = file_name,
                            streamId = stream_id,
                            tenant   = TenantId,
                            user     = Username
                        };

                        attachment = _mailBoxManager.AttachFile(TenantId, Username, mail_id,
                                                                file_name, posted_file.InputStream, stream_id);

                        return(new FileUploadResult
                        {
                            Success = true,
                            FileName = attachment.fileName,
                            FileURL = attachment.storedFileUrl,
                            Data = attachment
                        });
                    }
                    catch (AttachmentsException e)
                    {
                        string error_message;

                        switch (e.ErrorType)
                        {
                        case AttachmentsException.Types.BAD_PARAMS:
                            error_message = MailScriptResource.AttachmentsBadInputParamsError;
                            break;

                        case AttachmentsException.Types.EMPTY_FILE:
                            error_message = MailScriptResource.AttachmentsEmptyFileNotSupportedError;
                            break;

                        case AttachmentsException.Types.MESSAGE_NOT_FOUND:
                            error_message = MailScriptResource.AttachmentsMessageNotFoundError;
                            break;

                        case AttachmentsException.Types.TOTAL_SIZE_EXCEEDED:
                            error_message = MailScriptResource.AttachmentsTotalLimitError;
                            break;

                        case AttachmentsException.Types.DOCUMENT_NOT_FOUND:
                            error_message = MailScriptResource.AttachmentsDocumentNotFoundError;
                            break;

                        case AttachmentsException.Types.DOCUMENT_ACCESS_DENIED:
                            error_message = MailScriptResource.AttachmentsDocumentAccessDeniedError;
                            break;

                        default:
                            error_message = MailScriptResource.AttachmentsUnknownError;
                            break;
                        }
                        throw new Exception(error_message);
                    }
                    catch (ASC.Core.Tenants.TenantQuotaException)
                    {
                        throw;
                    }
                    catch (Exception)
                    {
                        throw new Exception(MailScriptResource.AttachmentsUnknownError);
                    }
                }
                throw new Exception(MailScriptResource.AttachmentsBadInputParamsError);
            }
            catch (Exception ex)
            {
                return(new FileUploadResult
                {
                    Success = false,
                    FileName = file_name,
                    Data = attachment,
                    Message = ex.Message,
                });
            }
        }
예제 #27
0
 protected Boolean isMinimized()
 {
     return(!String.IsNullOrEmpty(CookiesManager.GetCookies(CookiesType.MinimizedNavpanel)));
 }
예제 #28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var thirdPartyChat = ConfigurationManagerExtension.AppSettings["web.third-party-chat-url"];
            var isEnabledTalk  = ConfigurationManagerExtension.AppSettings["web.talk"] ?? "false";

            if (!String.IsNullOrEmpty(thirdPartyChat))
            {
                if (CoreContext.Configuration.CustomMode)
                {
                    Response.Redirect(thirdPartyChat + "?ask_key=" + HttpUtility.UrlEncode(CookiesManager.GetCookies(CookiesType.AuthKey)), true);
                }
                Response.Redirect(thirdPartyChat, true);
            }

            if (isEnabledTalk != "true")
            {
                Response.Redirect(CommonLinkUtility.GetDefault());
            }

            _cfg = new TalkConfiguration();

            Utility.RegisterTypeForAjax(GetType());

            Master.DisabledSidePanel      = true;
            Master.DisabledTopStudioPanel = true;

            Page
            .RegisterBodyScripts("~/addons/talk/js/gears.init.js",
                                 "~/addons/talk/js/gears.init.js",
                                 "~/addons/talk/js/iscroll.js",
                                 "~/addons/talk/js/talk.customevents.js",
                                 "~/js/third-party/jquery/jquery.notification.js",
                                 "~/js/third-party/moment.min.js",
                                 "~/js/third-party/moment-timezone.min.js",
                                 "~/addons/talk/js/talk.common.js",
                                 "~/addons/talk/js/talk.navigationitem.js",
                                 "~/addons/talk/js/talk.msmanager.js",
                                 "~/addons/talk/js/talk.mucmanager.js",
                                 "~/addons/talk/js/talk.roomsmanager.js",
                                 "~/addons/talk/js/talk.contactsmanager.js",
                                 "~/addons/talk/js/talk.messagesmanager.js",
                                 "~/addons/talk/js/talk.connectiomanager.js",
                                 "~/addons/talk/js/talk.default.js",
                                 "~/addons/talk/js/talk.init.js")
            .RegisterStyle("~/addons/talk/css/default/talk.style.css");
            if (Request.Browser != null && Request.Browser.Browser != "IE" && Request.Browser.Browser != "InternetExplorer")
            {
                Page
                .RegisterBodyScripts("~/js/third-party/firebase.js",
                                     "~/js/third-party/firebase-app.js",
                                     "~/js/third-party/firebase-auth.js",
                                     "~/js/third-party/firebase-database.js",
                                     "~/js/third-party/firebase-messaging.js");
            }

            var virtPath = "~/addons/talk/css/default/talk.style." + CultureInfo.CurrentCulture.Name.ToLower() + ".css";

            if (File.Exists(Server.MapPath(virtPath)))
            {
                Page.RegisterStyle(virtPath);
            }
            Page.RegisterStyle("~/addons/talk/css/default/talk.text-overflow.css");


            switch (_cfg.RequestTransportType.ToLower())
            {
            case "flash":
                Page.RegisterBodyScripts("~/addons/talk/js/jlib/plugins/strophe.flxhr.js",

                                         "~/addons/talk/js/jlib/flxhr/checkplayer.js",
                                         "~/addons/talk/js/jlib/flxhr/flensed.js",
                                         "~/addons/talk/js/jlib/flxhr/flxhr.js",
                                         "~/addons/talk/js/jlib/flxhr/swfobject.js",

                                         "~/js/third-party/xregexp.js",

                                         "~/addons/talk/js/jlib/strophe/base64.js",
                                         "~/addons/talk/js/jlib/strophe/md5.js",
                                         "~/addons/talk/js/jlib/strophe/core.js");

                break;

            default:
                Page.RegisterBodyScripts(
                    "~/addons/talk/js/jlib/strophe/base64.js",
                    "~/addons/talk/js/jlib/strophe/md5.js",
                    "~/addons/talk/js/jlib/strophe/core.js",
                    "~/js/third-party/xregexp.js",
                    "~/addons/talk/js/jlib/flxhr/swfobject.js");
                break;
            }

            Master.AddClientScript(new TalkClientScript(), new TalkClientScriptLocalization());

            try
            {
                Page.Title = TalkResource.ProductName + " - " + CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).DisplayUserName(false);
            }
            catch (System.Security.SecurityException)
            {
                Page.Title = TalkResource.ProductName + " - " + HeaderStringHelper.GetPageTitle(TalkResource.DefaultContactTitle);
            }
            try
            {
                Page.RegisterInlineScript("ASC.TMTalk.notifications && ASC.TMTalk.notifications.initialiseFirebase(" + GetFirebaseConfig() + ");");
            }
            catch (Exception) {}
        }
예제 #29
0
        private String GetStorePath(HttpContextBase context, String category, String uriString, ContentType contentType)
        {
            if (String.IsNullOrEmpty(category))
            {
                if (context.Request.Url != null)
                {
                    category = GetCategoryFromPath(context.Request.Url.AbsolutePath);
                }
                else if (String.IsNullOrEmpty(category))
                {
                    category = "common";
                }
            }

            var filePath = GetFullFileName(category, uriString, contentType);

            var cacheKey = String.Format("{0}-{1}", category, filePath);

            if (_cacheUri.ContainsKey(cacheKey))
            {
                return(_cacheUri[cacheKey]);
            }

            if (!StaticDataStorage.IsFile("common_static", filePath))
            {
                lock (_locker)
                {
                    if (_cacheUri.ContainsKey(cacheKey))
                    {
                        return(_cacheUri[cacheKey]);
                    }

                    var requestUri = uriString;

                    if (Uri.IsWellFormedUriString(uriString, UriKind.Relative))
                    {
                        var u          = context.Request.GetUrlRewriter();
                        var uriBuilder = new UriBuilder(u.Scheme, u.Host, u.Port, uriString);

                        requestUri = uriBuilder.ToString();
                    }

                    try
                    {
                        var req = (HttpWebRequest)WebRequest.Create(requestUri);

                        var currentTenant = CoreContext.TenantManager.GetCurrentTenant(false);

                        if (currentTenant != null && currentTenant.TenantId > -1)
                        {
                            req.CookieContainer = new CookieContainer();

                            var cookieDomain = CoreContext.TenantManager.GetCurrentTenant().TenantDomain;

                            if (req.RequestUri.Host.ToLower() == "localhost")
                            {
                                cookieDomain = "localhost";
                            }

                            req.CookieContainer.Add(new Cookie("asc_auth_key", CookiesManager.GetCookies(CookiesType.AuthKey), "/", cookieDomain));
                        }

                        using (var resp = (HttpWebResponse)req.GetResponse())
                            using (var stream = resp.GetResponseStream())
                            {
                                if (resp.StatusCode != HttpStatusCode.OK)
                                {
                                    throw new HttpException((int)resp.StatusCode, resp.StatusDescription);
                                }
                                if (ClientSettings.IsGZipEnabled)
                                {
                                    var compressedFileStream = new MemoryStream();

                                    using (var compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress, true))
                                    {
                                        stream.CopyTo(compressionStream);
                                    }

                                    Uri fileUri = StaticDataStorage.Save(String.Empty, filePath, compressedFileStream, "gzip", 365);
                                }
                                else
                                {
                                    StaticDataStorage.Save(filePath, stream);
                                }
                            }
                    }
                    catch (Exception exception)
                    {
                        _log.Error(exception);
                        _log.Error("Current Uri: " + context.Request.GetUrlRewriter().ToString());
                        _log.Error("Request Uri: " + requestUri);
                        throw;
                    }
                }
            }

            //HACK: support  for multi-cdn
            var result = WebPath.GetPath(filePath);

            if (!_cacheUri.ContainsKey(cacheKey))
            {
                _cacheUri.TryAdd(cacheKey, result);

                File.WriteAllText(_pathToCacheFile, JsonConvert.SerializeObject(_cacheUri));
            }

            return(result);
        }
예제 #30
0
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            if (!SecurityContext.IsAuthenticated)
            {
                if (CoreContext.Configuration.Personal)
                {
                    CheckSocialMedia();

                    SetLanguage();
                }

                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 cookie       = CookiesManager.GetCookies(CookiesType.AuthKey);
                int loginEventId = CookieStorage.GetLoginEventIdFromCookie(cookie);
                DbLoginEventsManager.LogOutEvent(loginEventId);

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

                ProcessLogout();

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