Exemple #1
0
        public static async Task <bool> HasNoRelatedEntities(Tag entity, IntranetApiContext context, IEnumerable <object> ignore = null)
        {
            // Eager load all navigation properties
            await context
            .Entry(entity)
            .Collection(c => c.FaqTags)
            .LoadAsync();

            await context
            .Entry(entity)
            .Collection(c => c.NewsTags)
            .LoadAsync();

            await context
            .Entry(entity)
            .Collection(c => c.PolicyTags)
            .LoadAsync();

            if (ignore.IsNotNull())
            {
                return
                    (((entity.FaqTags.Intersect(ignore).Any() && entity.FaqTags.Count == 1) || entity.FaqTags.Count == 0) &&
                     ((entity.NewsTags.Intersect(ignore).Any() && entity.NewsTags.Count == 1) || entity.NewsTags.Count == 0) &&
                     ((entity.PolicyTags.Intersect(ignore).Any() && entity.PolicyTags.Count == 1) || entity.PolicyTags.Count == 0));
            }

            return
                (entity.NewsTags.Count == 0 &&
                 entity.FaqTags.Count == 0 &&
                 entity.PolicyTags.Count == 0);
        }
 public NewsController(IntranetApiContext context,
                       IDateTimeFactory dateTimeFactory,
                       IFileStorageService fileStorageService)
 {
     _fileStorageService = fileStorageService;
     _context            = context;
     _dateTimeFactory    = dateTimeFactory;
 }
        // TODO: Add tests
        /// <summary>
        /// Adds keywords to <paramref name="news"/> based on <paramref name="keywordsAsOneString"/>. Will split on ',' and ';'.
        /// </summary>
        /// <param name="keywordsAsOneString"></param>
        /// <param name="news"></param>
        /// <param name="context"></param>
        public static void SetKeywords(string keywordsAsOneString, News news, IntranetApiContext context)
        {
            if (keywordsAsOneString.IsNull())
            {
                return;
            }

            var keywords = keywordsAsOneString?
                           .Split(',', ';')?
                           .Distinct()?
                           .Where(k => !String.IsNullOrWhiteSpace(k))?
                           .Select(k => k.Trim());

            var allKeywordEntities = context.Keywords?
                                     .Include(k => k.NewsKeyword)
                                     .ThenInclude(nk => nk.News)?
                                     .Where(k => keywords.Contains(k.Name, StringComparer.OrdinalIgnoreCase) || k.NewsKeyword.Any(nk => nk.NewsId.Equals(news.Id)))
                                     .ToList();

            var exisitingKeywordEntities = allKeywordEntities?
                                           .Where(k => keywords.Contains(k.Name, StringComparer.OrdinalIgnoreCase));

            var alreadyAttachedKeywordEntities = exisitingKeywordEntities
                                                 .Where(k => k.NewsKeyword.Any(nk => nk.News.Id == news.Id));

            var alreadyAttachedNewsKeywordEntities = exisitingKeywordEntities
                                                     .SelectMany(k => k.NewsKeyword)
                                                     .Where(nk => nk.News.Id == news.Id);

            var existingKeywords = exisitingKeywordEntities
                                   .Select(k => k.Name);

            var newKeywords = keywords?.Except(existingKeywords);

            var newKeywordEntities = newKeywords?
                                     .Select(name => new Keyword {
                Name = name
            });

            var allKeywordEntitiesToBeAttached = exisitingKeywordEntities?
                                                 .Except(alreadyAttachedKeywordEntities)
                                                 .Concat(newKeywordEntities ?? new List <Keyword>());

            var newsKeywordEntities = allKeywordEntitiesToBeAttached?
                                      .Select(k => new NewsKeyword {
                Keyword = k
            })
                                      .Concat(alreadyAttachedNewsKeywordEntities);

            news.NewsKeywords = newsKeywordEntities?.ToList();
        }
Exemple #4
0
        public static async Task <bool> HasNoRelatedEntities(Category entity, IntranetApiContext context, object ignore = null)
        {
            // Eager load all navigation properties
            await context
            .Entry(entity)
            .Collection(c => c.Faqs)
            .LoadAsync();

            await context
            .Entry(entity)
            .Collection(c => c.Policies)
            .LoadAsync();

            if (ignore.IsNotNull())
            {
                return
                    (((entity.Faqs.Contains(ignore) && entity.Faqs.Count == 1) || entity.Faqs.Count == 0) &&
                     ((entity.Policies.Contains(ignore) && entity.Policies.Count == 1) || entity.Policies.Count == 0));
            }

            return(entity.Policies.Count == 0 && entity.Faqs.Count == 0);
        }
Exemple #5
0
 public NewsController(IntranetApiContext intranetApiContext, IDateTimeFactory dateTimeFactory)
 {
     _dateTimeFactory    = dateTimeFactory;
     _intranetApiContext = intranetApiContext;
 }
 public PoliciesController(IntranetApiContext context, IFileStorageService fileStorageService)
 {
     _context            = context;
     _fileStorageService = fileStorageService;
 }
 public FaqsController(IntranetApiContext context)
 {
     _context = context;
 }
Exemple #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IntranetApiContext dbContext)
        {
            #region Migrate Database
            try
            {
                dbContext.Database.Migrate();
            }
            catch (Exception exception)
            {
                // TODO: Add logging, notification etc.
                Console.WriteLine(exception.Message);
                Environment.Exit(1);
            }
            #endregion

            #region Cookie Authentication
            // Add Authentication
            app.UseAuthentication();
            #endregion

            #region Logging
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            #endregion

            #region Response Compression
            app.UseResponseCompression();
            #endregion

            #region Static Files
            app.UseProtectFolder(new ProtectFolderOptions
            {
                Path = "/Assets",
            });

            app.UseProtectFolder(new ProtectFolderOptions
            {
                Path = "/Docs",
            });

            app.UseStaticFiles(); // For the wwwroot folder

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), @"Assets")
                    ),
                RequestPath = new PathString("/Assets")
            });

            app.UseFileServer(new FileServerOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), @"Documentation")
                    ),
                RequestPath = new PathString("/Docs")
            });
            #endregion

            #region Mvc
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=News}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "auth",
                    template: "{action=Index}",
                    defaults: new { controller = "Authentication" });
            });
            #endregion
        }
Exemple #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IntranetApiContext dbContext)
        {
            #region Logger
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            #endregion

            #region Migrate Database
            try
            {
                dbContext.Database.Migrate();
            }
            catch (Exception exception)
            {
                // TODO: Add logging, notification etc.
                Console.WriteLine(exception.Message);
                Environment.Exit(1);
            }
            #endregion

            #region Authentication
            var secretKey  = Configuration["INTRANET_JWT"];
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = "ExampleIssuer",

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience    = "ExampleAudience",

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero,
            };

            var jwtBearerOptions = new JwtBearerOptions
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = tokenValidationParameters
            };

            app.UseJwtBearerAuthentication(jwtBearerOptions);
            #endregion

            #region Swagger
            if (env.IsDevelopment())
            {
                app.UseSwagger(c =>
                {
                    c.RouteTemplate = "api-docs/swagger/{documentName}/swagger.json";
                });
            }
            #endregion

            #region CORS
            if (!env.IsProduction())
            {
                app.UseCors("CorsPolicy");
            }
            #endregion

            #region Mvc
            app.UseMvc();
            #endregion
        }
Exemple #10
0
 public CategoriesController(IntranetApiContext context)
 {
     _context = context;
 }