Commit ad272a87 by lcx

signalr日志推送添加授权

parent 7765af4a
...@@ -378,7 +378,7 @@ public ApiResponse SaveFile() ...@@ -378,7 +378,7 @@ public ApiResponse SaveFile()
[Route("returnlog/{userId}")] [Route("returnlog/{userId}")]
[HttpPost] [HttpPost]
[AllowAnonymous] [AllowAnonymous]
public void ReturnLog(int userId, [FromBody] MessageInfo request) public void ReturnLog(int userId, [FromBody] MessageInfo<object> request)
{ {
logger.LogInformation("返回日志:" + JsonHelper.Serialize(request)); logger.LogInformation("返回日志:" + JsonHelper.Serialize(request));
notificationsService.SendMessage(userId, request); notificationsService.SendMessage(userId, request);
......
...@@ -98,6 +98,48 @@ public void ConfigureServices(IServiceCollection services) ...@@ -98,6 +98,48 @@ public void ConfigureServices(IServiceCollection services)
#endregion json & fluentvalidation & filter #endregion json & fluentvalidation & filter
#region Authentication & signalr
services.AddAuthentication(Options =>
{
Options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
Options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Consts.Secret)),
ValidIssuer = Consts.Issuer,
ValidAudience = Consts.Audience,
ValidateIssuer = false,
ValidateAudience = false
};
x.Events = new JwtBearerEvents
{
OnMessageReceived = (context) =>
{
if (!context.HttpContext.Request.Path.HasValue)
return Task.CompletedTask;
//重点在于这里;判断是Signalr的路径
var accessToken = context.HttpContext.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!(string.IsNullOrWhiteSpace(accessToken)) && path.StartsWithSegments("/performance/allotLogHub"))
{
context.Token = accessToken;
return Task.CompletedTask;
}
return Task.CompletedTask;
}
};
});
#endregion
#region automapper #region automapper
Mapper.Initialize(cfg => cfg.AddProfile<AutoMapperConfigs>()); Mapper.Initialize(cfg => cfg.AddProfile<AutoMapperConfigs>());
...@@ -143,45 +185,6 @@ public void ConfigureServices(IServiceCollection services) ...@@ -143,45 +185,6 @@ public void ConfigureServices(IServiceCollection services)
#endregion redis #endregion redis
services.AddAuthentication(Options =>
{
Options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
Options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Consts.Secret)),
ValidIssuer = Consts.Issuer,
ValidAudience = Consts.Audience,
ValidateIssuer = false,
ValidateAudience = false
};
x.Events = new JwtBearerEvents
{
OnMessageReceived = (context) =>
{
if (!context.HttpContext.Request.Path.HasValue)
return Task.CompletedTask;
//重点在于这里;判断是Signalr的路径
var accessToken = context.HttpContext.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!(string.IsNullOrWhiteSpace(accessToken)) && path.StartsWithSegments("/performance/allotLogHub"))
{
context.Token = accessToken;
return Task.CompletedTask;
}
return Task.CompletedTask;
}
};
});
services.AddMemoryCache(); services.AddMemoryCache();
services.AddHostedService<QueuedHostedService>(); services.AddHostedService<QueuedHostedService>();
...@@ -285,6 +288,8 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF ...@@ -285,6 +288,8 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
//#endregion hangfire //#endregion hangfire
app.UseAuthentication();
app.UseCors("SignalrCore"); app.UseCors("SignalrCore");
app.UseSignalR(routes => routes.MapHub<AllotLogHub>("/performance/allotLogHub")); app.UseSignalR(routes => routes.MapHub<AllotLogHub>("/performance/allotLogHub"));
......
...@@ -1435,10 +1435,11 @@ ...@@ -1435,10 +1435,11 @@
</summary> </summary>
<returns></returns> <returns></returns>
</member> </member>
<member name="M:Performance.Api.Controllers.TemplateController.ReturnLog(Performance.DtoModels.MessageInfo)"> <member name="M:Performance.Api.Controllers.TemplateController.ReturnLog(System.Int32,Performance.DtoModels.MessageInfo)">
<summary> <summary>
返回日志 返回日志
</summary> </summary>
<param name="userId"></param>
<param name="request"></param> <param name="request"></param>
</member> </member>
<member name="M:Performance.Api.Controllers.TemplateController.ReturnLog(Performance.EntityModels.log_dbug)"> <member name="M:Performance.Api.Controllers.TemplateController.ReturnLog(Performance.EntityModels.log_dbug)">
......
...@@ -20,7 +20,7 @@ public enum Component ...@@ -20,7 +20,7 @@ public enum Component
Progress = 1, Progress = 1,
} }
public enum ComponentType public enum ComponentStatus
{ {
/// <summary> /// <summary>
/// 成功 /// 成功
......
...@@ -13,33 +13,33 @@ public MessageInfo() ...@@ -13,33 +13,33 @@ public MessageInfo()
} }
public MessageInfo(int allotId, string title, string message) public MessageInfo(int allotId, string title, string message)
: this(allotId, title, message, Component.Notification, ComponentType.info) : this(allotId, title, message, Component.Notification, ComponentStatus.info)
{ {
} }
public MessageInfo(int allotId, string title, string message, ComponentType type) public MessageInfo(int allotId, string title, string message, ComponentStatus status)
: this(allotId, title, message, Component.Notification, type) : this(allotId, title, message, Component.Notification, status)
{ {
} }
public MessageInfo(int allotId, string title, string message, Component component) public MessageInfo(int allotId, string title, string message, Component component)
: this(allotId, title, message, component, ComponentType.info) : this(allotId, title, message, component, ComponentStatus.info)
{ {
} }
public MessageInfo(int allotId, string title, string message, Component component, ComponentType type) public MessageInfo(int allotId, string title, string message, Component component, ComponentStatus status)
: this(Guid.NewGuid().ToString("N"), allotId, title, message, component, type) : this(Guid.NewGuid().ToString("N"), allotId, title, message, component, status)
{ {
} }
public MessageInfo(string uuid, int allotId, string title, string message, Component component, ComponentType type) public MessageInfo(string uuid, int allotId, string title, string message, Component component, ComponentStatus status)
{ {
Uuid = uuid; Uuid = uuid;
AllotId = allotId; AllotId = allotId;
Title = title; Title = title;
Message = message; Message = message;
Component = component; Component = component;
Status = type; Status = status;
} }
} }
...@@ -55,16 +55,16 @@ public class MessageInfo<TData> : IMessageInfo<TData> ...@@ -55,16 +55,16 @@ public class MessageInfo<TData> : IMessageInfo<TData>
public Component Component { get; set; } public Component Component { get; set; }
[JsonIgnore] //[JsonIgnore]
public ComponentType Status { get; set; } public ComponentStatus Status { get; set; }
public string Type //public string Type
{ //{
get // get
{ // {
return Status.ToString(); // return Status.ToString();
} // }
} //}
public MessageInfo() public MessageInfo()
: this(default, string.Empty, default) : this(default, string.Empty, default)
...@@ -72,33 +72,33 @@ public MessageInfo() ...@@ -72,33 +72,33 @@ public MessageInfo()
} }
public MessageInfo(int allotId, string title, TData message) public MessageInfo(int allotId, string title, TData message)
: this(allotId, title, message, Component.Notification, ComponentType.info) : this(allotId, title, message, Component.Notification, ComponentStatus.info)
{ {
} }
public MessageInfo(int allotId, string title, TData message, ComponentType type) public MessageInfo(int allotId, string title, TData message, ComponentStatus status)
: this(allotId, title, message, Component.Notification, type) : this(allotId, title, message, Component.Notification, status)
{ {
} }
public MessageInfo(int allotId, string title, TData message, Component component) public MessageInfo(int allotId, string title, TData message, Component component)
: this(allotId, title, message, component, ComponentType.info) : this(allotId, title, message, component, ComponentStatus.info)
{ {
} }
public MessageInfo(int allotId, string title, TData message, Component component, ComponentType type) public MessageInfo(int allotId, string title, TData message, Component component, ComponentStatus status)
: this(Guid.NewGuid().ToString("N"), allotId, title, message, component, type) : this(Guid.NewGuid().ToString("N"), allotId, title, message, component, status)
{ {
} }
public MessageInfo(string uuid, int allotId, string title, TData message, Component component, ComponentType type) public MessageInfo(string uuid, int allotId, string title, TData message, Component component, ComponentStatus status)
{ {
Uuid = uuid; Uuid = uuid;
AllotId = allotId; AllotId = allotId;
Title = title; Title = title;
Message = message; Message = message;
Component = component; Component = component;
Status = type; Status = status;
} }
} }
...@@ -132,11 +132,11 @@ public interface IMessageInfo<TData> ...@@ -132,11 +132,11 @@ public interface IMessageInfo<TData>
/// <summary> /// <summary>
/// 状态(完成、警告、错误、信息) /// 状态(完成、警告、错误、信息)
/// </summary> /// </summary>
ComponentType Status { get; set; } ComponentStatus Status { get; set; }
/// <summary> ///// <summary>
/// 状态文本值 ///// 状态文本值
/// </summary> ///// </summary>
string Type { get; } //string Type { get; }
} }
} }
...@@ -116,7 +116,7 @@ private PerExcel Import(per_allot allot) ...@@ -116,7 +116,7 @@ private PerExcel Import(per_allot allot)
} }
catch (Exception ex) catch (Exception ex)
{ {
notificationsService.SendGenerateMessage(allot.ID, $"读取excel文件:{ex.Message}。", ComponentType.error); notificationsService.SendGenerateMessage(allot.ID, $"读取excel文件:{ex.Message}。", ComponentStatus.error);
throw ex; throw ex;
} }
} }
......
...@@ -431,11 +431,11 @@ public void Generate(per_allot allot, string mail) ...@@ -431,11 +431,11 @@ public void Generate(per_allot allot, string mail)
notificationsService.SendGenerateMessage(allot.ID, $"正在生成报表数据:正在生成报表数据。"); notificationsService.SendGenerateMessage(allot.ID, $"正在生成报表数据:正在生成报表数据。");
var res = reportService.ImportData(allot); var res = reportService.ImportData(allot);
var flag = reportService.UpdateData(allot); var flag = reportService.UpdateData(allot);
notificationsService.SendGenerateMessage(allot.ID, $"绩效生成结束:绩效生成成功。", ComponentType.success); notificationsService.SendGenerateMessage(allot.ID, $"绩效生成结束:绩效生成成功。", ComponentStatus.success);
} }
catch (Exception ex) catch (Exception ex)
{ {
notificationsService.SendGenerateMessage(allot.ID, $"绩效生成失败:{ex.Message}。", ComponentType.error); notificationsService.SendGenerateMessage(allot.ID, $"绩效生成失败:{ex.Message}。", ComponentStatus.error);
logdbug.Add(allot.ID, "绩效生成失败", ex.ToString(), 4, 1); logdbug.Add(allot.ID, "绩效生成失败", ex.ToString(), 4, 1);
UpdateAllotStates(allot.ID, (int)AllotStates.GenerateFail, EnumHelper.GetDescription(AllotStates.GenerateFail)); UpdateAllotStates(allot.ID, (int)AllotStates.GenerateFail, EnumHelper.GetDescription(AllotStates.GenerateFail));
} }
......
...@@ -102,13 +102,13 @@ public string Main(int allotId, int hospitalId, int userId, string filePath = nu ...@@ -102,13 +102,13 @@ public string Main(int allotId, int hospitalId, int userId, string filePath = nu
catch (Exception ex) catch (Exception ex)
{ {
allot.IsExtracting = 3; allot.IsExtracting = 3;
notificationsService.SendExtractMessage(allotId, $"提取失败:数据提取过程中发生异常。", ComponentType.error); notificationsService.SendExtractMessage(allotId, $"提取失败:数据提取过程中发生异常。", ComponentStatus.error);
logger.LogError("提取数据中发生异常: " + ex.ToString()); logger.LogError("提取数据中发生异常: " + ex.ToString());
} }
finally finally
{ {
notificationsService.SendExtractProgress(allotId, 100, ComponentType.success); notificationsService.SendExtractProgress(allotId, 100, ComponentStatus.success);
notificationsService.SendExtractMessage(allotId, $"提取完成:绩效数据提取成功。", ComponentType.success); notificationsService.SendExtractMessage(allotId, $"提取完成:绩效数据提取成功。", ComponentStatus.success);
using (FileStream file = new FileStream(extractFilePath, FileMode.OpenOrCreate)) using (FileStream file = new FileStream(extractFilePath, FileMode.OpenOrCreate))
{ {
workbook.Write(file); workbook.Write(file);
......
...@@ -40,9 +40,11 @@ PerforLogdsignalrRepository repository ...@@ -40,9 +40,11 @@ PerforLogdsignalrRepository repository
/// <summary> 绩效提取 </summary> /// <summary> 绩效提取 </summary>
public const string AllotExtractKeyPrefix = "Allot-Extract-"; public const string AllotExtractKeyPrefix = "Allot-Extract-";
public void SendGenerateMessage(int allotId, string message, ComponentType type = ComponentType.info) public void SendGenerateMessage(int allotId, string message, ComponentStatus type = ComponentStatus.info)
{ {
logger.LogInformation(message);
var data = GetCache<SingleData>(AllotGenerateKeyPrefix + allotId); var data = GetCache<SingleData>(AllotGenerateKeyPrefix + allotId);
logger.LogInformation(JsonHelper.Serialize(data));
if (data == null || data.UserId == 0) if (data == null || data.UserId == 0)
return; return;
...@@ -50,7 +52,7 @@ public void SendGenerateMessage(int allotId, string message, ComponentType type ...@@ -50,7 +52,7 @@ public void SendGenerateMessage(int allotId, string message, ComponentType type
SendMessage(data.UserId, info); SendMessage(data.UserId, info);
} }
public void SendExtractMessage(int allotId, string message, ComponentType type = ComponentType.info) public void SendExtractMessage(int allotId, string message, ComponentStatus type = ComponentStatus.info)
{ {
var data = GetCache<SingleData>(AllotExtractKeyPrefix + allotId); var data = GetCache<SingleData>(AllotExtractKeyPrefix + allotId);
if (data == null || data.UserId == 0) if (data == null || data.UserId == 0)
...@@ -62,28 +64,28 @@ public void SendExtractMessage(int allotId, string message, ComponentType type = ...@@ -62,28 +64,28 @@ public void SendExtractMessage(int allotId, string message, ComponentType type =
else SendMessageToSite(data.UserId, info); else SendMessageToSite(data.UserId, info);
} }
public void SendExtractProgress(int allotId, decimal percentage, ComponentType type = ComponentType.info) public void SendExtractProgress(int allotId, decimal percentage, ComponentStatus type = ComponentStatus.info)
{ {
var data = GetCache<SingleData>(AllotExtractKeyPrefix + allotId); var data = GetCache<SingleData>(AllotExtractKeyPrefix + allotId);
if (data == null || data.UserId == 0) if (data == null || data.UserId == 0)
return; return;
percentage = type == ComponentType.success ? 100 percentage = type == ComponentStatus.success ? 100
: (type != ComponentType.success && percentage >= 100) ? 99 : percentage; : (type != ComponentStatus.success && percentage >= 100) ? 99 : percentage;
var info = new MessageInfo(data.Uuid, allotId, "数据提取进度", percentage.ToString(), Component.Progress, type); var info = new MessageInfo<decimal>(data.Uuid, allotId, "数据提取进度", percentage, Component.Progress, type);
if (data.IsSingle) SendMessage(data.UserId, info); if (data.IsSingle) SendMessage(data.UserId, info);
else SendMessageToSite(data.UserId, info); else SendMessageToSite(data.UserId, info);
} }
public void SendMessage(int userId, MessageInfo data) public void SendMessage<TData>(int userId, MessageInfo<TData> data)
{ {
string key = userId.ToString(); string key = userId.ToString();
if (cache.TryGetValue(key, out string connectionId) && !string.IsNullOrEmpty(connectionId)) if (cache.TryGetValue(key, out string connectionId) && !string.IsNullOrEmpty(connectionId))
{ {
string method = data.Component == Component.Notification ? "ReceiveMessage" : "ReceiveProgress"; string method = data.Component == Component.Notification ? "ReceiveMessage" : "ReceiveProgress";
SendMessageToClient(connectionId, data, method); SendMessageToClient(connectionId, method, data);
} }
} }
...@@ -92,12 +94,12 @@ private void SaveLogToDataBase() ...@@ -92,12 +94,12 @@ private void SaveLogToDataBase()
} }
private void SendMessageToClient(string connectionId, MessageInfo info, string method) private void SendMessageToClient<TData>(string connectionId, string method, MessageInfo<TData> info)
{ {
hubContext.Clients.Client(connectionId).SendAsync(method, info.Title, info); hubContext.Clients.Client(connectionId).SendAsync(method, info);
} }
private void SendMessageToSite(int userId, MessageInfo info) private void SendMessageToSite<TData>(int userId, MessageInfo<TData> info)
{ {
try try
{ {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment