/// <summary>
        /// Unlocks the webdav resource.
        /// </summary>
        /// <param name="resource">The resource.</param>
        public static void UnlockResource(int webDavElementPropertyId)
        {
            WebDavAbstractFactory             factory     = new WebDavAbstractFactory();
            WebDavStorageElementPropertiesRow propertyRow = null;

            try
            {
                propertyRow = new WebDavStorageElementPropertiesRow(webDavElementPropertyId);
            }
            catch
            {
                return;
            }
            ResourceInfo resInfo = GetResourceInfoFromPropertyRow(propertyRow);

            if (resInfo != null)
            {
                WebDavTicket ticket = WebDavTicket.Parse(resInfo.AbsolutePath);
                WebDavElementStorageProvider storageProvider =
                    factory.Create <WebDavElementStorageProvider>(ticket.AbsolutePath.StorageType);

                foreach (ActiveLockElement activeLockEl in storageProvider.GetActiveLocks(resInfo))
                {
                    OpaqueLockToken lockToken = OpaqueLockToken.Parse(activeLockEl.LockToken.InnerText);
                    storageProvider.Unlock(resInfo, lockToken);
                }
            }
        }
Example #2
0
        /// <summary>
        /// Gets the web dav URL by WebDavTicket.
        /// </summary>
        /// <param name="ticket">The ticket.</param>
        /// <returns></returns>
        public static string GetWebDavUrl(string ticket)
        {
            string       retVal       = string.Empty;
            WebDavTicket webDavTicket = WebDavTicket.Parse(ticket);

            //Попытаемся определить имя файла
            if (String.IsNullOrEmpty(webDavTicket.AbsolutePath.FileName))
            {
                if (webDavTicket.AbsolutePath.StorageType == ObjectTypes.File_FileStorage)
                {
                    FileStorageAbsolutePath fsAbsPath = webDavTicket.AbsolutePath as FileStorageAbsolutePath;
                    if (fsAbsPath != null)
                    {
                        FileStorage fs = new FileStorage();
                        Mediachase.IBN.Business.ControlSystem.FileInfo fileInfo = fs.GetFile(fsAbsPath.UniqueId);
                        if (fileInfo != null)
                        {
                            webDavTicket.AbsolutePath.FileName = fileInfo.Name;
                        }
                    }
                }
                else if (webDavTicket.AbsolutePath.StorageType == ObjectTypes.File_MetaData)
                {
                    MetaDataAbsolutePath mdAbsPath = webDavTicket.AbsolutePath as MetaDataAbsolutePath;
                    if (mdAbsPath != null)
                    {
                        Mediachase.Ibn.Data.Meta.FileInfo fileInfo = new Mediachase.Ibn.Data.Meta.FileInfo(mdAbsPath.FileUID);
                        webDavTicket.AbsolutePath.FileName = fileInfo.Name;
                    }
                }
                else if (webDavTicket.AbsolutePath.StorageType == ObjectTypes.File_MetaDataPlus)
                {
                    MetaDataPlusAbsolutePath mdpAbsPath = webDavTicket.AbsolutePath as MetaDataPlusAbsolutePath;
                    if (mdpAbsPath != null)
                    {
                        Mediachase.MetaDataPlus.MetaObject obj = MetaDataWrapper.LoadMetaObject(mdpAbsPath.MetaObjectId, mdpAbsPath.MetaObjectType);
                        MetaFile mf = obj[mdpAbsPath.MetaFieldName] as MetaFile;
                        if (mf != null)
                        {
                            webDavTicket.AbsolutePath.FileName = mf.Name;
                        }
                    }
                }
                else if (webDavTicket.AbsolutePath.StorageType == ObjectTypes.File_Incident)
                {
                    EmailStorageAbsolutePath emlAbsPath = webDavTicket.AbsolutePath as EmailStorageAbsolutePath;
                    if (emlAbsPath != null)
                    {
                        EMailMessageInfo emlInfo    = EMailMessageInfo.Load(emlAbsPath.EmailMsgId);
                        AttachmentInfo   attachInfo = emlInfo.Attachments[emlAbsPath.EmailAttachmentIndex];
                        webDavTicket.AbsolutePath.FileName = attachInfo.FileName;
                    }
                }
            }

            retVal = GetWebDavUrl(webDavTicket.AbsolutePath, true);


            return(retVal);
        }
Example #3
0
        /// <summary>
        /// Gets the web dav ticket.
        /// <remarks> Получает web dav ticket is URI формата shema://PortalHost:PortalPort/[App Portal Path]?/Ticket
        /// т.е абсолютный путь состоит только из авбсолютного пути портала http://ibn.mediachase.ru/portals/ + ticket </remarks>
        /// <remarks>Абсолютный путь портала может быть взят как из конфига  в случае вызова без httpContexta так и из веб контекста
        /// при вызове из веба</remarks>
        /// </summary>
        /// <exception cref="Exception">Incorrect URI</exception>
        /// <param name="uriString">The URI string.</param>
        /// <returns></returns>
        internal static WebDavTicket GetWebDavTicket(string uriString)
        {
            WebDavTicket retVal = null;

            ////Берем за базовый урл портала так как получить доступ к http request нет возможности
            //String appPath = Configuration.PortalLink;
            //if (HttpContext.Current != null)
            //{
            //    HttpRequest request = HttpContext.Current.Request;
            //    //Используем HttpContext
            //    appPath = request.ApplicationPath;
            //    appPath = appPath.TrimEnd('/');
            //}

            //int index = uriString.IndexOf(appPath, StringComparison.InvariantCultureIgnoreCase);
            //if (index != -1)
            //{
            //    //oтбрасывем общую часть, оставляем только ticket
            //    uriString = uriString.Substring(index + appPath.Length);
            //}
            Match match = RegExpWebDavTicketFromUri.Match(uriString.Trim());

            try
            {
                retVal = WebDavTicket.Parse(match.Groups["ticket"].Value);
            }
            catch (System.Exception)
            {
                throw new Exception("Incorrect URI.");
            }

            return(retVal);
        }
        /// <summary>
        /// Gets the file locked user id.
        /// </summary>
        /// <param name="fileUrl">The file URL.</param>
        /// <returns></returns>
        public static UserLight GetFileLockedUserId(string fileUrl)
        {
            UserLight retVal = null;

            try
            {
                WebDavTicket          ticket   = WebDavUrlBuilder.GetWebDavTicket(fileUrl);
                WebDavAbstractFactory factory  = new WebDavAbstractFactory();
                WebDavPropertyStorage provider =
                    factory.Create <WebDavElementStorageProvider>(ticket.AbsolutePath.StorageType) as WebDavPropertyStorage;
                if (provider != null)
                {
                    WebDavElementInfo elInfo = provider.GetElementInfo(ticket.ToString());
                    foreach (ActiveLockElement activeLock in provider.GetActiveLocks(elInfo))
                    {
                        UserLight user = UserLight.Load(activeLock.Owner);
                        if (user != null)
                        {
                            retVal = user;
                            break;
                        }
                    }
                }
            }
            catch (System.Exception)
            {
            }

            return(retVal);
        }
        private static ResourceInfo GetResourceInfoFromPropertyRow(WebDavStorageElementPropertiesRow propertyRow)
        {
            if (propertyRow == null)
            {
                throw new ArgumentNullException("propertyRow");
            }
            ResourceInfo          retVal  = null;
            WebDavAbstractFactory factory = new WebDavAbstractFactory();

            //For MetaData stored int hash for Guid value is not possible restore back from hash to Guid
            if ((ObjectTypes)propertyRow.ObjectTypeId != ObjectTypes.File_MetaData)
            {
                WebDavElementStorageProvider provider = factory.Create <WebDavElementStorageProvider>(propertyRow.ObjectTypeId);
                WebDavAbsolutePath           absPath  = WebDavAbsolutePath.CreateInstance((ObjectTypes)propertyRow.ObjectTypeId);
                absPath.UniqueId = propertyRow.ObjectId;
                absPath.FileName = "file";
                WebDavTicket ticket = WebDavTicket.CreateInstance(ePluginToken.webdav, Guid.Empty, absPath);
                try
                {
                    retVal = provider.GetElementInfo(ticket.ToString()) as ResourceInfo;
                }
                catch (Exception)
                {
                }
            }
            return(retVal);
        }
Example #6
0
        /// <summary>
        /// Saves the property collection.
        /// </summary>
        /// <param name="collection">The collection.</param>
        private void SavePropertyCollection(PropertyInfoCollection collection)
        {
            if (collection == null)
            {
                return;
            }

            bool haveStoredProp = false;
            WebDavStorageElementPropertiesRow row = null;

            foreach (PropertyInfo prop in collection)
            {
                if (prop.Calculated == false)
                {
                    haveStoredProp = true;
                    try
                    {
                        WebDavTicket ticket = WebDavTicket.Parse(collection.ElementInfo.AbsolutePath);
                        using (TransactionScope tran = DataContext.Current.BeginTransaction())
                        {
                            row = GetWebDavStoragePropertyRow(ticket.AbsolutePath.StorageType, ticket.AbsolutePath.UniqueId);
                            if (row == null)
                            {
                                row = new WebDavStorageElementPropertiesRow();
                                row.ObjectTypeId = (int)ticket.AbsolutePath.StorageType;
                                row.ObjectId     = ticket.AbsolutePath.UniqueId;
                                row.Key          = "propertyCollection";
                            }
                            string value = Mediachase.Ibn.Data.McXmlSerializer.GetString <PropertyInfoCollection>(collection);
                            row.Value = value;
                            row.Update();

                            tran.Commit();
                        }
                    }
                    catch (Exception)
                    {
                        throw new HttpException(500, "Internal Server Error");
                    }
                    break;
                }
            }

            //remove property file if empty
            if (haveStoredProp == false)
            {
                try
                {
                    DeleteWebDavStorageElementPropertiesRow(row);
                }
                catch (Exception)
                {
                    throw new HttpException(500, "Unable to delete property");
                }
            }
        }
Example #7
0
        protected ResourceInfo GetResourceInfo(WebDavTicket ticket)
        {
            FileStorageAbsolutePath absPath = ticket.AbsolutePath as FileStorageAbsolutePath;

            if (absPath == null)
            {
                throw new ArgumentException("ticket.AbsolutePath is null.");
            }

            ResourceInfo result = new ResourceInfo();

            Mediachase.IBN.Business.ControlSystem.FileInfo fileInfo = null;

            //Получаем оригинальный файл
            using (IDataReader reader = Mediachase.IBN.Database.ControlSystem.DBFile.GetById(Security.CurrentUser.TimeZoneId, absPath.UniqueId))
            {
                if (reader.Read())
                {
                    fileInfo = new Mediachase.IBN.Business.ControlSystem.FileInfo(reader);
                }
            }

            if (fileInfo == null)
            {
                throw new HttpException(404, "Not found");
            }

            FileHistoryInfo historyInfo = null;

            //Поддержка версий
            if (absPath.IsHistory)
            {
                foreach (FileHistoryInfo history in fileInfo.GetHistory())
                {
                    if (history.Id == absPath.HistoryId)
                    {
                        historyInfo = history;
                        break;
                    }
                }
            }

            DummyFileInfoWrapper dummyInfo = new DummyFileInfoWrapper(fileInfo, historyInfo);

            result.AbsolutePath  = ticket.ToString();
            result.Tag           = dummyInfo;
            result.Name          = dummyInfo.Name;
            result.ContentType   = dummyInfo.ContentType;
            result.ContentLength = dummyInfo.Length;
            result.ParentName    = "root";
            result.Modified      = dummyInfo.Modified;
            result.Created       = dummyInfo.Created;

            return(result);
        }
Example #8
0
        protected CollectionInfo GetCollectionInfo(WebDavTicket ticket)
        {
            CollectionInfo retVal = new CollectionInfo();

            retVal.Name         = "root";
            retVal.Created      = DateTime.MinValue;
            retVal.Modified     = DateTime.MinValue;
            retVal.AbsolutePath = ticket.ToString();

            return(retVal);
        }
Example #9
0
        /// <summary>
        /// Gets the properties.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns></returns>
        public override Mediachase.Net.Wdom.PropertyInfoCollection GetProperties(Mediachase.Net.Wdom.WebDavElementInfo element)
        {
            PropertyInfoCollection retVal = null;
            PropertyInfo           prop   = null;
            WebDavDocument         tmpDoc = WebDavDocument.CreateDocument();

            if (element == null)
            {
                return(retVal);
            }

            retVal = new PropertyInfoCollection();
            //FileInfo fileInfo = !!!!(FileInfo)element.Tag;!!!
            WebDavTicket ticket = WebDavTicket.Parse(element.AbsolutePath);

            WebDavStorageElementPropertiesRow row = GetWebDavStoragePropertyRow(ticket.AbsolutePath.StorageType, ticket.AbsolutePath.UniqueId);

            if (row != null)
            {
                retVal = Mediachase.Ibn.Data.McXmlSerializer.GetObject <PropertyInfoCollection>(row.Value);
            }

            #region CreateDefaultProperties
            foreach (PropertyInfo defaultProp in PropertyInfo.CreateDefaultProperties(element))
            {
                SetPropertyAndSave(retVal, defaultProp, false, false);
            }
            #endregion

            //Add <supportedlock> property
            if (((int)(WebDavApplication.Class & WebDavServerClass.Class2)) != 0)
            {
                prop            = PropertyInfo.CreateSupportedLockProperty();
                prop.Calculated = false;
                SetPropertyAndSave(retVal, prop, false, false);
            }

            //Add <resourcetype> property
            prop = PropertyInfo.CreateResourceTypeProperty(element);
            SetPropertyAndSave(retVal, prop, false, false);

            //Assign context and set closure to class member
            retVal.ElementInfo = element;


            return(retVal);
        }
Example #10
0
        private static int BasicAuthentificate(HttpContext context, WebDavTicket ticket)
        {
            int retVal = -1;

            //Пытаемся получить id пользователя из куков
            HttpCookie userCookie = context.Request.Cookies[COOCKIE_NAME];

            if (userCookie != null)
            {
                try
                {
                    Guid sessionId = new Guid(userCookie.Value);
                    retVal = TrySessionAuthentificate(sessionId);
                }
                catch (System.Exception)
                {
                }
            }

            if (retVal == -1)
            {
                //Пытаемся аутентифицироваться
                retVal = TryBasicAuthentificate(context.Request.Headers[HTTP_AUTH_HEADER]);
                if (retVal != -1)
                {
                    //Создаем сессию
                    Guid sessionId = MakeAuthSession(true, ticket.AbsolutePath.StorageType, ticket.AbsolutePath.UniqueId);
                    //Пишем в куки id сессии
                    context.Response.Cookies.Add(GetAuthSessionCookie(sessionId));
                }
            }

            if (retVal == -1)
            {
                //запрос аутентификации (тип)
                foreach (KeyValuePair <string, string> header in GetNeedAuthHeader(AuthenticationSchemes.Basic))
                {
                    //context.Response.AddHeader(header.Key, header.Value);
                    context.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    context.Response.StatusCode      = (int)HttpStatusCode.Unauthorized;
                    context.Response.Flush();
                }
            }

            return(retVal);
        }
Example #11
0
        protected override ResourceInfo GetResourceInfo(WebDavTicket ticket)
        {
            ResourceInfo             retVal  = new ResourceInfo();
            EmailStorageAbsolutePath absPath = ticket.AbsolutePath as EmailStorageAbsolutePath;

            if (absPath == null)
            {
                throw new ArgumentException("absPath");
            }

            EMailMessageRow row       = new EMailMessageRow(absPath.EmailMsgId);
            MemoryStream    memStream = new MemoryStream(row.EmlMessage.Length);

            memStream.Write(row.EmlMessage, 0, row.EmlMessage.Length);
            memStream.Position = 0;

            Pop3Message message         = new Pop3Message(memStream);
            int         attachmentIndex = absPath.EmailAttachmentIndex;

            Mediachase.IBN.Business.EMail.EMailMessageInfo.AttachmentData entry =
                EMailMessageInfo.GetAttachment(message.MimeEntries, ref attachmentIndex);

            if (entry != null)
            {
                retVal.AbsolutePath = ticket.ToString();
                retVal.Tag          = entry;
                retVal.Name         = entry.FileName;
                //Fix ET:26-11-2008 Solve trouble inconsistency Content-Type email attachment and file extension
                //try first get Content-Type by file extension
                retVal.ContentType = ContentTypeResolver.Resolve(Path.GetExtension(entry.FileName));
                if (String.IsNullOrEmpty(retVal.ContentType))
                {
                    //otherwise set ContentType as ContentType email attachment
                    retVal.ContentType = entry.ContentType;
                }
                retVal.ContentLength = entry.Data.Length;
                retVal.ParentName    = "root";
                DateTime created = Database.DBCommon.GetLocalDate(Security.CurrentUser.TimeZoneId, row.Created);
                retVal.Created  = created;
                retVal.Modified = created;
            }

            return(retVal);
        }
Example #12
0
        /// <summary>
        /// Webs the dav authenticates.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="ticket">The ticket.</param>
        /// <returns></returns>
        internal static bool WebDavAuthentificate(HttpContext context, WebDavTicket ticket)
        {
            int userId = -1;

            if (ticket == null)
            {
                throw new Exception("ticket");
            }

            System.Web.Configuration.AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication");

            //Если есть сессионный id в тикете
            if (ticket.SessionId != Guid.Empty)
            {
                CleanupAuthSession(ticket.AbsolutePath.StorageType);
                //Пытаемся получить id пользователя из тикета
                userId = TrySessionAuthentificate(ticket.SessionId);
            }
            //Пытемся аутентифицироваться из сессии
            if (userId == -1)
            {
                UserLight userLight = Security.CurrentUser;
                if (userLight != null)
                {
                    userId = userLight.UserID;
                }
            }
            ////Используем стандартный механизм аутентификации
            //if (userId == -1 && section.Mode == AuthenticationMode.Forms)
            //{
            //    System.Web.Security.FormsAuthentication.RedirectToLoginPage();
            //    return false;
            //}
            ////Используем Basic аутентификацию
            //else if (userId == -1)
            //{
            //    userId = BasicAuthentificate(context, ticket);
            //}

            return(userId != -1);
        }
Example #13
0
        protected override ResourceInfo GetResourceInfo(WebDavTicket ticket)
        {
            ResourceInfo retVal = new ResourceInfo();
            EmailStorageAbsolutePath absPath = ticket.AbsolutePath as EmailStorageAbsolutePath;
            if(absPath == null)
                throw new ArgumentException("absPath");

            EMailMessageRow row = new EMailMessageRow(absPath.EmailMsgId);
            MemoryStream memStream = new MemoryStream(row.EmlMessage.Length);
            memStream.Write(row.EmlMessage, 0, row.EmlMessage.Length);
            memStream.Position = 0;

            Pop3Message message = new Pop3Message(memStream);
            int attachmentIndex = absPath.EmailAttachmentIndex;
            Mediachase.IBN.Business.EMail.EMailMessageInfo.AttachmentData entry =
                            EMailMessageInfo.GetAttachment(message.MimeEntries, ref attachmentIndex);

            if (entry != null)
            {

                retVal.AbsolutePath = ticket.ToString();
                retVal.Tag = entry;
                retVal.Name = entry.FileName;
                //Fix ET:26-11-2008 Solve trouble inconsistency Content-Type email attachment and file extension
                //try first get Content-Type by file extension
                retVal.ContentType = ContentTypeResolver.Resolve(Path.GetExtension(entry.FileName));
                if (String.IsNullOrEmpty(retVal.ContentType))
                {
                    //otherwise set ContentType as ContentType email attachment
                    retVal.ContentType = entry.ContentType;
                }
                retVal.ContentLength = entry.Data.Length;
                retVal.ParentName = "root";
                DateTime created = Database.DBCommon.GetLocalDate(Security.CurrentUser.TimeZoneId, row.Created);
                retVal.Created = created;
                retVal.Modified = created;
            }

            return retVal;
        }
Example #14
0
        /// <summary>
        /// Webs the dav authenticates.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="ticket">The ticket.</param>
        /// <returns></returns>
        internal static bool WebDavAuthentificate(HttpContext context, WebDavTicket ticket)
        {
            int userId = -1;
            if (ticket == null)
                throw new Exception("ticket");

            System.Web.Configuration.AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication");

            //Если есть сессионный id в тикете
            if (ticket.SessionId != Guid.Empty)
            {
                CleanupAuthSession(ticket.AbsolutePath.StorageType);
                //Пытаемся получить id пользователя из тикета
                userId = TrySessionAuthentificate(ticket.SessionId);
            }
            //Пытемся аутентифицироваться из сессии
            if (userId == -1)
            {
                UserLight userLight = Security.CurrentUser;
                if(userLight != null)
                {
                    userId = userLight.UserID;
                }

            }
            ////Используем стандартный механизм аутентификации
            //if (userId == -1 && section.Mode == AuthenticationMode.Forms)
            //{
            //    System.Web.Security.FormsAuthentication.RedirectToLoginPage();
            //    return false;
            //}
            ////Используем Basic аутентификацию
            //else if (userId == -1)
            //{
            //    userId = BasicAuthentificate(context, ticket);
            //}

            return userId != -1;
        }
Example #15
0
        /// <summary>
        /// Gets the element info.
        /// </summary>
        /// <param name="webDavAbsPath">The web dav abs path.</param>
        /// <returns></returns>
        public override WebDavElementInfo GetElementInfo(string strTicket)
        {
            WebDavElementInfo retVal = null;

            try
            {
                WebDavTicket ticket = WebDavTicket.Parse(strTicket);
                if (ticket.IsCollection)
                {
                    retVal = GetCollectionInfo(ticket);
                }
                else
                {
                    retVal = GetResourceInfo(ticket);
                }
            }
            catch (System.FormatException)
            {
            }

            return(retVal);
        }
Example #16
0
        protected virtual ResourceInfo GetResourceInfo(WebDavTicket ticket)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException("ticket");
            }
            MetaDataPlusAbsolutePath metaAbsPath = ticket.AbsolutePath as MetaDataPlusAbsolutePath;

            if (metaAbsPath == null)
            {
                throw new NullReferenceException("metaAbsPath");
            }

            ResourceInfo retVal = new ResourceInfo();
            MetaObject   obj    = MetaDataWrapper.LoadMetaObject(metaAbsPath.MetaObjectId, metaAbsPath.MetaObjectType);

            if (obj == null)
            {
                throw new NullReferenceException("obj");
            }

            MetaFile metaFile = (MetaFile)obj[metaAbsPath.MetaFieldName];

            if (metaFile != null)
            {
                retVal.AbsolutePath  = ticket.ToString();
                retVal.Tag           = new object[] { obj, metaFile, metaAbsPath };
                retVal.Name          = metaFile.Name;
                retVal.ContentType   = ContentTypeResolver.Resolve(Path.GetExtension(metaFile.Name));
                retVal.ContentLength = metaFile.Size;
                retVal.ParentName    = "root";
                retVal.Modified      = metaFile.LastWriteTime;
                retVal.Created       = metaFile.CreationTime;
            }

            return(retVal);
        }
Example #17
0
        protected override ResourceInfo GetResourceInfo(WebDavTicket ticket)
        {
            MetaDataAbsolutePath metaAbsPath = ticket.AbsolutePath as MetaDataAbsolutePath;

            if (metaAbsPath == null)
            {
                throw new ArgumentException("absPath");
            }

            ResourceInfo retVal = new ResourceInfo();

            Mediachase.Ibn.Data.Meta.FileInfo fileInfo = new Mediachase.Ibn.Data.Meta.FileInfo(metaAbsPath.FileUID);

            retVal.AbsolutePath  = ticket.ToString();
            retVal.Tag           = fileInfo;
            retVal.Name          = fileInfo.Name;
            retVal.ContentType   = ContentTypeResolver.Resolve(Path.GetExtension(fileInfo.Name));
            retVal.ContentLength = fileInfo.Length;
            retVal.ParentName    = "root";
            retVal.Modified      = DateTime.Now;
            retVal.Created       = DateTime.Now;

            return(retVal);
        }
Example #18
0
        private static int BasicAuthentificate(HttpContext context, WebDavTicket ticket)
        {
            int retVal = -1;

            //Пытаемся получить id пользователя из куков
            HttpCookie userCookie = context.Request.Cookies[COOCKIE_NAME];
            if (userCookie != null)
            {
                try
                {
                    Guid sessionId = new Guid(userCookie.Value);
                    retVal = TrySessionAuthentificate(sessionId);
                }
                catch (System.Exception)
                {
                }
            }

            if (retVal == -1)
            {
                //Пытаемся аутентифицироваться
                retVal = TryBasicAuthentificate(context.Request.Headers[HTTP_AUTH_HEADER]);
                if (retVal != -1)
                {
                    //Создаем сессию
                    Guid sessionId = MakeAuthSession(true, ticket.AbsolutePath.StorageType, ticket.AbsolutePath.UniqueId);
                    //Пишем в куки id сессии
                    context.Response.Cookies.Add(GetAuthSessionCookie(sessionId));
                }
            }

            if (retVal == -1)
            {
                //запрос аутентификации (тип)
                foreach (KeyValuePair<string, string> header in GetNeedAuthHeader(AuthenticationSchemes.Basic))
                {
                    //context.Response.AddHeader(header.Key, header.Value);
                    context.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    context.Response.Flush();
                }
            }

            return retVal;
        }
Example #19
0
        internal static string GetWebDavUrl(WebDavAbsolutePath absPath, bool withAuthToken,
                                            bool detectServerEdit, Uri baseUrl)
        {
            if (absPath == null)
            {
                throw new ArgumentNullException("absPath");
            }
            if (baseUrl == null)
            {
                throw new ArgumentNullException("baseUrl");
            }

            Guid?  authToken       = null;
            bool?  bWebDavTurnOn   = PortalConfig.UseWebDav;
            string applicationPath = baseUrl.AbsolutePath;

            if (HttpContext.Current != null)
            {
                //try get cached token
                authToken       = (Guid?)HttpContext.Current.Items[AUTH_TOKEN_CACHE_NAME];
                applicationPath = HttpContext.Current.Request.ApplicationPath;
                applicationPath = applicationPath.TrimEnd('/');
            }

            ePluginToken pluginToken = ePluginToken.files;

            //Determine server editing
            if (detectServerEdit)
            {
                if (bWebDavTurnOn.HasValue && bWebDavTurnOn.Value && ContentTypeResolver.IsWebDAVSupportedExtension(Path.GetExtension(absPath.FileName)))
                {
                    pluginToken = ePluginToken.webdav;
                }
            }
            //Формировать authToken only for webdav resources
            if (pluginToken == ePluginToken.webdav)
            {
                //Использовать из кеша если нет то сгенерировать новый
                if (authToken == null)
                {
                    //authToken = withAuthToken ? WebDavAuthHelper.MakeAuthSession(true, absPath.StorageType, absPath.UniqueId) : Guid.Empty;
                    authToken = withAuthToken ? WebDavAuthHelper.MakeAuthSession(true, ObjectTypes.File_FileStorage, 0) : Guid.Empty;
                    if (HttpContext.Current != null && authToken != Guid.Empty)
                    {
                        //add to cache auth token
                        HttpContext.Current.Items[AUTH_TOKEN_CACHE_NAME] = authToken;
                    }
                }
            }
            else if (pluginToken == ePluginToken.files)
            {
                //never add auth token to file plugin token resources
                authToken = Guid.Empty;
            }

            WebDavTicket ticket     = WebDavTicket.CreateInstance(pluginToken, authToken.Value, absPath);
            UriBuilder   uriBuilder = new UriBuilder();

            uriBuilder.Scheme = baseUrl.Scheme;
            uriBuilder.Port   = baseUrl.Port;
            uriBuilder.Host   = baseUrl.Host;


            uriBuilder.Path = applicationPath + ticket.ToString();

            //Outer url to redirect page only for webdav access type
            if (ticket.PluginToken == ePluginToken.webdav && !withAuthToken)
            {
                uriBuilder.Path = applicationPath + AUTH_REDIRECT_PAGE;
                string webDavTicket = ticket.ToString("A");
                //Remove file name from ticket
                uriBuilder.Query = AUTH_TICKET_PARAM_NAME + String.Format("={0}", webDavTicket);
            }

            ////FileName = System.Web.HttpUtility.UrlPathEncode(FileName);

            return(Uri.EscapeUriString(uriBuilder.Uri.ToString()));
        }
Example #20
0
        protected virtual ResourceInfo GetResourceInfo(WebDavTicket ticket)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException("ticket");
            }
            MetaDataPlusAbsolutePath metaAbsPath = ticket.AbsolutePath as MetaDataPlusAbsolutePath;
            if (metaAbsPath == null)
            {
                throw new NullReferenceException("metaAbsPath");
            }

            ResourceInfo retVal = new ResourceInfo();
            MetaObject obj = MetaDataWrapper.LoadMetaObject(metaAbsPath.MetaObjectId, metaAbsPath.MetaObjectType);
            if (obj == null)
            {
                throw new NullReferenceException("obj");
            }

            MetaFile metaFile = (MetaFile)obj[metaAbsPath.MetaFieldName];

            if (metaFile != null)
            {
                retVal.AbsolutePath = ticket.ToString();
                retVal.Tag = new object[] { obj, metaFile, metaAbsPath};
                retVal.Name = metaFile.Name;
                retVal.ContentType = ContentTypeResolver.Resolve(Path.GetExtension(metaFile.Name));
                retVal.ContentLength = metaFile.Size;
                retVal.ParentName = "root";
                retVal.Modified = metaFile.LastWriteTime;
                retVal.Created = metaFile.CreationTime;
            }

            return retVal;
        }
Example #21
0
        protected ResourceInfo GetResourceInfo(WebDavTicket ticket)
        {
            FileStorageAbsolutePath absPath = ticket.AbsolutePath as FileStorageAbsolutePath;
            if (absPath == null)
                throw new ArgumentException("ticket.AbsolutePath is null.");

            ResourceInfo result = new ResourceInfo();

            Mediachase.IBN.Business.ControlSystem.FileInfo fileInfo = null;

            //Получаем оригинальный файл
            using (IDataReader reader = Mediachase.IBN.Database.ControlSystem.DBFile.GetById(Security.CurrentUser.TimeZoneId, absPath.UniqueId))
            {
                if (reader.Read())
                    fileInfo = new Mediachase.IBN.Business.ControlSystem.FileInfo(reader);
            }

            if (fileInfo == null)
                throw new HttpException(404, "Not found");

            FileHistoryInfo historyInfo = null;

            //Поддержка версий
            if (absPath.IsHistory)
            {
                foreach (FileHistoryInfo history in fileInfo.GetHistory())
                {
                    if (history.Id == absPath.HistoryId)
                    {
                        historyInfo = history;
                        break;
                    }
                }
            }

            DummyFileInfoWrapper dummyInfo = new DummyFileInfoWrapper(fileInfo, historyInfo);
            result.AbsolutePath = ticket.ToString();
            result.Tag = dummyInfo;
            result.Name = dummyInfo.Name;
            result.ContentType = dummyInfo.ContentType;
            result.ContentLength = dummyInfo.Length;
            result.ParentName = "root";
            result.Modified = dummyInfo.Modified;
            result.Created = dummyInfo.Created;

            return result;
        }
Example #22
0
        protected CollectionInfo GetCollectionInfo(WebDavTicket ticket)
        {
            CollectionInfo retVal = new CollectionInfo();

            retVal.Name = "root";
            retVal.Created = DateTime.MinValue;
            retVal.Modified = DateTime.MinValue;
            retVal.AbsolutePath = ticket.ToString();

            return retVal;
        }
Example #23
0
        protected override ResourceInfo GetResourceInfo(WebDavTicket ticket)
        {
            MetaDataAbsolutePath metaAbsPath = ticket.AbsolutePath as MetaDataAbsolutePath;
            if (metaAbsPath == null)
                throw new ArgumentException("absPath");

            ResourceInfo retVal = new ResourceInfo();

            Mediachase.Ibn.Data.Meta.FileInfo fileInfo = new Mediachase.Ibn.Data.Meta.FileInfo(metaAbsPath.FileUID);

            retVal.AbsolutePath = ticket.ToString();
            retVal.Tag = fileInfo;
            retVal.Name = fileInfo.Name;
            retVal.ContentType = ContentTypeResolver.Resolve(Path.GetExtension(fileInfo.Name));
            retVal.ContentLength = fileInfo.Length;
            retVal.ParentName = "root";
            retVal.Modified = DateTime.Now;
            retVal.Created = DateTime.Now;

            return retVal;
        }
Example #24
0
        public void ProcessRequest(HttpContext context)
        {
            //try
            //{
            //проверяем есть ли в ticket-е идентификатор сессии
            WebDavTicket ticket = WebDavUrlBuilder.GetWebDavTicket(context.Request.Url.ToString());

            if (ticket == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Incorrect URI.");
            }

            if (!WebDavAuthHelper.WebDavAuthentificate(context, ticket))
            {
                //Используем стандартный механизм аутентификации
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            //throw new HttpException((int)HttpStatusCode.Unauthorized, "Unauthorized");
            WebDavAbstractFactory        factory         = new WebDavAbstractFactory();
            WebDavElementStorageProvider storageProvider =
                factory.Create <WebDavElementStorageProvider>(ticket.AbsolutePath.StorageType);

            if (storageProvider == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Incorrect URI.");
            }


            //Запускаем механизм обработки web dav запроса
            WebDavTicketRequest  request  = new WebDavTicketRequest(context.Request, ePluginToken.webdav);
            WebDavTicketResponse response = new WebDavTicketResponse(context.Response);

            WebDavApplication.DefaultProvider = storageProvider;

            try
            {
                bool enableTrace = Convert.ToBoolean(ConfigurationManager.AppSettings[ConstEnableTrace]);
                if (enableTrace)
                {
                    WebDavTracer.TraceBinaryBody = false;
                    WebDavTracer.EnableTrace     = true;
                }
            }
            catch (FormatException)
            {
            }


            if (request.HttpMethod == WebDavHttpMethod.GET)
            {
                //для get запросов выключаем буферизацию для работы с большими файлами
                context.Response.BufferOutput = false;
                //Некоторые браузеры кешируют результаты GET запроса при редактировании на сервере.
                //Установка expires равную текущей дате позволят указать браузеру что кеширование не требуется
                HttpCachePolicy cache = HttpContext.Current.Response.Cache;
                cache.SetExpires(DateTime.Now);

                //Если для запрошенного файла стоит флаг ForceDownload и не включен фдаг WebDav
                //то вернуть как attachment для выбора пользователем приложения для работы с документом
                if (!string.IsNullOrEmpty(ticket.AbsolutePath.FileName))
                {
                    string fileExtension = Path.GetExtension(ticket.AbsolutePath.FileName);
                    if (!ContentTypeResolver.IsWebDAVSupportedExtension(fileExtension) &&
                        ContentTypeResolver.IsAllowForceDownload(fileExtension))
                    {
                        context.Response.AddHeader("Content-Disposition", "attachment;" + "filename=" + ticket.AbsolutePath.FileName);
                    }
                }
            }

            WebDavApplication.ProcessRequest(request, response);

            //}
            //catch (HttpException ex)
            //{
            //    // Http Exception
            //    context.Response.Clear();

            //    context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //    context.Response.StatusCode = ex.GetHttpCode();
            //    context.Response.StatusDescription = ex.Message;
            //}
            //catch (Exception ex)
            //{
            //    // Global Exception
            //    context.Response.Clear();

            //    context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            //    context.Response.StatusDescription = ex.Message;

            //    byte[] errorBuffer = System.Text.Encoding.UTF8.GetBytes(ex.ToString());
            //    context.Response.OutputStream.Write(errorBuffer, 0, errorBuffer.Length);
            //}

            //context.Response.Flush();
        }