You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
3.2 KiB
C#

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<User> 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<User>(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<IBaseRepository<User>>();
user = await resp.Db.Queryable<User>()
.LeftJoin<UserBaseInfo>((u, b) => u.GID == b.USERID)
.Select<User>((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);
}
}
}