Пример #1
0
        public bool IsWellKnownDb()
        {
            var serializer = new DomainSerializer("domains-approved.json");
            var domains    = serializer.Get();

            return(domains.Any(domain => DbConvention.GetCatalog(domain) == this.Catalog));
        }
Пример #2
0
        public void App_BeginRequest(object sender, EventArgs e)
        {
            var context = HttpContext.Current;

            if (context == null)
            {
                return;
            }

            string domain = DbConvention.GetDomain();

            Log.Verbose($"Got a {context.Request.HttpMethod} request {context.Request.AppRelativeCurrentExecutionFilePath} on domain {domain}.");

            bool enforceSsl = DbConvention.EnforceSsl(domain);

            if (!enforceSsl)
            {
                Log.Verbose($"SSL was not enforced on domain {domain}.");
                return;
            }

            if (context.Request.Url.Scheme == "https")
            {
                context.Response.AddHeader("Strict-Transport-Security", "max-age=31536000");
            }
            else if (context.Request.Url.Scheme == "http")
            {
                string path = "https://" + context.Request.Url.Host +
                              context.Request.Url.PathAndQuery;
                context.Response.Status = "301 Moved Permanently";
                context.Response.AddHeader("Location", path);
            }
        }
Пример #3
0
        public bool IsWellKnownDb()
        {
            var serializer = new DomainSerializer("DomainsApproved.json");
            var domains    = serializer.Get();

            return(domains.Any(domain => DbConvention.GetTenant(domain.DomainName) == this.Database));
        }
Пример #4
0
        public void Delete()
        {
            string tenant = DbConvention.GetTenant();
            string path   = $"~/Tenants/{tenant}/Areas/Frapid.WebsiteBuilder/Themes/{this.ThemeName}";

            path = HostingEnvironment.MapPath(path);

            if (path == null)
            {
                throw new ResourceRemoveException("Path to the file or directory is invalid.");
            }

            path = Path.Combine(path, this.Resource);

            if (Directory.Exists(path))
            {
                Directory.Delete(path);
                return;
            }

            if (File.Exists(path))
            {
                File.Delete(path);
                return;
            }

            throw new ResourceRemoveException("File or directory could not be found.");
        }
Пример #5
0
        public void Remove()
        {
            if (string.IsNullOrWhiteSpace(this.ThemeName))
            {
                Thread.Sleep(10000);
                throw new ThemeRemoveException("Access is denied.");
            }

            string defaultTheme = Configuration.GetDefaultTheme();

            if (this.ThemeName.ToLower().Equals(defaultTheme.ToLower()))
            {
                throw new ThemeRemoveException("Access is denied. You cannot remove this theme because it is in use.");
            }

            string tenant = DbConvention.GetTenant();
            string path   = $"~/Tenants/{tenant}/Areas/Frapid.WebsiteBuilder/Themes/{this.ThemeName}";

            path = HostingEnvironment.MapPath(path);

            if (path == null || !Directory.Exists(path))
            {
                throw new ThemeRemoveException("Invalid theme.");
            }

            Directory.Delete(path, true);
        }
Пример #6
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string profile = this.ProfileName;

            if (!string.IsNullOrWhiteSpace(profile))
            {
                this.CacheProfile = string.Empty;

                string tenant = DbConvention.GetTenant();

                var config = CacheConfig.Get(tenant, profile);

                if (config != null)
                {
                    this.Duration              = config.Duration;
                    this.Location              = config.Location;
                    this.NoStore               = config.NoStore;
                    this.SqlDependency         = config.SqlDependency;
                    this.VaryByContentEncoding = config.VaryByContentEncoding;
                    this.VaryByCustom          = config.VaryByCustom;
                    this.VaryByHeader          = config.VaryByHeader;
                    this.VaryByParam           = config.VaryByParam;
                }
            }

            base.OnActionExecuting(context);
        }
Пример #7
0
        protected string GetRazorView(string areaName, string path)
        {
            string tenant = DbConvention.GetTenant();
            string theme  = Configuration.GetDefaultTheme();


            string overridePath = "~/Tenants/{0}/Areas/Frapid.Dashboard/Themes/{1}/Areas/{2}/Views/" + path;

            overridePath = string.Format(CultureInfo.InvariantCulture, overridePath, tenant, theme, areaName);

            if (System.IO.File.Exists(HostingEnvironment.MapPath(overridePath)))
            {
                return(overridePath);
            }


            overridePath = "~/Tenants/{0}/Areas/{1}/Themes/{2}/Views/" + path;
            overridePath = string.Format(CultureInfo.InvariantCulture, overridePath, tenant, areaName, theme);

            if (System.IO.File.Exists(HostingEnvironment.MapPath(overridePath)))
            {
                return(overridePath);
            }

            string defaultPath = "~/Areas/{0}/Views/{1}";

            defaultPath = string.Format(CultureInfo.InvariantCulture, defaultPath, areaName, path);

            return(defaultPath);
        }
Пример #8
0
        public ActionResult GetResources(string themeName)
        {
            if (string.IsNullOrWhiteSpace(themeName))
            {
                return(this.Failed("Invalid theme name", HttpStatusCode.BadRequest));
            }

            string tenant = DbConvention.GetTenant();
            string path   = $"~/Tenants/{tenant}/Areas/Frapid.WebsiteBuilder/Themes/{themeName}/";

            path = HostingEnvironment.MapPath(path);

            if (path == null || !Directory.Exists(path))
            {
                return(this.Failed("Path not found", HttpStatusCode.NotFound));
            }

            var resource = ThemeResource.Get(path);

            resource = ThemeResource.NormalizePath(path, resource);

            string json = JsonConvert.SerializeObject(resource, Formatting.None,
                                                      new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            return(this.Content(json, "application/json"));
        }
Пример #9
0
        public ActionResult SetAsDefault(string themeName)
        {
            if (string.IsNullOrEmpty(themeName))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            string tenant = DbConvention.GetTenant();
            string path   = $"~/Tenants/{tenant}/Areas/Frapid.Dashboard/Themes/{themeName}";

            path = HostingEnvironment.MapPath(path);

            if (path == null || !Directory.Exists(path))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            path = $"~/Tenants/{tenant}/Areas/Frapid.Dashboard/Dashboard.config";
            path = HostingEnvironment.MapPath(path);

            if (path == null || !System.IO.File.Exists(path))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }


            ConfigurationManager.SetConfigurationValue(path, "DefaultTheme", themeName);
            return(this.Ok());
        }
Пример #10
0
        public void Create()
        {
            string tenant = DbConvention.GetTenant();
            string path   = $"~/Tenants/{tenant}";

            path = HostingEnvironment.MapPath(path);

            if (path == null || !Directory.Exists(path))
            {
                throw new ResourceCreateException("Could not create the file or directory because the tenant directory was not found.");
            }

            path = Path.Combine(path, this.Container);

            if (!Directory.Exists(path))
            {
                throw new ResourceCreateException("Could not create the file or directory is an invalid directory path.");
            }

            path = Path.Combine(path, this.File);

            if (this.Rewrite.Equals(false) && System.IO.File.Exists(path))
            {
                return;
            }

            if (this.IsDirectory)
            {
                Directory.CreateDirectory(path);
                return;
            }

            System.IO.File.WriteAllText(path, this.Contents, Encoding.UTF8);
        }
Пример #11
0
        /// <summary>
        /// Returns path to the static content on the tenant directory.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetFile(HttpContext context)
        {
            string tenant          = DbConvention.GetTenant();
            var    staticResources = GetConfig(tenant, "StaticResources").Or("").Split(',').Select(x => x.Trim()).ToList();

            if (!staticResources.Any())
            {
                return(string.Empty);
            }

            string rootDirectory = $"/Tenants/{tenant}/wwwroot/";

            string requestedFile = context.Request.Url.AbsolutePath;
            string query         = context.Request.Url.Query;
            string extension     = Path.GetExtension(requestedFile);

            if (staticResources.Contains(extension))
            {
                //This is a well-known file type
                string path = rootDirectory + requestedFile;
                if (File.Exists(HostingEnvironment.MapPath(path)))
                {
                    return(path + query);
                }
            }


            return(string.Empty);
        }
Пример #12
0
        public void Register()
        {
            try
            {
                var installed = new DomainSerializer("DomainsInstalled.json");

                foreach (var repository in
                         from domain in installed.Get()
                         let catalog = DbConvention.GetDbNameByConvention(domain.DomainName)
                                       select new AddInstalledDomainProcedure
                {
                    DomainName = domain.DomainName,
                    AdminEmail = domain.AdminEmail,
                    SkipValidation = true,
                    _Catalog = catalog
                })
                {
                    repository.Execute();
                }
            }
            catch (NpgsqlException ex)
            {
                Log.Error("Could not execute AddInstalledDomainProcedure. Exception: {Exception}", ex);
            }
        }
Пример #13
0
        public void Execute(IJobExecutionContext context)
        {
            string url = context.JobDetail.Key.Name;

            try
            {
                Log.Verbose($"Installing frapid on domain {url}.");
                string database = DbConvention.GetTenant(url);

                Log.Verbose($"Creating database {database}.");
                var db = new DbInstaller(database);
                db.Install();

                Log.Verbose("Getting installables.");
                var installables = GetInstallables(database);
                Log.Information($"The following apps will be installed:\n\n {installables}.");

                foreach (var installable in installables)
                {
                    Log.Verbose($"Installing module {installable.ApplicationName}.");
                    new AppInstaller(database, installable).Install();
                }

                var tenant =
                    new DomainSerializer("DomainsApproved.json").Get().FirstOrDefault(x => x.DomainName.Equals(url));
                DbInstalledDomains.Add(tenant);
            }
            catch (Exception ex)
            {
                Log.Error("Could not install frapid on {url} due to errors. Exception: {Exception}", url, ex);
                throw;
            }
        }
Пример #14
0
        public static MvcHtmlString GetAntiForgeryToken(this HtmlHelper helper)
        {
            if (DbConvention.IsStaticDomain())
            {
                return(new MvcHtmlString(string.Empty));
            }

            return(helper.AntiForgeryToken());
        }
Пример #15
0
        public void Upload()
        {
            if (string.IsNullOrWhiteSpace(this.ThemeName))
            {
                throw new ArgumentNullException(nameof(this.ThemeName));
            }

            string tenant = DbConvention.GetTenant();
            string path   = $"~/Tenants/{tenant}/Areas/Frapid.WebsiteBuilder/Themes/{this.ThemeName}";

            path = HostingEnvironment.MapPath(path);

            if (path == null || !Directory.Exists(path))
            {
                Log.Warning("Could not upload resource because the directory {directory} does not exist.", path);
                throw new ResourceUploadException("Invalid path. Check the log for more details.");
            }

            path = Path.Combine(path, this.Container);

            if (!Directory.Exists(path))
            {
                Log.Warning("Could not upload resource because the directory {directory} does not exist.", path);
                throw new ResourceUploadException("Invalid path. Check application logs for more information.");
            }


            string fileName = Path.GetFileName(this.PostedFile.FileName);

            if (fileName == null)
            {
                Log.Warning("Could not upload resource because the posted file name is null or invalid.");
                throw new ResourceUploadException(
                          "Could not upload resource because the posted file name is null or invalid.");
            }

            var    allowed   = FrapidConfig.GetAllowedUploadExtensions(DbConvention.GetTenant());
            string extension = Path.GetExtension(fileName);

            if (!allowed.Contains(extension))
            {
                Log.Warning("Could not upload resource because the uploaded file {file} has invalid extension.",
                            fileName);
                throw new ResourceUploadException(
                          "Could not upload resource because the uploaded file has invalid extension.");
            }

            var stream = this.PostedFile.InputStream;

            path = Path.Combine(Path.Combine(path, fileName));

            using (var fileStream = File.Create(path))
            {
                stream.CopyTo(fileStream);
            }
        }
Пример #16
0
        public ActionResult Index()
        {
            string domain = DbConvention.GetBaseDomain(this.HttpContext, true);

            if (string.IsNullOrWhiteSpace(domain))
            {
                return(this.Failed("Could not generate sitemap.", HttpStatusCode.InternalServerError));
            }
            string siteMap = SiteMapGenerator.Get(domain);

            return(this.Content(siteMap, "text/xml", Encoding.UTF8));
        }
Пример #17
0
        public static void Add(ApprovedDomain tenant)
        {
            string database = DbConvention.GetDbNameByConvention(tenant.DomainName);

            using (var db = DbProvider.Get(FrapidDbServer.GetSuperUserConnectionString(database)).GetDatabase())
            {
                dynamic poco = new ExpandoObject();
                poco.domain_name = tenant.DomainName;
                poco.admin_email = tenant.AdminEmail;

                db.Insert("account.installed_domains", "domain_id", true, poco);
            }
        }
Пример #18
0
        public string Locate()
        {
            string tenant = DbConvention.GetTenant();
            string path   = $"~/Tenants/{tenant}/Areas/Frapid.WebsiteBuilder/Themes/{this.ThemeName}/{this.File}";

            path = HostingEnvironment.MapPath(path);

            if (!System.IO.File.Exists(path))
            {
                throw new ThemeFileLocationException("Could not locate the requested file.");
            }

            return(path);
        }
Пример #19
0
        public void Execute(IJobExecutionContext context)
        {
            string url     = context.JobDetail.Key.Name;
            string catalog = DbConvention.GetCatalog(url);
            var    db      = new DbInstaller(catalog);

            db.Install();

            var installables = GetInstallables();

            foreach (var installable in installables)
            {
                new AppInstaller(catalog, installable).Install();
            }
        }
Пример #20
0
        public List <SearchResultContent> Search(string query)
        {
            var    context = new HttpContextWrapper(HttpContext.Current);
            var    result  = DAL.Contents.Search(query);
            string domain  = DbConvention.GetBaseDomain(context, true);

            return(result.Select(item => new SearchResultContent
            {
                Title = item.Title,
                Contents = item.Contents.ToText().Truncate(200),
                LastUpdatedOn = item.LastEditedOn,
                LinkUrl = item.IsBlog ?
                          UrlHelper.CombineUrl(domain, "/blog/" + item.CategoryAlias + "/" + item.Alias)
                : UrlHelper.CombineUrl(domain, "/site/" + item.CategoryAlias + "/" + item.Alias)
            }).ToList());
        }
Пример #21
0
        protected override void Initialize(RequestContext context)
        {
            string clientToken = context.HttpContext.Request.GetClientToken();
            var    provider    = new Provider(DbConvention.GetTenant());
            var    token       = provider.GetToken(clientToken);
            string tenant      = DbConvention.GetTenant();

            if (token != null)
            {
                bool isValid = AccessTokens.IsValid(token.ClientToken, context.HttpContext.GetClientIpAddress(),
                                                    context.HttpContext.GetUserAgent());

                if (isValid)
                {
                    AppUsers.SetCurrentLogin(tenant, token.LoginId);
                    var loginView = AppUsers.GetCurrent(tenant, token.LoginId);

                    this.MetaUser = new MetaUser
                    {
                        Tenant      = tenant,
                        ClientToken = token.ClientToken,
                        LoginId     = token.LoginId,
                        UserId      = token.UserId,
                        OfficeId    = token.OfficeId
                    };

                    var identity = new ClaimsIdentity(token.Claims, DefaultAuthenticationTypes.ApplicationCookie,
                                                      ClaimTypes.NameIdentifier, ClaimTypes.Role);
                    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier,
                                                token.LoginId.ToString(CultureInfo.InvariantCulture)));

                    if (loginView.RoleName != null)
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Role, loginView.RoleName));
                    }

                    if (loginView.Email != null)
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Email, loginView.Email));
                    }

                    context.HttpContext.User = new ClaimsPrincipal(identity);
                }
            }

            base.Initialize(context);
        }
Пример #22
0
        public ActionResult Get(string resource = "")
        {
            string configFile =
                HostingEnvironment.MapPath($"~/Tenants/{DbConvention.GetTenant()}/Configs/Frapid.config");

            if (!System.IO.File.Exists(configFile))
            {
                return(this.HttpNotFound());
            }

            var allowed = ConfigurationManager.ReadConfigurationValue(configFile, "MyAllowedResources").Split(',');

            if (string.IsNullOrWhiteSpace(resource) || allowed.Length.Equals(0))
            {
                return(this.HttpNotFound());
            }

            string directory = HostingEnvironment.MapPath(Configuration.GetCurrentThemePath());

            if (directory == null)
            {
                return(this.HttpNotFound());
            }

            string path = Path.Combine(directory, resource);

            if (!System.IO.File.Exists(path))
            {
                return(this.HttpNotFound());
            }

            string extension = Path.GetExtension(path);

            if (!allowed.Contains(extension))
            {
                return(this.HttpNotFound());
            }

            if (this._exceptions.Contains(extension))
            {
                return(this.HttpNotFound());
            }

            string mimeType = this.GetMimeType(path);

            return(this.File(path, mimeType));
        }
Пример #23
0
        public static RssChannel GetRssChannel(HttpContextBase context, string categoryAlias, int pageNumber)
        {
            string title     = Configuration.Get("BlogTitle");
            string copyright = Configuration.Get("RssCopyrightText");
            int    ttl       = Configuration.Get("RssTtl").To <int>();
            int    limit     = Configuration.Get("RssPageSize").To <int>();
            int    offset    = (pageNumber - 1) * limit;

            List <PublishedContentView> contents;
            string category = string.Empty;

            if (!string.IsNullOrWhiteSpace(categoryAlias))
            {
                contents = Contents.GetBlogContents(categoryAlias, limit, offset).ToList();
                category = contents.Select(x => x.CategoryName).FirstOrDefault();
            }
            else
            {
                contents = Contents.GetBlogContents(limit, offset).ToList();
            }


            string domain = DbConvention.GetBaseDomain(context, true);

            var items = contents.Select(view => new RssItem
            {
                Title         = view.Title,
                Description   = view.Contents,
                Link          = UrlHelper.CombineUrl(domain, "/blog/" + view.CategoryAlias + "/" + view.Alias),
                Ttl           = ttl,
                Category      = view.CategoryName,
                PublishDate   = view.PublishOn,
                LastBuildDate = view.LastEditedOn
            }).ToList();

            var channel = new RssChannel
            {
                Title       = title,
                Description = "Category: " + category,
                Link        = UrlHelper.CombineUrl(domain, "/blog"),
                Items       = items,
                Copyright   = copyright,
                Category    = category
            };

            return(channel);
        }
Пример #24
0
        public void Register()
        {
            try
            {
                var installed = new DomainSerializer("DomainsInstalled.json");

                foreach (var domain in installed.Get())
                {
                    string database = DbConvention.GetDbNameByConvention(domain.DomainName);
                    InstalledDomains.Add(database, domain.DomainName, domain.AdminEmail);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Could not execute AddInstalledDomainProcedure. Exception: {Exception}", ex);
            }
        }
Пример #25
0
        private string GetUploadDirectory()
        {
            string tenant          = DbConvention.GetTenant();
            string uploadDirectory = HostingEnvironment.MapPath($"~/Tenants/{tenant}/Temp/");

            if (uploadDirectory == null || !Directory.Exists(uploadDirectory))
            {
                Log.Warning("Could not upload theme because the temporary directory {uploadDirectory} does not exist.",
                            uploadDirectory);
                throw new ThemeUploadException(
                          "Could not upload your theme. Check application logs for more information.");
            }

            return(uploadDirectory);

            ;
        }
Пример #26
0
        private string GetReturnUrl()
        {
            string returnUrl = "/";
            var    referrer  = this.Request.UrlReferrer;

            if (referrer != null)
            {
                string domain    = referrer.DnsSafeHost;
                bool   wellKnown = DbConvention.IsValidDomain(domain);

                if (wellKnown)
                {
                    returnUrl = referrer.ToString();
                }
            }
            return(returnUrl);
        }
Пример #27
0
        public ActionResult GetThemes()
        {
            string tenant = DbConvention.GetTenant();
            string path   = $"~/Tenants/{tenant}/Areas/Frapid.Dashboard/Themes";

            path = HostingEnvironment.MapPath(path);

            if (path == null || !Directory.Exists(path))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
            }

            var directories = Directory.GetDirectories(path);
            var templates   = directories.Select(directory => new DirectoryInfo(directory).Name).ToList();

            return(this.Ok(templates));
        }
Пример #28
0
        public List <string> Discover()
        {
            string tenant = DbConvention.GetTenant();
            string path   = $"~/Tenants/{tenant}/Areas/Frapid.WebsiteBuilder/Themes";

            path = HostingEnvironment.MapPath(path);

            if (path == null || !Directory.Exists(path))
            {
                Log.Warning("Could not discover theme(s) on path {path}.", path);
                throw new ThemeDiscoveryException(
                          "Cannot find the theme directory. Check application logs for more information.");
            }

            var directories = Directory.GetDirectories(path);

            return(directories.Select(directory => new DirectoryInfo(directory).Name).ToList());
        }
Пример #29
0
        protected string GetRazorView(string areaName, string path)
        {
            string catalog = DbConvention.GetCatalog();

            string overridePath = "~/Catalogs/{0}/Areas/{1}/Views/" + path;

            overridePath = string.Format(CultureInfo.InvariantCulture, overridePath, catalog, areaName);

            if (System.IO.File.Exists(HostingEnvironment.MapPath(overridePath)))
            {
                return(overridePath);
            }

            string defaultPath = "~/Areas/{0}/Views/{1}";

            defaultPath = string.Format(CultureInfo.InvariantCulture, defaultPath, areaName, path);

            return(defaultPath);
        }
Пример #30
0
        private static Token GetToken(HubCallerContext context)
        {
            string clientToken = context.Request.GetClientToken();
            var    provider    = new Provider(DbConvention.GetTenant());
            var    token       = provider.GetToken(clientToken);

            if (token != null)
            {
                bool isValid = AccessTokens.IsValid(token.ClientToken, context.Request.GetClientIpAddress(),
                                                    context.Headers["User-Agent"]);

                if (isValid)
                {
                    return(token);
                }
            }

            return(null);
        }