Commit ad272a87 by lcx

signalr日志推送添加授权

parent 7765af4a
......@@ -378,7 +378,7 @@ public ApiResponse SaveFile()
[Route("returnlog/{userId}")]
[HttpPost]
[AllowAnonymous]
public void ReturnLog(int userId, [FromBody] MessageInfo request)
public void ReturnLog(int userId, [FromBody] MessageInfo<object> request)
{
logger.LogInformation("返回日志:" + JsonHelper.Serialize(request));
notificationsService.SendMessage(userId, request);
......
......@@ -98,6 +98,48 @@ public void ConfigureServices(IServiceCollection services)
#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
Mapper.Initialize(cfg => cfg.AddProfile<AutoMapperConfigs>());
......@@ -143,45 +185,6 @@ public void ConfigureServices(IServiceCollection services)
#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.AddHostedService<QueuedHostedService>();
......@@ -285,6 +288,8 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
//#endregion hangfire
app.UseAuthentication();
app.UseCors("SignalrCore");
app.UseSignalR(routes => routes.MapHub<AllotLogHub>("/performance/allotLogHub"));
......
......@@ -1435,10 +1435,11 @@
</summary>
<returns></returns>
</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>
<param name="userId"></param>
<param name="request"></param>
</member>
<member name="M:Performance.Api.Controllers.TemplateController.ReturnLog(Performance.EntityModels.log_dbug)">
......
......@@ -20,7 +20,7 @@ public enum Component
Progress = 1,
}
public enum ComponentType
public enum ComponentStatus
{
/// <summary>
/// 成功
......
......@@ -13,33 +13,33 @@ public MessageInfo()
}
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)
: this(allotId, title, message, Component.Notification, type)
public MessageInfo(int allotId, string title, string message, ComponentStatus status)
: this(allotId, title, message, Component.Notification, status)
{
}
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)
: this(Guid.NewGuid().ToString("N"), allotId, title, message, component, type)
public MessageInfo(int allotId, string title, string message, Component component, ComponentStatus status)
: 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;
AllotId = allotId;
Title = title;
Message = message;
Component = component;
Status = type;
Status = status;
}
}
......@@ -55,16 +55,16 @@ public class MessageInfo<TData> : IMessageInfo<TData>
public Component Component { get; set; }
[JsonIgnore]
public ComponentType Status { get; set; }
//[JsonIgnore]
public ComponentStatus Status { get; set; }
public string Type
{
get
{
return Status.ToString();
}
}
//public string Type
//{
// get
// {
// return Status.ToString();
// }
//}
public MessageInfo()
: this(default, string.Empty, default)
......@@ -72,33 +72,33 @@ public MessageInfo()
}
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)
: this(allotId, title, message, Component.Notification, type)
public MessageInfo(int allotId, string title, TData message, ComponentStatus status)
: this(allotId, title, message, Component.Notification, status)
{
}
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)
: this(Guid.NewGuid().ToString("N"), allotId, title, message, component, type)
public MessageInfo(int allotId, string title, TData message, Component component, ComponentStatus status)
: 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;
AllotId = allotId;
Title = title;
Message = message;
Component = component;
Status = type;
Status = status;
}
}
......@@ -132,11 +132,11 @@ public interface IMessageInfo<TData>
/// <summary>
/// 状态(完成、警告、错误、信息)
/// </summary>
ComponentType Status { get; set; }
ComponentStatus Status { get; set; }
/// <summary>
/// 状态文本值
/// </summary>
string Type { get; }
///// <summary>
///// 状态文本值
///// </summary>
//string Type { get; }
}
}
......@@ -116,7 +116,7 @@ private PerExcel Import(per_allot allot)
}
catch (Exception ex)
{
notificationsService.SendGenerateMessage(allot.ID, $"读取excel文件:{ex.Message}。", ComponentType.error);
notificationsService.SendGenerateMessage(allot.ID, $"读取excel文件:{ex.Message}。", ComponentStatus.error);
throw ex;
}
}
......
......@@ -431,11 +431,11 @@ public void Generate(per_allot allot, string mail)
notificationsService.SendGenerateMessage(allot.ID, $"正在生成报表数据:正在生成报表数据。");
var res = reportService.ImportData(allot);
var flag = reportService.UpdateData(allot);
notificationsService.SendGenerateMessage(allot.ID, $"绩效生成结束:绩效生成成功。", ComponentType.success);
notificationsService.SendGenerateMessage(allot.ID, $"绩效生成结束:绩效生成成功。", ComponentStatus.success);
}
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);
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
catch (Exception ex)
{
allot.IsExtracting = 3;
notificationsService.SendExtractMessage(allotId, $"提取失败:数据提取过程中发生异常。", ComponentType.error);
notificationsService.SendExtractMessage(allotId, $"提取失败:数据提取过程中发生异常。", ComponentStatus.error);
logger.LogError("提取数据中发生异常: " + ex.ToString());
}
finally
{
notificationsService.SendExtractProgress(allotId, 100, ComponentType.success);
notificationsService.SendExtractMessage(allotId, $"提取完成:绩效数据提取成功。", ComponentType.success);
notificationsService.SendExtractProgress(allotId, 100, ComponentStatus.success);
notificationsService.SendExtractMessage(allotId, $"提取完成:绩效数据提取成功。", ComponentStatus.success);
using (FileStream file = new FileStream(extractFilePath, FileMode.OpenOrCreate))
{
workbook.Write(file);
......
......@@ -40,9 +40,11 @@ PerforLogdsignalrRepository repository
/// <summary> 绩效提取 </summary>
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);
logger.LogInformation(JsonHelper.Serialize(data));
if (data == null || data.UserId == 0)
return;
......@@ -50,7 +52,7 @@ public void SendGenerateMessage(int allotId, string message, ComponentType type
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);
if (data == null || data.UserId == 0)
......@@ -62,28 +64,28 @@ public void SendExtractMessage(int allotId, string message, ComponentType type =
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);
if (data == null || data.UserId == 0)
return;
percentage = type == ComponentType.success ? 100
: (type != ComponentType.success && percentage >= 100) ? 99 : percentage;
percentage = type == ComponentStatus.success ? 100
: (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);
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();
if (cache.TryGetValue(key, out string connectionId) && !string.IsNullOrEmpty(connectionId))
{
string method = data.Component == Component.Notification ? "ReceiveMessage" : "ReceiveProgress";
SendMessageToClient(connectionId, data, method);
SendMessageToClient(connectionId, method, data);
}
}
......@@ -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
{
......
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