· 6 years ago · Nov 17, 2019, 08:54 AM
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Net;
5using System.Text;
6using System.Threading.Tasks;
7using Microsoft.AspNetCore.Authentication.JwtBearer;
8using Microsoft.AspNetCore.Builder;
9using Microsoft.AspNetCore.Hosting;
10using Microsoft.AspNetCore.HttpOverrides;
11using Microsoft.AspNetCore.HttpsPolicy;
12using Microsoft.AspNetCore.Identity;
13using Microsoft.AspNetCore.Mvc;
14using Microsoft.EntityFrameworkCore;
15using Microsoft.Extensions.Configuration;
16using Microsoft.Extensions.DependencyInjection;
17using Microsoft.Extensions.Logging;
18using Microsoft.Extensions.Options;
19using Microsoft.IdentityModel.Tokens;
20using Newtonsoft.Json.Serialization;
21using NSwag;
22using NSwag.Generation.Processors.Security;
23using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
24using projecten3_1920_backend_klim03.Data;
25using projecten3_1920_backend_klim03.Data.Repos;
26using projecten3_1920_backend_klim03.Domain.Models.Domain;
27using projecten3_1920_backend_klim03.Domain.Models.Interfaces;
28
29namespace projecten3_1920_backend_klim03
30{
31 public class Startup
32 {
33 public IConfiguration Configuration { get; }
34 public IHostingEnvironment Env { get; set; }
35
36 public Startup(IConfiguration configuration, IHostingEnvironment env)
37 {
38 Configuration = configuration;
39 Env = env;
40 }
41
42
43
44
45 // test
46 // This method gets called by the runtime. Use this method to add services to the container.
47 public void ConfigureServices(IServiceCollection services)
48 {
49 services.AddCors(o => o.AddPolicy("AllCors", builder =>
50 {
51 builder.AllowAnyOrigin()
52 .AllowAnyMethod()
53 .AllowAnyHeader();
54 }));
55
56 services.Configure<ForwardedHeadersOptions>(options =>
57 {
58 options.KnownProxies.Add(IPAddress.Parse("178.62.218.48"));
59 });
60
61 services.AddMvc()
62 .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
63 .AddJsonOptions(options =>
64 {
65 // Add option to ignore looping in JSON response (usefull for N:N relations)
66 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
67 options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
68 });
69
70 //services.AddDbContext<ApplicationDbContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("KlimaatMobielContext")));
71 //
72
73 if (Env.IsDevelopment())
74 {
75 string connectionString = $"Server=127.0.0.1;Database=db_klim_local;User=root;Password=rootroot";
76 services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("KlimaatMobielContext")));
77 //services.AddDbContextPool<ApplicationDbContext>(options => options.UseMySql(connectionString, mySqlOptions =>
78 //{
79 // mySqlOptions.ServerVersion(new Version(8, 0, 17), ServerType.MySql).DisableBackslashEscaping();
80 //}
81 //));
82 }
83 else
84 {
85 string connectionString = $"Server=178.62.218.48;Database=db_dev_klim_v2;User=dbklimuser;Password=pwklimuser";
86 services.AddDbContextPool<ApplicationDbContext>(options => options.UseMySql(connectionString, mySqlOptions =>
87 {
88 mySqlOptions.ServerVersion(new Version(8, 0, 17), ServerType.MySql).DisableBackslashEscaping();
89 }
90 ));
91 }
92
93
94
95
96 // Swagger configuration
97 // Swagger authentication is included and configured, add [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
98 // to the controller class / method to force authentication
99 services.AddOpenApiDocument(c =>
100 {
101 // TODO: Authentication key in project secrets
102 c.DocumentName = "apidocs";
103 c.Title = "Klimaatmobiel api";
104 c.Version = "v2";
105 c.Description = "api documentation";
106 c.AddSecurity("JWT", Enumerable.Empty<string>(), new OpenApiSecurityScheme
107 {
108 Type = OpenApiSecuritySchemeType.ApiKey,
109 Name = "Authorization",
110 In = OpenApiSecurityApiKeyLocation.Header,
111 Description = "Type into the textbox: Bearer {your JWT token}"
112 });
113
114 //c.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("JWT Token"));
115 c.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT"));
116
117 });
118
119 services.AddIdentity<AppUser, ApplicationRole>(cfg => cfg.User.RequireUniqueEmail = true)
120 .AddEntityFrameworkStores<ApplicationDbContext>();
121
122 services.AddAuthentication(x =>
123 {
124 x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
125 x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
126 x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
127 })
128 .AddJwtBearer(x =>
129 {
130 x.RequireHttpsMetadata = false;
131 x.SaveToken = true;
132 x.TokenValidationParameters = new TokenValidationParameters
133 {
134 ValidateIssuerSigningKey = true,
135 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])),
136 ValidateIssuer = false,
137 ValidateAudience = false,
138 RequireExpirationTime = false
139 };
140 });
141
142 services.Configure<IdentityOptions>(options =>
143 {
144 options.Password.RequireDigit = false;
145 options.Password.RequiredLength = 4;
146 options.Password.RequireNonAlphanumeric = false;
147 options.Password.RequireUppercase = false;
148 options.Password.RequireLowercase = false;
149
150 options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
151 options.Lockout.MaxFailedAccessAttempts = 5;
152 options.Lockout.AllowedForNewUsers = true;
153
154 // User settings.
155 options.User.RequireUniqueEmail = true;
156 });
157
158
159 services.AddScoped<IOrderRepo, OrderRepo>();
160 services.AddScoped<IOrderItemRepo, OrderItemRepo>();
161 services.AddScoped<IAppUserRepo, AppUserRepo>();
162 services.AddScoped<IGroupRepo, GroupRepo>();
163 services.AddScoped<IClassRoomRepo, ClassRoomRepo>();
164 services.AddScoped<IProductRepo, ProductRepo>();
165 services.AddScoped<IProjectRepo, ProjectRepo>();
166 services.AddScoped<ISchoolRepo, SchoolRepo>();
167 services.AddScoped<IApplicationDomainRepo, ApplicationDomainRepo>();
168
169 services.AddScoped<IProjectTemplateRepo, ProjectTemplateRepo>();
170 services.AddScoped<IProductTemplateRepo, ProductTemplateRepo>();
171
172
173 services.AddScoped<DataInit>();
174
175 }
176
177 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
178 public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataInit dataInit)
179 {
180 if (env.IsDevelopment())
181 {
182 app.UseDeveloperExceptionPage();
183 }
184 else
185 {
186 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
187 app.UseHsts();
188 }
189
190 app.UseHttpsRedirection();
191
192 app.UseForwardedHeaders(new ForwardedHeadersOptions
193 {
194 ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
195 });
196
197 app.UseAuthentication();
198
199 app.UseCors("AllCors");
200 app.UseMvc();
201
202 app.UseSwaggerUi3();
203 app.UseOpenApi();
204
205 dataInit.InitializeData().Wait();
206 }
207 }
208}