public UrlMapping GetUrlMapping(int siteId, string url)
        {
            var urlMapping = _db.UrlMapping.Where(item => item.SiteId == siteId && item.Url == url).FirstOrDefault();

            if (urlMapping == null)
            {
                var site = _sites.GetSite(siteId);
                if (site.CaptureBrokenUrls)
                {
                    urlMapping             = new UrlMapping();
                    urlMapping.SiteId      = siteId;
                    urlMapping.Url         = url;
                    urlMapping.MappedUrl   = "";
                    urlMapping.Requests    = 1;
                    urlMapping.CreatedOn   = DateTime.UtcNow;
                    urlMapping.RequestedOn = DateTime.UtcNow;
                    urlMapping             = AddUrlMapping(urlMapping);
                }
            }
            else
            {
                urlMapping.Requests   += 1;
                urlMapping.RequestedOn = DateTime.UtcNow;
                urlMapping             = UpdateUrlMapping(urlMapping);
            }
            return(urlMapping);
        }
        public void DeleteUrlMapping(int urlMappingId)
        {
            UrlMapping urlMapping = _db.UrlMapping.Find(urlMappingId);

            _db.UrlMapping.Remove(urlMapping);
            _db.SaveChanges();
        }
Ejemplo n.º 3
0
 public static UrlMappingDocument AsDocument(this UrlMapping entity)
 => new UrlMappingDocument
 {
     Code      = entity.Code,
     ShortLink = entity.ShortLink,
     LongLink  = entity.LongLink,
     ExpireAt  = entity.ExpireAt
 };
Ejemplo n.º 4
0
        private string ReplaceUrls(string sourcePostDescription)
        {
            if (string.IsNullOrWhiteSpace(sourcePostDescription))
            {
                return(string.Empty);
            }

            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(sourcePostDescription);

            foreach (var imgTag in doc.DocumentNode.Descendants("img").Where(img => img.Attributes["src"] != null).ToArray())
            {
                string       originalUrl = new Uri(imgTag.Attributes["src"].Value, UriKind.RelativeOrAbsolute).AbsoluteUri;
                ImageMapping newUrl      = _imageMappings.FirstOrDefault(map => map.FromUrl.Any(u => u == originalUrl));

                imgTag.Attributes["src"].Value = newUrl?.ToPath ?? originalUrl;

                if (imgTag.ParentNode.Name == "a" && imgTag.ParentNode.Attributes["href"] != null)
                {
                    var href = Path.GetFileName(
                        new Uri(imgTag.ParentNode.Attributes["href"].Value, UriKind.RelativeOrAbsolute).AbsolutePath);
                    var src = Path.GetFileName(new Uri(originalUrl, UriKind.RelativeOrAbsolute).AbsolutePath);

                    if (href == src)
                    {
                        imgTag.ParentNode.ParentNode.ReplaceChild(imgTag, imgTag.ParentNode);
                    }
                }
            }

            foreach (var aTag in doc.DocumentNode.Descendants("a").Where(img => img.Attributes["href"] != null)
                     .ToArray())
            {
                try
                {
                    string     originalUrl = new Uri(aTag.Attributes["href"].Value, UriKind.RelativeOrAbsolute).AbsoluteUri;
                    UrlMapping newUrl      = _urlMappings.FirstOrDefault(map => map.FromUrl == originalUrl);

                    if (newUrl != null)
                    {
                        aTag.Attributes["href"].Value = "/" + newUrl.ToUrl;
                    }
                }
                catch (UriFormatException)
                {
                    Console.WriteLine("Invalid Url : " + aTag.Attributes["href"].Value);
                }
            }

            return(doc.DocumentNode.OuterHtml);
        }
Ejemplo n.º 5
0
        public async Task <UrlMapping> FindAndExtend(UrlMapping entity)
        {
            var filter = Builders <UrlMappingDocument> .Filter.Eq("LongLink", entity.LongLink);

            var options = new FindOneAndUpdateOptions <UrlMappingDocument> {
                ReturnDocument = ReturnDocument.After
            };
            var documentBefore = await Collection.FindOneAndUpdateAsync(filter,
                                                                        Builders <UrlMappingDocument> .Update.Set(s => s.ExpireAt, entity.ExpireAt),
                                                                        options);

            return(documentBefore?.AsEntity());
        }
Ejemplo n.º 6
0
 public UrlMapping Post([FromBody] UrlMapping urlMapping)
 {
     if (ModelState.IsValid && urlMapping.SiteId == _alias.SiteId)
     {
         urlMapping = _urlMappings.AddUrlMapping(urlMapping);
         _logger.Log(LogLevel.Information, this, LogFunction.Create, "UrlMapping Added {UrlMapping}", urlMapping);
     }
     else
     {
         _logger.Log(LogLevel.Error, this, LogFunction.Security, "Unauthorized UrlMapping Post Attempt {Role}", urlMapping);
         HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
         urlMapping = null;
     }
     return(urlMapping);
 }
Ejemplo n.º 7
0
 public UrlMapping Put(int id, [FromBody] UrlMapping urlMapping)
 {
     if (ModelState.IsValid && urlMapping.SiteId == _alias.SiteId && _urlMappings.GetUrlMapping(urlMapping.UrlMappingId, false) != null)
     {
         urlMapping = _urlMappings.UpdateUrlMapping(urlMapping);
         _logger.Log(LogLevel.Information, this, LogFunction.Update, "UrlMapping Updated {UrlMapping}", urlMapping);
     }
     else
     {
         _logger.Log(LogLevel.Error, this, LogFunction.Security, "Unauthorized UrlMapping Put Attempt {UrlMapping}", urlMapping);
         HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
         urlMapping = null;
     }
     return(urlMapping);
 }
Ejemplo n.º 8
0
        private static void ChangeConfig(string sUrl, string toUrl)
        {
            UrlMapping         urlMap        = null;
            Configuration      config        = WebConfigurationManager.OpenWebConfiguration("~");
            UrlMappingsSection urlMapSection = (UrlMappingsSection)config.GetSection("system.web/urlMappings");

            if (urlMapSection.UrlMappings.Count > 0)
            {
                if (urlMapSection.UrlMappings[sUrl].Url == sUrl)
                {
                    urlMapSection.UrlMappings.Remove(sUrl);
                }

                urlMap = new UrlMapping(sUrl, toUrl);
                urlMapSection.UrlMappings.Add(urlMap);
                config.Save();
            }
        }
        public async Task <IActionResult> Post([FromQuery] string longUrl)
        {
            if (longUrl.Length > 2048)
            {
                return(new BadRequestObjectResult("Url too long. Limit 2K"));
            }

            var mapping = new UrlMapping {
                Url = longUrl
            };

            dbContext.Add(mapping);
            await dbContext.SaveChangesAsync();

            string shortUrl = Shortener.Encode(mapping.Id);

            return(new OkObjectResult(new { Long = longUrl, Short = Url.Action("Get", new { shortUrl = shortUrl }) }));
        }
Ejemplo n.º 10
0
        public async Task <UrlMapping> GenerateTinyUrl(string url)
        {
            try
            {
                //check in cache
                _cache.TryGetValue(url, out UrlMapping urlMapping);
                if (urlMapping != null)
                {
                    return(urlMapping);
                }

                //check in db
                var result = await IsUrlExits(url);

                if (result.Item2)
                {
                    return(result.Item1);
                }

                var lastInsertedId = await GetLastId();

                var code = _keyGenerator.GenerateKey(lastInsertedId + 1);

                urlMapping = new UrlMapping {
                    Code = code, Url = url
                };
                var now = DateTime.Now;

                await InsertAsync(urlMapping);

                await _context.SaveChangesAsync();

                return(urlMapping);
            }
            catch (System.Exception)
            {
                _logger.LogError("Error while generating tiny url");
                throw;
            }
        }
Ejemplo n.º 11
0
        public static async Task MWMS_Rewrite(HttpContext context)
        {
            UrlMapping u1 = new UrlMapping();

            u1.Path = "2222";
            Uri    url = new Uri(context.Request.Scheme + "://" + context.Request.Host + context.Request.Path);
            WebUri u   = new WebUri()
            {
                MainMobileUrl = "",
            };

            u.AddMapping(new UrlMapping()
            {
                Path         = "/acf/",
                PcDomain     = "/pc2/",
                MobileDomain = "/m/"
            });
            u.AddMapping(new UrlMapping()
            {
                Path         = "/",
                PcDomain     = "/",
                MobileDomain = "/m/"
            });
            u.AddMapping(new UrlMapping()
            {
                Path         = "mwms",
                PcDomain     = "www.mwms4.com",
                MobileDomain = "m.mwms4.com"
            });
            RequestUrl requestUrl = u.Build(url, context.Request.Headers["User-Agent"]);

            if (requestUrl.IsMobileBrowser && !requestUrl.IsMobileUrl)
            {
                //跳转至手机地址
            }
            context.Response.WriteAsync("");
        }
Ejemplo n.º 12
0
 public async Task AddAsync(UrlMapping entity)
 => await Collection.InsertOneAsync(entity.AsDocument());
Ejemplo n.º 13
0
 public async Task <UrlMapping> UpdateUrlMappingAsync(UrlMapping role)
 {
     return(await PutJsonAsync <UrlMapping>($"{Apiurl}/{role.UrlMappingId}", role));
 }
Ejemplo n.º 14
0
 public void AddUrlMapping(UrlMapping mapping)
 {
     _resolver.Add(mapping);
 }
 public void Remove(UrlMapping urlMapping)
 {
 }
Ejemplo n.º 16
0
 public async Task <UrlMapping> AddUrlMappingAsync(UrlMapping role)
 {
     return(await PostJsonAsync <UrlMapping>(Apiurl, role));
 }
Ejemplo n.º 17
0
 public UrlMapping UpdateUrlMapping(UrlMapping urlMapping)
 {
     _db.Entry(urlMapping).State = EntityState.Modified;
     _db.SaveChanges();
     return(urlMapping);
 }
 public void Add(UrlMapping urlMapping)
 {
 }
Ejemplo n.º 19
0
        public IActionResult OnGet()
        {
            AntiForgeryToken = _antiforgery.GetAndStoreTokens(HttpContext).RequestToken;

            if (_configuration.GetSection("Runtime").Exists())
            {
                Runtime = _configuration.GetSection("Runtime").Value;
            }

            if (_configuration.GetSection("RenderMode").Exists())
            {
                RenderMode = (RenderMode)Enum.Parse(typeof(RenderMode), _configuration.GetSection("RenderMode").Value, true);
            }

            // if framework is installed
            if (!string.IsNullOrEmpty(_configuration.GetConnectionString("DefaultConnection")))
            {
                var alias = _tenantManager.GetAlias();
                if (alias != null)
                {
                    Route route = new Route(HttpContext.Request.GetEncodedUrl(), alias.Path);

                    var site = _sites.GetSite(alias.SiteId);
                    if (site != null)
                    {
                        if (!string.IsNullOrEmpty(site.Runtime))
                        {
                            Runtime = site.Runtime;
                        }
                        if (!string.IsNullOrEmpty(site.RenderMode))
                        {
                            RenderMode = (RenderMode)Enum.Parse(typeof(RenderMode), site.RenderMode, true);
                        }
                        if (site.FaviconFileId != null)
                        {
                            FavIcon = Utilities.ContentUrl(alias, site.FaviconFileId.Value);
                        }
                        if (site.PwaIsEnabled && site.PwaAppIconFileId != null && site.PwaSplashIconFileId != null)
                        {
                            PWAScript = CreatePWAScript(alias, site, route);
                        }
                        Title     = site.Name;
                        ThemeType = site.DefaultThemeType;

                        if (site.VisitorTracking)
                        {
                            TrackVisitor(site.SiteId);
                        }

                        var page = _pages.GetPage(route.PagePath, site.SiteId);
                        if (page != null)
                        {
                            // set page title
                            if (!string.IsNullOrEmpty(page.Title))
                            {
                                Title = page.Title;
                            }
                            else
                            {
                                Title = Title + " - " + page.Name;
                            }

                            // include theme resources
                            if (!string.IsNullOrEmpty(page.ThemeType))
                            {
                                ThemeType = page.ThemeType;
                            }
                        }
                        else
                        {
                            // page does not exist
                            var url        = route.SiteUrl + "/" + route.PagePath;
                            var urlMapping = _urlMappings.GetUrlMapping(site.SiteId, url);
                            if (urlMapping == null)
                            {
                                if (site.CaptureBrokenUrls)
                                {
                                    urlMapping             = new UrlMapping();
                                    urlMapping.SiteId      = site.SiteId;
                                    urlMapping.Url         = url;
                                    urlMapping.MappedUrl   = "";
                                    urlMapping.Requests    = 1;
                                    urlMapping.CreatedOn   = DateTime.UtcNow;
                                    urlMapping.RequestedOn = DateTime.UtcNow;
                                    _urlMappings.AddUrlMapping(urlMapping);
                                }
                            }
                            else
                            {
                                urlMapping.Requests   += 1;
                                urlMapping.RequestedOn = DateTime.UtcNow;
                                _urlMappings.UpdateUrlMapping(urlMapping);

                                if (!string.IsNullOrEmpty(urlMapping.MappedUrl))
                                {
                                    return(RedirectPermanent(urlMapping.MappedUrl));
                                }
                            }
                        }
                    }

                    // include global resources
                    var assemblies = AppDomain.CurrentDomain.GetOqtaneAssemblies();
                    foreach (Assembly assembly in assemblies)
                    {
                        ProcessHostResources(assembly);
                        ProcessModuleControls(assembly);
                        ProcessThemeControls(assembly);
                    }

                    // set culture if not specified
                    if (HttpContext.Request.Cookies[CookieRequestCultureProvider.DefaultCookieName] == null)
                    {
                        // set default language for site if the culture is not supported
                        var languages = _languages.GetLanguages(alias.SiteId);
                        if (languages.Any() && languages.All(l => l.Code != CultureInfo.CurrentUICulture.Name))
                        {
                            var defaultLanguage = languages.Where(l => l.IsDefault).SingleOrDefault() ?? languages.First();
                            SetLocalizationCookie(defaultLanguage.Code);
                        }
                        else
                        {
                            SetLocalizationCookie(_localizationManager.GetDefaultCulture());
                        }
                    }
                }
            }
            return(Page());
        }
Ejemplo n.º 20
0
 public UrlMapping AddUrlMapping(UrlMapping urlMapping)
 {
     _db.UrlMapping.Add(urlMapping);
     _db.SaveChanges();
     return(urlMapping);
 }
Ejemplo n.º 21
0
        public bool Set(UrlMapping.UrlMappingItem item, string requesturl)
        {
            Url = item;

            string url;

            if (item.Index == null || item.SubIndex == null || item.SubsubIndex == null)
            {
                Dictionary<int, NavigationItem> menuItems = UrlMapping.UrlMappingModule.Instance.Provider.MenuItems;

                if (item.Index == null)
                {
                    double max = 0;
                    int maxi = 0, maxj = 0, maxk = 0;
                    foreach (int i in menuItems.Keys)
                    {
                        double d = 0;

                        foreach (int j in menuItems[i].Children.Keys)
                        {
                            NavigationItem ni = menuItems[i].Children[j];

                            foreach (int k in ni.Children.Keys)
                            {
                                NavigationItem nii = ni.Children[k];

                                url = trimUrl(nii.Url);
                                if (string.IsNullOrEmpty(url)) continue;

                                d = StringUtil.Similarity(requesturl, url);
                                if (d > max)
                                {
                                    max = d;

                                    maxi = i;
                                    maxj = j;
                                    maxk = k;
                                }
                            }

                            url = trimUrl(ni.Url);
                            if (string.IsNullOrEmpty(url))
                                continue;

                            d = StringUtil.Similarity(requesturl, url);
                            if (d > max)
                            {
                                max = d;

                                maxi = i;
                                maxj = j;
                                maxk = -1;
                            }
                        }

                        url = trimUrl(menuItems[i].Url);
                        if (string.IsNullOrEmpty(url))
                            continue;

                        d = StringUtil.Similarity(requesturl, url);
                        if (d > max)
                        {
                            max = d;

                            maxi = i;
                            maxj = -1;
                            maxk = -1;
                        }
                    }

                    if (max > 0)
                    {
                        Index = maxi;
                        SubIndex = maxj;
                        SubsubIndex = maxk;
                    }
                    else
                        return false;
                }
                else if (item.SubIndex == null)
                {
                    Index = item.Index.Value;

                    double max = 0;
                    int maxj = 0, maxk = 0;

                    double d = 0;

                    foreach (int j in menuItems[Index].Children.Keys)
                    {
                        NavigationItem ni = menuItems[Index].Children[j];

                        foreach (int k in ni.Children.Keys)
                        {
                            NavigationItem nii = ni.Children[k];

                            url = trimUrl(nii.Url);
                            if (string.IsNullOrEmpty(url)) continue;

                            d = StringUtil.Similarity(requesturl, url);
                            if (d > max)
                            {
                                max = d;

                                maxj = j;
                                maxk = k;
                            }
                        }

                        url = trimUrl(ni.Url);
                        if (string.IsNullOrEmpty(url))
                            continue;

                        d = StringUtil.Similarity(requesturl, url);
                        if (d > max)
                        {
                            max = d;

                            maxj = j;
                            maxk = -1;
                        }
                    }

                    if (max > 0)
                    {
                        SubIndex = maxj;
                        SubsubIndex = maxk;
                    }
                    else
                        return false;
                }
                else
                {
                    double max = 0;
                    int maxk = 0;

                    double d = 0;

                    NavigationItem ni = menuItems[Index].Children[SubIndex];

                    foreach (int k in ni.Children.Keys)
                    {
                        NavigationItem nii = ni.Children[k];

                        url = trimUrl(nii.Url);
                        if (string.IsNullOrEmpty(url)) continue;

                        d = StringUtil.Similarity(requesturl, url);
                        if (d > max)
                        {
                            max = d;

                            maxk = k;
                        }
                    }

                    if (max > 0)
                    {
                        SubsubIndex = maxk;
                    }
                    else
                        return false;
                }
            }
            else
            {
                Index = item.Index.Value;
                SubIndex = item.SubIndex.Value;
                SubsubIndex = item.SubsubIndex.Value;
            }

            Title = item.Title;
            Name = item.Name;

            foreach (string key in Url.Keys)
            {
                SetExtendedAttribute(key, Url[key]);
            }

            OK = true;

            return true;
        }
Ejemplo n.º 22
0
            public static MockRequestHttpContext FromPath(string path)
            {
                var applicationPath = UrlMapping.GetApplicationPath(path);

                return(new MockRequestHttpContext(new MockHttpRequest(applicationPath.AppRelativePath)));
            }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            string inputStr  = String.Empty;
            string optionStr = String.Empty;
            string parm1     = String.Empty;
            string parm2     = String.Empty;

            // Define a regular expression to allow only
            // alphanumeric inputs that are at most 20 character
            // long. For instance "/iii:".
            Regex rex = new Regex(@"[^\/w]{1,20}");

            parm1 = "none";
            parm2 = "false";

            // Parse the user's input.
            if (args.Length < 1)
            {
                // No option entered.
                Console.Write("Input parameters missing.");
                return;
            }
            else
            {
                // Get the user's options.
                inputStr = args[0].ToLower();


                if (args.Length == 3)
                {
                    // These to be used when serializing
                    // (writing) to the configuration file.
                    parm1 = args[1].ToLower();
                    parm2 = args[2].ToLower();

                    if (!(rex.Match(parm1)).Success &&
                        !(rex.Match(parm2)).Success)
                    {
                        // Wrong option format used.
                        Console.Write("Input format not allowed.");
                        return;
                    }
                }

                if (!(rex.Match(inputStr)).Success)
                {
                    // Wrong option format used.
                    Console.Write("Input format not allowed.");
                    return;
                }
            }

            // <Snippet1>

            // Get the Web application configuration.
            System.Configuration.Configuration configuration =
                WebConfigurationManager.OpenWebConfiguration(
                    "/aspnetTest");

            // Get the <urlMapping> section.
            UrlMappingsSection urlMappingSection =
                (UrlMappingsSection)configuration.GetSection(
                    "system.web/urlMappings");

            // <Snippet2>

            // Get the url mapping collection.
            UrlMappingCollection urlMappings =
                urlMappingSection.UrlMappings;

            // </Snippet2>

            // </Snippet1>

            try
            {
                switch (inputStr)
                {
                case "/add":

                    // <Snippet3>

                    // Create a new UrlMapping object.
                    urlMapping = new UrlMapping(
                        "~/home.aspx", "~/default.aspx?parm1=1");

                    // Add the urlMapping to
                    // the collection.
                    urlMappings.Add(urlMapping);

                    // Update the configuration file.
                    if (!urlMappingSection.IsReadOnly())
                    {
                        configuration.Save();
                    }

                    // </Snippet3>

                    shownUrl  = urlMapping.Url;
                    mappedUrl = urlMapping.MappedUrl;

                    msg = String.Format(
                        "Shown URL: {0}\nMapped URL:  {1}\n",
                        shownUrl, mappedUrl);


                    Console.Write(msg);

                    break;

                case "/clear":

                    // <Snippet4>

                    // Clear the url mapping collection.
                    urlMappings.Clear();

                    // Update the configuration file.

                    // Define the save modality.
                    ConfigurationSaveMode saveMode =
                        ConfigurationSaveMode.Minimal;

                    urlMappings.EmitClear =
                        Convert.ToBoolean(parm2);

                    if (parm1 == "none")
                    {
                        if (!urlMappingSection.IsReadOnly())
                        {
                            configuration.Save();
                        }
                        msg = String.Format(
                            "Default modality, EmitClear:      {0}",
                            urlMappings.EmitClear.ToString());
                    }
                    else
                    {
                        if (parm1 == "full")
                        {
                            saveMode = ConfigurationSaveMode.Full;
                        }
                        else
                        if (parm1 == "modified")
                        {
                            saveMode = ConfigurationSaveMode.Modified;
                        }

                        if (!urlMappingSection.IsReadOnly())
                        {
                            configuration.Save(saveMode);
                        }

                        msg = String.Format(
                            "Save modality:      {0}",
                            saveMode.ToString());
                    }

                    // </Snippet4>

                    Console.Write(msg);

                    break;

                case "/removeobject":

                    // <Snippet5>

                    // Create a UrlMapping object.
                    urlMapping = new UrlMapping(
                        "~/home.aspx", "~/default.aspx?parm1=1");

                    // Remove it from the collection
                    // (if exists).
                    urlMappings.Remove(urlMapping);

                    // Update the configuration file.
                    if (!urlMappingSection.IsReadOnly())
                    {
                        configuration.Save();
                    }

                    // </Snippet5>

                    shownUrl  = urlMapping.Url;
                    mappedUrl = urlMapping.MappedUrl;

                    msg = String.Format(
                        "Shown URL:      {0}\nMapped URL: {1}\n",
                        shownUrl, mappedUrl);

                    Console.Write(msg);

                    break;

                case "/removeurl":

                    // <Snippet6>

                    // Remove the URL with the
                    // specified name from the collection
                    // (if exists).
                    urlMappings.Remove("~/default.aspx");

                    // Update the configuration file.
                    if (!urlMappingSection.IsReadOnly())
                    {
                        configuration.Save();
                    }

                    // </Snippet6>

                    break;

                case "/removeindex":

                    // <Snippet7>

                    // Remove the URL at the
                    // specified index from the collection.
                    urlMappings.RemoveAt(0);

                    // Update the configuration file.
                    if (!urlMappingSection.IsReadOnly())
                    {
                        configuration.Save();
                    }

                    // </Snippet7>

                    break;

                case "/all":

                    // <Snippet8>

                    StringBuilder allUrlMappings = new StringBuilder();

                    foreach (UrlMapping url_Mapping in urlMappings)
                    {
                        // <Snippet9>
                        shownUrl = url_Mapping.Url;
                        // </Snippet9>

                        // <Snippet10>
                        mappedUrl = url_Mapping.MappedUrl;
                        // </Snippet10>

                        msg = String.Format(
                            "Shown URL:  {0}\nMapped URL: {1}\n",
                            shownUrl, mappedUrl);

                        allUrlMappings.AppendLine(msg);
                    }

                    // </Snippet8>

                    Console.Write(allUrlMappings.ToString());
                    break;


                default:
                    // Option is not allowed..
                    Console.Write("Input not allowed.");
                    break;
                }
            }
            catch (ArgumentException e)
            {
                // Never display this. Use it for
                // debugging purposes.
                msg = e.ToString();
            }
        }
Ejemplo n.º 24
0
        public Page Put(int id, [FromBody] Page page)
        {
            // get current page
            var currentPage = _pages.GetPage(page.PageId, false);

            if (ModelState.IsValid && page.SiteId == _alias.SiteId && currentPage != null && _userPermissions.IsAuthorized(User, EntityNames.Page, page.PageId, PermissionNames.Edit))
            {
                // get current page permissions
                var currentPermissions = _permissionRepository.GetPermissions(EntityNames.Page, page.PageId).ToList();

                page = _pages.UpdatePage(page);

                // save url mapping if page path changed
                if (currentPage.Path != page.Path)
                {
                    var urlMapping = new UrlMapping();
                    urlMapping.SiteId      = page.SiteId;
                    urlMapping.Url         = currentPage.Path;
                    urlMapping.MappedUrl   = page.Path;
                    urlMapping.Requests    = 0;
                    urlMapping.CreatedOn   = System.DateTime.UtcNow;
                    urlMapping.RequestedOn = System.DateTime.UtcNow;
                    _urlMappings.AddUrlMapping(urlMapping);
                }

                // get differences between current and new page permissions
                var newPermissions = _permissionRepository.DecodePermissions(page.Permissions, page.SiteId, EntityNames.Page, page.PageId).ToList();
                var added          = GetPermissionsDifferences(newPermissions, currentPermissions);
                var removed        = GetPermissionsDifferences(currentPermissions, newPermissions);

                // synchronize module permissions
                if (added.Count > 0 || removed.Count > 0)
                {
                    foreach (PageModule pageModule in _pageModules.GetPageModules(page.PageId, "").ToList())
                    {
                        var modulePermissions = _permissionRepository.GetPermissions(EntityNames.Module, pageModule.Module.ModuleId).ToList();
                        // permissions added
                        foreach (Permission permission in added)
                        {
                            if (!modulePermissions.Any(item => item.PermissionName == permission.PermissionName &&
                                                       item.RoleId == permission.RoleId && item.UserId == permission.UserId && item.IsAuthorized == permission.IsAuthorized))
                            {
                                _permissionRepository.AddPermission(new Permission
                                {
                                    SiteId         = page.SiteId,
                                    EntityName     = EntityNames.Module,
                                    EntityId       = pageModule.ModuleId,
                                    PermissionName = permission.PermissionName,
                                    RoleId         = permission.RoleId,
                                    UserId         = permission.UserId,
                                    IsAuthorized   = permission.IsAuthorized
                                });
                            }
                        }
                        // permissions removed
                        foreach (Permission permission in removed)
                        {
                            var modulePermission = modulePermissions.FirstOrDefault(item => item.PermissionName == permission.PermissionName &&
                                                                                    item.RoleId == permission.RoleId && item.UserId == permission.UserId && item.IsAuthorized == permission.IsAuthorized);
                            if (modulePermission != null)
                            {
                                _permissionRepository.DeletePermission(modulePermission.PermissionId);
                            }
                        }
                    }
                }

                _syncManager.AddSyncEvent(_alias.TenantId, EntityNames.Site, page.SiteId);
                _logger.Log(LogLevel.Information, this, LogFunction.Update, "Page Updated {Page}", page);
            }
            else
            {
                _logger.Log(LogLevel.Error, this, LogFunction.Security, "Unauthorized Page Put Attempt {Page}", page);
                HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                page = null;
            }
            return(page);
        }
Ejemplo n.º 25
0
 public void Add(UrlMapping urlMapping)
 {
 }
Ejemplo n.º 26
0
 private async Task InsertAsync(UrlMapping entity)
 {
     _cache.Set(entity.Url, entity);
     await _context.UrlMapping.AddAsync(entity);
 }
Ejemplo n.º 27
0
 public void Remove(UrlMapping urlMapping)
 {
 }