This commit is contained in:
luolan 2025-04-12 00:57:04 +08:00
parent 56e210d9c0
commit 347b263ecf
2 changed files with 114 additions and 59 deletions

View File

@ -3,10 +3,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
<<<<<<< HEAD
=======
using System.Data; using System.Data;
>>>>>>> parent of 5dc3041 ()
using System.Security.Claims; using System.Security.Claims;
using static asg_form.blog; using static asg_form.blog;
@ -189,8 +186,6 @@ namespace asg_form.Controllers
<<<<<<< HEAD
=======
/// <summary> /// <summary>
/// 职位时间设置接口 /// 职位时间设置接口
/// </summary> /// </summary>
@ -210,9 +205,8 @@ namespace asg_form.Controllers
user.joinTime = msg.joinTime; user.joinTime = msg.joinTime;
await userManager.UpdateAsync(user); await userManager.UpdateAsync(user);
return Ok(new { code = 200, message = "你成功修改了自己加入ASG的时间" }); return Ok(new { code = 200, message = "你成功修改了自己加入ASG的时间" });
>>>>>>> parent of 5dc3041 ()
} }
}
} }

View File

@ -9,38 +9,60 @@ using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Mirai.Net.Sessions; using Mirai.Net.Sessions;
using Mirai.Net.Sessions.Http.Managers;
using MrHuo.OAuth; using MrHuo.OAuth;
using MrHuo.OAuth.Github; using MrHuo.OAuth.Github;
using MrHuo.OAuth.Microsoft; using MrHuo.OAuth.Microsoft;
using Scalar.AspNetCore; using Scalar.AspNetCore;
using System; using System;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Reflection;
using System.Text; using System.Text;
using Zack.EventBus; using Zack.EventBus;
Console.WriteLine("\n _____ _________ ________ \n / _ \\ / _____// _____/ \n / /_\\ \\ \\_____ \\/ \\ ___ \n/ | \\/ \\ \\_\\ \\\n\\____|__ /_______ /\\______ /\n \\/ \\/ \\/ \n__________ __ ___________ .___\n\\______ \\_____ ____ | | __\\_ _____/ ____ __| _/\n | | _/\\__ \\ _/ ___\\| |/ / | __)_ / \\ / __ | \n | | \\ / __ \\\\ \\___| < | \\ | \\/ /_/ | \n |______ /(____ /\\___ >__|_ \\/_______ /___| /\\____ | \n \\/ \\/ \\/ \\/ \\/ \\/ \\/ ");
Console.WriteLine("\n _____ _________ ________ \n / _ \\ / _____// _____/ \n / /_\\ \\ \\_____ \\/ \\ ___ \n/ | \\/ \\ \\_\\ \\\n\\____|__ /_______ /\\______ /\n \\/ \\/ \\/ \n__________ __ ___________ .___\n\\______ \\_____ ____ | | __\\_ _____/ ____ __| _/\n | | _/\\__ \\ _/ ___\\| |/ / | __)_ / \\ / __ | \n | | \\ / __ \\\\ \\___| < | \\ | \\/ /_/ | \n |______ /(____ /\\___ >__|_ \\/_______ /___| /\\____ | \n \\/ \\/ \\/ \\/ \\/ \\/ \\/ ");
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// 添加控制器服务 //builder.AddServiceDefaults();
builder.Services.AddControllers();
// 配置Swagger/OpenAPI // Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSignalR();
builder.Services.AddSwaggerGen(c => builder.Services.AddSwaggerGen(c =>
{ {
c.SwaggerDoc("v1", new OpenApiInfo c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{ {
Title = "ASG 赛事官网-后端API文档", Title = "ASG 赛事官网-后端API文档",
Version = "V 1.9.7", Version = "V 1.9.7",
Description = "这是由罗澜使用ASP.NET.Core开发的ASG赛事组后端系统包括官网和后台管理系统。使用 sqlserver作为数据库identity框架进行账号控制。", Description = "这是由罗澜使用ASP.NET.Core开发的ASG赛事组后端系统包括官网和后台管理系统。使用 sqlserver作为数据库identity框架进行账号控制。",
}); });
var file = Path.Combine(AppContext.BaseDirectory, "ASG后端.xml"); var file = Path.Combine(AppContext.BaseDirectory, "ASG后端.xml");
c.IncludeXmlComments(file, true); var path = Path.Combine(AppContext.BaseDirectory, file);
c.IncludeXmlComments(path, true);
c.OrderActionsBy(o => o.RelativePath); c.OrderActionsBy(o => o.RelativePath);
var scheme = new OpenApiSecurityScheme var scheme = new OpenApiSecurityScheme()
{ {
Description = "Authorization header. \r\nExample: 'Bearer 12345abcdef'", Description = "Authorization header. \r\nExample: 'Bearer 12345abcdef'",
Reference = new OpenApiReference Reference = new OpenApiReference
@ -54,29 +76,34 @@ builder.Services.AddSwaggerGen(c =>
Type = SecuritySchemeType.ApiKey, Type = SecuritySchemeType.ApiKey,
}; };
c.AddSecurityDefinition("Authorization", scheme); c.AddSecurityDefinition("Authorization", scheme);
c.AddSecurityRequirement(new OpenApiSecurityRequirement var requirement = new OpenApiSecurityRequirement();
{ requirement[scheme] = new List<string>();
[scheme] = new List<string>() c.AddSecurityRequirement(requirement);
});
}); });
// 配置CORS策略
builder.Services.AddCors(options =>
options.AddDefaultPolicy(policy =>
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()));
// 配置数据库上下文
builder.Services.AddDbContext<IDBcontext>(opt => string[] urls = new[] { "https://idvasg.cn", "https://nocdn.idvasg.cn", "http://localhost:8080", "https://commentary.idvasg.cn", "https://admin.idvasg.cn", "https://www.idvasg.cn" };
builder.Services.AddCors(options =>
options.AddDefaultPolicy(builder => builder.WithOrigins(urls)
.AllowAnyMethod().AllowAnyHeader().AllowCredentials()));
IServiceCollection services = builder.Services;
services.AddDbContext<IDBcontext>(opt =>
{ {
string connStr = @"Host=172.30.121.91;Port=2345;Database=postgres;Username=asg;Password=luolan12323;"; string connStr = @"Host=172.30.121.91;Port=2345;Database=postgres;Username=asg;Password=luolan12323;";
opt.UseNpgsql(connStr); opt.UseNpgsql(connStr);
}); });
//services.AddHostedService<qqbot>();
// 配置身份验证和授权
builder.Services.AddIdentityCore<User>(options => services.AddDataProtection();
services.AddIdentityCore<User>(options =>
{ {
options.Password.RequireDigit = false; options.Password.RequireDigit = false;
options.Password.RequireLowercase = false; options.Password.RequireLowercase = false;
@ -86,48 +113,64 @@ builder.Services.AddIdentityCore<User>(options =>
options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider; options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider;
options.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider; options.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider;
}); });
new IdentityBuilder(typeof(User), typeof(Role), builder.Services) var idBuilder = new IdentityBuilder(typeof(User), typeof(Role), services);
.AddEntityFrameworkStores<IDBcontext>() idBuilder.AddEntityFrameworkStores<IDBcontext>()
.AddDefaultTokenProviders() .AddDefaultTokenProviders()
.AddRoleManager<RoleManager<Role>>() .AddRoleManager<RoleManager<Role>>()
.AddUserManager<UserManager<User>>(); .AddUserManager<UserManager<User>>();
// 配置JWT身份验证
builder.Services.Configure<JWTOptions>(builder.Configuration.GetSection("JWT"));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(x =>
{
var jwtOpt = builder.Configuration.GetSection("JWT").Get<JWTOptions>();
byte[] keyBytes = Encoding.UTF8.GetBytes(jwtOpt.SigningKey);
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(keyBytes)
};
});
// 配置OAuth
builder.Services.AddSingleton(new GithubOAuth(OAuthConfig.LoadFrom(builder.Configuration, "oauth:github")));
builder.Services.AddSingleton(new MicrosoftOAuth(OAuthConfig.LoadFrom(builder.Configuration, "oauth:microsoft")));
// 添加Application Insights
builder.Services.AddApplicationInsightsTelemetry();
// 配置全局异常处理过滤器
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//add error 处理器
builder.Services.Configure<MvcOptions>(options => builder.Services.Configure<MvcOptions>(options =>
{ {
options.Filters.Add<MyExceptionFilter>(); options.Filters.Add<MyExceptionFilter>();
}); });
// 构建应用程序
var app = builder.Build();
// 使用中间件
services.Configure<JWTOptions>(builder.Configuration.GetSection("JWT"));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(x =>
{
var jwtOpt = builder.Configuration.GetSection("JWT").Get<JWTOptions>();
byte[] keyBytes = Encoding.UTF8.GetBytes(jwtOpt.SigningKey);
var secKey = new SymmetricSecurityKey(keyBytes);
x.TokenValidationParameters = new()
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = secKey
};
});
services.AddSingleton(new GithubOAuth(OAuthConfig.LoadFrom(builder.Configuration, "oauth:github")));
services.AddSingleton(new MicrosoftOAuth(OAuthConfig.LoadFrom(builder.Configuration, "oauth:microsoft")));
builder.Services.AddApplicationInsightsTelemetry();
var app = builder.Build();
//app.MapDefaultEndpoints();
app.UseCors(); app.UseCors();
// Configure the HTTP request pipeline.
app.UseSwagger(); app.UseSwagger();
//app.UseSwaggerUI();
app.MapScalarApiReference(options =>
{
options.WithOpenApiRoutePattern("/swagger/v1/swagger.json");
// or
options.OpenApiRoutePattern = "/swagger/v1/swagger.json";
});
app.UseStaticFiles(); app.UseStaticFiles();
AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true); AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true);
@ -150,14 +193,16 @@ RegisterStaticFiles("loge", "/loge");
RegisterStaticFiles("video", "/video"); RegisterStaticFiles("video", "/video");
RegisterStaticFiles("doc", "/doc"); RegisterStaticFiles("doc", "/doc");
RegisterStaticFiles("excel", "/excel"); RegisterStaticFiles("excel", "/excel");
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.MapHub<room>("/room"); app.MapHub<room>("/room");
app.UseResponseCaching(); app.UseResponseCaching();
app.MapControllers(); app.MapControllers();
// 启动Flandre机器人线程
new Thread(o => new Thread(o =>
{ {
try try
@ -168,10 +213,17 @@ new Thread(o =>
ContentRootPath = AppDomain.CurrentDomain.BaseDirectory ContentRootPath = AppDomain.CurrentDomain.BaseDirectory
}); });
// 安装一个适配器,并添加在这里。
// builder.Adapters.Add(new YourAdapter());
builder1.Adapters.AddOneBot(builder1.Configuration.GetSection("Adapters:OneBot")); builder1.Adapters.AddOneBot(builder1.Configuration.GetSection("Adapters:OneBot"));
builder1.Plugins.Add<qqbot>(); builder1.Plugins.Add<qqbot>();
var app1 = builder1.Build(); var app1 = builder1.Build();
// 添加内置中间件。
// 这些中间件保证 Flandre 的正常运转。你也可以加入自己的中间件,并灵活调整其顺序。
app1.UseCommandSession(); app1.UseCommandSession();
// app.UseMiddleware(async (ctx, next) => { /* ... */ });
app1.UseCommandParser(); app1.UseCommandParser();
app1.UseCommandInvoker(); app1.UseCommandInvoker();
runbot.runbotr = app1.Bots.First(); runbot.runbotr = app1.Bots.First();
@ -179,8 +231,17 @@ new Thread(o =>
} }
catch (Exception ex) catch (Exception ex)
{ {
//输出详细全部信息
Console.WriteLine(ex.ToString());
} }
}) })
{ IsBackground = true }.Start(); { IsBackground = true }.Start();
app.Run(); app.Run();