using EntrustSettle.Common; using EntrustSettle.Common.Caches; using EntrustSettle.Common.Const; using EntrustSettle.IRepository.Base; using EntrustSettle.Model.Models.DJY; using Microsoft.AspNetCore.Http; using System; using System.Security.Claims; using System.Threading.Tasks; namespace EntrustSettle.Extensions.Middlewares { public class SetAppUserMiddleware { private readonly RequestDelegate _next; private readonly ICaching _caching; public SetAppUserMiddleware(RequestDelegate next, IBaseRepository repository, ICaching caching) { _next = next; _caching = caching; } public async Task Invoke(HttpContext context) { var userId = App.User?.ID; if (!string.IsNullOrEmpty(userId)) { var user = _caching.Get(CacheConst.KeyUserInfoCache + userId); if (user != null) { ClaimsIdentity identity = new ClaimsIdentity("AuthenticationTypes.Federation"); identity.AddClaim(new Claim(type: ClaimConst.LOGIN_ID, value: user.GID)); identity.AddClaim(new Claim(type: ClaimConst.LOGIN_NAME, value: user.SHOWNAME)); identity.AddClaim(new Claim(type: ClaimConst.LOGIN_COMPANYID, value: user.CompId)); identity.AddClaim(new Claim(type: ClaimConst.LOGIN_COMPANYNAME, value: user.COMNAME)); identity.AddClaim(new Claim(type: ClaimConst.LOGIN_MOBILE, value: user.Mobile)); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity); context.User = claimsPrincipal; } else { var resp = App.GetService>(); user = await resp.Db.Queryable() .LeftJoin((u, b) => u.GID == b.USERID) .Select((u, b) => u, true) .FirstAsync(u => u.GID == App.User.ID && !u.IsLeave); if (user != null) { _caching.Set(CacheConst.KeyUserInfoCache + userId, user, TimeSpan.FromMinutes(AppSettings.app("Startup", "UserInfoCacheTime").ObjToInt())); ClaimsIdentity identity = new ClaimsIdentity("AuthenticationTypes.Federation"); identity.AddClaim(new Claim(type: ClaimConst.LOGIN_ID, value: user.GID)); identity.AddClaim(new Claim(type: ClaimConst.LOGIN_NAME, value: user.SHOWNAME)); identity.AddClaim(new Claim(type: ClaimConst.LOGIN_COMPANYID, value: user.CompId)); identity.AddClaim(new Claim(type: ClaimConst.LOGIN_COMPANYNAME, value: user.COMNAME)); identity.AddClaim(new Claim(type: ClaimConst.LOGIN_MOBILE, value: user.Mobile)); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity); context.User = claimsPrincipal; } } } await _next(context); } } }