Beispiel #1
0
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="mobileToken"></param>
        /// <param name="targetUserId"></param>
        public JsonResult GetUserByObjectID(string userCode, string targetUserId)
        {
            return(ExecuteFunctionRun(() =>
            {
                OThinker.Organization.User user = this.Engine.Organization.GetUnit(targetUserId) as OThinker.Organization.User;
                if (user == null)
                {
                    Json("", JsonRequestBehavior.AllowGet);
                }
                ;

                UserValidator userValidator = UserValidatorFactory.GetUserValidator(this.Engine, user.Code);
                MobileAccess mobile = new MobileAccess();
                MobileAccess.MobileUser mobileUser = mobile.GetMobileUser(this.UserValidator, user,
                                                                          userValidator.ImagePath,
                                                                          userValidator.DepartmentName,
                                                                          string.Empty);

                var result = new
                {
                    MobileUser = mobileUser
                };
                return Json(result, JsonRequestBehavior.AllowGet);
            }));
        }
        /// <summary>
        /// 创建微信用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="department"></param>
        public bool CreateWeChatUser(OThinker.Organization.User user, int department)
        {
            WXUser wechatUser = new WXUser()
            {
                userid     = user.Code,
                name       = user.Name,
                department = new int[] { department },
                email      = string.IsNullOrEmpty(user.Email) ? "" : user.Email.Replace("null", "").Replace("undefined", ""),
                enable     = user.State == State.Active ? 1 : 0,
                mobile     = string.IsNullOrEmpty(user.Mobile) ? "" : user.Mobile.Replace("null", "").Replace("undefined", ""),
                weixinid   = user.WeChatAccount,
                position   = user.Appellation,
                order      = new int[] { 5000 - user.SortKey },
                telephone  = string.IsNullOrEmpty(user.OfficePhone) ? "" : user.OfficePhone.Replace("null", "").Replace("undefined", ""),
                gender     = ((int)user.Gender).ToString()
            };
            string res = PostWebRequest(string.Format(URL_CreateUser, AccessToken), JsonConvert.SerializeObject(wechatUser), WeChatEncoding);

            this.LogWriter.Write("创建微信用户返回:" + user.Code + ",Result=" + res);
            WXResult wxRes = JsonConvert.DeserializeObject <WXResult>(res);

            if (wxRes.errcode == 0)
            {
                #region insert to C_H3_Wechat_OrgSync表
                InsertToWechatUserRelation(user.Code, user.Name, user.Mobile);
                return(true);

                #endregion
            }
            else
            {
                this.LogWriter.Write("创建微信用户失败的参数:" + JsonConvert.SerializeObject(wechatUser));
                return(false);
            }
        }
Beispiel #3
0
        /// <summary>
        /// 微信集成登录
        /// </summary>
        /// <param name="context"></param>
        public JsonResult ValidateLoginForWeChat(string state, string code)
        {
            OThinker.Organization.User currentUser = null;
            UserValidator userValidator            = null;
            string        userImage = string.Empty;

            // 微信登录
            if (this.UserValidator != null)
            {
                userValidator = this.UserValidator;
            }
            else
            {
                IEngine engine = AppUtility.Engine;
                userValidator = UserValidatorFactory.LoginAsWeChatReturnUserValidator(state, code);
            }

            object result = null;

            if (userValidator == null)
            {
                result = new
                {
                    Success  = false,
                    Messages = "UserNotExist"
                };
            }
            else
            {
                currentUser = userValidator.User;
                if (currentUser == null ||
                    currentUser.State == State.Inactive ||
                    currentUser.ServiceState == UserServiceState.Dismissed ||
                    currentUser.IsVirtualUser)
                {
                    result = new
                    {
                        Success  = false,
                        Messages = "InvalidUser"
                    };
                }

                userImage = userValidator.ImagePath;
                MobileAccess            mobile     = new MobileAccess();
                MobileAccess.MobileUser mobileUser = mobile.GetMobileUser(userValidator, currentUser, userImage, string.Empty, string.Empty);
                result = new
                {
                    Success        = true,
                    PortalRoot     = this.PortalRoot,
                    MobileUser     = mobileUser,
                    DirectoryUnits = GetDirectoryUnits(currentUser.ObjectID, userValidator)
                };
                FormsAuthentication.SetAuthCookie(currentUser.Code, false);
                // 当前用户登录
                Session[Sessions.GetUserValidator()] = userValidator;
                Session[Sessions.GetWeChatLogin()]   = true;
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Beispiel #4
0
        public JsonResult SubmitWorkItem(string userCode, string workItemId, string paramValues)
        {
            // 获取工作项
            OThinker.H3.WorkItem.WorkItem item = this.Engine.WorkItemManager.GetWorkItem(workItemId);
            if (item == null)
            {
                throw new Exception("工作任务不存在");
            }
            OThinker.Organization.User user = this.Engine.Organization.GetUserByCode(userCode) as OThinker.Organization.User;
            if (user == null)
            {
                throw new Exception("用户不存在");
            }
            List <DataItemParam> listParamValues = JSSerializer.Deserialize <List <DataItemParam> >(paramValues);

            // 保存数据项
            SaveBizObject(item, user, OThinker.Data.BoolMatchValue.True, listParamValues);

            // 结束工作项
            this.Engine.WorkItemManager.FinishWorkItem(
                item.ObjectID,
                user.UnitID,
                OThinker.H3.WorkItem.AccessPoint.ExternalSystem,
                null,
                OThinker.Data.BoolMatchValue.True,
                string.Empty,
                null,
                OThinker.H3.WorkItem.ActionEventType.Forward,
                11);

            // 需要通知实例事件管理器结束事件
            AsyncEndMessage endMessage = new OThinker.H3.Messages.AsyncEndMessage(
                MessageEmergencyType.Normal,
                item.InstanceId,
                item.ActivityCode,
                item.TokenId,
                OThinker.Data.BoolMatchValue.True,
                false,
                OThinker.Data.BoolMatchValue.True,
                true,
                null);

            this.Engine.InstanceManager.SendMessage(endMessage);
            return(Json(new
            {
                Result = true,
                Message = string.Empty
            }));
        }
        /// <summary>
        /// 微信登录,返回当前用户信息
        /// </summary>
        /// <param name="EngineCode"></param>
        /// <param name="WeChatCode"></param>
        /// <returns></returns>
        public static UserValidator LoginAsWeChatReturnUserValidator(string EngineCode, string WeChatCode)
        {
            UserValidator user           = null;
            string        userCode       = string.Empty;
            string        tempImagesPath = Path.Combine(HttpContext.Current.Server.MapPath("."), "TempImages");

            switch (AppConfig.ConnectionMode)
            {
            case ConnectionStringParser.ConnectionMode.Mono:
                IEngine engine = AppUtility.Engine;
                userCode = engine.WeChatAdapter.GetUserCode(WeChatCode);
                OThinker.Organization.User unit = engine.Organization.GetUserByCode(userCode);
                if (unit == null)
                {
                    return(null);
                }
                //离职、禁用用户以及虚拟用户不能登录
                if (unit == null ||
                    unit.ServiceState == UserServiceState.Dismissed ||
                    unit.IsVirtualUser ||
                    unit.State == State.Inactive)
                {
                    return(null);
                }
                user = new UserValidator(engine, unit.ObjectID, tempImagesPath, null);
                break;

            case ConnectionStringParser.ConnectionMode.Shared:
                OThinker.H3.Connection conn = new Connection();
                string userId = string.Empty;
                if (conn.Open(AppConfig.ConnectionStringParser.Servers[0],
                              Clusterware.AuthenticationType.WeChat,
                              EngineCode, WeChatCode, "WeChat", out userId) != Clusterware.ConnectionResult.Success)
                {
                    return(null);
                }
                user = new UserValidator(conn.Engine, userId, tempImagesPath, null);
                break;

            default:
                throw new NotImplementedException();
            }

            OThinker.H3.Controllers.AppUtility.OnUserLogin(user, HttpContext.Current.Request, Site.PortalType.WeChat);
            return(user);
        }
 /// <summary>
 /// 验证用户的身份和密码
 /// </summary>
 /// <param name="Organization">组织结构管理器</param>
 /// <param name="UserAlias">用户登录名</param>
 /// <param name="Password">用户登录密码</param>
 /// <param name="EnableADValidation">是否使用AD认证</param>
 /// <param name="ADPathes">AD地址</param>
 /// <returns>如果用户验证成功,则返回User,否则返回null</returns>
 public static OThinker.Organization.User ValidateUser(
     OThinker.Organization.IOrganization Organization,
     string UserAlias,
     string Password,
     bool EnableADValidation,
     string ADPathes)
 {
     if (UserAlias == null)
     {
         return(null);
     }
     OThinker.Organization.User user = Organization.GetUserByCode(UserAlias);
     if (user == null || user.State == State.Inactive ||
         user.ServiceState == UserServiceState.Dismissed || user.IsVirtualUser)
     {// 虚拟用户、离职、禁用用户不允许登录
         return(null);
     }
     if (EnableADValidation && (!user.IsSystemUser || !user.IsAdministrator))
     {
         // 使用AD认证
         bool success = false;
         if (!string.IsNullOrEmpty(ADPathes))
         {
             string[] ads = ADPathes.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
             foreach (string ad in ads)
             {
                 success = IsAuthenticated(ad, UserAlias, Password);
                 if (success)
                 {
                     return(user);
                 }
             }
         }
     }
     else if (user.ValidatePassword(Password))
     {
         // 密码正确
         return(user);
     }
     return(null);
 }
Beispiel #7
0
        /// <summary>
        /// 根据用户帐号查找
        /// </summary>
        /// <param name="userCodes"></param>
        /// <returns></returns>
        private List <PortalTreeNode> LoadNodesByUserCodes(string userCodes)
        {
            List <PortalTreeNode> childNodes = new List <PortalTreeNode>();

            string[] codes = userCodes.Split(new string[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries);
            if (codes.Length == 0)
            {
                return(childNodes);
            }
            foreach (string code in codes)
            {
                OThinker.Organization.User user = this.Engine.Organization.GetUserByCode(code);
                if (user != null)
                {
                    PortalTreeNode childNode = this.GetTreeNodeFromUnit(user);
                    childNodes.Add(childNode);
                }
            }

            return(childNodes);
        }
Beispiel #8
0
        /// <summary>
        /// 保存表单数据
        /// </summary>
        /// <param name="workItem"></param>
        /// <param name="user"></param>
        /// <param name="boolMatchValue"></param>
        /// <param name="paramValues"></param>
        private void SaveBizObject(OThinker.H3.WorkItem.WorkItem workItem, OThinker.Organization.User user, OThinker.Data.BoolMatchValue boolMatchValue, List <DataItemParam> paramValues)
        {
            InstanceContext InstanceContext = this.Engine.InstanceManager.GetInstanceContext(workItem.InstanceId);
            string          bizObjectId     = InstanceContext == null ? string.Empty : InstanceContext.BizObjectId;

            OThinker.H3.DataModel.BizObjectSchema schema = this.Engine.BizObjectManager.GetPublishedSchema(InstanceContext.BizObjectSchemaCode);
            OThinker.H3.DataModel.BizObject       bo     = new OThinker.H3.DataModel.BizObject(this.Engine, schema, workItem.Participant);
            bo.ObjectID = bizObjectId;
            bo.Load();

            // 设置数据项的值
            foreach (DataItemParam param in paramValues)
            {
                OThinker.H3.DataModel.PropertySchema property = schema.GetProperty(param.ItemName);
                if (property.LogicType == DataLogicType.Comment)
                {// 审核意见
                    CommentParam comment = JSSerializer.Deserialize <CommentParam>(param.ItemValue + string.Empty);
                    this.Engine.BizObjectManager.AddComment(new Comment()
                    {
                        BizObjectId         = bo.ObjectID,
                        BizObjectSchemaCode = schema.SchemaCode,
                        InstanceId          = workItem.InstanceId,
                        TokenId             = workItem.TokenId,
                        Approval            = boolMatchValue,
                        Activity            = workItem.ActivityCode,
                        DataField           = property.Name,
                        UserID      = user.ObjectID,
                        SignatureId = comment.SignatureId,
                        Text        = comment.Text
                    });
                }
                else
                {
                    new BPM().SetItemValue(bo, property, param.ItemValue);
                }
            }

            bo.Update();
        }
        /// <summary>
        /// 更新微信用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="department"></param>
        private bool UpdateWeChatUser(OThinker.Organization.User user, int department)
        {
            WXUser wechatUser = new WXUser()
            {
                userid     = user.Code,
                name       = user.Name,
                department = new int[] { department },
                email      = string.IsNullOrEmpty(user.Email) ? "" : user.Email.Replace("null", "").Replace("undefined", ""),
                enable     = user.State == State.Active ? 1 : 0,
                mobile     = string.IsNullOrEmpty(user.Mobile) ? "" : user.Mobile.Replace("null", "").Replace("undefined", ""),
                weixinid   = user.WeChatAccount,
                position   = user.Appellation,
                order      = new int[] { 5000 - user.SortKey },
                telephone  = string.IsNullOrEmpty(user.OfficePhone) ? "" : user.OfficePhone.Replace("null", "").Replace("undefined", ""),
                gender     = ((int)user.Gender).ToString()
            };

            //加上离职的用户:禁用企业微信;
            if (user.ServiceState == UserServiceState.Dismissed)
            {
                wechatUser.enable = 0;
            }

            string res = PostWebRequest(string.Format(URL_UpdateUser, AccessToken), JsonConvert.SerializeObject(wechatUser), WeChatEncoding);

            this.LogWriter.Write("更新微信用户返回:" + res);
            WXResult wxRes = JsonConvert.DeserializeObject <WXResult>(res);

            if (wxRes.errcode == 0)
            {
                return(true);
            }
            else
            {
                this.LogWriter.Write("更新微信用户失败的参数:" + JsonConvert.SerializeObject(wechatUser));
                return(false);
            }
        }
Beispiel #10
0
        public System.Web.Mvc.ActionResult RejectWorkItem(string appId, string pwd, string userCode, string workItemId, string rejectToActivity, string paramValues)
        {
            // 获取工作项
            OThinker.H3.WorkItem.WorkItem item = this.Engine.WorkItemManager.GetWorkItem(workItemId);
            if (item == null)
            {
                throw new Exception("工作任务不存在");
            }
            OThinker.Organization.User user = this.Engine.Organization.GetUserByCode(userCode) as OThinker.Organization.User;
            if (user == null)
            {
                throw new Exception("用户不存在");
            }
            List <DataItemParam> listParamValues = JSSerializer.Deserialize <List <DataItemParam> >(paramValues);

            // 保存数据项
            SaveBizObject(item, user, OThinker.Data.BoolMatchValue.True, listParamValues);

            // 获取驳回节点
            if (string.IsNullOrEmpty(rejectToActivity))
            {// 目标节点为空,则判断当前节点允许驳回的环节
                PublishedWorkflowTemplate template = this.Engine.WorkflowManager.GetPublishedTemplate(item.WorkflowCode, item.WorkflowVersion);
                ParticipativeActivity     activity = template.GetActivityByCode(item.ActivityCode) as ParticipativeActivity;
                if (activity == null)
                {
                    throw new Exception("当前环节不允许驳回");
                }
                if (activity.PermittedActions.RejectToStart)
                {
                    rejectToActivity = template.StartActivityCode;                                          // 驳回到开始
                }
                else if (activity.PermittedActions.RejectToFixed || activity.PermittedActions.RejectToAny)
                {
                    if (activity.PermittedActions.RejectToActivityCodes != null && activity.PermittedActions.RejectToActivityCodes.Length > 0)
                    {
                        rejectToActivity = activity.PermittedActions.RejectToActivityCodes[0];
                    }
                }
                else if (activity.PermittedActions.Reject)
                {// 驳回上一步
                    InstanceContext context = this.Engine.InstanceManager.GetInstanceContext(item.InstanceId);
                    int[]           tokens  = context.GetToken(item.TokenId).PreTokens;
                    if (tokens != null && tokens.Length > 0)
                    {
                        rejectToActivity = context.GetToken(tokens[0]).Activity;
                    }
                }

                if (string.IsNullOrEmpty(rejectToActivity))
                {
                    rejectToActivity = template.StartActivityCode;
                }
            }

            // 结束工作项
            this.Engine.WorkItemManager.FinishWorkItem(
                item.ObjectID,
                user.ObjectID,
                AccessPoint.ExternalSystem,
                null,
                OThinker.Data.BoolMatchValue.False,
                string.Empty,
                null,
                ActionEventType.Backward,
                10);
            // 准备触发后面Activity的消息
            OThinker.H3.Messages.ActivateActivityMessage activateMessage
                = new OThinker.H3.Messages.ActivateActivityMessage(
                      OThinker.H3.Messages.MessageEmergencyType.Normal,
                      item.InstanceId,
                      rejectToActivity,
                      OThinker.H3.Instance.Token.UnspecifiedID,
                      null,
                      new int[] { item.TokenId },
                      false,
                      ActionEventType.Backward);

            // 通知该Activity已经完成
            OThinker.H3.Messages.AsyncEndMessage endMessage =
                new OThinker.H3.Messages.AsyncEndMessage(
                    OThinker.H3.Messages.MessageEmergencyType.Normal,
                    item.InstanceId,
                    item.ActivityCode,
                    item.TokenId,
                    OThinker.Data.BoolMatchValue.False,
                    true,
                    OThinker.Data.BoolMatchValue.False,
                    false,
                    activateMessage);
            this.Engine.InstanceManager.SendMessage(endMessage);
            return(Json(new
            {
                Result = true,
                Message = string.Empty
            }));
        }
Beispiel #11
0
        public System.Web.Mvc.ActionResult GetInstanceInfo(string appId, string pwd, string userCode, string workItemId)
        {
            OThinker.H3.WorkItem.WorkItem workItem = this.Engine.WorkItemManager.GetWorkItem(workItemId);
            if (workItem == null)
            {
                throw new Exception("工作任务不存在");
            }
            OThinker.H3.Instance.InstanceContext instance = this.Engine.InstanceManager.GetInstanceContext(workItem.InstanceId);

            OThinker.H3.WorkflowTemplate.PublishedWorkflowTemplate template = this.Engine.WorkflowManager.GetPublishedTemplate(instance.WorkflowCode, instance.WorkflowVersion);
            OThinker.H3.WorkflowTemplate.Activity activity = template.GetActivityByCode(workItem.ActivityCode);

            InstanceInfo result = new InstanceInfo()
            {
                ActivityCode    = activity.ActivityCode,
                ActivityName    = activity.DisplayName,
                DataPermissions = (activity is OThinker.H3.WorkflowTemplate.ParticipativeActivity) ? ((OThinker.H3.WorkflowTemplate.ParticipativeActivity)activity).DataPermissions : null,
                InstanceId      = instance.InstanceId,
                InstanceState   = instance.State,
                Originator      = instance.Originator,
                TokenId         = workItem.TokenId,
                WorkflowCode    = template.WorkflowCode,
                WorkflowName    = template.WorkflowFullName,
                SequenceNo      = instance.SequenceNo,
                WorkItemState   = workItem.State
            };

            OThinker.Organization.User user = this.Engine.Organization.GetUserByCode(userCode) as OThinker.Organization.User;
            if (user != null)
            {
                OThinker.Organization.Signature[] signatures = this.Engine.Organization.GetSignaturesByUnit(user.ObjectID);
                result.MySignatures = new List <SignatureParam>();
                if (signatures != null)
                {
                    foreach (OThinker.Organization.Signature signature in signatures)
                    {
                        result.MySignatures.Add(new SignatureParam()
                        {
                            IsDefault     = signature.IsDefault,
                            SignatureName = signature.Name,
                            SignautreId   = signature.ObjectID,
                            SortKey       = signature.SortKey
                        });
                    }
                }

                result.FrequentlyComment = this.Engine.Organization.GetFrequentlyUsedCommentTextsByUser(user.ObjectID);

                if (activity is OThinker.H3.WorkflowTemplate.ParticipativeActivity)
                {
                    // PermittedActions actions = new PermittedActions();
                    OThinker.H3.WorkflowTemplate.ParticipativeActivity participative = activity as OThinker.H3.WorkflowTemplate.ParticipativeActivity;
                    //actions.AdjustParticipant = participative.PermittedActions.AdjustParticipant;
                    //actions.Assist = participative.PermittedActions.Assist;
                    //actions.CancelIfUnfinished = participative.PermittedActions.CancelIfUnfinished;
                    //actions.Choose = participative.PermittedActions.Choose;
                    //actions.Circulate = participative.PermittedActions.Circulate;
                    //actions.Consult = participative.PermittedActions.Consult;
                    //actions.Forward = participative.PermittedActions.Forward;
                    //actions.Reject = participative.PermittedActions.Reject || participative.PermittedActions.RejectToAny || participative.PermittedActions.RejectToFixed;

                    if (participative.PermittedActions.RejectToAny)
                    {// 获取允许驳回的节点
                        List <ActivityParam> rejectActivies = new List <ActivityParam>();
                        foreach (OThinker.H3.Instance.Token token in instance.Tokens)
                        {
                            if (token.Activity == activity.ActivityCode)
                            {
                                continue;
                            }
                            ParticipativeActivity act = template.GetActivityByCode(token.Activity) as ParticipativeActivity;
                            if (act == null)
                            {
                                continue;
                            }
                            rejectActivies.Add(new ActivityParam()
                            {
                                ActivityCode = act.ActivityCode,
                                DisplayName  = act.DisplayName
                            });
                        }
                        result.RejectActivies = rejectActivies;
                    }

                    result.PermittedActions = participative.PermittedActions;
                }
            }

            return(Json(result));
        }
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="AuthenticationType">验证方式</param>
        /// <param name="EngineCode">引擎编码</param>
        /// <param name="UserName">用户名</param>
        /// <param name="Password">密码</param>
        /// <param name="LoginType">登录类型</param>
        /// <param name="isAdminLogin">是否后台登录</param>
        /// <returns>返回登录是否成功</returns>
        public static bool Login(Clusterware.AuthenticationType AuthenticationType,
                                 string EngineCode,
                                 string UserName,
                                 string Password,
                                 PortalType LoginType,
                                 bool isAdminLogin = false)
        {
            UserValidator user           = null;
            string        tempImagesPath = Path.Combine(HttpContext.Current.Server.MapPath("."), "TempImages");

            switch (AppConfig.ConnectionMode)
            {
            case ConnectionStringParser.ConnectionMode.Mono:
                IEngine engine = AppUtility.Engine;
                Dictionary <string, object> settings = engine.SettingManager.GetSheetSettings();
                bool   enableAD = false;
                string adPath   = string.Empty;
                bool.TryParse(settings[OThinker.H3.Settings.CustomSetting.Setting_EnableADValidation] + string.Empty, out enableAD);
                adPath = settings[OThinker.H3.Settings.CustomSetting.Setting_ADPathes] + string.Empty;

                if (!Validate(engine.Organization, UserName, Password, enableAD, adPath))
                {
                    return(false);
                }

                user = GetUserValidator(AppUtility.Engine,
                                        tempImagesPath,
                                        UserName,
                                        settings);
                break;

            case ConnectionStringParser.ConnectionMode.Shared:
                OThinker.H3.Connection conn = new Connection();
                if (conn.Open(AppConfig.ConnectionStringParser.Servers[0],
                              AuthenticationType,
                              EngineCode, UserName, Password) != Clusterware.ConnectionResult.Success)
                {
                    return(false);
                }
                OThinker.Organization.User unit = conn.Engine.Organization.GetUserByCode(UserName);
                if (unit == null)
                {
                    return(false);
                }
                user = new UserValidator(conn.Engine,
                                         unit.UnitID,
                                         tempImagesPath,
                                         null);
                break;

            default:
                throw new NotImplementedException();
            }

            //如果不是后台登陆,登陆成功即可;如是后台登陆,则判断是否有后台登陆权限
            if (isAdminLogin && !(user.User.IsConsoleUser || user.ValidateAdministrator()))
            {
                return(false);
            }

            HttpContext.Current.Session[Sessions.GetUserValidator()] = user;
            OThinker.H3.Controllers.AppUtility.OnUserLogin(user, HttpContext.Current.Request, LoginType);

            return(true);
        }
        /// <summary>
        /// 钉钉登陆,返回当前用户信息
        /// </summary>
        /// <param name="DingTalkCode">临时授权码,JSAPI获取</param>
        /// <returns></returns>
        public static UserValidator LoginAsDingTalkReturnUserValidator(string EngineCode, string DingTalkCode)
        {
            UserValidator user           = null;
            string        userCode       = string.Empty;
            string        tempImagesPath = Path.Combine(HttpContext.Current.Server.MapPath("."), "TempImages");

            switch (AppConfig.ConnectionMode)
            {
            case ConnectionStringParser.ConnectionMode.Mono:
                IEngine engine = AppUtility.Engine;

                OThinker.H3.DingTalk.DingTalkUserInfo dingUser = engine.DingTalkAdapter.GetUserInfo(DingTalkCode);
                if (dingUser == null)
                {
                    return(null);
                }
                userCode = dingUser.userid;
                engine.LogWriter.Write("DingTalk---deviceid:" + dingUser.deviceId + ",userid:" + dingUser.userid);

                OThinker.Organization.User unit = engine.Organization.GetUserByCode(userCode);
                if (unit == null)
                {
                    //通过手机号匹配
                    OThinker.H3.DingTalk.DingTalkUserByUserid DingTalkUserInfo = engine.DingTalkAdapter.GetUserInfoByUserid(userCode);
                    if (DingTalkUserInfo != null)
                    {
                        string uCode = engine.Organization.GetUserCodeByMobile(DingTalkUserInfo.mobile);
                        unit = engine.Organization.GetUserByCode(uCode);
                    }
                }

                //离职、禁用用户以及虚拟用户不能登录
                if (unit == null ||
                    unit.ServiceState == UserServiceState.Dismissed ||
                    unit.IsVirtualUser ||
                    unit.State == State.Inactive)
                {
                    return(null);
                }

                //DingTalkAccount为空时做一次更新
                if (string.IsNullOrEmpty(unit.DingTalkAccount))
                {
                    unit.DingTalkAccount = dingUser.userid;
                    engine.Organization.UpdateUnit(User.AdministratorID, unit);
                }
                user = new UserValidator(engine, unit.ObjectID, tempImagesPath, null);
                break;

            case ConnectionStringParser.ConnectionMode.Shared:
                OThinker.H3.Connection conn = new Connection();
                string userId = string.Empty;
                if (conn.Open(AppConfig.ConnectionStringParser.Servers[0],
                              Clusterware.AuthenticationType.WeChat,
                              EngineCode, DingTalkCode, "DingTalk", out userId) != Clusterware.ConnectionResult.Success)
                {
                    return(null);
                }
                user = new UserValidator(conn.Engine, userId, tempImagesPath, null);
                break;

            default:
                throw new NotImplementedException();
            }

            OThinker.H3.Controllers.AppUtility.OnUserLogin(user, HttpContext.Current.Request, Site.PortalType.DingTalk);
            return(user);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="Controller"></param>
        /// <param name="PortalRoot"></param>
        /// <param name="Message"></param>
        /// <returns></returns>
        public static UserValidator GetUserValidator(System.Web.Mvc.Controller Controller, string PortalRoot, out string Message)
        {
            Message = null;
            string        windowsAlias  = string.Empty; // Windows 集成中获取到的帐号
            string        urlAlias      = string.Empty; // URL 中获取到的帐号
            UserValidator userInSession = null;         // Session 中的对象

            // 1.取 Session 帐号
            userInSession = Controller.Session[Sessions.GetUserValidator()] as UserValidator;
            try
            {
                urlAlias = Controller.Request.QueryString[SheetEnviroment.Param_LoginName];
            }
            catch { }
            //异步话,这里已经登录成功了
            if (userInSession != null)
            {
                if (string.IsNullOrEmpty(urlAlias) || (!string.IsNullOrEmpty(urlAlias) && userInSession.UserCode == urlAlias))
                {
                    return(userInSession);
                }
            }

            string tempImagesPath = AppConfig.TempImagesPath;

            // 2.如果 Windows 集成,并且当前 Windows 帐号和 Session 不一致,那么切换用户
            windowsAlias = Controller.User.Identity.Name;
            if (!string.IsNullOrEmpty(windowsAlias))
            {
                if (windowsAlias.IndexOf("|") > -1)
                {
                    windowsAlias = windowsAlias.Substring(windowsAlias.LastIndexOf("|") + 1);
                }
                string windowsAliasNoDomain = windowsAlias;
                if (windowsAlias.IndexOf("\\") > -1)
                {
                    windowsAliasNoDomain = windowsAlias.Substring(windowsAlias.IndexOf("\\") + 1);
                }
                if (userInSession == null || (userInSession.UserCode != windowsAlias && userInSession.UserCode != windowsAliasNoDomain))
                {
                    Dictionary <string, object> settings = AppUtility.Engine.SettingManager.GetSheetSettings();
                    // 切换Windows帐号登录
                    if ((bool)settings[H3.Settings.CustomSetting.Setting_ADLoginNameIncludeDomain])
                    {
                        // 带域帐号的登录
                        userInSession = GetUserValidator(AppUtility.Engine, tempImagesPath, windowsAlias, settings);
                    }
                    if (userInSession == null)
                    {
                        // 不带域帐号的登录
                        userInSession = GetUserValidator(AppUtility.Engine, tempImagesPath, windowsAliasNoDomain, settings);
                    }
                    if (userInSession == null || userInSession.User.State == Organization.State.Inactive)
                    {
                        Message = Configs.Global.ResourceManager.GetString("UserValidatorFactory_User") + windowsAlias + " " + Configs.Global.ResourceManager.GetString("UserValidatorFactory_Mssg");
                        return(null);
                    }
                    Controller.Session[Sessions.GetUserValidator()] = userInSession;
                    FormsAuthentication.SetAuthCookie(userInSession.UserCode, false);
                }

                return(userInSession);
            }

            // 4.如果非Windows认证,那么检测URL认证帐号信息(此方式得去除)
            urlAlias = Controller.Request.QueryString[SheetEnviroment.Param_LoginName];
            urlAlias = System.Web.HttpUtility.UrlDecode(urlAlias);


            // 5.移动端单点登录 SID、Token、UserCode 进行唯一登录
            string sid   = Controller.Request.QueryString[OThinker.H3.Controllers.SheetEnviroment.Param_LoginSID];
            string token = Controller.Request.QueryString[OThinker.H3.Controllers.SheetEnviroment.Param_MobileToken];

            if (!string.IsNullOrEmpty(urlAlias) &&
                !string.IsNullOrEmpty(sid) &&
                !string.IsNullOrEmpty(token) &&
                AppConfig.ConnectionMode == ConnectionStringParser.ConnectionMode.Mono)
            {
                OThinker.Organization.User user = AppUtility.Engine.Organization.GetUserByCode(urlAlias);
                if (user != null)
                {
                    if (sid == user.SID && OThinker.Security.MD5Encryptor.GetMD5(token) == user.MobileToken)
                    {
                        userInSession = GetUserValidator(OThinker.H3.Controllers.AppUtility.Engine, urlAlias);
                        Controller.Session[Sessions.GetUserValidator()] = userInSession;
                        FormsAuthentication.SetAuthCookie(userInSession.UserCode, false);
                    }
                }
            }

            // 6.支持H3的SSO,URL中传入 Token
            token = Controller.Request.QueryString["Token"] + string.Empty;
            string secret = ConfigurationManager.AppSettings["Secret"] + string.Empty;

            if (token != string.Empty && secret != string.Empty)
            {
                string userCode = AppUtility.Engine.SSOManager.GetUserCode(OThinker.H3.Configs.ProductInfo.ProductName, secret, token);
                userInSession = GetUserValidator(OThinker.H3.Controllers.AppUtility.Engine, userCode);
                if (userInSession != null)
                {
                    Controller.Session[Sessions.GetUserValidator()] = userInSession;
                    FormsAuthentication.SetAuthCookie(userInSession.UserCode, false);
                }
            }
            return(userInSession);
        }