Authentication

using System;
using System.Web;
using LXYD.WebGame.Util.FeatureHelpers;
using System.Collections.Generic;
using LXYD.WebGame.Util.EnumHelpers;
using LXYD.WebGame.Util.MiscHelpers;
using System.Linq;
using LXYD.WebGame.BLL.WEBCommon;
using System.Threading.Tasks;
using LXYD.WebGame.Common.Misc;
using LXYD.WebGame.Model.Entity.VR;
using LXYD.WebGame.Common.Misc.ExtensionsFunc;
using Newtonsoft.Json;
using LXYD.WebGame.Common.Enums;
using LXYD.WebGame.Common.Entity.ThirdPartyGame;
using LXYD.WebGame.Common.Enums.ThirdPartyGame;

namespace LXYD.WebGame.Security.Common
{
public class Authentication
{
private static int RedisTimeOut = 6;
private static TimeSpan RunTimeOut = CacheTimeOut.ThirtySecond;
private const string HighPassword = “HIGHPASSWORD”;
///
/// 登录存储客户端的Cookie名称
///
private const string LoginToken = “LoginSessionID”;

    private static string GetOnlineUserKey(int compnayId, string homeView = "")
    {
        //LogsManager.Info($"{CacheKeys.CompanyOnlineUser}_{compnayId}_{homeView}_{DateTime.Now:yyyyMMdd}");
        return $"{CacheKeys.CompanyOnlineUser}_{compnayId}_{homeView}_{DateTime.Now:yyyyMMdd}";
    }

    private static string GetGameOnlineUserKey(int companyId, int gameId, string homeView)
    {
        return $"{CacheKeys.CompanyGameOnlineUSer}_{companyId}_{homeView}_{gameId}";
    }

    private static string GetContextKey(object userId)
    {
        return $"{FeatureHelpers.WebSiteGroupID}_LoginContext_{userId}";
    }
    public static void AutoCheckStatus()
    {
        #region <自动检查踢掉的用户>
        try
        {
            var hset = CacheHelper.GetAllItemsFromSet(CacheKeys.KickAccountList);
            if (hset != null && hset.Any())
            {
                List<string> removeKeys = new List<string>();
                foreach (var userId in hset)
                {
                    if (!string.IsNullOrWhiteSpace(userId))
                    {
                        KickAccount(int.Parse(userId), false);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.Error("自动检查踢掉的用户异常");
        }
        #endregion
    }

    #region <登录>
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="context"></param>
    public static bool Login(Context context, bool isIgnoreValid = false)
    {
        try
        {
            string listId = GetContextKey(context.Id);
            var CacheContext = CacheHelper.Get<Context>(listId);
            if (CacheContext != null && isIgnoreValid == false)
            {
                var configRows = CompanyConfigUtil.GetCompanySysConfig(context.CompanyId);
                bool IsValidateUniqueLogin = configRows.GetConfigValue(CompanyConfigKeys.IsValidateUniqueLogin, true);
                if (IsValidateUniqueLogin)
                {
                    CacheHelper.RemoveAll(CacheContext.LoginSessionID, listId);
                }
            }
            context.LoginStatus = context.Status;
            context.GuidKey = GuidUtil.GuidKey;
            string url = SkinManager.Url.Replace("//www.", "").Replace("//WWW.", "");
            context.Token = EncryptionHelpers.Md5Encryption(context.GuidKey, url);
            string loginSessionID = EncryptionHelpers.Md5Encryption(context.GuidKey, context.Id.ToString(), SessionRedis.SessionID);
            context.LoginSessionID = $"{LoginToken}_{loginSessionID}";
            CookieHelpers.Set(LoginToken, loginSessionID);
            AddSessionID(context.LoginSessionID, context);
            var hset = CacheHelper.GetAllItemsFromSet(CacheKeys.KickAccountList);
            if (hset != null && hset.Any() && hset.Contains(context.Id.ToString()))
            {
                CacheHelper.RemoveItemFromSet(CacheKeys.KickAccountList, context.Id.ToString());
            }

            LogsManager.Debug($"用户登录成功, 当前Session: {CurrentSessionID}, loginSessionId: {context.LoginSessionID}, 登录账号: {context.UserName}");
            return true;
        }
        catch (Exception ex)
        {
            ex.Error(string.Format("用户登录写入COOKIE异常"));
            return false;
        }
    }
    #endregion

    public static bool Approved
    {
        get
        {
            return IsAuthenticated();
        }
    }

    /// <summary>
    /// 登出
    /// </summary>
    /// <param name="isSelf"></param>
    public static void Logout(bool isSelf = false)
    {
        try
        {
            int userID = CacheContext.Id;
            if (userID > 0)
            {
                //三方游戏登出
                ThirdPartyGamLoginOut();
                var sessionId = CurrentSessionID;
                LogsManager.Debug($"自主登出:用户[{userID}]自主登出,CurrentSessionID:{sessionId}");
                string listId = GetContextKey(userID);

                var setId = GetOnlineUserKey(CacheContext.CompanyId, HomeView);
                RemoveSessionID(sessionId, listId, setId, userID, isSelf);
            }
            HttpContext.Current.Session.Remove(HighPassword);

        }
        catch (Exception ex)
        {
            ex.Error("Logout异常");
        }
        string[] cookieNames = new string[] { LoginToken, "LastRequestTime" };
        foreach (string cookieName in cookieNames)
        {
            CookieHelpers.Remove(cookieName);
        }
    }

    /// <summary>
    /// 第三方游戏登出
    /// </summary>
    public static void ThirdPartyGamLoginOut()
    {
        var userId = Id;
        var companyId = CompanyID;
        var homeView = HomeView;
        //后台登出不调用三方登出
        if (userId == companyId) return;
        ThirdPartyGamLoginOut(userId, companyId, homeView);
    }


    /// <summary>
    /// 第三方游戏登录
    /// </summary>
    /// <param name="accountId">用户编号</param>
    /// <param name="companyId">公司编号</param>
    /// <param name="homeView">公司编号</param>
    public static void ThirdPartyGamLoginOut(int accountId, int companyId, string homeView)
    {
        #region VR登出
        Task.Factory.StartNew(() =>
        {
            try
            {

                #region 登出VR游戏
                //验证是否开通VR游戏
                var isOpenVR = CompanyConfigUtil.GetCompanySysConfigByKey(companyId, CompanyConfigKeys.IsOpenVRGame, "False").Value<bool>();
                if (isOpenVR)
                {
                    dynamic VRConfig = ThirdPartyGameConfig.VRConfigV2(companyId, homeView);

                    //验证游戏配置
                    if (VRConfig != null)
                    {
                        var userName = accountId.ConverToPlayerName();
                        var playerNameObj = new
                        {
                            playerName = userName
                        };
                        string versionNo = VRConfig.VersionNo;//版本号
                        string merchantId = VRConfig.MerchantId;//商户号
                        string secretKey = VRConfig.SecretKey;//密钥
                        string loginOutUrl = VRConfig.LoginOutUrl;//登出地址
                        var para = $"version={versionNo}&id={merchantId}&data={HttpUtility.UrlEncode(EncryptUtil.Encrypt(JsonConvert.SerializeObject(playerNameObj), secretKey))}";
                        var resultMsg = WebApiClient.DoPost(loginOutUrl, para);
                        var info = EncryptUtil.Decrypt(resultMsg, secretKey);
                        var code = JsonConvert.DeserializeObject<VRMsgResult>(info).errorCode;
                        if (code == 0)
                        {
                            LogsManager.Debug($"VR用户登出,用户编号:{accountId}");
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                ex.Error("[VR用户登出异常]");
            }
        });
        #endregion

        #region CQ9登出
        Task.Factory.StartNew(() =>
        {
            try
            {
                #region 登出电子游戏-CQ9
                var isExist = CommonClass.AccountService.CheckThirdPartyGameAccountExists(ThirdPartyGameType.CQ9, accountId);
                //先判断该用户是否有玩游戏,再判断是否需要登出
                if (!isExist) return;
                var game = CommonClass.AccountService.GetUserGameEntity(accountId, false, true, homeView).Find(x => x.FGameType == (int)SystemGameType.Electronic && x.FAbbreviation.ToUpper().Contains("CQ9") && x.FGroupID == 3);
                if (game.FIsEnabled)
                {
                    var CQ9Config = ThirdPartyGameConfig.Cq9ConfigV2(companyId, homeView);
                    //验证游戏配置
                    if (CQ9Config != null)
                    {
                        var playerName = accountId.ConverToPlayerName();
                        var para = $"account={playerName}";
                        //string rstInfo = WebApiClient.DoPost(CQ9Config.loginout.ToString(), para, CQ9Config.token.ToString());
                        Tuple<bool, string> rstInfo = WebApiClient.Https(CQ9Config.loginout.ToString(), para, CQ9Config.token.ToString());
                        var result = JsonConvert.DeserializeObject<CQ9LogoutResult>(rstInfo.Item2);
                        if (result.status.code == "0")
                        {
                            LogsManager.Debug($"[电子游戏CQ9]用户登出成功,用户编号:{accountId}");
                        }
                        else
                        {
                            LogsManager.Error($"[电子游戏CQ9]用户登出失败,用户编号:{accountId},Code:{result.status.code},Message:{result.status.message}");
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                ex.Error("[电子游戏CQ9]用户登出异常");
            }
        });
        #endregion

        #region 欧必登出
        List<string> keys = new List<string>();
        string cacheKey = string.Format(CacheKeys.ThirdPartyGameOBTYCookieKey, CompanyID, HomeView, Id);
        string cookieResult = CacheHelper.Get(cacheKey);
        if (!string.IsNullOrEmpty(cookieResult))
        {
            dynamic dto = cookieResult.ToObject<dynamic>();

            var cok = HttpContext.Current.Request.Cookies[dto.cookieName.ToString()];
            if (cok != null)
            {
                cok.Path = "/";
                cok.Value = "";
                cok.Domain = dto.domain.ToString();
                cok.Expires = DateTime.Now.AddMonths(-1);
                HttpContext.Current.Response.AppendCookie(cok);
                keys.Add(cacheKey);
            }
        }

        #endregion

        #region BooonGO登出
        string booonGoKey = string.Format(CacheKeys.BooonGoGameAccountKey, Id, CompanyID);
        string BNGToken = CacheHelper.Get(booonGoKey);
        if (!string.IsNullOrEmpty(BNGToken))
        {
            keys.Add(string.Format(CacheKeys.BooonGoGameUserKey, BNGToken));
            keys.Add(booonGoKey);
        }
        CacheHelper.RemoveAll(keys);
        #endregion

    }

    /// <summary>
    /// 登出
    /// </summary>
    /// <param name="accountID"></param>
    public static void KickAccount(int accountID, bool isAdd = true)
    {
        if (isAdd)
            CacheHelper.AddItemToSet(CacheKeys.KickAccountList, accountID.ToString(), 1);
        bool flag = false;
        IEnumerable<string> keys = CacheUtil.SearchKeys($"{LoginToken}_*");
        if (keys != null)
        {
            foreach (var sessionId in keys)
            {
                Context context = CacheUtil.Get<Context>(sessionId);
                if (context != null)
                {
                    if (context.Id == accountID)
                    {
                        string listId = GetContextKey(context.Id);
                        var setId = GetOnlineUserKey(context.CompanyId, context.HomeView);
                        RemoveSessionID(sessionId, listId, setId, context.Id);
                        flag = true;
                        break;
                    }
                }
            }
        }
        if (flag)
        {
            CacheHelper.RemoveItemFromSet(CacheKeys.KickAccountList, accountID.ToString());
            LogsManager.Debug(string.Format("后台踢出:用户[{0}]已被后台管理者踢出系统,自动登出", accountID));
        }
    }

    #region <当前登录用户对象>
    /// <summary>
    /// 当前登录用户对象
    /// </summary>
    internal static Context CacheContext
    {
        get
        {
            return GetCurrentContext();
        }
    }

    private static Context GetCurrentContext()
    {
        string loginSessionID = CurrentSessionID;
        Context context = new Context();
        try
        {
            if (!string.IsNullOrWhiteSpace(loginSessionID))
            {
                context = CacheUtil.Get<Context>(loginSessionID);
                if (context == null)
                {
                    string listId = CacheHelper.Get<string>(loginSessionID);
                    if (!string.IsNullOrWhiteSpace(listId))
                    {
                        context = CacheHelper.Get<Context>(listId);
                        if (context == null)
                        {
                            RemoveSessionID(loginSessionID, listId);
                            LogsManager.Error(string.Format("Redis缓存数据为空,key:{0}", listId));
                        }
                        else
                        {
                            context.LoginSessionID = loginSessionID;
                            AddSessionID(loginSessionID, context);
                        }
                    }
                    else
                    {
                        RemoveSessionID(loginSessionID, listId);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.Error("获取用户缓存信息异常");
        }
        if (context == null)
        {
            context = new Context();
        }
        return context;
    }
    #endregion
    private static void RemoveSessionID(string loginSessionID, string listId, string setId = null, int userId = 0, bool isSelf = false)
    {
        if (!string.IsNullOrWhiteSpace(loginSessionID))
        {
            CacheHelper.Remove(loginSessionID);
            CacheUtil.Remove(loginSessionID);
        }
        if (!string.IsNullOrWhiteSpace(listId) && !isSelf)
        {
            CacheHelper.Remove(listId);
            CacheUtil.Remove(listId);
        }

        if (!string.IsNullOrWhiteSpace(setId))
        {
            //修改时间, 不移除, 为了日访问量统计
            CacheHelper.AddItemToSortedSet(setId, userId.ToString(), TimeStamp.DateTimeToUnix(DateTime.Now.AddMinutes(-10)));
        }
    }

    public static Context GetLoginUesr(string loginSessionID)
    {
        loginSessionID = $"{LoginToken}_{loginSessionID}";
        var listId = CacheHelper.Get<string>(loginSessionID);
        if (string.IsNullOrWhiteSpace(listId))
            return null;
        else
            return CacheHelper.Get<Context>(listId);
    }

    private static void AddSessionID(string loginSessionID, Context context)
    {
        UpdateGameOnlineInfo(context);

        string listId = GetContextKey(context.Id);
        CacheUtil.Set(loginSessionID, context, RunTimeOut);
        CacheUtil.Set(listId, loginSessionID, RunTimeOut);
        CacheHelper.Set(loginSessionID, listId, RedisTimeOut);
        CacheHelper.Set(listId, context, RedisTimeOut);

        var setId = GetOnlineUserKey(context.CompanyId, context.HomeView);
        var timeStamp = TimeStamp.DateTimeToUnix(DateTime.Now);
        CacheHelper.AddItemToSortedSet(setId, context.Id.ToString(), timeStamp);
    }

    private static bool IsAuthenticated()
    {
        bool isAuthenticated = false;
        if (string.IsNullOrWhiteSpace(CurrentSessionID))
        {
            isAuthenticated = false;
        }
        else
        {
            var uc = CacheContext;
            if (uc != null && uc.Id > 0)
            {
                isAuthenticated = true;
            }
        }
        return isAuthenticated;
    }

    /// <summary>
    /// 返回登录状态:0-正常,1-未登录过,2-登录超时,3-首次登录要求强制修改密码
    /// </summary>
    /// <returns></returns>
    public static int CheckAuthentication()
    {
        int isAuthenticated;
        bool flag = IsAuthenticated();
        if (flag)
        {
            if (CacheContext.ForcesChangePWD)  //需要强制修改密码
                isAuthenticated = 3;
            else
                isAuthenticated = 0;
        }
        else
        {
            isAuthenticated = 1;//未登录过
        }
        return isAuthenticated;
    }

    /// <summary>
    /// 用户客户端的SessionID
    /// </summary>
    public static string CurrentSessionID
    {
        get
        {
            string loginSessionId = string.Empty;
            if (FeatureHelpers.IsApi)
            {
                loginSessionId = HttpContext.Current.Request.Headers.Get(LoginToken);
                //LogsManager.Debug("IsApiloginSessionId:" + loginSessionId);
            }
            else if (FeatureHelpers.IsApp)
            {
                loginSessionId = HttpContext.Current.Request["SessionId"] ?? "";
                if (string.IsNullOrWhiteSpace(loginSessionId))
                {
                    loginSessionId = HttpContext.Current.Request.Form["SessionId"] ?? "";
                }
                //LogsManager.Debug("IsApploginSessionId:" + loginSessionId);
            }
            else
            {
                loginSessionId = CookieHelpers.Get(LoginToken);
                //LogsManager.Debug("loginSessionId:" + loginSessionId);
            }
            if (!string.IsNullOrWhiteSpace(loginSessionId))
            {
                return $"{LoginToken}_{loginSessionId}";
            }
            return loginSessionId;
        }
    }

    #region <获取需要更新登录时间的用户>
    /// <summary>
    /// 获取需要更新登录时间的用户
    /// </summary>
    /// <returns></returns>
    public static Dictionary<string, int> GetHasUpdateLoginTimeUsers()
    {
        Dictionary<string, int> result = new Dictionary<string, int>();
        IEnumerable<string> keys = CacheUtil.SearchKeys($"{LoginToken}_*");
        var defaultTime = DateTime.Now.Date.AddHours(2);
        foreach (var key in keys)
        {
            var context = CacheUtil.Get<Context>(key);
            if (context != null)
            {
                if (context.LoginTime.HasValue)
                {
                    if (context.LoginTime.Value <= defaultTime)
                    {
                        result.Add(key, context.Id);
                    }
                }
                else
                {
                    result.Add(key, context.Id);
                }
            }
        }
        return result;
    }
    #endregion

    #region <更新缓存中的用户登录时间>
    /// <summary>
    /// 更新缓存中的用户登录时间
    /// </summary>
    /// <param name="keys"></param>
    public static void UpdateCacheUserLoginTime(IEnumerable<string> keys)
    {
        foreach (var key in keys)
        {
            var uc = CacheUtil.Get<Context>(key);
            uc.LoginTime = DateTime.Now;
            CacheUtil.Set(key, uc, RunTimeOut);
            string listId = GetContextKey(uc.Id);
            CacheHelper.Set(listId, uc, RedisTimeOut);
        }
    }
    #endregion

    /// <summary>
    /// 验证登录
    /// </summary>
    /// <returns></returns>
    public static bool ValidateUserLogin()
    {
        if (string.IsNullOrWhiteSpace(CurrentSessionID))
        {
            return true;
        }
        if (Id == 0)
        {
            return true;
        }
        string listId = GetContextKey(Id);
        string loginSessionId = CacheUtil.Get<string>(listId);
        if (string.IsNullOrWhiteSpace(loginSessionId))
        {
            var context = CacheHelper.Get<Context>(listId);
            if (context != null)
            {
                loginSessionId = context.LoginSessionID;
                CacheUtil.Set(listId, loginSessionId, RunTimeOut);
            }
        }
        if (!string.IsNullOrWhiteSpace(loginSessionId))
        {
            if (!loginSessionId.Trim().Equals(CurrentSessionID.Trim()))
            {
                LogsManager.WarnFormat("用户[{0}]登录SessionID发生变化,Cookie值[{1}],缓存值[{2}]", Id, CurrentSessionID, loginSessionId);
                return false;
            }
        }
        return true;
    }

    /// <summary>
    /// 验证登录身份
    /// </summary>
    public static bool ValidateIdentity
    {
        get
        {
            try
            {
                if (CacheContext == null)
                    return true;
                if (HttpContext.Current == null || HttpContext.Current.Request == null)
                    return true;
                if (CacheContext != null && !string.IsNullOrWhiteSpace(CacheContext.Token))
                {
                    string url = SkinManager.Url.Replace("//www.", "").Replace("//WWW.", "");
                    string token = EncryptionHelpers.Md5Encryption(CacheContext.GuidKey, url);
                    if (!token.Equals(CacheContext.Token))
                    {
                        LogType.Login.WriterLog($"用户[{CacheContext.Id}]登录Token发生变化,请求值[{token}],缓存值[{CacheContext.Token}]详情:[{CacheContext.GuidKey}, {url}]");
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                ex.Error("验证登录身份异常");
                return true;
            }
        }
    }

    public static void AfterChangePWD()
    {
        var context = CacheContext;
        if (context != null && context.Id > 0)
        {
            context.ForcesChangePWD = false;
            context.IsGeneralize = false;

            CacheUtil.Set(CurrentSessionID, context, RunTimeOut);
            string listId = GetContextKey(context.Id);
            CacheHelper.Set(listId, context, RedisTimeOut);
        }
    }

    public static void ChangeGame(int gameId)
    {
        var context = CacheContext;
        if (context != null && context.Id > 0)
        {
            //记录改变的数据
            if (context.OldPlayGameId != 0)
            {
                //非第一次进来
                context.OldPlayGameId = context.CurrentPlayGameId;//
            }
            else
            {
                //第一次进来
                context.OldPlayGameId = gameId;
            }

            context.CurrentPlayGameId = gameId;

            //这个方法只移除旧的游戏在线人数数据. 新增游戏在线人数在 AddSessionID() 里添加. 把新增和删除分开是为了避免当此方法调用时, 运行时缓存同时失效, 导致AddSessionID()进行了调用
            RemoveOldGameOnlineInfo(context);

            string listId = GetContextKey(context.Id);
            CacheHelper.Set(listId, context, RedisTimeOut);

            CacheUtil.Remove(CurrentSessionID); //移除运行时缓存. 让他们更新游戏在线人数和最后请求时间.
        }
    }

    private static void UpdateGameOnlineInfo(Context context)
    {
        var timeStamp = TimeStamp.DateTimeToUnix(DateTime.Now);
        if (context.CurrentPlayGameId != 0) //记录某游戏中在线人数 (目前仅用于微投机器人)
        {
            var gameOnlineUSerSetId = GetGameOnlineUserKey(context.CompanyId, context.CurrentPlayGameId, context.HomeView);
            CacheHelper.AddItemToSortedSet(gameOnlineUSerSetId, context.Id.ToString(), timeStamp);
        }
    }

    private static void RemoveOldGameOnlineInfo(Context context)
    {
        if (context.OldPlayGameId != 0 && context.OldPlayGameId != context.CurrentPlayGameId) //如果不是第一次. 则表示需要删除旧的数据.
        {
            var gameOnlineUSerSetId = GetGameOnlineUserKey(context.CompanyId, context.OldPlayGameId, context.HomeView);
            CacheHelper.RemoveItemFromSortedSet(gameOnlineUSerSetId, context.Id.ToString());

            if (context.CurrentPlayGameId == 0) //退出的情况下重置掉0.
            {
                context.OldPlayGameId = 0;
            }
        }
    }

    public static int CurrentPlayGameId => CacheContext.CurrentPlayGameId;

    /// <summary>
    /// 用户编号
    /// </summary>
    public static int Id => CacheContext.Id;

    /// <summary>
    /// 用户账号
    /// </summary>
    public static string UserName => CacheContext.UserName;
    /// <summary>
    /// 用户等级名称
    /// </summary>
    public static string GradeName => CacheContext.GradeName;
    /// <summary>
    /// 用户等级
    /// </summary>
    public static int GradeId => CacheContext.GradeId;
    /// <summary>
    /// 是否为测试账号
    /// </summary>
    public static bool IsTestAccount => CacheContext.IsTestAccount;
    /// <summary>
    /// 公司编号
    /// </summary>
    public static int CompanyID
    {
        get
        {
            if (CacheContext != null && CacheContext.CompanyId > 0)
            {
                return CacheContext.CompanyId;
            }
            string url = SkinManager.Url;
            var skinModel = SkinManager.GetUrlDirectory(url);
            return skinModel != null ? skinModel.CompanyID : 0;
        }
    }
    /// <summary>
    /// 用户状态
    /// </summary>
    public static int Status
    {
        get
        {
            var context = CacheContext;
            if (context != null && context.Id > 0)
            {
                return context.Status;
            }
            return -1;
        }
    }
    /// <summary>
    /// 登录状态
    /// </summary>
    public static int LoginStatus => CacheContext.LoginStatus;
    /// <summary>
    /// 用户角色
    /// </summary>
    public static string Role => CacheContext.Role.ToString();
    /// <summary>
    /// 用户上级
    /// </summary>
    public static int ParentId => CacheContext.ParentID;

    /// <summary>
    /// 是否代理
    /// </summary>
    public static bool IsAgent => CacheContext.IsAgent;
    /// <summary>
    /// 权限编号
    /// </summary>
    public static int AuthorityID => CacheContext.AuthorityID;
    /// <summary>
    /// 权限等级
    /// </summary>
    public static int AuthorityGradeID => CacheContext.AuthorityGradeID;

    /// <summary>
    /// 用户登录IP
    /// </summary>
    public static string Ip => CacheContext.Ip;

    /// <summary>
    /// 是否需要强制修改密码
    /// </summary>
    public static bool ForcesChangePWD
    {
        get
        {
            string loginSessionID = CurrentSessionID;
            if (string.IsNullOrWhiteSpace(loginSessionID))
            {
                return false;
            }
            string listId = CacheHelper.Get<string>(loginSessionID);
            if (string.IsNullOrWhiteSpace(listId))
            {
                return false;
            }
            var context = CacheHelper.Get<Context>(listId);
            if (context == null)
            {
                return false;
            }
            return context.ForcesChangePWD;
        }
    }

    /// <summary>
    /// 是否为API登录
    /// </summary>
    public static bool IsAPI => CacheContext.IsAPI;
    /// <summary>
    /// 是否推广用户
    /// </summary>
    public static bool IsGeneralize => CacheContext.IsGeneralize;
    / <summary>
    / 用户认证key
    / </summary>
    //private static string AuthorizationKey
    //{
    //    get
    //    {
    //        return $"{nameof(Authentication)}{Id}";
    //    }
    //}
    / <summary>
    / 缓存用户认证信息
    / </summary>
    / <param name="sysAuthorization"></param>
    //public static void CacheUserAuthorization(SysAuthorization sysAuthorization)
    //{
    //    if (CacheHelper.ContainsKey(AuthorizationKey))
    //    {
    //        CacheHelper.Remove(AuthorizationKey);
    //    }
    //    CacheHelper.Add(AuthorizationKey, sysAuthorization);
    //}
    / <summary>
    / 用户认证信息
    / </summary>
    //public static SysAuthorization UserAuthorization
    //{
    //    get
    //    {
    //        return CacheHelper.Get<SysAuthorization>(AuthorizationKey);
    //    }
    //}
    /// <summary>
    /// 登录SessionID
    /// </summary>
    public static string LoginSessionID => CacheContext.LoginSessionID;
    /// <summary>
    /// 是否公司客服账号
    /// </summary>
    public static bool IsCustomerServiceAccount => CacheContext.IsCustomerServiceAccount;

    /// <summary>
    /// 当前浏览器的SessionID
    /// </summary>
    public static string SessionID => CookieHelpers.Get("ASP.NET_SessionId");


    /// <summary>
    ///  当前用户的皮肤
    ///  注意:仅供前台用户使用
    /// </summary>
    public static string HomeView
    {
        get
        {
            if (CacheContext != null && !string.IsNullOrWhiteSpace(CacheContext.HomeView))
            {
                return CacheContext.HomeView;
            }
            else
            {
                string url = $"{HttpContext.Current.Request.Url.Scheme}://{HttpContext.Current.Request.Url.Authority}/";
                var skinModel = SkinManager.GetUrlDirectory(url);
                return skinModel != null ? skinModel.HomeView : "";
            }
        }
    }


}

[Serializable]
public class ErrorPassword
{
    public int AccountID { get; set; }
    public DateTime DateTime { get; set; }
    public int ErrorCount { get; set; }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值