sync with OpenAuth.Core

This commit is contained in:
yubaolee 2020-12-27 00:00:28 +08:00
parent 368eae8d63
commit 20a717b2e6
19 changed files with 451 additions and 199 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
<log4net> <log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!--定义文件存放位置--> <!--定义文件存放位置-->
<file value="log\\" /> <file value="log/" />
<appendToFile value="true" /> <appendToFile value="true" />
<rollingStyle value="Date" /> <rollingStyle value="Date" />
<datePattern value="yyyyMMdd'.txt'" /> <datePattern value="yyyyMMdd'.txt'" />

View File

@ -65,6 +65,11 @@ namespace OpenAuth.App
/// <returns></returns> /// <returns></returns>
public List<UploadFile> Add(IFormFileCollection files) public List<UploadFile> Add(IFormFileCollection files)
{ {
if (!_auth.CheckLogin())
{
throw new Exception("必需登录才能上传附件");
}
var result = new List<UploadFile>(); var result = new List<UploadFile>();
foreach (var file in files) foreach (var file in files)
{ {

View File

@ -1,4 +1,5 @@
using Infrastructure; using System.ComponentModel.DataAnnotations;
using Infrastructure;
using OpenAuth.Repository.Domain; using OpenAuth.Repository.Domain;
namespace OpenAuth.App.Request namespace OpenAuth.App.Request
@ -18,6 +19,7 @@ namespace OpenAuth.App.Request
/// <summary> /// <summary>
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Required(ErrorMessage = "账号肯定不能为空啊~~")]
public string Account { get; set; } public string Account { get; set; }
/// <summary> /// <summary>
@ -27,9 +29,10 @@ namespace OpenAuth.App.Request
/// <summary> /// <summary>
/// 组织名称 /// 用户姓名
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Required(ErrorMessage="姓名不能为空")]
public string Name { get; set; } public string Name { get; set; }
@ -50,6 +53,7 @@ namespace OpenAuth.App.Request
/// 所属组织Id多个可用分隔 /// 所属组织Id多个可用分隔
/// </summary> /// </summary>
/// <value>The organizations.</value> /// <value>The organizations.</value>
[Required(ErrorMessage = "请为用户分配机构")]
public string OrganizationIds { get; set; } public string OrganizationIds { get; set; }
public static implicit operator UpdateUserReq(User user) public static implicit operator UpdateUserReq(User user)

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.Extensions.Logging;
using OpenAuth.App.Interface; using OpenAuth.App.Interface;
using OpenAuth.App.Request; using OpenAuth.App.Request;
using OpenAuth.Repository.Domain; using OpenAuth.Repository.Domain;
@ -8,10 +9,13 @@ using OpenAuth.Repository.Interface;
namespace OpenAuth.App namespace OpenAuth.App
{ {
public class RevelanceManagerApp :BaseApp<Relevance> public class RevelanceManagerApp : BaseApp<Relevance>
{ {
public RevelanceManagerApp(IUnitWork unitWork, IRepository<Relevance> repository,IAuth auth) : base(unitWork, repository, auth) private readonly ILogger<RevelanceManagerApp> _logger;
public RevelanceManagerApp(IUnitWork unitWork, IRepository<Relevance> repository, IAuth auth, ILogger<RevelanceManagerApp> logger) : base(unitWork,
repository, auth)
{ {
_logger = logger;
} }
/// <summary> /// <summary>
@ -57,7 +61,7 @@ namespace OpenAuth.App
} }
else else
{ {
DeleteBy(req.type, req.secIds.ToLookup(u => req.firstId)); DeleteBy(req.type, req.secIds.ToLookup(u => req.firstId));
} }
} }
@ -72,16 +76,23 @@ namespace OpenAuth.App
{ {
foreach (var value in sameVals) foreach (var value in sameVals)
{ {
UnitWork.Delete<Relevance>(u => u.Key == key && u.FirstId == sameVals.Key && u.SecondId == value); _logger.LogInformation($"start=> delete {key} {sameVals.Key} {value}");
try
{
UnitWork.Delete<Relevance>(u => u.Key == key && u.FirstId == sameVals.Key && u.SecondId == value);
}
catch (Exception e)
{
_logger.LogError(e,e.Message);
}
_logger.LogInformation($"end=> {key} {sameVals.Key} {value}");
} }
} }
UnitWork.Save();
} }
public void DeleteBy(string key, params string[] firstIds) public void DeleteBy(string key, params string[] firstIds)
{ {
UnitWork.Delete<Relevance>(u => firstIds.Contains(u.FirstId) && u.Key == key); UnitWork.Delete<Relevance>(u => firstIds.Contains(u.FirstId) && u.Key == key);
UnitWork.Save();
} }
@ -97,12 +108,12 @@ namespace OpenAuth.App
if (returnSecondIds) if (returnSecondIds)
{ {
return Repository.Find(u => u.Key == key return Repository.Find(u => u.Key == key
&& ids.Contains(u.FirstId)).Select(u => u.SecondId).ToList(); && ids.Contains(u.FirstId)).Select(u => u.SecondId).ToList();
} }
else else
{ {
return Repository.Find(u => u.Key == key return Repository.Find(u => u.Key == key
&& ids.Contains(u.SecondId)).Select(u => u.FirstId).ToList(); && ids.Contains(u.SecondId)).Select(u => u.FirstId).ToList();
} }
} }
@ -125,6 +136,11 @@ namespace OpenAuth.App
/// <param name="request"></param> /// <param name="request"></param>
public void AssignData(AssignDataReq request) public void AssignData(AssignDataReq request)
{ {
if (!request.Properties.Any())
{
return;
}
var relevances = new List<Relevance>(); var relevances = new List<Relevance>();
foreach (var requestProperty in request.Properties) foreach (var requestProperty in request.Properties)
{ {
@ -137,6 +153,7 @@ namespace OpenAuth.App
OperateTime = DateTime.Now OperateTime = DateTime.Now
}); });
} }
UnitWork.BatchAdd(relevances.ToArray()); UnitWork.BatchAdd(relevances.ToArray());
UnitWork.Save(); UnitWork.Save();
} }
@ -149,25 +166,24 @@ namespace OpenAuth.App
{ {
if (request.Properties == null || request.Properties.Length == 0) if (request.Properties == null || request.Properties.Length == 0)
{ {
if (string.IsNullOrEmpty(request.ModuleCode)) //模块为空,直接把角色的所有授权删除 if (string.IsNullOrEmpty(request.ModuleCode)) //模块为空,直接把角色的所有授权删除
{ {
DeleteBy(Define.ROLEDATAPROPERTY, request.RoleId); DeleteBy(Define.ROLEDATAPROPERTY, request.RoleId);
} }
else //把角色的某一个模块权限全部删除 else //把角色的某一个模块权限全部删除
{ {
DeleteBy(Define.ROLEDATAPROPERTY, new []{ request.ModuleCode }.ToLookup(u =>request.RoleId)); DeleteBy(Define.ROLEDATAPROPERTY, new[] {request.ModuleCode}.ToLookup(u => request.RoleId));
} }
} }
else //按具体的id删除 else //按具体的id删除
{ {
foreach (var property in request.Properties) foreach (var property in request.Properties)
{ {
UnitWork.Delete<Relevance>(u => u.Key == Define.ROLEDATAPROPERTY UnitWork.Delete<Relevance>(u => u.Key == Define.ROLEDATAPROPERTY
&& u.FirstId == request.RoleId && u.FirstId == request.RoleId
&& u.SecondId == request.ModuleCode && u.SecondId == request.ModuleCode
&& u.ThirdId == property); && u.ThirdId == property);
} }
UnitWork.Save();
} }
} }

View File

@ -29,29 +29,37 @@ namespace OpenAuth.App
} }
/// <summary>
/// 添加角色如果当前登录用户不是System则直接把新角色分配给当前登录用户
/// </summary>
public void Add(RoleView obj) public void Add(RoleView obj)
{ {
UnitWork.ExecuteWithTransaction(() =>
Role role = obj; {
role.CreateTime = DateTime.Now; Role role = obj;
Repository.Add(role); role.CreateTime = DateTime.Now;
obj.Id = role.Id; //要把保存后的ID存入view UnitWork.Add(role);
UnitWork.Save();
obj.Id = role.Id; //要把保存后的ID存入view
//如果当前账号不是SYSTEM则直接分配 //如果当前账号不是SYSTEM则直接分配
var loginUser = _auth.GetCurrentUser(); var loginUser = _auth.GetCurrentUser();
if (loginUser.User.Account != Define.SYSTEM_USERNAME) if (loginUser.User.Account != Define.SYSTEM_USERNAME)
{ {
_revelanceApp.Assign(new AssignReq _revelanceApp.Assign(new AssignReq
{ {
type = Define.USERROLE, type = Define.USERROLE,
firstId = loginUser.User.Id, firstId = loginUser.User.Id,
secIds = new[] {role.Id} secIds = new[] {role.Id}
}); });
} }
});
} }
/// <summary>
/// 更新角色属性
/// </summary>
/// <param name="obj"></param>
public void Update(RoleView obj) public void Update(RoleView obj)
{ {
Role role = obj; Role role = obj;

View File

@ -22,7 +22,7 @@ namespace OpenAuth.App.Test
var cachemock = new Mock<ICacheContext>(); var cachemock = new Mock<ICacheContext>();
cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")) cachemock.Setup(x => x.Get<UserAuthSession>("tokentest"))
.Returns(new UserAuthSession { Account = "System" }); .Returns(new UserAuthSession { Account = Define.SYSTEM_USERNAME });
services.AddScoped(x => cachemock.Object); services.AddScoped(x => cachemock.Object);
var httpContextAccessorMock = new Mock<IHttpContextAccessor>(); var httpContextAccessorMock = new Mock<IHttpContextAccessor>();
@ -56,5 +56,32 @@ namespace OpenAuth.App.Test
Console.WriteLine(JsonHelper.Instance.Serialize(result)); Console.WriteLine(JsonHelper.Instance.Serialize(result));
} }
[Test]
public void UnAssign()
{
var app = _autofacServiceProvider.GetService<RevelanceManagerApp>();
app.UnAssignData(new AssignDataReq
{
ModuleCode = "WmsInboundOrderTbl",
Properties = new string[]{},
RoleId = "09ee2ffa-7463-4938-ae0b-1cb4e80c7c13"
});
app.UnAssignData(new AssignDataReq
{
ModuleCode = "Category",
Properties = new string[]{},
RoleId = "09ee2ffa-7463-4938-ae0b-1cb4e80c7c13"
});
app.UnAssignData(new AssignDataReq
{
ModuleCode = "Resource",
Properties = new string[]{},
RoleId = "09ee2ffa-7463-4938-ae0b-1cb4e80c7c13"
});
}
} }
} }

View File

@ -21,7 +21,7 @@ namespace OpenAuth.App.Test
var cachemock = new Mock<ICacheContext>(); var cachemock = new Mock<ICacheContext>();
cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")) cachemock.Setup(x => x.Get<UserAuthSession>("tokentest"))
.Returns(new UserAuthSession { Account = "System" }); .Returns(new UserAuthSession { Account = Define.SYSTEM_USERNAME });
services.AddScoped(x => cachemock.Object); services.AddScoped(x => cachemock.Object);
var httpContextAccessorMock = new Mock<IHttpContextAccessor>(); var httpContextAccessorMock = new Mock<IHttpContextAccessor>();

View File

@ -20,7 +20,7 @@ namespace OpenAuth.App.Test
var services = new ServiceCollection(); var services = new ServiceCollection();
var cachemock = new Mock<ICacheContext>(); var cachemock = new Mock<ICacheContext>();
cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = "System" }); cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = Define.SYSTEM_USERNAME });
services.AddScoped(x => cachemock.Object); services.AddScoped(x => cachemock.Object);
var httpContextAccessorMock = new Mock<IHttpContextAccessor>(); var httpContextAccessorMock = new Mock<IHttpContextAccessor>();

View File

@ -17,7 +17,7 @@ namespace OpenAuth.App.Test
var services = new ServiceCollection(); var services = new ServiceCollection();
var cachemock = new Mock<ICacheContext>(); var cachemock = new Mock<ICacheContext>();
cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = "System" }); cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = Define.SYSTEM_USERNAME});
services.AddScoped(x => cachemock.Object); services.AddScoped(x => cachemock.Object);
var httpContextAccessorMock = new Mock<IHttpContextAccessor>(); var httpContextAccessorMock = new Mock<IHttpContextAccessor>();
@ -28,6 +28,27 @@ namespace OpenAuth.App.Test
return services; return services;
} }
/// <summary>
/// 测试添加用户时,数据校验。
/// 因为请求数据没有AccountName等该测试会提示异常
/// </summary>
[Test]
public void TestValidation()
{
var app = _autofacServiceProvider.GetService<UserManagerApp>();
try
{
app.AddOrUpdate(new UpdateUserReq
{
OrganizationIds = "08f41bf6-4388-4b1e-bd3e-2ff538b44b1b",
});
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
[Test] [Test]
public void TestAdd() public void TestAdd()
{ {

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Castle.Core.Internal; using Castle.Core.Internal;
using Infrastructure.Extensions;
using OpenAuth.App.Interface; using OpenAuth.App.Interface;
using OpenAuth.App.Request; using OpenAuth.App.Request;
using OpenAuth.App.Response; using OpenAuth.App.Response;
@ -115,6 +116,8 @@ namespace OpenAuth.App
public void AddOrUpdate(UpdateUserReq request) public void AddOrUpdate(UpdateUserReq request)
{ {
request.ValidationEntity(u => new {u.Account,u.Name, u.OrganizationIds});
if (string.IsNullOrEmpty(request.OrganizationIds)) if (string.IsNullOrEmpty(request.OrganizationIds))
throw new Exception("请为用户分配机构"); throw new Exception("请为用户分配机构");
User requser = request; User requser = request;

View File

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Security.Claims; using System.Security.Claims;
using IdentityModel; using IdentityModel;
using IdentityServer4.Test; using IdentityServer4.Test;
using OpenAuth.App;
namespace OpenAuth.IdentityServer.Quickstart namespace OpenAuth.IdentityServer.Quickstart
{ {
@ -13,7 +14,7 @@ namespace OpenAuth.IdentityServer.Quickstart
{ {
public static List<TestUser> Users = new List<TestUser> public static List<TestUser> Users = new List<TestUser>
{ {
new TestUser{SubjectId = "System", Username = "System", Password = "123456", new TestUser{SubjectId = "System", Username = Define.SYSTEM_USERNAME, Password = Define.SYSTEM_USERPWD,
Claims = Claims =
{ {
new Claim(JwtClaimTypes.Name, "System"), new Claim(JwtClaimTypes.Name, "System"),

View File

@ -1,15 +1,31 @@
using Microsoft.EntityFrameworkCore; using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using OpenAuth.Repository.Domain; using OpenAuth.Repository.Domain;
using OpenAuth.Repository.QueryObj; using OpenAuth.Repository.QueryObj;
namespace OpenAuth.Repository namespace OpenAuth.Repository
{ {
public partial class OpenAuthDBContext : DbContext public partial class OpenAuthDBContext : DbContext
{ {
public OpenAuthDBContext(DbContextOptions<OpenAuthDBContext> options) private ILoggerFactory _LoggerFactory;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.EnableSensitiveDataLogging (true); //允许打印参数
optionsBuilder.UseLoggerFactory (_LoggerFactory);
base.OnConfiguring (optionsBuilder);
}
public OpenAuthDBContext(DbContextOptions<OpenAuthDBContext> options, ILoggerFactory loggerFactory)
: base(options) : base(options)
{} {
_LoggerFactory = loggerFactory;
}
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {

View File

@ -91,13 +91,17 @@ namespace OpenAuth.WebApi.Controllers
/// </summary> /// </summary>
/// <param name="request"></param> /// <param name="request"></param>
/// <returns></returns> /// <returns></returns>
private static string lockobj = "lock";
[HttpPost] [HttpPost]
public Response UnAssignDataProperty(AssignDataReq request) public Response UnAssignDataProperty(AssignDataReq request)
{ {
var result = new Response(); var result = new Response();
try try
{ {
_app.UnAssignData(request); lock (lockobj)
{
_app.UnAssignData(request);
}
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -67,7 +67,6 @@ namespace OpenAuth.WebApi.Controllers
/// <param name="files"></param> /// <param name="files"></param>
/// <returns>服务器存储的文件信息</returns> /// <returns>服务器存储的文件信息</returns>
[HttpPost] [HttpPost]
[AllowAnonymous]
public Response<IList<UploadFile>> Upload(IFormFileCollection files) public Response<IList<UploadFile>> Upload(IFormFileCollection files)
{ {
var result = new Response<IList<UploadFile>>(); var result = new Response<IList<UploadFile>>();

View File

@ -41,8 +41,10 @@ namespace OpenAuth.WebApi.Controllers
return result; return result;
} }
//添加或修改 /// <summary>
[HttpPost] /// 添加角色如果当前登录用户不是System则直接把新角色分配给当前登录用户
/// </summary>
[HttpPost]
public Response<RoleView> Add(RoleView obj) public Response<RoleView> Add(RoleView obj)
{ {
var result = new Response<RoleView>(); var result = new Response<RoleView>();
@ -60,8 +62,12 @@ namespace OpenAuth.WebApi.Controllers
return result; return result;
} }
//添加或修改 /// <summary>
/// 更新角色属性
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
[HttpPost] [HttpPost]
public Response Update(RoleView obj) public Response Update(RoleView obj)
{ {

View File

@ -17,8 +17,6 @@ namespace OpenAuth.WebApi
.ConfigureLogging((hostingContext, logging) => .ConfigureLogging((hostingContext, logging) =>
{ {
logging.ClearProviders(); //去掉默认的日志 logging.ClearProviders(); //去掉默认的日志
logging.AddFilter("System", LogLevel.Error);
logging.AddFilter("Microsoft", LogLevel.Error);
logging.AddLog4Net(); logging.AddLog4Net();
}) })
.UseServiceProviderFactory( .UseServiceProviderFactory(

View File

@ -4,10 +4,10 @@ using System.IO;
using System.Linq; using System.Linq;
using Autofac; using Autofac;
using IdentityServer4.AccessTokenValidation; using IdentityServer4.AccessTokenValidation;
using Infrastructure.Extensions;
using Infrastructure.Extensions.AutofacManager; using Infrastructure.Extensions.AutofacManager;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -38,6 +38,11 @@ namespace OpenAuth.WebApi
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.AddSingleton(provider => services.AddSingleton(provider =>
{ {
var service = provider.GetRequiredService<ILogger<StartupLogger>>(); var service = provider.GetRequiredService<ILogger<StartupLogger>>();
@ -161,8 +166,10 @@ namespace OpenAuth.WebApi
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostEnvironment env) public void Configure(IApplicationBuilder app, IHostEnvironment env, ILoggerFactory loggerFactory)
{ {
loggerFactory.AddLog4Net();
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();

View File

@ -2,8 +2,9 @@
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Debug", "Default": "Debug",
"System": "Information", "System": "Error",
"Microsoft": "Information" "Microsoft": "Error",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
} }
} }
} }