Example #1
0
        public static string GetAllJsValidations()
        {
            var assembly       = AssemblyIdentifier.Get();
            var validatorTypes = assembly.GetTypes()
                                 .Where(x =>
                                        (x.BaseType?.IsGenericType ?? false) &&
                                        x.BaseType.GetGenericTypeDefinition() == typeof(AbstractValidator <>))
                                 .Select(x => x);

            var jsValidatorObjectBuilder = new StringBuilder();

            jsValidatorObjectBuilder.AppendLine("{");

            foreach (var type in validatorTypes)
            {
                try
                {
                    dynamic validator = Activator.CreateInstance(type);
                    jsValidatorObjectBuilder.Append(JsConverter.GetJavascript(validator));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
            jsValidatorObjectBuilder.AppendLine("};");
            return(jsValidatorObjectBuilder.ToString());
        }
Example #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddResponseCaching();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest).AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Application.AssemblyIdentifier>());

            //Add RedisCache
            services.AddDistributedRedisCache(options =>
            {
                options.InstanceName  = "honoplay";
                options.Configuration = Environment.GetEnvironmentVariable("REDIS_CACHE_SERVICE")?.ToString();
            });
            services.Configure <RouteOptions>(options => options.LowercaseUrls = true);
            // Add MediatR
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>));
            //services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPerformanceBehaviour<,>));
            //services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestValidationBehavior<,>)); // TODO: çalışan bir nokta görülmediği için kontrol amaçlı kapatıldı
            services.AddMediatR(AssemblyIdentifier.Get());

            services.AddScoped <ITraineeUserService, TraineeUserService>();
            services.AddSingleton <ICacheService, CacheManager>();

            // Add DbContext using SQL Server Provider
            services.AddDbContextPool <HonoplayDbContext>(options =>
                                                          options.UseSqlServer(StringConstants.ConnectionString,
                                                                               b => b.MigrationsAssembly("Honoplay.Persistence")));

            // configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = System.Text.Encoding.ASCII.GetBytes(appSettings.JWTSecret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                //x.RequireHttpsMetadata = false;
                //x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };
                x.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        if (!string.IsNullOrEmpty(accessToken))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = y =>
                    {
                        if (y.Principal.Claims.First(c => c.Type == ClaimTypes.Webpage).Value != y.HttpContext.Request.Host.Host)
                        {
                            y.Fail(new UnauthorizedAccessException());
                        }
                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = y =>
                    {
                        Console.WriteLine("Exception:{0}", y.Exception.Message);
                        return(Task.CompletedTask);
                    }
                };
            });

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "HonoPlay API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer",
                                        new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Please enter into field the word 'Bearer' following by space and JWT",
                    Name        = "Authorization",
                    Type        = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() },
                });
                // Configure Swagger to use the xml documentation file
                var xmlFile = Configuration.GetValue <string>(WebHostDefaults.ContentRootKey) + "/SwaggerDoc.xml";
                c.IncludeXmlComments(xmlFile);
            });
        }