You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
298 lines
13 KiB
298 lines
13 KiB
using Infrastructure.Application.Services.Settings;
|
|
using Infrastructure.Data;
|
|
using Infrastructure.Extensions;
|
|
using Infrastructure.Security;
|
|
using Infrastructure.Web;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using Newtonsoft.Json;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Text.Encodings.Web;
|
|
using System.Text.Unicode;
|
|
using System.Threading.Tasks;
|
|
using TeacherExt.Data;
|
|
using TeacherExt.Entities;
|
|
|
|
namespace TeacherExt
|
|
{
|
|
public class Startup
|
|
{
|
|
private readonly string _origins = "AllowAllHeaders";
|
|
|
|
public Startup(IConfiguration configuration, IHostEnvironment hostEnvironment)
|
|
{
|
|
Configuration = configuration;
|
|
HostEnvironment = hostEnvironment;
|
|
}
|
|
|
|
public IConfiguration Configuration { get; }
|
|
|
|
public IHostEnvironment HostEnvironment { get; }
|
|
|
|
public void ConfigureServices(IServiceCollection services)
|
|
{
|
|
services.AddSwaggerGen();
|
|
services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
|
|
services.AddHttpContextAccessor();
|
|
services.AddCors(options => options.AddPolicy(_origins, builder =>
|
|
{
|
|
builder.SetIsOriginAllowed(o => true)
|
|
.AllowAnyMethod()
|
|
.AllowAnyHeader()
|
|
.AllowCredentials();
|
|
}));
|
|
var database = Configuration.GetValue<string>("database");
|
|
//if (database=="sqlite")
|
|
//{
|
|
// services.AddDbContext<TeacherDbContext2>(o => o.UseSqlite(Configuration.GetConnectionString("sqlite")));
|
|
//}
|
|
//else
|
|
//{
|
|
// var connstr = Configuration.GetConnectionString("mysql");
|
|
// services.AddDbContext<TeacherDbContext>(o => o.UseMySql(connstr, ServerVersion.AutoDetect(connstr)));
|
|
//}
|
|
services.AddTransient<AesHelper>();
|
|
var connstr = Configuration.GetConnectionString("mariyadb");
|
|
services.AddDbContext<TeacherDbContext>(o => o.UseMySql(connstr, ServerVersion.AutoDetect(connstr)));
|
|
|
|
services.AddDistributedMemoryCache();
|
|
services.AddScoped<DbContext, TeacherDbContext>();
|
|
services.AddTransient(typeof(IRepository<>), typeof(EfRepository<>));
|
|
services.AddTransient<IEncryptionService, EncryptionService>();
|
|
services.AddTransient<SettingService>();
|
|
services.AddTransient<ISettingService, CachedSettingService>();
|
|
services.AddTransient<IUserService, UserService>();
|
|
services.AddMvc()
|
|
.AddNewtonsoftJson()
|
|
.AddControllersAsServices();
|
|
services.AddControllers()
|
|
.ConfigureApiBehaviorOptions(options =>
|
|
{
|
|
options.SuppressConsumesConstraintForFormFileParameters = true;
|
|
options.SuppressInferBindingSourcesForParameters = true;
|
|
options.SuppressModelStateInvalidFilter = true;
|
|
options.SuppressMapClientErrors = true;
|
|
//options.ClientErrorMapping[404].Link = "https://httpstatuses.com/404";
|
|
})
|
|
.AddNewtonsoftJson(o =>
|
|
{
|
|
o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
|
|
});
|
|
services.AddAuthentication(x =>
|
|
{
|
|
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
}).AddJwtBearer(o =>
|
|
{
|
|
services.AddSingleton(o);
|
|
o.TokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
ValidateIssuerSigningKey = true,
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["jwt:key"])),
|
|
ValidateIssuer = false,
|
|
ValidIssuer = Configuration["jwt:issuer"],
|
|
ValidateAudience = false,
|
|
ValidAudience = Configuration["jwt:audience"]
|
|
};
|
|
o.Events = new JwtBearerEvents
|
|
{
|
|
OnTokenValidated = context =>
|
|
{
|
|
if (context.SecurityToken == null)
|
|
{
|
|
context.Fail("token error");
|
|
}
|
|
else if (DateTime.UtcNow > context.SecurityToken.ValidTo)
|
|
{
|
|
context.Fail("token time out");
|
|
}
|
|
return Task.CompletedTask;
|
|
},
|
|
OnForbidden = context =>
|
|
{
|
|
return context.Response.WriteAsync("403 forbidden");
|
|
},
|
|
OnAuthenticationFailed = context =>
|
|
{
|
|
return Task.CompletedTask;
|
|
},
|
|
OnChallenge = context =>
|
|
{
|
|
if (!context.Request.IsAjax())
|
|
{
|
|
context.Response.Redirect(Configuration["Admin:login"] ?? "/Account/Login");
|
|
context.HandleResponse();
|
|
}
|
|
return Task.CompletedTask;
|
|
},
|
|
OnMessageReceived = context =>
|
|
{
|
|
if (!context.Request.IsStatic())
|
|
{
|
|
if (context.Request.Query.ContainsKey("access_token"))
|
|
{
|
|
context.Token = context.Request.Query["access_token"];
|
|
}
|
|
else
|
|
{
|
|
var jwtCookieName = context.HttpContext.GetJwtCookieName();
|
|
if (!context.Request.Headers.ContainsKey("Authorization") && context.Request.Cookies.Keys.Contains(jwtCookieName))
|
|
{
|
|
context.Token = context.Request.Cookies[jwtCookieName];
|
|
}
|
|
}
|
|
}
|
|
return Task.CompletedTask;
|
|
}
|
|
};
|
|
o.SecurityTokenValidators.Clear();
|
|
o.SecurityTokenValidators.Insert(0, new JwtTokenValidator(services.BuildServiceProvider()));
|
|
});
|
|
}
|
|
|
|
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
|
{
|
|
app.UseSwagger();
|
|
app.UseSwaggerUI(c =>
|
|
{
|
|
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
|
|
});
|
|
app.UseStaticFiles();
|
|
app.UseRouting();
|
|
app.UseCors(_origins);
|
|
app.UseAuthentication();
|
|
app.UseAuthorization();
|
|
app.UseEndpoints(endpoints =>
|
|
{
|
|
endpoints.MapControllerRoute(
|
|
name: "default",
|
|
pattern: "{controller=Home}/{action=Index}/{id?}");
|
|
});
|
|
//using var scope = app.ApplicationServices.CreateScope();
|
|
//var encryptionService = scope.ServiceProvider.GetRequiredService<IEncryptionService>();
|
|
//var salt = "111111";
|
|
//var password = encryptionService.CreatePasswordHash(salt, salt);
|
|
//using var db = scope.ServiceProvider.GetRequiredService<DbContext>();
|
|
//if (db.Database.EnsureCreated())
|
|
//{
|
|
// db.Set<Role>().Add(new Role { Name = "局管理员" });
|
|
// db.Set<Role>().Add(new Role { Name = "校管理员" });
|
|
// db.Set<Role>().Add(new Role { Name = "教职工" });
|
|
// db.SaveChanges();
|
|
|
|
// db.Set<Organ>().Add(new Organ
|
|
// {
|
|
// Name = "教育局",
|
|
// Number = "jiaoyuju",
|
|
// Children = new List<Organ> {
|
|
// new Organ
|
|
// {
|
|
// Name="学校1",
|
|
// Number="xuexiao1"
|
|
// },
|
|
// new Organ
|
|
// {
|
|
// Name="学校2",
|
|
// Number="xuexiao2"
|
|
// }
|
|
// }
|
|
// });
|
|
// db.SaveChanges();
|
|
|
|
// db.Set<User>().Add(new User
|
|
// {
|
|
// UserName = "admin",
|
|
// PasswordSalt = salt,
|
|
// PasswordHash = password,
|
|
// RealName = "教育局管理员",
|
|
// OrganId = db.Set<Organ>().FirstOrDefault(o => o.Number == "jiaoyuju").Id,
|
|
// UserRoles = new List<UserRole> { new UserRole { RoleId = db.Set<Role>().FirstOrDefault(o => o.Name == "局管理员").Id } }
|
|
// });
|
|
// db.Set<User>().Add(new User
|
|
// {
|
|
// UserName = "admin1",
|
|
// PasswordSalt = salt,
|
|
// PasswordHash = password,
|
|
// RealName = "校管理员1",
|
|
// OrganId = db.Set<Organ>().FirstOrDefault(o => o.Number == "xuexiao1").Id,
|
|
// UserRoles = new List<UserRole> { new UserRole { RoleId = db.Set<Role>().FirstOrDefault(o => o.Name == "校管理员").Id } }
|
|
// });
|
|
// db.Set<User>().Add(new User
|
|
// {
|
|
// UserName = "xiaozhang1",
|
|
// PasswordSalt = salt,
|
|
// PasswordHash = password,
|
|
// RealName = "校长1",
|
|
// OrganId = db.Set<Organ>().FirstOrDefault(o => o.Number == "xuexiao1").Id,
|
|
// UserRoles = new List<UserRole> { new UserRole { RoleId = db.Set<Role>().FirstOrDefault(o => o.Name == "教职工").Id } }
|
|
// });
|
|
// db.Set<User>().Add(new User
|
|
// {
|
|
// UserName = "laoshi1",
|
|
// PasswordSalt = salt,
|
|
// PasswordHash = password,
|
|
// RealName = "老师1",
|
|
// OrganId = db.Set<Organ>().FirstOrDefault(o => o.Number == "xuexiao1").Id,
|
|
// UserRoles = new List<UserRole> { new UserRole { RoleId = db.Set<Role>().FirstOrDefault(o => o.Name == "教职工").Id } }
|
|
// });
|
|
// db.Set<User>().Add(new User
|
|
// {
|
|
// UserName = "zhigong1",
|
|
// PasswordSalt = salt,
|
|
// PasswordHash = password,
|
|
// RealName = "职工1",
|
|
// OrganId = db.Set<Organ>().FirstOrDefault(o => o.Number == "xuexiao1").Id,
|
|
// UserRoles = new List<UserRole> { new UserRole { RoleId = db.Set<Role>().FirstOrDefault(o => o.Name == "教职工").Id } }
|
|
// });
|
|
// db.Set<User>().Add(new User
|
|
// {
|
|
// UserName = "admin2",
|
|
// PasswordSalt = salt,
|
|
// PasswordHash = password,
|
|
// RealName = "校管理员2",
|
|
// OrganId = db.Set<Organ>().FirstOrDefault(o => o.Number == "xuexiao2").Id,
|
|
// UserRoles = new List<UserRole> { new UserRole { RoleId = db.Set<Role>().FirstOrDefault(o => o.Name == "校管理员").Id } }
|
|
// });
|
|
// db.Set<User>().Add(new User
|
|
// {
|
|
// UserName = "xiaozhang2",
|
|
// PasswordSalt = salt,
|
|
// PasswordHash = password,
|
|
// RealName = "校长2",
|
|
// OrganId = db.Set<Organ>().FirstOrDefault(o => o.Number == "xuexiao2").Id,
|
|
// UserRoles = new List<UserRole> { new UserRole { RoleId = db.Set<Role>().FirstOrDefault(o => o.Name == "教职工").Id } }
|
|
// });
|
|
// db.Set<User>().Add(new User
|
|
// {
|
|
// UserName = "laoshi2",
|
|
// PasswordSalt = salt,
|
|
// PasswordHash = password,
|
|
// RealName = "老师2",
|
|
// OrganId = db.Set<Organ>().FirstOrDefault(o => o.Number == "xuexiao2").Id,
|
|
// UserRoles = new List<UserRole> { new UserRole { RoleId = db.Set<Role>().FirstOrDefault(o => o.Name == "教职工").Id } }
|
|
// });
|
|
// db.Set<User>().Add(new User
|
|
// {
|
|
// UserName = "zhigong2",
|
|
// PasswordSalt = salt,
|
|
// PasswordHash = password,
|
|
// RealName = "职工2",
|
|
// OrganId = db.Set<Organ>().FirstOrDefault(o => o.Number == "xuexiao2").Id,
|
|
// UserRoles = new List<UserRole> { new UserRole { RoleId = db.Set<Role>().FirstOrDefault(o => o.Name == "教职工").Id } }
|
|
// });
|
|
// db.SaveChanges();
|
|
//}
|
|
}
|
|
}
|
|
}
|