123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203 |
- // <author></author>
- // <date></date>
- // <description></description>
- using ERP.Framework.Cache;
- using ERP.Framework.Config;
- using ERP.Framework.Constants;
- using ERP.Framework.Emum;
- using ERP.Framework.Exceptions;
- using ERP.Framework.Resource;
- using ERP.Framework.Security.Core;
- using ERP.Framework.Utils;
- using Microsoft.AspNetCore.Http;
- using Newtonsoft.Json;
- namespace ERP.Framework.Security
- {
- public class LoginHelper
- {
- /// <summary>
- /// 根据设备进行登录
- /// </summary>
- /// <param name="userInfo"></param>
- /// <param name="securityConfig"></param>
- /// <param name="device"></param>
- /// <param name="deviceKey"></param>
- /// <returns></returns>
- public static string LoginByDevice(
- LoginUser userInfo
- , SecurityConfig securityConfig
- , DeviceEnum device)
- {
- string tokenId;
- var tokenList = GetTokenList(userInfo.UserId);
- var result = TokenHelper.CreateToken(
- securityConfig.JwtSecurityKey
- , userInfo.UserId
- , userInfo.UserName
- , securityConfig.TimeOut
- , out tokenId);
- //Todo 不允许并发登录处理
- HandleExceedToken(tokenList, securityConfig);
- tokenList.Add(new TokenSign
- {
- TokenId = tokenId,
- Device = device
- });
- SetTokenList(userInfo.UserId, tokenList);
- SetLastActivity(tokenId, securityConfig.ActivityTimeOut, securityConfig.TimeOut);
- SetUserInfo(tokenId, userInfo, securityConfig.TimeOut);
- return result;
- }
- /// <summary>
- /// 获取当前用户
- /// </summary>
- /// <returns></returns>
- /// <exception cref="Exception"></exception>
- public static LoginUser GetLoginUser()
- {
- var httpContextAccessor = new HttpContextAccessor();
- var httpContext = httpContextAccessor.HttpContext;
- var loginUser = httpContext!.Items["LoginUser"] as LoginUser;
- if (loginUser != null)
- {
- return loginUser;
- }
- var tokenId = httpContext!.Items["TokenId"] as string;
- var redisData = RedisHelper.Get(AuthConstant.USER_INFO + tokenId);
- var result = JsonConvert.DeserializeObject<LoginUser>(redisData);
- if (result != null)
- {
- httpContext.Items["LoginUser"] = result;
- return result;
- }
- else
- {
- throw new CodeException(message: FrameworkI18N.NoUser, code: ErrorCode.NO_USER);
- }
- }
- /// <summary>
- /// 获取当前用户Id
- /// </summary>
- /// <returns></returns>
- public static long GetUserId()
- {
- var httpContextAccessor = new HttpContextAccessor();
- var httpContext = httpContextAccessor.HttpContext;
- var result = httpContext!.Items["UserId"] as string;
- return result!.ToLong()!.Value;
- }
- public static bool IsAdmin()
- {
- var httpContextAccessor = new HttpContextAccessor();
- var httpContext = httpContextAccessor.HttpContext;
- var userName = httpContext!.Items["UserName"] as string;
- return userName == FrameworkConstant.ADMIN;
- }
- /// <summary>
- /// 获取TokenList缓存
- /// </summary>
- /// <param name="userId"></param>
- /// <returns></returns>
- private static List<TokenSign> GetTokenList(long userId)
- {
- var tokenListData = RedisHelper.Get(AuthConstant.TOKEN_LIST + CryptoUtil.MD5(userId.ToString()));
- if (!tokenListData.IsNullOrEmpty())
- {
- var data = JsonConvert.DeserializeObject<List<TokenSign>>(tokenListData)!;
- return data;
- }
- return new List<TokenSign>();
- }
- /// <summary>
- /// 创建Last Activity
- /// </summary>
- /// <param name="tokenId"></param>
- /// <param name="activityTimeOut"></param>
- private static void SetLastActivity(string tokenId, int activityTimeOut, int tokenTimeOut)
- {
- var key = AuthConstant.LAST_ACTIVITY + tokenId;
- var val = DateTime.Now.AddMinutes(activityTimeOut).ToDateLongString();
- RedisHelper.SaveExpire(key, val, tokenTimeOut);
- }
- /// <summary>
- /// 处理超出的会话
- /// </summary>
- /// <param name="list"></param>
- /// <param name="maxCount"></param>
- private static void HandleExceedToken(List<TokenSign> list, SecurityConfig config)
- {
- if (list.Count > config.MaxLoginCount)
- {
- var num = list.Count - config.MaxLoginCount;
- var substituteList = list.Take(num).ToList();
- foreach (var item in substituteList)
- {
- SubstitutedUser(item.TokenId, config.TimeOut);
- }
- list.RemoveRange(0, num);
- }
- }
- /// <summary>
- /// 顶下用户
- /// </summary>
- /// <param name="tokenId"></param>
- /// <param name="activityTimeOut"></param>
- private static void SubstitutedUser(string tokenId, int tokenTimeOut)
- {
- var key = AuthConstant.LAST_ACTIVITY + tokenId;
- RedisHelper.SaveExpire(key, AuthConstant.SUBSTITUTED, tokenTimeOut);
- }
- /// <summary>
- /// 创建Token List缓存
- /// </summary>
- /// <param name="tokenId"></param>
- /// <param name="activityTimeOut"></param>
- private static void SetTokenList(long userId, List<TokenSign> list)
- {
- var key = AuthConstant.TOKEN_LIST + CryptoUtil.MD5(userId.ToString());
- var val = JsonConvert.SerializeObject(list);
- RedisHelper.Save(key, val);
- }
- /// <summary>
- /// 创建UserInfo
- /// </summary>
- /// <param name="tokenId"></param>
- /// <param name="activityTimeOut"></param>
- private static void SetUserInfo(string tokenId, LoginUser loginUser, int tokenTimeOut)
- {
- var key = AuthConstant.USER_INFO + tokenId;
- var val = JsonConvert.SerializeObject(loginUser);
- RedisHelper.SaveExpire(key, val, tokenTimeOut);
- }
- }
- }
|