Exemplo n.º 1
0
        public ActionResult Save([FromBody] ConnectionStringDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var result = _services.Post(model);

            return(Ok(result));
        }
Exemplo n.º 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(options =>
            {
                options.AddPolicy(CorsPolicy, builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().Build());
            });
            services.AddControllers();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    ValidAudience    = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

            services.AddDbContext <ApplicationDbContext>(options =>
            {
                options.UseSqlServer(_connectionString); // SQL SERVER
            });

            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ILoginService, LoginService>();
            services.AddScoped <IPaymentService, PaymentService>();
            services.AddScoped <IOrderService, OrderService>();
            services.AddScoped <IBucketService, BucketService>();
            services.AddScoped <IHistoryService, HistoryService>();

            services.AddMvc();

            var cs = new ConnectionStringDto()
            {
                ConnectionString = _connectionString
            };

            services.AddSingleton(cs);

            var mappingConfig = new AutoMapper.MapperConfiguration(cfg =>
            {
                cfg.Mapping();
            });

            services.AddSingleton(x => mappingConfig.CreateMapper());
            services.AddScoped <DbContext, ApplicationDbContext>();
            services.AddScoped <DbContextOptions <ApplicationDbContext> >();
        }
Exemplo n.º 3
0
 public BaseTest()
 {
     _testcs = new ConnectionStringDto();
     _testcs.ConnectionString = "Server=BASTION-1603\\UCZELNIA;Initial Catalog=Kawiarnia;User ID=Coffe;Password=coffe;Connection Timeout=30;";
     if (!_isInitialized)
     {
         Mapper.Initialize(cfg =>
         {
             cfg.AddProfile <AutoMapperProfile>();
         });
         _isInitialized = true;
     }
 }
Exemplo n.º 4
0
        public OperationResult <ConnectionStringEntity> Post(ConnectionStringDto model)
        {
            var result = new OperationResult <ConnectionStringEntity>();

            var modelo = _mapper.Map <ConnectionStringEntity>(model);

            _services.ConnectionStrings.Add(modelo);
            _services.SaveChanges();

            result.Success      = true;
            result.ResultObject = modelo;

            return(result);
        }
Exemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Framework Services
            // Add framework services.
            services.AddOptions();
            services.AddApplicationInsightsTelemetry(Configuration);
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(10);
                options.Cookie.HttpOnly = true;
            });
            services.AddDbContext <ApplicationDbContext>(options =>
            {
                options.UseSqlServer(_connectionString);  // SQL SERVER
            });
            services.AddDefaultIdentity <User>()
            .AddEntityFrameworkStores <ApplicationDbContext>();
            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
            services.Configure <FormOptions>(x =>
            {
                x.ValueLengthLimit         = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;
                x.KeyLengthLimit           = int.MaxValue;
            });
            services.AddScoped <UserManager <IdentityUser>, UserManager <IdentityUser> >();
            services.AddScoped <IUserStore <IdentityUser>, UserStore <IdentityUser> >();
            services.AddScoped <IPasswordHasher <IdentityUser>, PasswordHasher <IdentityUser> >();
            services.AddScoped <SignInManager <IdentityUser>, SignInManager <IdentityUser> >();
            services.AddScoped <IUserClaimsPrincipalFactory <IdentityUser>, UserClaimsPrincipalFactory <IdentityUser> >();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            #endregion

            #region Our Services
            var cs = new ConnectionStringDto()
            {
                ConnectionString = _connectionString
            };
            services.AddSingleton(cs);
            services.AddScoped <DbContext, ApplicationDbContext>();
            services.AddScoped <DbContextOptions <ApplicationDbContext> >();
            #endregion
            Services = services;
        }
Exemplo n.º 6
0
        public OperationResult <ConnectionStringEntity> Put(ConnectionStringDto model)
        {
            var result = new OperationResult <ConnectionStringEntity>();

            try
            {
                var modelo = _mapper.Map <ConnectionStringEntity>(model);
                _services.ConnectionStrings.Add(modelo);
                _services.SaveChanges();

                result.Success      = true;
                result.ResultObject = modelo;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Framework Services
            // Add framework services.
            services.Configure <JwtIssuerOptions>(options => Configuration.GetSection("JwtIssuerOptions").Bind(options));
            services.AddOptions();
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(10);
                options.Cookie.HttpOnly = true;
            });

            services.AddDbContext <ApplicationDbContext>(options =>
            {
                options.UseSqlServer(_connectionString);  // SQL SERVER
                //options.UseMySql(_connectionString); // My SQL
            });

            services.AddIdentity <User, Role>(o =>
            {
                o.Password.RequireDigit           = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireLowercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.User.RequireUniqueEmail         = false;
            }).AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

            // Uncomment to enable cors
            //var corsBuilder = new CorsPolicyBuilder();
            //corsBuilder.AllowAnyHeader();
            //corsBuilder.WithMethods("GET", "POST", "PUT", "DELETE");
            ////corsBuilder.WithOrigins("http://localhost:4583");
            //corsBuilder.AllowCredentials();

            //services.AddCors(options =>
            //{
            //    options.AddPolicy("AllowCors", corsBuilder.Build());
            //});

            services.Configure <FormOptions>(x =>
            {
                x.ValueLengthLimit         = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;
                x.KeyLengthLimit           = int.MaxValue;
            });
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "Jwt";
                options.DefaultChallengeScheme    = "Jwt";
            }).AddJwtBearer("Jwt", options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false,
                    //ValidAudience = "the audience you want to validate",
                    ValidateIssuer = false,
                    //ValidIssuer = "the isser you want to validate",

                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtIssuerOptions:SecretKey"])),

                    ValidateLifetime = true,            //validate the expiration and not before values in the token

                    ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date
                };
            });
            services.AddScoped((serviceProvider) =>
            {
                var config = serviceProvider.GetRequiredService <IConfiguration>();
                return(new SmtpClient()
                {
                    Host = config.GetValue <String>("Email:Smtp:Host"),
                    Port = config.GetValue <int>("Email:Smtp:Port"),
                    Credentials = new NetworkCredential(
                        config.GetValue <String>("Email:Smtp:Username"),
                        config.GetValue <String>("Email:Smtp:Password")
                        )
                });
            });
            #endregion

            #region Our Services

            var cs = new ConnectionStringDto()
            {
                ConnectionString = _connectionString
            };
            services.AddSingleton(cs);
            var mappingConfig = new AutoMapper.MapperConfiguration(cfg =>
            {
                cfg.Mapping();
            });
            services.AddSingleton(x => mappingConfig.CreateMapper());
            services.AddScoped <DbContext, ApplicationDbContext>();
            services.AddScoped <DbContextOptions <ApplicationDbContext> >();
            services.AddScoped <IGroupService, GroupService>();
            services.AddScoped <IGradeService, GradeService>();
            services.AddScoped <ISubjectService, SubjectService>();
            services.AddScoped <ITeacherService, TeacherService>();
            services.AddScoped <IStudentService, StudentService>();
            #endregion
            Services = services;

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

            services.AddDbContext <SchoolRegisterWebContext>(options =>
                                                             options.UseSqlServer(Configuration.GetConnectionString("SchoolRegisterWebContext")));
        }
Exemplo n.º 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Framework Services
            // Add framework services.
            services.AddOptions();
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(10);
                options.Cookie.HttpOnly = true;
            });

            services.AddDbContext <ApplicationDbContext <User, Role, int> >(options =>
            {
                options.UseSqlServer(_connectionString);  // SQL SERVER
                                                          // options.UseMySql(_connectionString); // My SQL
            });

            services.AddIdentity <User, Role>(o =>
            {
                o.Password.RequireDigit           = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireLowercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.User.RequireUniqueEmail         = false;
            }).AddEntityFrameworkStores <ApplicationDbContext <User, Role, int> >()
            .AddDefaultTokenProviders();
            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.WithMethods("GET", "POST", "PUT", "DELETE");
            corsBuilder.WithOrigins("*");
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("AllowCors", corsBuilder.Build());
            });
            services.Configure <FormOptions>(x =>
            {
                x.ValueLengthLimit         = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;
                x.KeyLengthLimit           = int.MaxValue;
            });
            services.AddMvc();

            // enable JwT Token authentication for WEB API
            //services.AddAuthentication(options =>
            //{
            //    options.DefaultAuthenticateScheme = "Jwt";
            //    options.DefaultChallengeScheme = "Jwt";
            //}).AddJwtBearer("Jwt", options =>
            //{
            //    options.TokenValidationParameters = new TokenValidationParameters
            //    {
            //        ValidateAudience = false,
            //        //ValidAudience = "the audience you want to validate",
            //        ValidateIssuer = false,
            //        //ValidIssuer = "the isser you want to validate",
            //        ValidateIssuerSigningKey = true,
            //        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtIssuerOptions:SecretKey"])),
            //        ValidateLifetime = true, //validate the expiration and not before values in the token
            //        ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date
            //    };
            //});
            #endregion

            #region Our Services

            var cs = new ConnectionStringDto()
            {
                ConnectionString = _connectionString
            };
            services.AddSingleton(cs);

            services.AddScoped <DbContext, ApplicationDbContext <User, Role, int> >();
            services.AddScoped <DbContextOptions <ApplicationDbContext <User, Role, int> > >();
            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddTransient <IEmailSender, EmailSender>();
            var mappingConfig = new AutoMapper.MapperConfiguration(cfg =>
            {
                cfg.Mapping(services.BuildServiceProvider().GetService <UserManager <User> >());
            });

            services.AddSingleton(x => mappingConfig.CreateMapper());
            services.AddScoped <IRepository <User>, EntityFrameworkRepository <User> >();
            services.AddScoped <IRepository <Role>, EntityFrameworkRepository <Role> >();
            services.AddScoped <IRepository <IdentityUserRole <int> >, EntityFrameworkRepository <IdentityUserRole <int> > >();

            // >> KPA
            services.AddScoped <ICategoryService, CategoryService>();



            // << KPA
            #endregion
            Services = services;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Framework Services
            // Add framework services.
            services.AddOptions();

            services.AddApplicationInsightsTelemetry(Configuration);

            DbLocation databaseLocation = new DbLocation(DatabaseLocation.InMemory);

            services.AddDbContext <PermissionManagerDbContext <User, Role, int> >(options =>
            {
                if (databaseLocation.DatabaseLocation == DatabaseLocation.InMemory)
                {
                    options.UseInMemoryDatabase(); // in memory DB
                }
                else if (databaseLocation.DatabaseLocation == DatabaseLocation.SqlServer)
                {
                    options.UseSqlServer(_connectionString); // existing database
                }
            });

            services.AddIdentity <User, Role>(o =>
            {
                o.Password.RequireDigit           = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireLowercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.User.RequireUniqueEmail         = true;
                o.Cookies.ApplicationCookie.AutomaticChallenge = false;
                o.Cookies.ApplicationCookie.LoginPath          = null;
            })
            .AddEntityFrameworkStores <PermissionManagerDbContext <User, Role, int>, int>()
            .AddDefaultTokenProviders();

            //services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

            var corsBuilder = new CorsPolicyBuilder();
            corsBuilder.AllowAnyHeader();
            corsBuilder.AllowAnyMethod();
            corsBuilder.AllowAnyOrigin();
            corsBuilder.AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", corsBuilder.Build());
            });


            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddAuthorization(options =>
            {
                options.AddPolicy("IdentityUser",
                                  policy => policy.RequireClaim("IdentityUser", "User"));
            });

            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));


            // Configure JwtIssuerOptions
            int tokenExpirationMinutes = 20;

#if DEBUG
            tokenExpirationMinutes = 150000;
#endif


            services.Configure <JwtIssuerOptions>(options =>
            {
                options.Issuer             = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience           = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
                options.ValidFor           = TimeSpan.FromMinutes(tokenExpirationMinutes);
            });

            #endregion

            #region Our Services

            var cs = new ConnectionStringDto()
            {
                ConnectionString = _connectionString
            };
            services.AddSingleton <ConnectionStringDto>(cs);
            services.AddSingleton <DbLocation>(databaseLocation);
            services.AddScoped <DbContext, PermissionManagerDbContext <User, Role, int> >();
            services.AddScoped <DbContextOptions <PermissionManagerDbContext <User, Role, int> > >();
            services.AddScoped <PermissionManager <User, Role, int> >();
            services.AddScoped <PermissionManagerDbContext <User, Role, int> >();
            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddScoped <TokenProviderMiddleware>();

            var mappingConfig = new AutoMapper.MapperConfiguration(cfg =>
            {
                cfg.AddAdminMapping();
            });

            services.AddSingleton(x => mappingConfig.CreateMapper());
            services.AddScoped <IRepository <User>, EntityFrameworkRepository <User> >();
            // services.AddScoped<IRepository<IdentityUser<int>>, EntityFrameworkRepository<IdentityUser<int>>>();
            services.AddScoped <IRepository <Role>, EntityFrameworkRepository <Role> >();
            services.AddScoped <IRepository <IdentityUserRole <int> >, EntityFrameworkRepository <IdentityUserRole <int> > >();
            services.AddScoped <IRepository <Permission>, EntityFrameworkRepository <Permission> >();
            services.AddScoped <IRepository <PermissionGroup>, EntityFrameworkRepository <PermissionGroup> >();
            services.AddScoped <IRepository <PermissionRole <Role, int> >, EntityFrameworkRepository <PermissionRole <Role, int> > >();

            #endregion
        }
 public ChatRepository(ConnectionStringDto connectionStringDto)
 {
     _connectionStringDto = connectionStringDto;
 }
Exemplo n.º 11
0
 public ApplicationDbContext(ConnectionStringDto connectionStringDto)
 {
     _connectionStringDto = connectionStringDto;
 }
Exemplo n.º 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Framework Services
            // Add framework services.
            services.AddOptions();
            services.AddApplicationInsightsTelemetry(Configuration);
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                {
                    new CultureInfo("en"),
                    new CultureInfo("pl-PL")
                    // add other cultures
                };
                options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;
            });
            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(10);
                options.Cookie.HttpOnly = true;
            });
            services.AddDbContext <ApplicationDbContext>(options =>
            {
                options.UseSqlServer(_connectionString);  // SQL SERVER
            });
            services.AddIdentity <User, Role>()
            .AddRoles <Role>()
            .AddRoleManager <RoleManager <Role> >()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddSignInManager <SignInManager <User> >()
            .AddDefaultUI()
            .AddDefaultTokenProviders();
            services.AddScoped <IUserClaimsPrincipalFactory <User>, UserClaimsPrincipalFactory <User, Role> >();
            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
            services.Configure <FormOptions>(x =>
            {
                x.ValueLengthLimit         = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;
                x.KeyLengthLimit           = int.MaxValue;
            });

            services.AddScoped((serviceProvider) =>
            {
                var config = serviceProvider.GetRequiredService <IConfiguration>();
                return(new SmtpClient()
                {
                    Host = config.GetValue <String>("Email:Smtp:Host"),
                    Port = config.GetValue <int>("Email:Smtp:Port"),
                    Credentials = new NetworkCredential(
                        config.GetValue <String>("Email:Smtp:Username"),
                        config.GetValue <String>("Email:Smtp:Password")
                        )
                });
            });

            services.AddScoped <IGroupService, GroupService>();
            services.AddScoped <IGradeService, GradeService>();
            services.AddScoped <ISubjectService, SubjectService>();
            services.AddScoped <ITeacherService, TeacherService>();
            services.AddScoped <IStudentService, StudentService>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(x =>
                            x.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat)
            .AddViewLocalization()
            .AddDataAnnotationsLocalization();
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddSignalR();
            #endregion

            #region Our Services
            var cs = new ConnectionStringDto()
            {
                ConnectionString = _connectionString
            };
            services.AddSingleton(cs);
            var mappingConfig = new AutoMapper.MapperConfiguration(cfg =>
            {
                cfg.Mapping();
            });
            services.AddSingleton(x => mappingConfig.CreateMapper());
            services.AddScoped <DbContext, ApplicationDbContext>();
            services.AddScoped <DbContextOptions <ApplicationDbContext> >();
            services.AddScoped <ISubjectService, SubjectService>();
            #endregion
            Services = services;
        }
Exemplo n.º 13
0
 public DataContext(ConnectionStringDto connectionString)
 {
     _connectionString = connectionString;
 }