SystemService.cs 10.5 KB
using ApkInfo;
using Hh.Mes.Common;
using Hh.Mes.Common.Json;
using Hh.Mes.Common.log;
using Hh.Mes.Common.Redis;
using Hh.Mes.Pojo.System;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.EnumEntitys;
using Hh.Mes.POJO.Response;
using Hh.Mes.POJO.ViewModel;
using Hh.Mes.Service.Repository;
using Hh.Mes.Service.SystemAuth;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Hh.Mes.Service
{
    public class SystemService : RepositorySqlSugar<sys_user>
    {
        AuthContextFactory authContextFactory;
        public SystemService(AuthContextFactory authContextFactory)
        {
            this.authContextFactory = authContextFactory;
        }
        /// <summary>
        /// 登入
        /// </summary>
        public dynamic Login(string userName, string password, string appKey, string appSecret)
        {
            return ExceptionsHelp.Instance.ExecuteT<dynamic>(() =>
            {
                var response = new Response();

                #region 获取应用信息
                var appInfo = Context.Queryable<sys_info>().First(u => u.appKey == appKey);
                if (appInfo == null)
                {
                    response.Code = 500;
                    response.Message = "应用不存在,请检查应用密钥";
                    return response;
                }
                if (Encryption.Decrypt(appInfo.appSecret) != appSecret)
                {
                    response.Code = 500;
                    response.Message = "应用密钥不正确!";
                    return response;
                }
                #endregion

                #region 获取用户信息
                var userInfo = Context.Queryable<sys_user>().First(u => u.account == userName);
                if (userInfo == null || userInfo.account != userName)
                {
                    response.Code = 500;
                    response.Token = "";
                    response.Message = "用户不存在!";
                    return response;
                }
                if (Encryption.Decrypt(userInfo.password) != password)
                {
                    response.Code = 500;
                    response.Token = "";
                    response.Message = "密码错误!";
                    return response;
                }
                #endregion
                var token = Guid.NewGuid().ToString("N");
                var currentSession = new UserAuthSession
                {
                    Id = userInfo.id,
                    Account = userInfo.account,
                    Name = userInfo.name,
                    Sex = userInfo.sex,

                    Token = token,
                    CreateTime = DateTime.Now,
                };

                //创建Session
                var cli = new RedisBase();
                cli.SetT(token, currentSession, cli.dayTime);
                response.Code = 200;
                response.Status = true;
                response.Token = token;
                response.Result = currentSession;
                response.Message = "登入成功";
                return response;
            });
        }

        /// <summary>
        /// 获取PDA用户可访问的模块列表
        /// </summary>
        public dynamic GetPDAModules(string token)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response<List<PDAModule>>();
                if (string.IsNullOrEmpty(token)) return response.ResponseError("参数【token】为空!");

                var cl = new RedisBase();
                var userAuthSession = cl.GetT<UserAuthSession>(token);
                if (userAuthSession == null) return response.ResponseError("登录已过期,请重新登录!");

                //直接从redis中获取用户权限
                var authStrategy = cl.GetT<AuthStrategyContext>(userAuthSession.Account);
                if (authStrategy == null)
                {
                    authStrategy = authContextFactory.GetAuthStrategyContext(userAuthSession.Account);
                }
                #region 根据用户权限,组合能访问的PDA模块
                List<PDAModule> pdaModules = new List<PDAModule>();
                var pdaModuleList = authStrategy.Modules.Where(t => t.Name.ToLower().StartsWith("pda"));
                foreach (var moduleItem in pdaModuleList)
                {
                    //组合PDA模块
                    PDAModule pdaModule = new PDAModule();
                    pdaModule.code = moduleItem.Code;
                    pdaModule.name = moduleItem.Name;
                    pdaModule.details = new List<PDAModuleLevel2>();
                    pdaModules.Add(pdaModule);

                    var sunModuleList = authStrategy.Modules.Where(t => t.ParentId == moduleItem.Id);
                    foreach (var sunModuleItem in sunModuleList)
                    {
                        //组合PDA二级模块
                        PDAModuleLevel2 pdaModuleLevel2 = new PDAModuleLevel2();
                        pdaModuleLevel2.code = sunModuleItem.Code;
                        pdaModuleLevel2.name = sunModuleItem.Name;
                        pdaModuleLevel2.details = new List<PDAElement>();
                        pdaModule.details.Add(pdaModuleLevel2);

                        foreach (var elementItem in sunModuleItem.Elements)
                        {
                            //组合PDA窗体
                            PDAElement pdaElement = new PDAElement();
                            pdaElement.icon = elementItem.Class;
                            pdaElement.tit = elementItem.Name;
                            pdaElement.path = elementItem.DomId;
                            pdaModuleLevel2.details.Add(pdaElement);
                        }
                    }
                }
                #endregion
                response.Result = pdaModules;
                return response;
            });
        }

        /// <summary>
        /// 登退 【删除redis,删除  sys_user_online】
        /// </summary>
        public dynamic Logout(string token)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {

                var response = new Response();
                if (string.IsNullOrEmpty(token)) return response.ResponseError("参数【token】为空");

                var cl = new RedisBase();
                var result = cl.redisClient.Exists(token);
                if (result)
                {
                    //再清空用户登录信息
                    cl.redisClient.Del(token);
                }
                Context.Deleteable<sys_user_online>().Where(it => it.token == token).ExecuteCommand();
                return response.ResponseSuccess();
            });
        }

        /// <summary>
        /// 判断token是否存在,过期
        /// </summary>
        public dynamic AppCheckToken(string token)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                if (string.IsNullOrEmpty(token)) return response.ResponseError("参数【token】为空");
                var isOk = new RedisBase().ExistsKey(token);
                return isOk ? response.ResponseSuccess() : response.ResponseError("token失效,请退出重新登入!");
            });
        }

        /// <summary>
        /// APP检查 最新版本 升级
        /// </summary>
        /// <returns></returns>
        public dynamic AppCheckVerByAppNameAndVer(string appId, double ver)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var response = new Response();
                var app = Context.Queryable<sys_app>().OrderBy(x => x.ver, OrderByType.Desc).First(x => x.appId == appId && x.ver > ver);
                if (app == null)
                {
                    response.Code = 400;
                    response.Status = false;
                    response.Message = $"当前APP【应用标识appId:{appId}、版本ver:{ver}】没有最新的版本更新!";
                    return response;
                }
                response.Result = new
                {
                    wgtUrl = app.filePath,
                    installPath = "_downloads/UploadFile/APP"
                };
                return response;
            });
        }

        /// <summary>
        /// 第3方登入
        /// </summary>
        /// <returns></returns>
        public dynamic OtherLogin(string otherToken)
        {
            var response = new Response();

            #region  before
            if (string.IsNullOrEmpty(otherToken))
            {
                return response.ResponseError("参数【token】传入为空!");
            }
            var json = JwtEncryption.Decode(otherToken);
            var userInfo = DynamicJson.Parse(json);
            var token = Guid.NewGuid().ToString("N");
            var cli = new RedisBase();
            //直接从redis中获取用户权限
            var authStrategy = cli.GetT<UserAuthSession>(token);
            if (authStrategy == null)
            {
                var user = GetSysUserByAccount(userInfo.loginName);
                if (user == null)
                {
                    return response.ResponseError($"第三方登入没有查询到您的用户信息,请核实信息【loginName】。或者在中控系统【用户管理】新增此用户{user.loginName}!");
                }
                var currentSession = new UserAuthSession
                {
                    Id = user.id,
                    Account = user.account,
                    Name = user.name,
                    Sex = user.sex,
                    Idcard = user.idcard,

                    Token = token,
                    CreateTime = DateTime.Now,
                };
                //创建Session
                cli.SetT(token, currentSession, cli.dayTime);
            }

            response.Token = token;
            return response.ResponseSuccess("登入成功!");
            #endregion
        }



        /// <summary>
        /// 枚举对象
        /// </summary>
        public string GetState()
        {
            string json = typeof(EnumLog).GetJsonEnums();

            json = json.Replace("var ", "\"").Replace("=", "\":");
            json = "{" + json + "}";
            return json;
        }

        private sys_user GetSysUserByAccount(string account)
        {
            return Context.Queryable<sys_user>().First(x => x.account == account);
        }
    }
}