premik na samo program.cs

This commit is contained in:
2026-06-22 16:19:22 +02:00
parent bcde4178df
commit b4f70ad250
7 changed files with 2970 additions and 365 deletions

View File

@@ -11,16 +11,19 @@ using Microsoft.EntityFrameworkCore;
using ProjecThing.Models.CodeTable;
using ProjecThing.Models.Invoice;
using ProjecThing.Models.Project;
using Microsoft.AspNetCore.DataProtection.EntityFrameworkCore;
namespace ProjecThing.Data
{
public class ApplicationDbContext : IdentityDbContext<IdentityApplicationUser, IdentityApplicationRole, int>
public class ApplicationDbContext : IdentityDbContext<IdentityApplicationUser, IdentityApplicationRole, int>, IDataProtectionKeyContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<DataProtectionKey> DataProtectionKeys { get; set; }
public DbSet<CodeTableEmployee> CodeTableEmployees { get; set; }
public DbSet<CodeTableCountry> CodeTableCountries { get; set; }
public DbSet<CodeTableCompany> CodeTableCompanies { get; set; }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ProjecThing.Migrations
{
public partial class AddDataProtectionKeys : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "DataProtectionKeys",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
FriendlyName = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
Xml = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_DataProtectionKeys", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DataProtectionKeys");
}
}
}

View File

@@ -1,9 +1,9 @@
// <auto-generated />
// <auto-generated />
using System;
using ProjecThing.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using ProjecThing.Data;
#nullable disable
@@ -19,6 +19,130 @@ namespace ProjecThing.Migrations
.HasAnnotation("ProductVersion", "6.0.1")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("FriendlyName")
.HasColumnType("longtext");
b.Property<string>("Xml")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("DataProtectionKeys");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("IdRoleClaim");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<int>("RoleId")
.HasColumnType("int")
.HasColumnName("IdRoleFk");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("IdentityRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("IdUserClaim");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<int>("UserId")
.HasColumnType("int")
.HasColumnName("IdUserFk");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("IdentityUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderKey")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("longtext");
b.Property<int>("UserId")
.HasColumnType("int")
.HasColumnName("IdUserFk");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("IdentityUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<int>", b =>
{
b.Property<int>("UserId")
.HasColumnType("int")
.HasColumnName("IdUserFk");
b.Property<int>("RoleId")
.HasColumnType("int")
.HasColumnName("IdRoleFk");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("IdentityUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
{
b.Property<int>("UserId")
.HasColumnType("int")
.HasColumnName("IdUserFk");
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("Name")
.HasColumnType("varchar(255)");
b.Property<string>("Value")
.HasColumnType("longtext");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("IdentityUserTokens", (string)null);
});
modelBuilder.Entity("ProjecThing.Models.CodeTable.CodeTableCompany", b =>
{
b.Property<int>("IdCompany")
@@ -1549,109 +1673,53 @@ namespace ProjecThing.Migrations
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("IdRoleClaim");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<int>("RoleId")
.HasColumnType("int")
.HasColumnName("IdRoleFk");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("IdentityRoleClaims", (string)null);
b.HasOne("ProjecThing.Models.IdentityApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("IdUserClaim");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<int>("UserId")
.HasColumnType("int")
.HasColumnName("IdUserFk");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("IdentityUserClaims", (string)null);
b.HasOne("ProjecThing.Models.IdentityApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderKey")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("longtext");
b.Property<int>("UserId")
.HasColumnType("int")
.HasColumnName("IdUserFk");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("IdentityUserLogins", (string)null);
b.HasOne("ProjecThing.Models.IdentityApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<int>", b =>
{
b.Property<int>("UserId")
.HasColumnType("int")
.HasColumnName("IdUserFk");
b.HasOne("ProjecThing.Models.IdentityApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Property<int>("RoleId")
.HasColumnType("int")
.HasColumnName("IdRoleFk");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("IdentityUserRoles", (string)null);
b.HasOne("ProjecThing.Models.IdentityApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
{
b.Property<int>("UserId")
.HasColumnType("int")
.HasColumnName("IdUserFk");
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("Name")
.HasColumnType("varchar(255)");
b.Property<string>("Value")
.HasColumnType("longtext");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("IdentityUserTokens", (string)null);
b.HasOne("ProjecThing.Models.IdentityApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ProjecThing.Models.CodeTable.CodeTableCompany", b =>
@@ -2273,57 +2341,6 @@ namespace ProjecThing.Migrations
b.Navigation("Company");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
{
b.HasOne("ProjecThing.Models.IdentityApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
{
b.HasOne("ProjecThing.Models.IdentityApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
{
b.HasOne("ProjecThing.Models.IdentityApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<int>", b =>
{
b.HasOne("ProjecThing.Models.IdentityApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ProjecThing.Models.IdentityApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
{
b.HasOne("ProjecThing.Models.IdentityApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ProjecThing.Models.CodeTable.CodeTableCompany", b =>
{
b.Navigation("CompanyDepartement");

View File

@@ -1,16 +1,31 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Web;
using ProjecThing.Data;
using ProjecThing.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Threading.Tasks;
using NLog;
using NLog.Web;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace ProjecThing
{
@@ -21,35 +36,223 @@ namespace ProjecThing
//var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
//logger.Debug("INIT");
CreateHostBuilder(args).Build().Run();
var builder = WebApplication.CreateBuilder(args);
// Configure NLog
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Host.UseNLog();
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//builder.Services.Configure<ForwardedHeadersOptions>(options =>
//{
// options.KnownProxies.Add(IPAddress.Parse("192.168.111.78"));
//});
// Database connection
string connectionString = builder.Configuration.GetConnectionString("DataConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
//builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DataConnection")));
// Session
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromHours(3);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.MaxAge = TimeSpan.FromHours(3);
});
// JWT
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "ProjecThing",
ValidAudience = "Android",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("!Appli$cation#9999#!"))
};
});
// Identity
builder.Services.AddIdentity<IdentityApplicationUser, IdentityApplicationRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
builder.Services.AddRazorPages(options =>
{
//options.Conventions.AddPageRoute("/Administration/Users", "/AdministrationUsers");
}).AddRazorRuntimeCompilation();
//builder.Services.Configure<ForwardedHeadersOptions>(options =>
//{
// options.ForwardedHeaders =
// ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
// options.KnownProxies.Add(IPAddress.Parse("192.168.111.78"));
// //options.ForwardedForHeaderName = "X-Forwarded-For-My-Custom-Header-Name";
//});
builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
builder.Services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 8;
options.Password.RequiredUniqueChars = 1;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 3;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
options.User.RequireUniqueEmail = true;
});
builder.Services.ConfigureApplicationCookie(options =>
{
// Cookie
options.Cookie.MaxAge = TimeSpan.FromHours(3);
options.Cookie.HttpOnly = true;
options.SlidingExpiration = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.None;//Samo unencripted na locas
options.LoginPath = $"/User/Login";
options.LogoutPath = $"/User/Logout";
options.AccessDeniedPath = $"/";
options.ExpireTimeSpan = TimeSpan.FromHours(3);//Povecano na 15min
});
builder.Services.AddDistributedMemoryCache();
builder.Services.Configure<IISOptions>(options =>
{
options.AutomaticAuthentication = false;
});
//builder.Services.AddDataProtection().SetApplicationName("ProjecThing").PersistKeysToFileSystem(new DirectoryInfo(@"Keys/"));
builder.Services.AddDataProtection()
.SetApplicationName("ProjecThing")
.PersistKeysToDbContext<ApplicationDbContext>()
.AddKeyManagementOptions(options =>
{
options.NewKeyLifetime = new TimeSpan(365, 0, 0, 0);
options.AutoGenerateKeys = true;
});
var app = builder.Build();
// Apply migrations in production
#if !DEBUG
ApplyMigrations(app);
#endif
// ===== Configure Middleware Pipeline =====
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseForwardedHeaders();
}
else
{
app.UseExceptionHandler("/Error");
//app.UseForwardedHeaders();
app.UseHsts();
}
//app.UseForwardedHeaders(new ForwardedHeadersOptions
//{
// ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
//});
var defaultCulture = new CultureInfo("sl-SI");
var localizationOptions = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(defaultCulture),
SupportedCultures = new List<CultureInfo> { defaultCulture },
SupportedUICultures = new List<CultureInfo> { defaultCulture }
};
app.UseRequestLocalization(localizationOptions);
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.MapRazorPages();
app.MapControllers();
app.Run();
//CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(
webBuilder =>
private static void ApplyMigrations(IHost app)
{
using var scope = app.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
// Check and apply pending migrations
var pendingMigrations = dbContext.Database.GetPendingMigrations();
if (pendingMigrations.Any())
{
webBuilder.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
}).UseNLog();
Console.WriteLine("Applying pending migrations...");
dbContext.Database.Migrate();
Console.WriteLine("Migrations applied successfully.");
}
else
{
Console.WriteLine("No pending migrations found.");
}
}
#if !DEBUG
webBuilder.UseKestrel(opts =>
{
var appServices = opts.ApplicationServices;
//opts.Listen(IPAddress.Parse("192.168.1.150"), 80);
//opts.Listen(IPAddress.Parse("192.168.1.150"), 443, o => o.UseHttps(h => { h.UseLettuceEncrypt(appServices); }));
// public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(
// webBuilder =>
// {
// webBuilder.ConfigureLogging(logging =>
// {
// logging.ClearProviders();
// logging.AddConsole();
// }).UseNLog();
//opts.Listen(IPAddress.Parse("192.168.111.77"), 5005);
opts.Listen(IPAddress.Parse("192.168.178.205"), 5005);//novi server
opts.Listen(IPAddress.Loopback, port: 8081);
//opts.ListenLocalhost(4433, opts => opts.UseHttps());
opts.ListenLocalhost(5005);
//opts.ListenLocalhost(5005, opts => opts.UseHttps());
});
#endif
webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
webBuilder.UseStartup<Startup>();
});
//#if !DEBUG
// webBuilder.UseKestrel(opts =>
// {
// var appServices = opts.ApplicationServices;
// //opts.Listen(IPAddress.Parse("192.168.1.150"), 80);
// //opts.Listen(IPAddress.Parse("192.168.1.150"), 443, o => o.UseHttps(h => { h.UseLettuceEncrypt(appServices); }));
// //opts.Listen(IPAddress.Parse("192.168.111.77"), 5005);
// opts.Listen(IPAddress.Parse("192.168.178.205"), 5005);//novi server
// opts.Listen(IPAddress.Loopback, port: 8081);
// //opts.ListenLocalhost(4433, opts => opts.UseHttps());
// opts.ListenLocalhost(5005);
// //opts.ListenLocalhost(5005, opts => opts.UseHttps());
// });
//#endif
// webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
// webBuilder.UseStartup<Startup>();
// });
}
}

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<CopyRefAssembliesToPublishDirectory>false</CopyRefAssembliesToPublishDirectory>
<StartupObject>ProjecThing.Program</StartupObject>
<UserSecretsId>26f134e2-3bc7-4885-b726-e8a92f2abb2e</UserSecretsId>
@@ -37,6 +37,7 @@
<PackageReference Include="MailKit" Version="3.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Negotiate" Version="6.0.2" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection.EntityFrameworkCore" Version="6.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" />

View File

@@ -1,197 +0,0 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection;
using ProjecThing.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using ProjecThing.Data;
using Microsoft.AspNetCore.Authentication.Negotiate;
using Microsoft.AspNetCore.HttpOverrides;
namespace ProjecThing
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//services.Configure<ForwardedHeadersOptions>(options =>
//{
// options.KnownProxies.Add(IPAddress.Parse("192.168.111.78"));
//});
// Database connection
string connectionString = Configuration.GetConnectionString("DataConnection");
services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
//services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DataConnection")));
// Session
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromHours(3);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.MaxAge = TimeSpan.FromHours(3);
});
// JWT
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "ProjecThing",
ValidAudience = "Android",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("!Appli$cation#9999#!"))
};
});
// Identity
services.AddIdentity<IdentityApplicationUser, IdentityApplicationRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
services.AddRazorPages(options =>
{
//options.Conventions.AddPageRoute("/Administration/Users", "/AdministrationUsers");
}).AddRazorRuntimeCompilation();
//services.Configure<ForwardedHeadersOptions>(options =>
//{
// options.ForwardedHeaders =
// ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
// options.KnownProxies.Add(IPAddress.Parse("192.168.111.78"));
// //options.ForwardedForHeaderName = "X-Forwarded-For-My-Custom-Header-Name";
//});
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 8;
options.Password.RequiredUniqueChars = 1;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 3;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
options.User.RequireUniqueEmail = true;
});
services.ConfigureApplicationCookie(options =>
{
// Cookie
options.Cookie.MaxAge = TimeSpan.FromHours(3);
options.Cookie.HttpOnly = true;
options.SlidingExpiration = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.None;//Samo unencripted na locas
options.LoginPath = $"/User/Login";
options.LogoutPath = $"/User/Logout";
options.AccessDeniedPath = $"/";
options.ExpireTimeSpan = TimeSpan.FromHours(3);//Povecano na 15min
});
services.AddDistributedMemoryCache();
services.Configure<IISOptions>(options =>
{
options.AutomaticAuthentication = false;
});
services.AddDataProtection().SetApplicationName("ProjecThing").PersistKeysToFileSystem(new DirectoryInfo(@"Keys/"));
//services.AddHttpsRedirection(options =>
//{
// options.RedirectStatusCode = (int)HttpStatusCode.PermanentRedirect;
// options.HttpsPort = 443;
//});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseForwardedHeaders();
}
else
{
app.UseExceptionHandler("/Error");
//app.UseForwardedHeaders();
app.UseHsts();
}
//app.UseForwardedHeaders(new ForwardedHeadersOptions
//{
// ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
//});
var defaultCulture = new CultureInfo("sl-SI");
var localizationOptions = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(defaultCulture),
SupportedCultures = new List<CultureInfo> { defaultCulture },
SupportedUICultures = new List<CultureInfo> { defaultCulture }
};
app.UseRequestLocalization(localizationOptions);
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
}
}
}