Selaa lähdekoodia

修复ApptaskDomainService.cs changeSession失败的问题

xfe 1 viikko sitten
vanhempi
commit
84f0f6f021

+ 4 - 10
src/Hotline.Application/Jobs/ApptaskJob.cs

@@ -33,15 +33,12 @@ namespace Hotline.Application.Jobs
             //Console.WriteLine($"执行ApptaskJob: {DateTime.Now}");
             var task = await _apptaskDomainService.GetWaitingTaskAsync(context.CancellationToken);
             if (task is null) return;
+            var httpContextAccessor = _serviceProvider.GetRequiredService<IHttpContextAccessor>();
+            httpContextAccessor.HttpContext ??= new DefaultHttpContext();
             ApptaskExecuteResult? result = null;
             switch (task.TaskType)
             {
                 case ETaskType.OrderDelay:
-                    var a = _serviceProvider.GetService<IHttpContextAccessor>();
-                    var b = a?.HttpContext;
-                    var ac = a?.GetHashCode();
-                    var bc = b?.GetHashCode();
-
                     var delayExecutor = _serviceProvider.GetService<IApptaskExecutor<OrderDelayReviewWithSessionRequest>>();
                     result = await _apptaskDomainService.ExecuteAsync(delayExecutor, task, context.CancellationToken);
                     break;
@@ -65,7 +62,7 @@ namespace Hotline.Application.Jobs
                     //todo check if task is all complete
                     //pub all complete
                     var isCompleted = await _apptaskDomainService.IsCompletedAsync(task.ApptaskId, context.CancellationToken);
-                    if (isCompleted) 
+                    if (isCompleted)
                         await _publisher.PublishAsync(new ApptaskCompletedNotify(task), PublishStrategy.Async, context.CancellationToken);
                 }
                 else
@@ -73,7 +70,6 @@ namespace Hotline.Application.Jobs
                     //todo pub single complete fail
                     await _publisher.PublishAsync(new ApptaskFailNotify(task), PublishStrategy.Async, context.CancellationToken);
                 }
-
             }
         }
 
@@ -82,7 +78,5 @@ namespace Hotline.Application.Jobs
         {
             GC.SuppressFinalize(this);
         }
-
-
     }
-}
+}

+ 56 - 19
src/Hotline/Authentications/SessionContextManager.cs

@@ -22,6 +22,8 @@ public interface ISessionContextManager
     /// 依据source创建对应Session
     /// </summary>
     void ChangeSessionContext(string source);
+
+    void ChangeSessionContext(ISessionContext sessionContext);
 }
 
 public class SessionContextManager : ISessionContextManager, IScopeDependency
@@ -49,22 +51,32 @@ public class SessionContextManager : ISessionContextManager, IScopeDependency
             .Includes(d => d.Roles)
             .FirstAsync(d => d.Id == userId, cancellation);
 
-        List<Claim> userClaims =
-        [
-            new(JwtClaimTypes.Subject, account.Id),
-            new(JwtClaimTypes.PhoneNumber, account.PhoneNo ?? string.Empty),
-            new(ClaimTypes.NameIdentifier, account.Id),
-            new(AppClaimTypes.UserDisplayName, account.Name),
-            new(AppClaimTypes.DepartmentId, account.User?.OrgId ?? string.Empty),
-            new(AppClaimTypes.DepartmentIsCenter, account.User?.Organization?.IsCenter.ToString() ?? string.Empty),
-            new(AppClaimTypes.DepartmentName, account.User?.Organization?.Name ?? string.Empty),
-            new(AppClaimTypes.DepartmentAreaCode, account.User?.Organization?.AreaCode ?? string.Empty),
-            new(AppClaimTypes.DepartmentAreaName, account.User?.Organization?.AreaName ?? string.Empty),
-            new(AppClaimTypes.DepartmentLevel, account.User?.Organization?.Level.ToString() ?? string.Empty),
-            new(AppClaimTypes.AreaId, account.User?.OrgId?.GetHigherOrgId() ?? string.Empty),
-        ];
-        userClaims.AddRange(account.Roles.Select(d => new Claim(JwtClaimTypes.Role, d.Name)));
-        httpContextAccessor.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
+        ChangeSession(account.Id, account.Name,
+            account.User?.OrgId, account.User?.Organization?.Name,
+            account.User?.Organization?.Level,
+            account.User?.Organization?.IsCenter,
+            account.PhoneNo,
+            account.User?.Organization?.AreaCode,
+            account.User?.Organization?.AreaName,
+            account.Roles.Select(d=>d.Name).ToList()
+        );
+        //
+        // List<Claim> userClaims =
+        // [
+        //     new(JwtClaimTypes.Subject, account.Id),
+        //     new(JwtClaimTypes.PhoneNumber, account.PhoneNo ?? string.Empty),
+        //     new(ClaimTypes.NameIdentifier, account.Id),
+        //     new(AppClaimTypes.UserDisplayName, account.Name),
+        //     new(AppClaimTypes.DepartmentId, account.User?.OrgId ?? string.Empty),
+        //     new(AppClaimTypes.DepartmentIsCenter, account.User?.Organization?.IsCenter.ToString() ?? string.Empty),
+        //     new(AppClaimTypes.DepartmentName, account.User?.Organization?.Name ?? string.Empty),
+        //     new(AppClaimTypes.DepartmentAreaCode, account.User?.Organization?.AreaCode ?? string.Empty),
+        //     new(AppClaimTypes.DepartmentAreaName, account.User?.Organization?.AreaName ?? string.Empty),
+        //     new(AppClaimTypes.DepartmentLevel, account.User?.Organization?.Level.ToString() ?? string.Empty),
+        //     new(AppClaimTypes.AreaId, account.User?.OrgId?.GetHigherOrgId() ?? string.Empty),
+        // ];
+        // userClaims.AddRange(account.Roles.Select(d => new Claim(JwtClaimTypes.Role, d.Name)));
+        // httpContextAccessor.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
     }
 
     /// <summary>
@@ -86,9 +98,27 @@ public class SessionContextManager : ISessionContextManager, IScopeDependency
         ChangeSession(config.UserId, config.UserName, config.OrgId, config.OrgName, config.OrgId.CalcOrgLevel());
     }
 
+    public void ChangeSessionContext(ISessionContext sessionContext)
+    {
+        ChangeSession(sessionContext.UserId, sessionContext.UserName,
+            sessionContext.OrgId, sessionContext.OrgName,
+            sessionContext.OrgLevel, sessionContext.OrgIsCenter,
+            sessionContext.Phone,
+            sessionContext.OrgAreaCode, sessionContext.OrgAreaName,
+            sessionContext.Roles.ToList());
+    }
+
     #region private
 
-    private void ChangeSession(string userId, string username, string orgId, string orgname, int orgLevel)
+    private void ChangeSession(
+        string userId, string username,
+        string orgId, string orgname,
+        int? orgLevel, 
+        bool? isCenter = null,
+        string? phoneNo = null,
+        string? orgAreaCode = null,
+        string? orgAreaName = null,
+        List<string>? roles = null)
     {
         var httpContextAccessor = _serviceProvider.GetRequiredService<IHttpContextAccessor>();
         if (httpContextAccessor.HttpContext == null)
@@ -99,12 +129,19 @@ public class SessionContextManager : ISessionContextManager, IScopeDependency
             new(JwtClaimTypes.Subject, userId),
             new(ClaimTypes.NameIdentifier, userId),
             new(AppClaimTypes.UserDisplayName, username),
+            new(JwtClaimTypes.PhoneNumber, phoneNo ?? string.Empty),
             new(AppClaimTypes.DepartmentId, orgId ?? string.Empty),
-            new(AppClaimTypes.DepartmentIsCenter, orgId?.IsCenter().ToString() ?? string.Empty),
             new(AppClaimTypes.DepartmentName, orgname ?? string.Empty),
-            new(AppClaimTypes.DepartmentLevel, orgLevel.ToString() ?? string.Empty),
+            new(AppClaimTypes.DepartmentIsCenter, isCenter.HasValue 
+                ? isCenter.Value.ToString() 
+                : (orgId?.IsCenter().ToString() ?? string.Empty)),
+            new(AppClaimTypes.DepartmentAreaCode, orgAreaCode ?? string.Empty),
+            new(AppClaimTypes.DepartmentAreaName, orgAreaName ?? string.Empty),
+            new(AppClaimTypes.DepartmentLevel, orgLevel?.ToString() ?? string.Empty),
             new(AppClaimTypes.AreaId, orgId?.GetHigherOrgId() ?? string.Empty),
         ];
+        if (roles != null && roles.Count > 0)
+            userClaims.AddRange(roles.Select(d => new Claim(JwtClaimTypes.Role, d)));
         httpContextAccessor.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
     }
 

+ 0 - 7
src/Hotline/Authentications/SessionContextProvider.cs

@@ -86,16 +86,9 @@ public class SessionContextProvider : ISessionContextProvider, IScopeDependency
 
     public void ChangeSession(string userId, string username, string orgId, string orgname, int orgLevel, string orgAreaCode, string orgAreaName, string[] roles)
     {
-        var a = _serviceProvider.GetService<IHttpContextAccessor>();
-        var b = a?.HttpContext;
-        var ac = a?.GetHashCode();
-        var bc = b?.GetHashCode();
-
         var httpContext = _serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
         httpContext ??= new DefaultHttpContext();
 
-        var bc1 = httpContext?.GetHashCode();
-
         List<Claim> userClaims =
         [
             new(JwtClaimTypes.Subject, userId),

+ 2 - 26
src/Hotline/BatchTask/ApptaskDomainService.cs

@@ -17,9 +17,6 @@ public class ApptaskDomainService : IApptaskDomainService, IScopeDependency
 {
     private readonly IRepository<Apptask> _apptaskRepository;
     private readonly IRepository<ApptaskItem> _apptaskItemRepository;
-    private readonly ISessionContextProvider _sessionContextProvider;
-    private readonly IHttpContextAccessor _httpContextAccessor;
-    private readonly ISessionContext _sessionContext;
     private readonly ISessionContextManager _sessionContextManager;
     private readonly IMapper _mapper;
     private readonly ILogger<ApptaskDomainService> _logger;
@@ -27,23 +24,15 @@ public class ApptaskDomainService : IApptaskDomainService, IScopeDependency
     public ApptaskDomainService(
         IRepository<Apptask> apptaskRepository,
         IRepository<ApptaskItem> apptaskItemRepository,
-        ISessionContextProvider sessionContextProvider,
-        IHttpContextAccessor httpContextAccessor,
-        ISessionContext sessionContext,
         ISessionContextManager sessionContextManager,
         IMapper mapper,
         ILogger<ApptaskDomainService> logger)
     {
         _apptaskRepository = apptaskRepository;
         _apptaskItemRepository = apptaskItemRepository;
-        _sessionContextProvider = sessionContextProvider;
-        _httpContextAccessor = httpContextAccessor;
-        _sessionContext = sessionContext;
         _sessionContextManager = sessionContextManager;
         _mapper = mapper;
         _logger = logger;
-
-        _httpContextAccessor.HttpContext ??= new DefaultHttpContext();
     }
 
     /// <summary>
@@ -189,21 +178,8 @@ public class ApptaskDomainService : IApptaskDomainService, IScopeDependency
             if (request is null)
                 throw new UserFriendlyException($"任务参数反序列化失败, taskItemId: {apptaskItem.Id}");
 
-            var a = _httpContextAccessor;
-            var b = a?.HttpContext;
-            var ac = a?.GetHashCode();
-            var bc = b?.GetHashCode();
-            var cc = _sessionContext?.GetHashCode();
-
-            var dc = _sessionContext.UserId;
-            _sessionContextProvider.ChangeSession(request.SessionContext);
-            //await _sessionContextManager.ChangeSessionContextByUserIdAsync(request.SessionContext.UserId, cancellation);
-            var dc1 = _sessionContext.UserId;
-
-            var ac1 = a?.GetHashCode();
-            var bc1 = b?.GetHashCode();
-            var cc1 = _sessionContext?.GetHashCode();
-
+            _sessionContextManager.ChangeSessionContext(request.SessionContext);
+            
             //if (request is IApptaskRequest reqWithSession)
             //    _sessionContextProvider.ChangeSession(reqWithSession.SessionContext);
             var result = await executor.ExecuteAsync(request, cancellation);

+ 5 - 0
test/Hotline.Tests/Controller/TestSessionContextManager.cs

@@ -85,6 +85,11 @@ public class TestSessionContextManager : ISessionContextManager, IScopeDependenc
         ChangeSession(config.UserId, config.UserName, config.OrgId, config.OrgName, config.OrgId.CalcOrgLevel());
     }
 
+    public void ChangeSessionContext(ISessionContext sessionContext)
+    {
+        throw new NotImplementedException();
+    }
+
     #region private
 
     private void ChangeSession(string userId, string username, string orgId, string orgname, int orgLevel)