This commit is contained in:
杨毅 2024-12-29 00:12:46 +08:00
parent cc545a5896
commit 3e02e6ca3c
13 changed files with 298 additions and 111 deletions

View File

@ -5,8 +5,6 @@ using asg_form.Controllers.Store;
using asg_form.Controllers.Teamregistration;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.DataEncryption;
using Microsoft.EntityFrameworkCore.DataEncryption.Providers;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System.Security.Cryptography;

View File

@ -1,7 +1,6 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using System.Reflection.Metadata;
using System.Security.Claims;
using static asg_form.Controllers.excel;

View File

@ -0,0 +1,139 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using MrHuo.OAuth.Github;
using MrHuo.OAuth.Microsoft;
using System.IdentityModel.Tokens.Jwt;
using System.Management;
using System.Security.Claims;
using System.Text;
namespace asg_form.Controllers
{
public class OAuthController : Controller
{
private readonly RoleManager<Role> roleManager;
private readonly UserManager<User> userManager;
public OAuthController(
RoleManager<Role> roleManager, UserManager<User> userManager)
{
this.roleManager = roleManager;
this.userManager = userManager;
}
[HttpGet("oauth/setpassword")]
public async Task<object> SetPasswordAsync(string username,string password, [FromServices] IOptions<JWTOptions> jwtOptions)
{
var user = await userManager.FindByNameAsync(username);
await userManager.AddPasswordAsync(user, password);
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
var roles = await userManager.GetRolesAsync(user);
foreach (string role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
string jwtToken = BuildToken(claims, jwtOptions.Value);
return jwtToken;
}
[HttpGet("oauth/{type}")]
public IActionResult Index(
string type,string recall,
[FromServices] GithubOAuth githubOAuth,
[FromServices] MicrosoftOAuth microsoftOAuth
)
{
var redirectUrl = "";
switch (type.ToLower())
{
case "github":
{
redirectUrl = githubOAuth.GetAuthorizeUrl();
break;
}
case "microsoft":
{
redirectUrl = microsoftOAuth.GetAuthorizeUrl();
break;
}
default:
return NotFound($"没有实现【{type}】登录方式!");
}
return Redirect(redirectUrl);
}
private static string BuildToken(IEnumerable<Claim> claims, JWTOptions options)
{
DateTime expires = DateTime.Now.AddSeconds(options.ExpireSeconds);
byte[] keyBytes = Encoding.UTF8.GetBytes(options.SigningKey);
var secKey = new SymmetricSecurityKey(keyBytes);
var credentials = new SigningCredentials(secKey,
SecurityAlgorithms.HmacSha256Signature);
var tokenDescriptor = new JwtSecurityToken(expires: expires,
signingCredentials: credentials, claims: claims);
return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
}
[HttpGet("oauth/{type}callback")]
public async Task<IActionResult> LoginCallback(
string type,
[FromServices] GithubOAuth githubOAuth,
[FromServices] IOptions<JWTOptions> jwtOptions,
[FromQuery] string code,
[FromQuery] string state)
{
try
{
switch (type.ToLower())
{
case "github":
{
var authorizeResult = await githubOAuth.AuthorizeCallback(code, state);
if (!authorizeResult.IsSccess)
{
throw new Exception(authorizeResult.ErrorMessage);
}
var userinfo = await githubOAuth.GetUserInfoAsync(authorizeResult.AccessToken);
//如果该Gitgub用户不存在则创建一个
var user = new User() { Id=20,UserName = $"gh{userinfo.Name}", Email = userinfo.Email };
if (user == null)
{
var user_new = await userManager.FindByNameAsync(userinfo.Name);
var r = await userManager.CreateAsync(user);
return Redirect($"https://commentary.idvasg.cn/oauth/next?username=gh{userinfo.Name}");
}
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
var roles = await userManager.GetRolesAsync(user);
foreach (string role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
string jwtToken = BuildToken(claims, jwtOptions.Value);
return Redirect($"https://commentary.idvasg.cn/oauth/loginok?token={jwtToken}");
}
default:
throw new Exception($"没有实现【{type}】登录回调!");
}
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
}
}

View File

@ -65,12 +65,9 @@ namespace asg_form.Controllers.Teamregistration
using (TestDbContext sub = new TestDbContext())
{
if (msg.userId == null)
{
return Ok(new error_mb { code = 400, message = "用户ID为空" });
}
if (sub.T_Comform.Find(msg.userId) != null)
if (msg.id == null&&sub.T_Comform.Find(msg.userId) != null)
{
return Ok(new error_mb { code = 400, message = "你已经提交过表单了,请不要重复提交" });
}

View File

@ -9,20 +9,17 @@ using Newtonsoft.Json.Linq;
using RestSharp;
using static asg_form.blog;
using static asg_form.Controllers.schedule;
using static NPOI.HSSF.Util.HSSFColor;
using NLog;
using System.Security.Authentication;
using System.Text.Json;
using Microsoft.AspNetCore.SignalR;
using asg_form.Controllers.Hubs;
using NPOI.OpenXmlFormats.Spreadsheet;
using Mirai.Net.Data.Shared;
using MimeKit;
using MailKit.Net.Smtp;
using Mirai.Net.Utils.Scaffolds;
using Mirai.Net.Sessions.Http.Managers;
using asg_form.Controllers.Store;
using NPOI.SS.Formula.Functions;
using static asg_form.Controllers.Store.Storehttp;
using Flandre.Framework;
using Flandre.Core.Common;
@ -305,43 +302,62 @@ namespace asg_form.Controllers
/// <summary>
/// 获取所有用户-支持分页(整合api:allperson_c)
/// </summary>
/// <param name="page"></param>
/// <param name="page_long"></param>
/// <param name="keyword"></param>
/// <returns></returns>
/// <param name="keyword">搜索关键字</param>
/// <param name="pageindex">页码默认为1</param>
/// <param name="pagesize">每页大小默认为10</param>
/// <param name="officum">部门筛选条件</param>
/// <returns>返回分页后的用户列表及总数</returns>
[Route("api/v2/admin/allperson")]
[HttpGet]
[Authorize]
public async Task<ActionResult<post_user_v2>> getalladmin_v2(string? keyword, short pageindex = 1, short pagesize = 10,string? offficum = null)
public async Task<ActionResult<all_record>> GetAdminUsersV2(string? keyword = null, short pageindex = 1, short pagesize = 10, string? officum = null)
{
bool isAdmin = this.User.FindAll(ClaimTypes.Role).Any(a => a.Value == "admin");
if (isAdmin)
{
var a = new all_record();
if(keyword== null && offficum == null)
{
a.cout = userManager.Users.Count();
a.msg = await userManager.Users.Paginate(pageindex, pagesize).Select(a => new { a.Id, a.Email, a.chinaname, a.UserName, a.Integral, a.officium,a.qqnumber,a.roleListName,a.roleListCode }).ToListAsync();
}
if (keyword == null)
{
a.cout = userManager.Users.Count();
a.msg = await userManager.Users.Paginate(pageindex, pagesize).Where(a=>a.officium==offficum).Select(a => new { a.Id, a.Email, a.chinaname, a.UserName, a.Integral, a.officium,a.qqnumber,a.roleListName,a.roleListCode}).ToListAsync();
}
else
{
a.cout = userManager.Users.Where(a => a.chinaname.Contains(keyword) || a.UserName == keyword || a.Email == keyword).Count();
a.msg = await userManager.Users.Where(a => a.chinaname.Contains(keyword) || a.UserName == keyword || a.Email == keyword&&a.officium==offficum).Paginate(pageindex, pagesize).Select(a => new { a.Id, a.Email, a.chinaname, a.UserName, a.Integral, a.officium,a.qqnumber, a.roleListName, a.roleListCode }).ToListAsync();
}
return Ok(a);
}
else
// 检查用户是否有管理员权限
if (!this.User.HasClaim(ClaimTypes.Role, "admin"))
{
return BadRequest(new error_mb { code = 400, message = "无权访问" });
}
var query = userManager.Users.AsQueryable();
// 根据关键词和部门进行过滤
if (!string.IsNullOrEmpty(keyword))
{
query = query.Where(u => u.chinaname.Contains(keyword) || u.UserName == keyword || u.Email == keyword);
}
if (!string.IsNullOrEmpty(officum))
{
query = query.Where(u => u.officium == officum);
}
// 获取总记录数
int total = await query.CountAsync();
// 分页查询
var paginatedUsers = await query.Paginate(pageindex, pagesize)
.Select(u => new
{
u.Id,
u.Email,
u.chinaname,
u.UserName,
u.Integral,
u.officium,
u.qqnumber,
u.roleListName,
u.roleListCode
})
.ToListAsync();
// 构建返回结果
var result = new all_record
{
cout = total,
msg = paginatedUsers
};
return Ok(result);
}
public class post_user_v2

View File

@ -3,7 +3,6 @@ using ChatGPT.Net;
using ChatGPT.Net.DTO.ChatGPT;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using static asg_form.Controllers.login;
namespace asg_form.Controllers

View File

@ -11,7 +11,6 @@ using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using NLog;
using NPOI.OpenXmlFormats.Spreadsheet;
using RestSharp;
using SixLabors.ImageSharp;
using System.ComponentModel.DataAnnotations;

View File

@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using OfficeOpenXml.Packaging.Ionic.Zlib;
using RestSharp;
using System.IdentityModel.Tokens.Jwt;

View File

@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Authorization;
using static asg_form.blog;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
using NPOI.OpenXmlFormats.Spreadsheet;
using Castle.Components.DictionaryAdapter;
using Flandre.Core.Messaging;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;

View File

@ -16,6 +16,9 @@ using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Mirai.Net.Sessions;
using Mirai.Net.Sessions.Http.Managers;
using MrHuo.OAuth;
using MrHuo.OAuth.Github;
using MrHuo.OAuth.Microsoft;
using System;
using System.Data;
using System.Drawing;
@ -143,6 +146,9 @@ services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
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();
@ -212,9 +218,8 @@ app.MapControllers();
//新开一个线程,显示当前时间
new Thread(o =>
{
try
{
var builder1 = FlandreApp.CreateBuilder(new HostApplicationBuilderSettings
{
Args = args,
@ -236,6 +241,16 @@ new Thread(o =>
app1.UseCommandInvoker();
runbot.runbotr = app1.Bots.First();
app1.Run();
}
catch(Exception ex)
{
//输出详细全部信息
Console.WriteLine(ex.ToString());
}
})

View File

@ -39,5 +39,57 @@
}
]
}
},
"oauth": {
"qq": {
"app_id": "qq_app_id",
"app_key": "qq_app_key",
"redirect_uri": "https://oauthlogin.net/oauth/qqcallback",
"scope": "get_user_info"
},
"github": {
"app_id": "Ov23liKQaqPOMKJCzdep",
"app_key": "37dc8fdc1a91f4f464fd05f46b158801ff9f9a61",
"scope": "repo"
},
"microsoft": {
"client_id": "9206e9e3-4608-4501-85ae-88b42c7f2fe1",
"tenant_id": "7ed846b8-c314-431e-b72c-27562dc7bf04",
"client_secret": "E5O8Q~OPLX3AjKwQz.5hlo7SUDoIdOaurL6F8cWl",
"redirect_uri": "https://api.idvasg.cn/oauth/microsoftcallback",
"scope": "snsapi_userinfo"
},
"huawei": {
"app_id": "huawei_app_id",
"app_key": "huawei_app_key",
"redirect_uri": "https://oauthlogin.net/oauth/huaweicallback",
"scope": "https://www.huawei.com/auth/account"
},
"gitee": {
"app_id": "gitee_app_id",
"app_key": "gitee_app_key",
"redirect_uri": "http://oauthlogin.net/oauth/giteecallback",
"scope": "user_info"
},
"baidu": {
"app_id": "baidu_app_id",
"app_key": "baidu_app_key",
"redirect_uri": "http://oauthlogin.net/oauth/baiducallback",
"scope": "basic"
},
"alipay": {
"app_id": "alipay_app_id",
"app_key": "alipay_app_key",
"redirect_uri": "https://oauthlogin.net/oauth/alipaycallback",
"scope": "auth_user",
"private_key": "private_key",
"public_key": "public_key"
},
"gitlab": {
"app_id": "gitlab_app_id",
"app_key": "gitlab_app_key",
"redirect_uri": "http://oauthlogin.net/oauth/gitlabcallback",
"scope": "read_user"
}
}
}

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
@ -15,6 +15,14 @@
<ContainerBaseImage>mcr.microsoft.com/dotnet/aspnet:8.0</ContainerBaseImage>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<IsPublishable>True</IsPublishable>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<IsPublishable>True</IsPublishable>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Controllers\PlayerC\**" />
<Content Remove="Controllers\PlayerC\**" />
@ -27,50 +35,27 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.12.0" />
<PackageReference Include="ChatGPT.Net" Version="2.0.0" />
<PackageReference Include="EntityFrameworkCore.DataEncryption" Version="5.0.0" />
<PackageReference Include="EPPlus" Version="7.5.1" />
<PackageReference Include="Flandre.Adapters.OneBot.Extensions" Version="2.0.0-rc.3" />
<PackageReference Include="Flandre.Core" Version="1.0.0-rc.4" />
<PackageReference Include="Flandre.Framework" Version="1.0.0-rc.11" />
<PackageReference Include="IGeekFan.AspNetCore.Knife4jUI" Version="0.0.16" />
<PackageReference Include="ini-parser" Version="2.5.2" />
<PackageReference Include="MailKit" Version="4.3.0" />
<PackageReference Include="Masuit.Tools.Abstractions" Version="2024.5.8" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.22.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="9.0.0" />
<PackageReference Include="Microsoft.IO.RecyclableMemoryStream" Version="3.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="MiniExcel" Version="1.35.0" />
<PackageReference Include="Mirai.Net" Version="2.5.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="MrHuo.OAuth.Core" Version="1.1.1" />
<PackageReference Include="MrHuo.OAuth.Github" Version="1.1.1" />
<PackageReference Include="MrHuo.OAuth.Microsoft" Version="1.1.1" />
<PackageReference Include="NLog" Version="5.2.4" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
<PackageReference Include="Onebot.Protocol" Version="2.0.143" />
<PackageReference Include="Panda.SimpleExcel" Version="1.3.2" />
<PackageReference Include="RestSharp" Version="106.12.0" />
<PackageReference Include="SkiaSharp" Version="2.88.8" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="2.88.8" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.1.0" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<PackageReference Include="Zack.EventBus" Version="1.1.3" />
</ItemGroup>
@ -84,10 +69,6 @@
<ContainerPort Include="8081" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\asg_form.ServiceDefaults\asg_form.ServiceDefaults.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="Dockerfile">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>

View File

@ -8,18 +8,13 @@ using System.Reactive.Linq;
using Microsoft.EntityFrameworkCore;
using Mirai.Net.Data.Events.Concretes.Bot;
using static asg_form.Controllers.schedule;
using NPOI.OpenXmlFormats.Spreadsheet;
using Manganese.Array;
using static NPOI.HSSF.Util.HSSFColor;
using System.Drawing;
using System.Drawing.Imaging;
using Masuit.Tools.Hardware;
using Masuit.Tools.Win32;
using Masuit.Tools;
using Microsoft.AspNetCore.Connections;
using NPOI.SS.Formula.Functions;
using Onebot.Protocol;
using Onebot.Protocol.Models.Messages;
using Zack.EventBus;
using Flandre.Framework.Common;
using Flandre.Framework.Routing;
@ -27,7 +22,6 @@ using static asg_form.Controllers.InviteReferee;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using Azure.Identity;
using Flandre.Core.Messaging;
using Flandre.Core.Common;
using Microsoft.OpenApi.Models;