sync with OpenAuth.Core

This commit is contained in:
yubaolee
2020-12-20 23:14:09 +08:00
parent 7217e7a924
commit 7540baa322
25 changed files with 347 additions and 169 deletions

View File

@@ -1,29 +1,35 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Infrastructure;
using Infrastructure.Extensions;
using Infrastructure.Helpers;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Interface;
namespace OpenAuth.App
{
/// <summary>
/// 文件
/// 文件管理
/// </summary>
public class FileApp : BaseApp<UploadFile>
{
private ILogger<FileApp> _logger;
private string _filePath;
private string _dbFilePath; //数据库中的文件路径
private string _dbThumbnail; //数据库中的缩略图路径
private string _dbFilePath; //数据库中的文件路径
private string _dbThumbnail; //数据库中的缩略图路径
public FileApp( IOptions<AppSetting> setOptions, IUnitWork unitWork, IRepository<UploadFile> repository, ILogger<FileApp> logger, IAuth auth)
:base(unitWork, repository, auth)
public FileApp(IOptions<AppSetting> setOptions, IUnitWork unitWork, IRepository<UploadFile> repository,
ILogger<FileApp> logger, IAuth auth)
: base(unitWork, repository, auth)
{
_logger = logger;
_filePath = setOptions.Value.UploadPath;
@@ -33,6 +39,30 @@ namespace OpenAuth.App
}
}
/// <summary>
/// 加载附件列表
/// </summary>
public async Task<TableData> Load(QueryFileListReq request)
{
var result = new TableData();
var objs = UnitWork.Find<UploadFile>(null);
if (!string.IsNullOrEmpty(request.key))
{
objs = objs.Where(u => u.FileName.Contains(request.key) || u.FilePath.Contains(request.key));
}
result.data = objs.OrderByDescending(u => u.CreateTime)
.Skip((request.page - 1) * request.limit)
.Take(request.limit);
result.count = objs.Count();
return result;
}
/// <summary>
/// 批量添加附件
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
public List<UploadFile> Add(IFormFileCollection files)
{
var result = new List<UploadFile>();
@@ -55,20 +85,22 @@ namespace OpenAuth.App
{
_logger.LogWarning("收到新文件为空");
}
if (file != null && file.Length > 0 && file.Length < 10485760)
{
using (var binaryReader = new BinaryReader(file.OpenReadStream()))
{
var fileName = Path.GetFileName(file.FileName);
var data = binaryReader.ReadBytes((int)file.Length);
UploadFile(fileName, data);
var data = binaryReader.ReadBytes((int) file.Length);
SaveFile(fileName, data);
var filedb = new UploadFile
{
FilePath = _dbFilePath,
Thumbnail = _dbThumbnail,
FileName = fileName,
FileSize = file.Length,
FileSize = file.Length.ToInt(),
CreateUserName = _auth.GetUserName(),
FileType = Path.GetExtension(fileName),
Extension = Path.GetExtension(fileName)
};
@@ -81,8 +113,33 @@ namespace OpenAuth.App
throw new Exception("文件过大");
}
}
/// <summary>
/// 删除附件
/// </summary>
/// <param name="ids"></param>
public override void Delete(string[] ids)
{
var files = base.Repository.Find(u => ids.Contains(u.Id)).ToList();
for (int i = 0; i < files.Count(); i++)
{
var uploadPath = Path.Combine(_filePath, files[i].FilePath);
FileHelper.FileDel(uploadPath);
if (!string.IsNullOrEmpty(files[i].Thumbnail))
{
FileHelper.FileDel(Path.Combine(_filePath, files[i].Thumbnail));
}
Repository.Delete(u =>u.Id == files[i].Id);
}
}
private void UploadFile(string fileName, byte[] fileBuffers)
/// <summary>
/// 存储文件,如果是图片文件则生成缩略图
/// </summary>
/// <param name="fileName"></param>
/// <param name="fileBuffers"></param>
/// <exception cref="Exception"></exception>
private void SaveFile(string fileName, byte[] fileBuffers)
{
string folder = DateTime.Now.ToString("yyyyMMdd");
@@ -98,7 +155,7 @@ namespace OpenAuth.App
throw new Exception("文件不能为空");
}
var uploadPath = Path.Combine(_filePath , folder );
var uploadPath = Path.Combine(_filePath, folder);
_logger.LogInformation("文件写入:" + uploadPath);
if (!Directory.Exists(uploadPath))
{
@@ -108,21 +165,22 @@ namespace OpenAuth.App
var ext = Path.GetExtension(fileName).ToLower();
string newName = GenerateId.GenerateOrderNumber() + ext;
using (var fs = new FileStream(Path.Combine(uploadPath , newName), FileMode.Create))
using (var fs = new FileStream(Path.Combine(uploadPath, newName), FileMode.Create))
{
fs.Write(fileBuffers, 0, fileBuffers.Length);
fs.Close();
//生成缩略图
if (ext.Contains(".jpg") || ext.Contains(".jpeg") || ext.Contains(".png") || ext.Contains(".bmp") || ext.Contains(".gif"))
if (ext.Contains(".jpg") || ext.Contains(".jpeg") || ext.Contains(".png") || ext.Contains(".bmp") ||
ext.Contains(".gif"))
{
string thumbnailName = GenerateId.GenerateOrderNumber() + ext;
ImgHelper.MakeThumbnail(Path.Combine(uploadPath , newName), Path.Combine(uploadPath , thumbnailName));
_dbThumbnail = Path.Combine(folder , thumbnailName);
ImgHelper.MakeThumbnail(Path.Combine(uploadPath, newName), Path.Combine(uploadPath, thumbnailName));
_dbThumbnail = Path.Combine(folder, thumbnailName);
}
_dbFilePath = Path.Combine(folder , newName);
_dbFilePath = Path.Combine(folder, newName);
}
}
}

View File

@@ -62,6 +62,9 @@ namespace OpenAuth.App
return _revelanceApp.Get(Define.ROLEDATAPROPERTY, roleId, moduleCode);
}
/// <summary>
/// 根据某角色ID获取可访问某模块的菜单项
/// </summary>
public IEnumerable<ModuleElement> LoadMenusForRole(string moduleId, string roleId)
{
var elementIds = _revelanceApp.Get(Define.ROLEELEMENT, true, roleId);
@@ -90,6 +93,10 @@ namespace OpenAuth.App
}
/// <summary>
/// 新增菜单
/// <para>当前登录用户的所有角色会自动分配菜单</para>
/// </summary>
public void AddMenu(ModuleElement model)
{
var loginContext = _auth.GetCurrentUser();

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp5.0</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">

View File

@@ -0,0 +1,7 @@
namespace OpenAuth.App.Request
{
public class QueryFileListReq : PageReq
{
//todo:添加自己的请求字段
}
}

View File

@@ -72,14 +72,16 @@ namespace OpenAuth.App
{
foreach (var value in sameVals)
{
Repository.Delete(u => u.Key == key && u.FirstId == sameVals.Key && u.SecondId == value);
UnitWork.Delete<Relevance>(u => u.Key == key && u.FirstId == sameVals.Key && u.SecondId == value);
}
}
UnitWork.Save();
}
public void DeleteBy(string key, params string[] firstIds)
{
Repository.Delete(u => firstIds.Contains(u.FirstId) && u.Key == key);
UnitWork.Delete<Relevance>(u => firstIds.Contains(u.FirstId) && u.Key == key);
UnitWork.Save();
}
@@ -160,11 +162,12 @@ namespace OpenAuth.App
{
foreach (var property in request.Properties)
{
Repository.Delete(u => u.Key == Define.ROLEDATAPROPERTY
UnitWork.Delete<Relevance>(u => u.Key == Define.ROLEDATAPROPERTY
&& u.FirstId == request.RoleId
&& u.SecondId == request.ModuleCode
&& u.ThirdId == property);
}
UnitWork.Save();
}
}
@@ -174,18 +177,21 @@ namespace OpenAuth.App
/// <param name="request"></param>
public void AssignRoleUsers(AssignRoleUsers request)
{
//删除以前的所有用户
UnitWork.Delete<Relevance>(u => u.SecondId == request.RoleId && u.Key == Define.USERROLE);
//批量分配用户角色
UnitWork.BatchAdd((from firstId in request.UserIds
select new Relevance
{
Key = Define.USERROLE,
FirstId = firstId,
SecondId = request.RoleId,
OperateTime = DateTime.Now
}).ToArray());
UnitWork.Save();
UnitWork.ExecuteWithTransaction(() =>
{
//删除以前的所有用户
UnitWork.Delete<Relevance>(u => u.SecondId == request.RoleId && u.Key == Define.USERROLE);
//批量分配用户角色
UnitWork.BatchAdd((from firstId in request.UserIds
select new Relevance
{
Key = Define.USERROLE,
FirstId = firstId,
SecondId = request.RoleId,
OperateTime = DateTime.Now
}).ToArray());
UnitWork.Save();
});
}
/// <summary>
@@ -194,18 +200,21 @@ namespace OpenAuth.App
/// <param name="request"></param>
public void AssignOrgUsers(AssignOrgUsers request)
{
//删除以前的所有用户
UnitWork.Delete<Relevance>(u => u.SecondId == request.OrgId && u.Key == Define.USERORG);
//批量分配用户角色
UnitWork.BatchAdd((from firstId in request.UserIds
select new Relevance
{
Key = Define.USERORG,
FirstId = firstId,
SecondId = request.OrgId,
OperateTime = DateTime.Now
}).ToArray());
UnitWork.Save();
UnitWork.ExecuteWithTransaction(() =>
{
//删除以前的所有用户
UnitWork.Delete<Relevance>(u => u.SecondId == request.OrgId && u.Key == Define.USERORG);
//批量分配用户角色
UnitWork.BatchAdd((from firstId in request.UserIds
select new Relevance
{
Key = Define.USERORG,
FirstId = firstId,
SecondId = request.OrgId,
OperateTime = DateTime.Now
}).ToArray());
UnitWork.Save();
});
}
}
}

View File

@@ -0,0 +1,52 @@
using System;
using System.Threading.Tasks;
using Castle.Core.Logging;
using Infrastructure;
using Infrastructure.Cache;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using OpenAuth.App.Request;
using OpenAuth.App.SSO;
namespace OpenAuth.App.Test
{
class TestFileApp :TestBase
{
public override ServiceCollection GetService()
{
var services = new ServiceCollection();
var cachemock = new Mock<ICacheContext>();
cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = "System" });
services.AddScoped(x => cachemock.Object);
var httpContextAccessorMock = new Mock<IHttpContextAccessor>();
httpContextAccessorMock.Setup(x => x.HttpContext.Request.Query[Define.TOKEN_NAME]).Returns("tokentest");
services.AddScoped(x => httpContextAccessorMock.Object);
var logMock = new Mock<ILogger<FileApp>>();
services.AddScoped(x => logMock.Object);
return services;
}
[Test]
public void TestLoad()
{
var app = _autofacServiceProvider.GetService<FileApp>();
var result = app.Load(new QueryFileListReq()
{
page = 1,
limit = 10
});
Console.WriteLine(JsonHelper.Instance.Serialize(result.Result));
}
}
}

View File

@@ -119,47 +119,52 @@ namespace OpenAuth.App
throw new Exception("请为用户分配机构");
User requser = request;
requser.CreateId = _auth.GetCurrentUser().User.Id;
if (string.IsNullOrEmpty(request.Id))
UnitWork.ExecuteWithTransaction(() =>
{
if (UnitWork.Any<User>(u => u.Account == request.Account))
if (string.IsNullOrEmpty(request.Id))
{
throw new Exception("用户账号已存在");
if (UnitWork.Any<User>(u => u.Account == request.Account))
{
throw new Exception("用户账号已存在");
}
if (string.IsNullOrEmpty(requser.Password))
{
requser.Password = requser.Account; //如果客户端没提供密码,默认密码同账号
}
requser.CreateTime = DateTime.Now;
UnitWork.Add(requser);
request.Id = requser.Id; //要把保存后的ID存入view
}
if (string.IsNullOrEmpty(requser.Password))
{
requser.Password = requser.Account; //如果客户端没提供密码,默认密码同账号
}
requser.CreateTime = DateTime.Now;
UnitWork.Add(requser);
request.Id = requser.Id; //要把保存后的ID存入view
}
else
{
UnitWork.Update<User>(u => u.Id == request.Id, u => new User
{
Account = requser.Account,
BizCode = requser.BizCode,
Name = requser.Name,
Sex = requser.Sex,
Status = requser.Status
});
if (!string.IsNullOrEmpty(requser.Password)) //密码为空的时候,不做修改
else
{
UnitWork.Update<User>(u => u.Id == request.Id, u => new User
{
Password = requser.Password
Account = requser.Account,
BizCode = requser.BizCode,
Name = requser.Name,
Sex = requser.Sex,
Status = requser.Status
});
if (!string.IsNullOrEmpty(requser.Password)) //密码为空的时候,不做修改
{
UnitWork.Update<User>(u => u.Id == request.Id, u => new User
{
Password = requser.Password
});
}
}
}
UnitWork.Save();
string[] orgIds = request.OrganizationIds.Split(',').ToArray();
UnitWork.Save();
string[] orgIds = request.OrganizationIds.Split(',').ToArray();
_revelanceApp.DeleteBy(Define.USERORG, requser.Id);
_revelanceApp.Assign(Define.USERORG, orgIds.ToLookup(u => requser.Id));
_revelanceApp.DeleteBy(Define.USERORG, requser.Id);
_revelanceApp.Assign(Define.USERORG, orgIds.ToLookup(u => requser.Id));
});
}
/// <summary>
@@ -168,10 +173,14 @@ namespace OpenAuth.App
/// <param name="ids"></param>
public override void Delete(string[] ids)
{
UnitWork.Delete<Relevance>(u =>(u.Key == Define.USERROLE || u.Key == Define.USERORG)
&& ids.Contains(u.FirstId));
UnitWork.Delete<User>(u => ids.Contains(u.Id));
UnitWork.Save();
UnitWork.ExecuteWithTransaction(() =>
{
UnitWork.Delete<Relevance>(u =>(u.Key == Define.USERROLE || u.Key == Define.USERORG)
&& ids.Contains(u.FirstId));
UnitWork.Delete<User>(u => ids.Contains(u.Id));
UnitWork.Save();
});
}