Parcourir la source

团组操作新增 返回Id

leiy il y a 1 an
Parent
commit
c53d4e92fe

+ 16 - 0
OASystem/OASystem.Api/Controllers/AuthController.cs

@@ -750,5 +750,21 @@ namespace OASystem.API.Controllers
             await hubContext.Clients.All.SendAll(date);
 
         }
+
+
+        /// <summary>
+        /// 测试 
+        /// 发送指定消息给指定的用户
+        /// </summary>
+        /// <param name="date"></param>
+        /// <param name="hubContext"></param>
+        /// <returns></returns>
+        [HttpPost("SendMessageByUser")]
+        public async Task<IActionResult> SendMessageByUser(string username,string date, [FromServices] IHubContext<ChatHub, IChatClient> hubContext)
+        {
+            await hubContext.Clients.User(username).SendMessageByUser(date);
+
+            return Ok("Send Successful!");
+        }
     }
 }

+ 3 - 4
OASystem/OASystem.Api/Controllers/GroupsController.cs

@@ -502,16 +502,15 @@ namespace OASystem.API.Controllers
                     return Ok(JsonView(false, groupData.Msg));
                 }
 
+                int diId = 0;
                 //添加时 默认加入团组汇率
                 if (dto.Status == 1)
                 {
-                    int diId = groupData.Data;
-
+                    diId = groupData.Data;
                     GeneralMethod.PostGroupRateAddInit(dto.UserId, diId);
                 }
 
-
-                return Ok(JsonView(true));
+                return Ok(JsonView(true,"操作成功!", diId));
             }
             catch (Exception ex)
             {

+ 2 - 0
OASystem/OASystem.Api/OAMethodLib/SignalR/HubClients/IChatClient.cs

@@ -3,5 +3,7 @@
     public interface IChatClient
     {
         Task SendAll(object message);
+
+        Task SendMessageByUser(object message);
     }
 }

+ 5 - 0
OASystem/OASystem.Api/OAMethodLib/SignalR/HubService/CommonService.cs

@@ -6,5 +6,10 @@
         {
             return $"Hello {new Random().Next(0, 100)} {data} ";
         }
+
+        internal object SendMessageByUser(string data)
+        {
+            return $"Hello {new Random().Next(0, 100)} {data} ";
+        }
     }
 }

+ 54 - 4
OASystem/OASystem.Api/OAMethodLib/SignalR/Hubs/ChatHub.cs

@@ -1,19 +1,49 @@
 using Microsoft.AspNetCore.SignalR;
 using OASystem.API.OAMethodLib.Hub.HubClients;
+using OASystem.API.OAMethodLib.SignalR.Hubs;
 using OASystem.API.OAMethodLib.SignalR.HubService;
+using System.DirectoryServices.Protocols;
+using System.Text.RegularExpressions;
+using static OASystem.API.OAMethodLib.Hub.Hubs.ChatHub;
+using static OASystem.API.OAMethodLib.JWTHelper;
 
 namespace OASystem.API.OAMethodLib.Hub.Hubs
 {
-    [Authorize]
     public class ChatHub : Hub<IChatClient>
     {
-        ILogger<ChatHub> _logger;
-        public ChatHub(ILogger<ChatHub> logger, CommonService common)
+        private readonly ILogger<ChatHub> _logger;
+        private readonly IHttpContextAccessor _accessor;
+        private readonly CommonService _common;
+
+            /// <summary>
+           /// 已登录的用户信息
+           /// </summary>
+           public static List<UserModel> OnlineUser { get; set; } = new List<UserModel>();
+
+        public ChatHub(ILogger<ChatHub> logger, CommonService common, IHttpContextAccessor accessor)
         {
             _logger = logger;
             _common = common;
+            _accessor = accessor;
         }
-        readonly CommonService _common;
+
+        /// <summary>
+        /// SignalR登录验证
+        /// </summary>
+        public async Task SignalRLogin(int userId)
+        {
+            string connid = Context.ConnectionId;
+            bool status = false;
+            if (!OnlineUser.Exists(u => u.ConnectionId == connid))
+            {
+                status = true;
+                OnlineUser.Add( new UserModel() { UserId = userId,ConnectionId = connid,GroupName = "FMGJ-OASystem" });
+
+            }
+            //给当前连接返回消息
+            await Clients.Client(connid).SendAsync("SignalRLoginResponse", status);
+        }
+
         /// <summary>
         /// 客户端连接服务端
         /// </summary>
@@ -22,8 +52,15 @@ namespace OASystem.API.OAMethodLib.Hub.Hubs
         {
             var id = Context.ConnectionId;
             _logger.LogInformation($"Client ConnectionId=> [[{id}]] Already Connection Server!");
+
+            //验证Token
+            //var token = _accessor.HttpContext.Request.Query["access_token"];
+            //var user = JwtHelper.SerializeJwt(token);
+
+
             return base.OnConnectedAsync();
         }
+
         /// <summary>
         /// 客户端断开连接
         /// </summary>
@@ -35,6 +72,9 @@ namespace OASystem.API.OAMethodLib.Hub.Hubs
             _logger.LogInformation($"Client ConnectionId=> [[{id}]] Already Close Connection Server!");
             return base.OnDisconnectedAsync(exception);
         }
+
+       
+
         /**
          * 测试 
          * */
@@ -47,5 +87,15 @@ namespace OASystem.API.OAMethodLib.Hub.Hubs
             Console.WriteLine("Have one Data!");
             await Clients.All.SendAll(_common.SendAll(data));
         }
+
+
+        public class UserModel
+        {
+            public int UserId { get; set; }
+
+            public string ConnectionId { get; set; }
+
+            public string GroupName { get; set; }
+        }
     }
 }

+ 58 - 0
OASystem/OASystem.Api/OAMethodLib/SignalR/Hubs/GroupStore.cs

@@ -0,0 +1,58 @@
+namespace OASystem.API.OAMethodLib.SignalR.Hubs
+{
+    /// <summary>
+    /// 分组
+    /// </summary>
+    public static class GroupStore
+    {
+        public static Dictionary<string, List<string>> Groups = new Dictionary<string, List<string>>();
+        public static void Add(string groupname, string Id)
+        {
+            if (Groups.ContainsKey(groupname))
+            {
+                if (Groups.TryGetValue(groupname, out var values))
+                {
+                    if (values.Contains(Id))
+                        return;
+                    values.Add(Id);
+                }
+                else
+                {
+                    throw new Exception("Add group Error");
+                }
+            }
+            else
+            {
+                var newvalues = new List<string>() { Id };
+                Groups.Add(groupname, newvalues);
+            }
+        }
+        public static void Remove(string groupname, string Id)
+        {
+            if (Groups.ContainsKey(groupname))
+            {
+                if (Groups.TryGetValue(groupname, out var values))
+                {
+                    if (!values.Contains(Id))
+                        return;
+                    values.Remove(Id);
+                    if (!(values.Count > 0))
+                        Groups.Remove(groupname);
+                }
+                else
+                {
+                    throw new Exception("Remove group Error");
+                }
+            }
+        }
+        /// <summary>
+        /// 连接断开时删除
+        /// </summary>
+        /// <param name="Id"></param>
+        public static void UnConnection(string Id)
+        {
+            Groups.Where(x => x.Value.Contains(Id)).AsParallel().ForAll(x => x.Value.Remove(Id));
+        }
+
+    }
+}

+ 20 - 20
OASystem/OASystem.Api/Program.cs

@@ -53,8 +53,8 @@ builder.Services.AddControllers()
         //options.JsonSerializerOptions.Converters.Add(new JsonConverterDecimal(0.0000M));
     });
 
-// 添加授权服务
-builder.Services.AddMyJWTBearerAuth();
+//// 添加授权服务
+//builder.Services.AddMyJWTBearerAuth();
 
 #region Cors
 builder.Services.AddCors(policy =>
@@ -211,23 +211,23 @@ if (AppSettingsHelper.Get("UseSwagger").ToBool())
 
 #region 添加校验
 
-//builder.Services.AddTransient<OASystemAuthentication>();
-//builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
-//    .AddJwtBearer(options =>
-//        {
-//            options.TokenValidationParameters = new TokenValidationParameters
-//            {
-//                ValidateIssuer = true,
-//                ValidateAudience = true,
-//                ValidateLifetime = true,
-//                ValidateIssuerSigningKey = true,
-//                ValidAudience = "OASystem.com",
-//                ValidIssuer = "OASystem.com",
-//                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
-//                ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
-//                RequireExpirationTime = true,
-//            };
-//        });
+builder.Services.AddTransient<OASystemAuthentication>();
+builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
+    .AddJwtBearer(options =>
+        {
+            options.TokenValidationParameters = new TokenValidationParameters
+            {
+                ValidateIssuer = true,
+                ValidateAudience = true,
+                ValidateLifetime = true,
+                ValidateIssuerSigningKey = true,
+                ValidAudience = "OASystem.com",
+                ValidIssuer = "OASystem.com",
+                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
+                ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
+                RequireExpirationTime = true,
+            };
+        });
 #endregion
 
 #region 初始化日志
@@ -322,7 +322,7 @@ app.UseAuthentication(); // 
 app.UseAuthorization();  // 授权
 
 // 授权路径
-app.MapGet("generatetoken", c => c.Response.WriteAsync(JWTBearer.GenerateToken(c)));
+//app.MapGet("generatetoken", c => c.Response.WriteAsync(JWTBearer.GenerateToken(c)));
 
 #region 启用swaggerUI
 if (AppSettingsHelper.Get("UseSwagger").ToBool())

+ 1 - 0
OASystem/OASystem.Domain/Entities/Groups/Grp_DelegationInfo.cs

@@ -214,6 +214,7 @@ namespace OASystem.Domain.Entities.Groups
         /// </summary>
         [SugarColumn(IsNullable = true, ColumnDataType = "varchar(50)")]
         public string ZZSCSPWH { get; set; }
+
         #region 新增团组op提成等级
         /// <summary>
         /// Op提成等级