// ------------------------------------------------------- // 保存 删除 // ------------------------------------------------------- #region 函数:Save(XmlDocument doc) /// <summary>保存记录</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string Save(XmlDocument doc) { ForumCommentInfo param = new ForumCommentInfo(); param = (ForumCommentInfo)AjaxUtil.Deserialize(param, doc); param.IP = IPQueryContext.GetClientIP(); param.AccountId = KernelContext.Current.User.Id; param.AccountName = KernelContext.Current.User.Name; param.ModifiedDate = System.DateTime.Now; param.CreatedDate = System.DateTime.Now; // 是否有附件 param.AttachmentFileCount = AttachmentStorageContext.Instance.AttachmentFileService.FindAllByEntityId(KernelContext.ParseObjectType(typeof(ForumCommentInfo)), param.Id).Count; string categoryId = XmlHelper.Fetch("categoryId", doc); // 保存操作 this.service.Save(param); string tipInfo = "保存成功!"; ForumCategoryInfo categoryInfo = ForumContext.Instance.ForumCategoryService.FindOne(categoryId); if (categoryInfo != null) { int score = categoryInfo.PublishCommentPoint; ForumContext.Instance.ForumMemberService.SetPoint(param.AccountId, 1); tipInfo = "回复帖子成功,积分+" + score + "!"; } return("{\"message\":{\"returnCode\":0,\"value\":\"" + tipInfo + "\",\"commentId\":\"" + Guid.NewGuid().ToString() + "\"}}"); }
/// <summary>忘记密码</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string ForgotPassword(XmlDocument doc) { string mobile = XmlHelper.Fetch("mobile", doc); string email = XmlHelper.Fetch("email", doc); IAccountInfo account = null; if (!string.IsNullOrEmpty(mobile)) { account = MembershipManagement.Instance.AccountService.FindOneByCertifiedMobile(mobile); if (account != null) { VerificationCodeInfo verificationCode = VerificationCodeContext.Instance.VerificationCodeService.Create("Mobile", mobile, "忘记密码"); EmailClientContext.Instance.Send(mobile, "密码找回", string.Format("尊敬的用户,\r\n您好,您正在通过忘记密码功能找回密码。当前验证码:{0}, \r\nIP:{1}\r\nDate:{2} ", verificationCode.Code, IPQueryContext.GetClientIP(), DateTime.Now.ToString())); return("{message:{\"returnCode\":0,\"value\":\"验证码发送成功。\"}}"); } else { return("{message:{\"returnCode\":1,\"value\":\"验证码发送失败,不存在的手机号码。\"}}"); } } else if (!string.IsNullOrEmpty(email)) { account = MembershipManagement.Instance.AccountService.FindOneByCertifiedEmail(email); if (account != null) { VerificationCodeInfo verificationCode = VerificationCodeContext.Instance.VerificationCodeService.Create("Mail", email, "忘记密码"); IPQueryContext.GetClientIP(); // 您好 {date} 您通过了忘记密码功能找回密码。验证码: {code} // // IP 地址 EmailClientContext.Instance.Send(email, "密码找回", string.Format("尊敬的用户,\r\n您好,您正在通过忘记密码功能找回密码。当前验证码:{0}, \r\nIP:{1}\r\nDate:{2} ", verificationCode.Code, IPQueryContext.GetClientIP(), DateTime.Now.ToString())); return("{message:{\"returnCode\":0,\"value\":\"验证码发送成功。\"}}"); } else { return("{message:{\"returnCode\":1,\"value\":\"验证码发送失败,不存在的邮箱地址。\"}}"); } } return("{message:{\"returnCode\":2,\"value\":\"必须填写手机号码或邮箱地址。\"}}"); }
/// <summary>注销</summary> public ActionResult SignOut() { string accountIdentityName = KernelContext.Current.AuthenticationManagement.IdentityName; // 获取当前用户信息 IAccountInfo account = KernelContext.Current.User; KernelContext.Current.AuthenticationManagement.Logout(); // ------------------------------------------------------- // Session // ------------------------------------------------------- Session.Abandon(); HttpAuthenticationCookieSetter.ClearUserCookies(); Response.Cookies[accountIdentityName].Value = null; Response.Cookies[accountIdentityName].Expires = DateTime.Now.AddDays(-1); // ------------------------------------------------------- // IIdentity // ------------------------------------------------------- if (this.User != null && this.User.Identity.IsAuthenticated) { FormsAuthentication.SignOut(); } // 记录帐号操作日志 MembershipManagement.Instance.AccountLogService.Log(account.Id, "退出", string.Format("【{0}】在 {1} 登录了系统。【IP:{2}】", account.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), IPQueryContext.GetClientIP())); return(View("/views/" + LocateFolder("main") + "/account/sign-out.cshtml")); }
/// <summary></summary> /// <param name="accountId"></param> /// <param name="phoneNumber"></param> /// <param name="validationType"></param> /// <returns></returns> public int Send(string accountId, string phoneNumber, string validationType) { if (string.IsNullOrEmpty(phoneNumber)) { throw new NullReferenceException(phoneNumber); } string objectType = VerificationObjectType.Mobile.ToString(); // 获取验证码信息 VerificationCodeInfo verificationCode = VerificationCodeContext.Instance.VerificationCodeService.Create(objectType, phoneNumber, validationType, IPQueryContext.GetClientIP()); // 获取验证模板信息 VerificationCodeTemplateInfo template = VerificationCodeContext.Instance.VerificationCodeTemplateService.FindOne(objectType, validationType); string messageContent = TemplateContentContext.Instance.TemplateContentService.GetHtml(template.TemplateContentName); string serialNumber = DateTime.Now.ToString("yyyyMMddHHmmssfff") + StringHelper.ToRandom("0123456789", 3); // 设置短信内容 ShortMessage message = new ShortMessage(); message.SerialNumber = serialNumber; message.PhoneNumber = phoneNumber; message.MessageContent = string.Format(messageContent, verificationCode.Code); if (string.IsNullOrEmpty(template.Options)) { template.Options = "{}"; } // 在参数中加入验证码对象 template.Options = template.Options.Insert(1, "\"code\":\"" + verificationCode.Code + "\","); // 设置短信模板代码 JsonData data = JsonMapper.ToObject(template.Options); message.MessageTemplateCode = JsonHelper.GetDataValue(data, "templateCode"); // message.MessageTemplateParam = "{\"code\":\"" + verificationCode.Code + "\",\"product\":\"" + JsonHelper.GetDataValue(data, "product") + "\"}"; message.MessageTemplateParam = data.ToJson(); // 发送短信 string returnCode = client.Send(message); // 保存结果至数据库 this.provider.Send(serialNumber, accountId, phoneNumber, message.MessageContent, returnCode); if (string.IsNullOrEmpty(returnCode)) { return(0); } return(Convert.ToInt32(returnCode)); }
/// <summary></summary> public override void ProcessRequest(HttpContext context) { string responseText = string.Empty; // 示例: /api/application.method.hi.aspx // 获取客户端签名 clientId 和 clientSecret 或 clientId, clientSignature, timestamp, nonce string clientId = this.TryFetchRequstValue(context, "clientId", "client_id"); string clientSecret = this.TryFetchRequstValue(context, "clientSecret", "client_secret"); string clientSignature = this.TryFetchRequstValue(context, "clientSignature", "client_signature"); string timestamp = context.Request["timestamp"] == null ? string.Empty : context.Request["timestamp"]; string nonce = context.Request["nonce"] == null ? string.Empty : context.Request["nonce"]; string accessToken = this.TryFetchRequstValue(context, "accessToken", "access_token"); string name = context.Request.QueryString["name"]; // 验证权限 bool allowAccess = false; if (!string.IsNullOrEmpty(accessToken) && ConnectContext.Instance.ConnectAccessTokenService.IsExist(accessToken)) { // 验证会话 allowAccess = true; } else if (!string.IsNullOrEmpty(clientId)) { // 2.第三方应用连接 ConnectInfo connect = ConnectContext.Instance.ConnectService[clientId]; if (connect == null) { allowAccess = false; } else { if (!string.IsNullOrEmpty(clientSignature) && !string.IsNullOrEmpty(timestamp) && !string.IsNullOrEmpty(nonce)) { // 加密方式签名 var signature = Encrypter.EncryptSHA1(Encrypter.SortAndConcat(connect.AppSecret, timestamp, nonce)); if (clientSignature == signature) { allowAccess = true; } } else if (!string.IsNullOrEmpty(clientSecret) && connect.AppSecret == clientSecret) { // 明文客户端密钥 allowAccess = true; } else if (name == "connect.auth.authorize" || name == "connect.auth.token" || name == "connect.auth.callback" || name == "connect.oauth2.authorize" || name == "connect.oauth2.token" || name == "connect.oauth2.callback" || name == "session.me") { // 3.如果以上场景都不是,确认是否是用户登录验证的方法 allowAccess = true; } else { allowAccess = false; } } } else if (name == "membership.member.login" || name == "session.me") { // 3.如果以上场景都不是,确认是否是用户登录验证的方法 allowAccess = true; } if (!allowAccess) { ApplicationError.Write(401); } string xml = (context.Request.Form["xhr-xml"] == null) ? string.Empty : context.Request.Form["xhr-xml"]; if (!string.IsNullOrEmpty(name) && (!string.IsNullOrEmpty(xml) || context.Request.QueryString.Count > 1)) { XmlDocument doc = new XmlDocument(); if (string.IsNullOrEmpty(xml)) { doc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<root></root>"); } else { doc.LoadXml(xml); } // 将 QueryString 中,除 xhr-name 外的所有参数转为统一的Xml文档的数据 if (context.Request.QueryString.Count > 1) { for (int i = 0; i < context.Request.QueryString.Count; i++) { if (context.Request.QueryString.Keys[i] == null) { continue; } if (context.Request.QueryString.Keys[i] != "xhr-name") { XmlElement element = CreateXmlElement(doc, context.Request.QueryString.Keys[i]); element.InnerText = context.Request.QueryString[i]; doc.DocumentElement.AppendChild(element); } } } // 将表单中,除 xhr-name 和 xhr-xml 外的所有参数转为统一的Xml文档的数据 if (context.Request.HttpMethod == "POST" && context.Request.Form.Count > 1) { for (int i = 0; i < context.Request.Form.Count; i++) { if (context.Request.Form.Keys[i] == null) { continue; } if (context.Request.Form.Keys[i] != "xhr-name" && context.Request.Form.Keys[i] != "xhr-xml") { XmlElement element = CreateXmlElement(doc, context.Request.Form.Keys[i]); element.InnerText = context.Request.Form[i]; doc.DocumentElement.AppendChild(element); } } } string clientTargetObject = XmlHelper.Fetch("clientTargetObject", doc); string resultType = (context.Request.Form["resultType"] == null) ? "json" : context.Request.Form["resultType"]; // 设置输出的内容类型,默认为 json 格式。 HttpContentTypeHelper.SetValue(resultType); try { // 记录 if (ConnectConfigurationView.Instance.EnableCallLog == "ON") { ConnectCallInfo call = new ConnectCallInfo(clientId, context.Request.RawUrl, doc.InnerXml); try { call.Start(); responseText = X3Platform.Web.APIs.Methods.MethodInvoker.Invoke(name, doc, logger); call.ReturnCode = 0; } catch { call.ReturnCode = 1; throw; } finally { call.Finish(); call.IP = IPQueryContext.GetClientIP(); ConnectContext.Instance.ConnectCallService.Save(call); } } else { responseText = X3Platform.Web.APIs.Methods.MethodInvoker.Invoke(name, doc, logger); } if (resultType == "json" && responseText.IndexOf("\"message\":") > -1 && !string.IsNullOrEmpty(clientTargetObject)) { responseText = responseText.Insert(responseText.IndexOf("\"message\":"), "\"clientTargetObject\":\"" + clientTargetObject + "\","); } } catch (ThreadAbortException threadAbortException) { responseText = "{\"message\":{" + "\"returnCode\":\"2\"," + "\"category\":\"exception\"," + "\"value\":\"" + StringHelper.ToSafeJson(threadAbortException.Message) + "\"," + "\"description\":\"" + StringHelper.ToSafeJson(threadAbortException.ToString()) + "\"" + "}}"; } catch (Exception generalException) { responseText = "{\"message\":{" + "\"returnCode\":\"1\"," + "\"category\":\"exception\"," + "\"value\":\"" + StringHelper.ToSafeJson(generalException.Message) + "\"," + "\"description\":\"" + StringHelper.ToSafeJson(generalException.ToString()) + "\"" + "}}"; } HttpContext.Current.Response.ContentType = HttpContentTypeHelper.GetValue(true); HttpContext.Current.Response.Write(responseText); HttpContext.Current.Response.End(); } }
/// <summary></summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string SendVerificationMail(XmlDocument doc) { if (SecurityConfigurationView.Instance.CaptchaMode == "ON") { // 验证码 string captcha = XmlHelper.Fetch("captcha", doc); if (HttpContext.Current.Session["captcha"] == null || captcha != HttpContext.Current.Session["captcha"].ToString()) { return("{\"message\":{\"returnCode\":1,\"value\":\"验证码错误。\"}}"); } } // 检查验证码发送时间 if (HttpContext.Current.Session["VerificationCodeSendTime"] != null && HttpContext.Current.Session["VerificationCodeSendTime"] is DateTime) { DateTime time = (DateTime)HttpContext.Current.Session["VerificationCodeSendTime"]; if (time.AddSeconds(VerificationCodeConfigurationView.Instance.SendInterval) > DateTime.Now) { return("{\"message\":{\"returnCode\":1,\"value\":\"发送太频繁,请稍后再试。\"}}"); } } // 邮件地址 string email = XmlHelper.Fetch("email", doc); // 验证类型 string validationType = XmlHelper.Fetch("validationType", doc); VerificationCodeInfo verificationCode = VerificationCodeContext.Instance.VerificationCodeService.Create("Mail", email, validationType, IPQueryContext.GetClientIP()); VerificationCodeTemplateInfo template = VerificationCodeContext.Instance.VerificationCodeTemplateService.FindOne("Mail", validationType); JsonData options = JsonMapper.ToObject(template.Options); string content = TemplateContentContext.Instance.TemplateContentService.GetHtml(template.TemplateContentName); EmailClientContext.Instance.Send(email, JsonHelper.GetDataValue(options, "subject"), string.Format(content, verificationCode.Code), EmailFormat.Html); HttpContext.Current.Session["VerificationCodeSendTime"] = DateTime.Now; return("{\"message\":{\"returnCode\":0,\"value\":\"发送成功。\"}}"); }
//------------------------------------------------------- // 保存 删除 //------------------------------------------------------- #region 函数:SetMemberCard(XmlDocument doc) /// <summary>设置员工卡片信息</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string SetMemberCard(XmlDocument doc) { IAccountInfo account = KernelContext.Current.User; MemberInfo member = new MemberInfo(); MemberExtensionInformation memberProperties = new MemberExtensionInformation(); member = (MemberInfo)AjaxUtil.Deserialize(member, doc); member.ExtensionInformation.Load(doc); // 更新自己的帐号信息 member.Id = member.AccountId = account.Id; if (string.IsNullOrEmpty(member.AccountId)) { return("{\"message\":{\"returnCode\":1,\"value\":\"必须填写相关帐号标识。\"}}"); } else { member.Account.IdentityCard = XmlHelper.Fetch("identityCard", doc); } this.service.SetMemberCard(member); // 记录帐号操作日志 MembershipManagement.Instance.AccountLogService.Log(account.Id, "hr.general.setMemberCard", "【" + account.Name + "】更新了自己的个人信息,【IP:" + IPQueryContext.GetClientIP() + "】。", account.Id); return(MessageObject.Stringify("0", I18n.Strings["msg_save_success"])); }
/// <summary></summary> /// <param name="doc"></param> /// <returns></returns> public string SetGlobalName(XmlDocument doc) { string id = XmlHelper.Fetch("id", doc); string globalName = XmlHelper.Fetch("globalName", doc); IAccountInfo account = MembershipManagement.Instance.AccountService.FindOne(id); IAccountInfo optionAccount = KernelContext.Current.User; if (account == null || optionAccount == null) { return("{message:{\"returnCode\":1,\"value\":\"未检测到当前用户的合法信息。\"}}"); } int reuslt = this.service.SetGlobalName(id, globalName); MembershipManagement.Instance.AccountLogService.Log(account.Id, "设置全局名称", "【" + optionAccount.Name + "】将用户【" + account.Name + "】的全局名称设置为【" + globalName + "】,【IP:" + IPQueryContext.GetClientIP() + "】。", optionAccount.Id); return("{\"message\":{\"returnCode\":0,\"value\":\"设置全局名称成功。\"}}"); }
/// <summary>获取认证的用户信息</summary> public override IAccountInfo GetAuthUser() { string accountIdentity = this.GetIdentityValue(); IAccountInfo account = SessionContext.Instance.GetAuthAccount <AccountInfo>(strategy, accountIdentity); if (account == null && HttpContext.Current.User.Identity.IsAuthenticated) { string longinName = HttpContext.Current.User.Identity.Name; int index = longinName.IndexOf("\\") + 1; longinName = longinName.Substring(index, longinName.Length - index); account = MembershipManagement.Instance.AccountService.FindOneByLoginName(longinName); if (account == null) { return(null); } else { SessionContext.Instance.Write(this.strategy, accountIdentity, account); HttpAuthenticationCookieSetter.SetUserCookies(accountIdentity); // 记录登录时间 if (account.LoginDate.AddHours(8) < DateTime.Now) { MembershipManagement.Instance.AccountService.SetIPAndLoginDate(account.Id, IPQueryContext.GetClientIP(), DateTime.Now); } } } if (account != null && HttpContext.Current.User.Identity.IsAuthenticated) { HttpAuthenticationCookieSetter.SetUserCookies(accountIdentity); return(account); } else { return(null); } }
// ------------------------------------------------------- // 注册帐号 // ------------------------------------------------------- #region 函数:Register(XmlDocument doc) /// <summary>注册帐号</summary> /// <param name="doc">Xml 文档对象</param> /// <returns></returns> public string Register(XmlDocument doc) { IAccountInfo param = new AccountInfo(); // Registration 注册类型: email | mobile | default string registration = XmlHelper.Fetch("registration", doc); // 登陆名 string loginName = XmlHelper.Fetch("loginName", doc); // 姓名 string name = XmlHelper.Fetch("name", doc); // 手机号码 string mobile = XmlHelper.Fetch("mobile", doc); // 邮箱 string email = XmlHelper.Fetch("email", doc); // 密码 string password = XmlHelper.Fetch("password", doc); string code = XmlHelper.Fetch("code", doc); if (registration == "mail") { if (string.IsNullOrEmpty(email)) { return("{\"message\":{\"returnCode\":1,\"value\":\"必须填写电子邮箱。\"}}"); } if (MembershipManagement.Instance.AccountService.IsExistCertifiedEmail(email)) { return("{\"message\":{\"returnCode\":1,\"value\":\"此邮箱已经存在。\"}}"); } if (!VerificationCodeContext.Instance.VerificationCodeService.Validate("Mail", email, "用户注册", code)) { return("{\"message\":{\"returnCode\":1,\"value\":\"邮件验证码错误。\"}}"); } param.LoginName = email; param.DisplayName = ((AccountInfo)param).Name = ((AccountInfo)param).GlobalName = email; param.CertifiedEmail = email; if (MembershipManagement.Instance.AccountService.IsExistLoginName(param.LoginName)) { return("{\"message\":{\"returnCode\":1,\"value\":\"此登录名已经存在。\"}}"); } } else if (registration == "mobile") { if (string.IsNullOrEmpty(mobile)) { return("{\"message\":{\"returnCode\":1,\"value\":\"必须填写手机号码。\"}}"); } if (MembershipManagement.Instance.AccountService.IsExistCertifiedMobile(mobile)) { return("{\"message\":{\"returnCode\":1,\"value\":\"此手机号码已经存在。\"}}"); } if (!VerificationCodeContext.Instance.VerificationCodeService.Validate("Mobile", mobile, "用户注册", code)) { return("{\"message\":{\"returnCode\":1,\"value\":\"短信验证码错误。\"}}"); } param.LoginName = mobile; param.DisplayName = ((AccountInfo)param).Name = mobile; param.CertifiedMobile = mobile; if (MembershipManagement.Instance.AccountService.IsExistLoginName(param.LoginName)) { return("{\"message\":{\"returnCode\":1,\"value\":\"此登录名已经存在。\"}}"); } } else { if (string.IsNullOrEmpty(loginName) || string.IsNullOrEmpty(name)) { return("{\"message\":{\"returnCode\":1,\"value\":\"必须填写登录名和全局名称。\"}}"); } if (MembershipManagement.Instance.AccountService.IsExistLoginNameAndGlobalName(loginName, name)) { return("{\"message\":{\"returnCode\":1,\"value\":\"此登录名已经存在。\"}}"); } param.LoginName = loginName; ((AccountInfo)param).GlobalName = name; if (MembershipManagement.Instance.AccountService.IsExistLoginNameAndGlobalName(param.LoginName, param.GlobalName)) { return("{\"message\":{\"returnCode\":1,\"value\":\"此登录名已经存在。\"}}"); } } param.Id = DigitalNumberContext.Generate("Key_Guid"); param.LoginDate = new DateTime(1970, 1, 1); param.Status = 1; param.IP = IPQueryContext.GetClientIP(); param = MembershipManagement.Instance.AccountService.Save(param); if (param != null) { MembershipManagement.Instance.AccountService.SetPassword(param.Id, password); var result = this.service.Save(new MemberInfo() { Id = param.Id, AccountId = param.Id, Mobile = mobile }); if (result != null) { // 设置帐号在线状态信息 string accountIdentity = DigitalNumberContext.Generate("Key_Guid"); SessionContext.Instance.Write(KernelContext.Current.AuthenticationManagement.GetAccountStorageStrategy(), accountIdentity, param); HttpAuthenticationCookieSetter.SetUserCookies(accountIdentity); } } // this.RegisterMember(param.Id, doc); return("{\"message\":{\"returnCode\":0,\"value\":\"帐号注册成功。\"}}"); }
/// <summary>处理请求</summary> public static string ProcessRequest(HttpContextBase context, string methodName, string rawInput, ILog logger, APIInvokeDelegate methodInvoke) { // 请求响应的内容 string responseText = string.Empty; // clientId string clientId = RequestHelper.Fetch("clientId", new string[] { "client_id", "app_key", "appKey" }); // accessToken string accessToken = RequestHelper.Fetch("accessToken", "access_token"); // 默认支持 form-data 方式 string xml = (context.Request.Form["xhr-xml"] == null) ? string.Empty : context.Request.Form["xhr-xml"]; // 支持 application/xml 请求方式 if (context.Request.ContentType.IndexOf("application/xml") > -1 && string.IsNullOrEmpty(xml) && !string.IsNullOrEmpty(rawInput)) { xml = rawInput; } // 支持 application/json 请求方式 if (context.Request.ContentType.IndexOf("application/json") > -1 && string.IsNullOrEmpty(xml) && !string.IsNullOrEmpty(rawInput)) { XmlDocument xmlDoc = JsonHelper.ToXmlDocument(rawInput); xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<request>" + xmlDoc.DocumentElement.InnerXml + "</request>"; } if (!string.IsNullOrEmpty(xml) || context.Request.QueryString.Count > 0 || (context.Request.HttpMethod == "POST" && context.Request.Form.Count > 0)) { XmlDocument doc = new XmlDocument(); if (string.IsNullOrEmpty(xml)) { doc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<request></request>"); } else { doc.LoadXml(xml); } // 将 QueryString 中,除 xhr-name 外的所有参数转为统一的Xml文档的数据 if (context.Request.QueryString.Count > 0) { for (int i = 0; i < context.Request.QueryString.Count; i++) { if (string.IsNullOrEmpty(context.Request.QueryString.Keys[i])) { continue; } if (context.Request.QueryString.Keys[i] != "xhr-name" && context.Request.QueryString.Keys[i].IndexOf("[") == -1) { XmlElement element = doc.CreateElement(context.Request.QueryString.Keys[i]); element.InnerText = context.Request.QueryString[i]; doc.DocumentElement.AppendChild(element); } } doc = AnalyzePagingXml(doc, context.Request.QueryString); doc = AnalyzeQueryXml(doc, context.Request.QueryString); } // 将表单中,除 xhr-name 和 xhr-xml 外的所有参数转为统一的Xml文档的数据 if (context.Request.HttpMethod == "POST" && context.Request.Form.Count > 0) { for (int i = 0; i < context.Request.Form.Count; i++) { if (string.IsNullOrEmpty(context.Request.Form.Keys[i])) { continue; } if (context.Request.Form.Keys[i] != "xhr-name" && context.Request.Form.Keys[i] != "xhr-xml" && context.Request.Form.Keys[i].IndexOf("[") == -1) { XmlElement element = doc.CreateElement(context.Request.Form.Keys[i]); element.InnerText = context.Request.Form[i]; doc.DocumentElement.AppendChild(element); } } doc = AnalyzeQueryXml(doc, context.Request.QueryString); } string clientTargetObject = XmlHelper.Fetch("clientTargetObject", doc); try { // 记录 if (ConnectConfigurationView.Instance.EnableCallLog == "ON") { ConnectCallInfo call = new ConnectCallInfo(clientId, context.Request.RawUrl, string.IsNullOrEmpty(rawInput) ? doc.InnerXml : rawInput); call.AccessToken = accessToken; try { call.Start(); var responseObject = methodInvoke(methodName, doc, logger); responseText = call.ResponseData = (responseObject == null) ? string.Empty : responseObject.ToString(); if (call.RequestData.Length > 2048) { call.RequestData = "[Long String] " + call.RequestData.Length; } if (call.ResponseData.Length > 2048) { call.ResponseData = "[Long String] " + call.ResponseData.Length; } call.ReturnCode = 0; } catch { call.ReturnCode = 1; throw; } finally { call.Finish(); call.IP = IPQueryContext.GetClientIP(); ConnectContext.Instance.ConnectCallService.Save(call); } } else { var responseObject = methodInvoke(methodName, doc, logger); responseText = (responseObject == null) ? string.Empty : responseObject.ToString(); } if (responseText.IndexOf("\"message\":") > -1 && !string.IsNullOrEmpty(clientTargetObject)) { responseText = responseText.Insert(responseText.IndexOf("\"message\":"), "\"clientTargetObject\":\"" + clientTargetObject + "\","); } } catch (GenericException genericException) { responseText = genericException.ToString(); } catch (ThreadAbortException threadAbortException) { GenericException exception = new GenericException("9999", threadAbortException); responseText = exception.ToString(); } catch (Exception ex) { GenericException exception = null; if (ex.InnerException is GenericException) { exception = (GenericException)ex.InnerException; } else { exception = new GenericException("-1", ex); } responseText = exception.ToString(); } } // JSONP string callback = context.Request["callback"]; return(string.IsNullOrEmpty(callback) ? responseText : callback + "(" + responseText + ")"); }
/// <summary>上传头像</summary> /// <param name="doc"></param> /// <returns></returns> public string Upload(XmlDocument doc) { StringBuilder outString = new StringBuilder(); string data = XmlHelper.Fetch("data", doc); Bitmap bitmap = null; int height; int width; IAccountInfo account = KernelContext.Current.User; if (account == null) { return(MessageObject.Stringify("1", "必须登陆后才能上传头像。")); } string directoryName = this.GetDirectoryName(account.Id); string path = MembershipConfigurationView.Instance.AvatarPhysicalFolder + directoryName + "\\"; string filePath = null; if (!Directory.Exists(path)) { DirectoryHelper.Create(path); } byte[] buffer = Convert.FromBase64String(data); using (MemoryStream stream = new MemoryStream(buffer)) { bitmap = new Bitmap(stream); } string[] sizes = MembershipConfigurationView.Instance.AvatarSizes.Split(','); height = width = Convert.ToInt32(sizes[0]); filePath = string.Format(@"{0}\{1}_" + height + "x" + width + ".png", path, account.Id); bitmap = KiResizeImage(bitmap, width, height); bitmap.Save(filePath, ImageFormat.Png); // 设置头像记录 filePath = account.CertifiedAvatar = "{avatar}" + directoryName + "/" + account.Id + "_" + height + "x" + width + ".png"; MembershipManagement.Instance.AccountService.SetCertifiedAvatar(account.Id, filePath); IAccountStorageStrategy strategy = KernelContext.Current.AuthenticationManagement.GetAccountStorageStrategy(); string accountIdentity = KernelContext.Current.AuthenticationManagement.GetIdentityValue(); SessionContext.Instance.Write(strategy, accountIdentity, account); // 保存其他格式图片 for (int i = 1; i < sizes.Length; i++) { height = width = Convert.ToInt32(sizes[i]); filePath = string.Format(@"{0}\{1}_" + height + "x" + width + ".png", path, account.Id); bitmap = KiResizeImage(bitmap, height, height); bitmap.Save(filePath, ImageFormat.Png); } // 记录帐号操作日志 MembershipManagement.Instance.AccountLogService.Log(account.Id, "membership.account.avatar.upload", "【" + account.Name + "】更新了自己的头像,【IP:" + IPQueryContext.GetClientIP() + "】。", account.Id); return("{\"data\":{\"virtualPath\":\"" + account.CertifiedAvatar.Replace("{avatar}", MembershipConfigurationView.Instance.AvatarVirtualFolder).Replace("//", "/") + "\"},\"message\":{\"returnCode\":0,\"value\":\"上传成功。\"}}"); }
/// <summary>查询所有没有默认角色的用户信息</summary> /// <returns>返回一个相关的实例列表.</returns> public string SetContactCard(XmlDocument doc) { Dictionary <string, string> contactItems = new Dictionary <string, string>(); contactItems.Add("Mobile", XmlHelper.Fetch("mobile", doc)); contactItems.Add("Telephone", XmlHelper.Fetch("telephone", doc)); contactItems.Add("QQ", XmlHelper.Fetch("qq", doc)); contactItems.Add("MSN", XmlHelper.Fetch("msn", doc)); contactItems.Add("Email", XmlHelper.Fetch("email", doc)); contactItems.Add("Rtx", XmlHelper.Fetch("rtx", doc)); contactItems.Add("PostCode", XmlHelper.Fetch("postCode", doc)); contactItems.Add("Address", XmlHelper.Fetch("address", doc)); IAccountInfo account = KernelContext.Current.User; this.service.SetContactCard(account.Id, contactItems); // 记录帐号操作日志 MembershipManagement.Instance.AccountLogService.Log(account.Id, "设置联系方式", "【" + account.Name + "】更新了自己的联系信息,【IP:" + IPQueryContext.GetClientIP() + "】。", account.Id); return("{message:{\"returnCode\":0,\"value\":\"设置联系信息成功。\"}}"); }
/// <summary></summary> /// <param name="doc"></param> /// <returns></returns> public string SetStatus(XmlDocument doc) { string id = XmlHelper.Fetch("id", doc); int status = Convert.ToInt32(XmlHelper.Fetch("status", doc)); IAccountInfo account = MembershipManagement.Instance.AccountService.FindOne(id); IAccountInfo optionAccount = KernelContext.Current.User; if (account == null || optionAccount == null) { return("{message:{\"returnCode\":1,\"value\":\"未检测到当前用户的合法信息。\"}}"); } int reuslt = this.service.SetStatus(id, status); MembershipManagement.Instance.AccountLogService.Log(account.Id, "设置帐号状态", "【" + optionAccount.Name + "】将用户【" + account.Name + "】的状态设置为【" + (status == 0 ? "禁用" : "启用") + "】,【IP:" + IPQueryContext.GetClientIP() + "】。", optionAccount.Id); return("{\"message\":{\"returnCode\":0,\"value\":\"设置帐号状态成功。\"}}"); }
/// <summary></summary> public string SetLoginName(XmlDocument doc) { string id = XmlHelper.Fetch("id", doc); string loginName = XmlHelper.Fetch("loginName", doc); IAccountInfo account = MembershipManagement.Instance.AccountService.FindOne(id); IAccountInfo optionAccount = KernelContext.Current.User; if (account == null || optionAccount == null) { return("{message:{\"returnCode\":1,\"value\":\"未检测到当前用户的合法信息。\"}}"); } if (string.IsNullOrEmpty(loginName)) { return("{message:{\"returnCode\":1,\"value\":\"登录名不能为空。\"}}"); } else if (!this.service.IsExistLoginName(loginName)) { this.service.SetLoginName(id, loginName); // 记录帐号操作日志 MembershipManagement.Instance.AccountLogService.Log(account.Id, "设置登录名", "【" + optionAccount.Name + "】将用户【" + account.Name + "】的登录名设置为【" + loginName + "】,【IP:" + IPQueryContext.GetClientIP() + "】。", optionAccount.Id); return("{message:{\"returnCode\":0,\"value\":\"设置登录名成功。\"}}"); } else { return("{message:{\"returnCode\":1,\"value\":\"已存在此登录名。\"}}"); } }
/// <summary>设置密码</summary> public string SetPassword(XmlDocument doc) { string id = XmlHelper.Fetch("id", doc); string password = XmlHelper.Fetch("password", doc); IAccountInfo account = MembershipManagement.Instance.AccountService.FindOne(id); IAccountInfo optionAccount = KernelContext.Current.User; if (account == null || optionAccount == null) { return("{message:{\"returnCode\":1,\"value\":\"未检测到当前用户的合法信息。\"}}"); } this.service.SetPassword(id, password); // 记录帐号操作日志 MembershipManagement.Instance.AccountLogService.Log(account.Id, "设置密码", "【" + optionAccount.Name + "】重新设置了用户【" + account.Name + "】的密码,【IP:" + IPQueryContext.GetClientIP() + "】。", optionAccount.Id); return("{\"message\":{\"returnCode\":0,\"value\":\"设置密码成功。\"}}"); }
/// <summary>设置人员卡片信息</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string SetMemberCard(XmlDocument doc) { IAccountInfo account = KernelContext.Current.User; if (!HumanResourceManagement.IsHumanResourceOfficer(account)) { return("{\"message\":{\"returnCode\":1,\"value\":\"只有人力资源管理应用的管理员才能设置此信息。\"}}"); } MemberInfo member = new MemberInfo(); MemberExtensionInformation memberProperties = new MemberExtensionInformation(); member = (MemberInfo)AjaxUtil.Deserialize(member, doc); member.ExtensionInformation.Load(doc); if (string.IsNullOrEmpty(member.AccountId)) { return("{\"message\":{\"returnCode\":1,\"value\":\"必须填写相关帐号标识。\"}}"); } else { member.Account.Code = XmlHelper.Fetch("code", doc); member.Account.IdentityCard = XmlHelper.Fetch("identityCard", doc); } string partTimeJobsText = XmlHelper.Fetch("partTimeJobsText", doc); this.ResetPartTimeJobss(member, partTimeJobsText); HumanResourceManagement.Instance.GeneralAccountService.SetMemberCard(member); // 记录帐号操作日志 MembershipManagement.Instance.AccountLogService.Log(member.AccountId, "设置用户信息", "【" + account.Name + "】更新了【" + member.Account.Name + "】的个人信息,【IP:" + IPQueryContext.GetClientIP() + "】。", account.Id); return("{\"message\":{\"returnCode\":0,\"value\":\"设置用户信息成功。\"}}"); }
/// <summary>获取认证的用户信息</summary> public override IAccountInfo GetAuthUser() { string accountIdentity = this.GetIdentityValue(); // 获取帐号信息 IAccountInfo account = this.GetSessionAccount(accountIdentity); if (account == null) { // 如果当前帐号为空, 则连接到验证服务器验证用户的会话信息. string loginName = GetAccountLoginName(); // 没有登录信息则返回空 if (string.IsNullOrEmpty(loginName)) { return(null); } account = MembershipManagement.Instance.AccountService.FindOneByLoginName(loginName); if (account != null && account.LoginName == loginName) { accountIdentity = string.Format("{0}-{1}", account.Id, DigitalNumberContext.Generate("Key_Session")); HttpAuthenticationCookieSetter.SetUserCookies(accountIdentity); // 记录登录时间 if (account.LoginDate.AddHours(8) < DateTime.Now) { MembershipManagement.Instance.AccountService.SetIPAndLoginDate(account.Id, IPQueryContext.GetClientIP(), DateTime.Now); } } } if (account == null) { return(null); } // 写入临时存储 if (!this.cacheStorage.ContainsKey(accountIdentity)) { lock (this.cacheSyncRoot) { if (!this.cacheStorage.ContainsKey(accountIdentity)) { this.AddSession(accountIdentity, account); } } } return(account); }
// ------------------------------------------------------- // 登录帐号 // ------------------------------------------------------- #region 函数:Auth(XmlDocument doc) /// <summary>验证</summary> public string Auth(XmlDocument doc) { // ------------------------------------------------------- // 验证码 验证 // ------------------------------------------------------- // 帐号信息 IAccountInfo account = null; // 用户信息 IMemberInfo member = null; string loginName = XmlHelper.Fetch("loginName", doc); string password = XmlHelper.Fetch("password", doc); switch (KernelConfigurationView.Instance.AuthenticationManagementType) { // Http 方式验证 (生产环境) case "X3Platform.Membership.Authentication.HttpAuthenticationManagement,X3Platform.Membership": string serverValidateCode = (HttpContext.Current.Session["ServerValidateCode"] == null ? string.Empty : HttpContext.Current.Session["AdminCheckCode"].ToString()); string clientValidateCode = XmlHelper.Fetch("validatecode", doc); if (string.IsNullOrEmpty(clientValidateCode)) { // -*- 不设置验证码 -*- // 3.验证码失效. // return "{\"message\":{\"returnCode\":3,\"value\":\"验证码失效。\"}}"; } else if (clientValidateCode != serverValidateCode.ToUpper()) { // 2.验证码不匹配. return("{\"message\":{\"returnCode\":2,\"value\":\"验证码不匹配。\"}}"); } account = MembershipManagement.Instance.AccountService.LoginCheck(loginName, password); break; // Http 方式验证 (测试环境) case "X3Platform.Membership.Authentication.MockAuthenticationManagement,X3Platform.Membership": if (password == MembershipConfigurationView.Instance.MockAuthenticationPassword) { account = MembershipManagement.Instance.AccountService.FindOneByLoginName(loginName); } else { return("{\"message\":{\"returnCode\":1,\"value\":\"密码错误, 系统当前的验证方式是模拟测试验证, 请从联系管理员获取测试密码。\"}}"); } break; case "X3Platform.Membership.Authentication.NLMAuthenticationManagement,X3Platform.Membership": return("{\"message\":{\"returnCode\":1,\"value\":\"系统当前的验证方式是Windows集成验证, 请使用Windows验证方式登录。\"}}"); case "X3Platform.Membership.Authentication.SSOAuthenticationManagement,X3Platform.Membership": return("{\"message\":{\"returnCode\":1,\"value\":\"系统当前的验证方式是单点登录验证, 请从门户登录。\"}}"); default: return("{\"message\":{\"returnCode\":1,\"value\":\"系统未设置任何登录方式, 请从联系管理员。\"}}"); } if (account == null) { // 1.用户名和密码不正确. return("{\"message\":{\"returnCode\":1,\"value\":\"用户名和密码不正确。\"}}"); } else { if (account.Status == 0) { // 2.用户名和密码不正确. return("{\"message\":{\"returnCode\":1,\"value\":\"此帐号被禁用,如有问题请联系提供管理员。\"}}"); } MembershipManagement.Instance.AccountService.SetIPAndLoginDate(account.Id, IPQueryContext.GetClientIP(), DateTime.Now); member = this.service.FindOne(account.Id); // 4.此帐号无此权限,请联系管理员。 if (member == null) { return("{\"message\":{\"returnCode\":4,\"value\":\"此帐号无此权限,请联系管理员。\"}}"); } // 设置帐号在线状态信息 member.Account.LoginName = loginName; member.Account.IP = IPQueryContext.GetClientIP(); string accountIdentity = string.Format("{0}-{1}", account.Id, DigitalNumberContext.Generate("Key_Session")); KernelContext.Current.AuthenticationManagement.AddSession(string.Empty, accountIdentity, account); HttpAuthenticationCookieSetter.SetUserCookies(accountIdentity); // 设置本地登录帐号 HttpContext.Current.Response.Cookies.Add(new HttpCookie("session-local-account", "{\"id\":\"" + account.Id + "\",\"name\":\"" + HttpUtility.UrlEncode(account.Name) + "\",\"loginName\":\"" + account.LoginName + "\"}")); // 设置本地服务器状态 HttpContext.Current.Response.Cookies.Add(new HttpCookie("session-local-status", "1")); MembershipManagement.Instance.AccountLogService.Log(account.Id, "membership.member.quit", string.Format("【{0}】在 {1} 登录了系统。【IP:{2}】", ((IAuthorizationObject)member.Account).Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), member.Account.IP)); FormsAuthentication.SetAuthCookie(loginName, false); } return("{\"message\":{\"returnCode\":0,\"value\":\"登录成功。\"}}"); }
/// <summary></summary> public string ChangePassword(XmlDocument doc) { string id = XmlHelper.Fetch("id", doc); string loginName = XmlHelper.Fetch("loginName", doc); string password = XmlHelper.Fetch("password", doc); string originalPassword = XmlHelper.Fetch("originalPassword", doc); IAccountInfo account = MembershipManagement.Instance.AccountService.FindOneByLoginName(loginName); IAccountInfo optionAccount = KernelContext.Current.User; if (account == null || optionAccount == null) { return("{message:{\"returnCode\":1,\"value\":\"未检测到当前用户的合法信息。\"}}"); } if (optionAccount.LoginName == loginName) { int result = this.service.ChangePassword(loginName, password, originalPassword); if (result == 0) { // 记录帐号操作日志 MembershipManagement.Instance.AccountLogService.Log(optionAccount.Id, "修改密码", "用户【" + optionAccount.Name + "】修改密码成功。"); return("{message:{\"returnCode\":0,\"value\":\"修改成功。\"}}"); } else { // 记录帐号操作日志 MembershipManagement.Instance.AccountLogService.Log(optionAccount.Id, "修改密码", "用户【" + optionAccount.Name + "】修改密码失败,【IP:" + IPQueryContext.GetClientIP() + "】。"); return("{message:{\"returnCode\":1,\"value\":\"修改失败, 用户或密码错误.\"}}"); } } else { // 记录帐号操作日志 MembershipManagement.Instance.AccountLogService.Log(account.Id, "修改密码", "【" + optionAccount.Name + "】尝试修改另一个用户【" + account.Name + "】的密码,【IP:" + IPQueryContext.GetClientIP() + "】。", optionAccount.Id); return("{message:{\"returnCode\":1,\"value\":\"修改失败, 用户或密码错误.\"}}"); } }
// ------------------------------------------------------- // 保存 删除 // ------------------------------------------------------- #region 函数:Save(XmlDocument doc) /// <summary>保存记录</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string Save(XmlDocument doc) { ForumThreadInfo param = new ForumThreadInfo(); param = (ForumThreadInfo)AjaxUtil.Deserialize(param, doc); if (string.IsNullOrEmpty(param.Title.Trim())) { return("{\"message\":{\"returnCode\":\"1\",\"value\":\"帖子标题不能为空。\"}}"); } param.Id = param.Id == "" ? Guid.NewGuid().ToString() : param.Id; param.CommentCount = ForumContext.Instance.ForumCommentService.GetCommentCount(param.Id); // 是否有附件 param.AttachmentFileCount = AttachmentStorageContext.Instance.AttachmentFileService.FindAllByEntityId(KernelContext.ParseObjectType(typeof(ForumThreadInfo)), param.Id).Count; // 查询最后回帖信息 string lastCommentInfo = ForumContext.Instance.ForumCommentService.GetLastComment(param.Id); if (!string.IsNullOrEmpty(lastCommentInfo)) { string[] info = lastCommentInfo.Split(','); param.LatestCommentAccountId = info[0]; param.LatestCommentAccountName = info[1]; } if (!string.IsNullOrEmpty(param.UpdateHistoryLog)) { param.UpdateHistoryLog = "该内容已在" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "被" + KernelContext.Current.User.Name + "编辑过。"; } param.IP = IPQueryContext.GetClientIP(); bool isNewObject = !this.service.IsExist(param.Id); // 保存操作 this.service.Save(param); string message = "保存成功。"; if (param.Status == 1) { ForumCategoryInfo categoryInfo = ForumContext.Instance.ForumCategoryService.FindOne(param.CategoryId); if (categoryInfo != null) { if (this.service.IsExist(param.Id) && !string.IsNullOrEmpty(param.UpdateHistoryLog)) { message = "帖子修改成功。"; } else { int score = categoryInfo == null ? 0 : categoryInfo.PublishThreadPoint; ForumContext.Instance.ForumMemberService.SetPoint(param.AccountId, score); ForumContext.Instance.ForumMemberService.SetThreadCount(param.AccountId); message = "帖子发布成功。"; if (param.Anonymous == 0) { // 发送 Timeline 数据 ApplicationInfo application = AppsContext.Instance.ApplicationService[ForumConfiguration.ApplicationName]; Uri actionUri = new Uri(KernelConfigurationView.Instance.HostName + "/api/timeline.save.aspx?client_id=" + application.Id + "&client_secret=" + application.ApplicationSecret); string taskCode = DigitalNumberContext.Generate("Key_Guid"); string content = string.Format("发布了帖子【{0}】。<a href=\"{1}/forum/article/{2}.aspx\" target=\"_blank\" >网页链接</a>", param.Title, KernelConfigurationView.Instance.HostName, param.Id); string xml = string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?> <request> <id><![CDATA[{0}]]></id> <applicationId><![CDATA[{1}]]></applicationId> <accountId><![CDATA[{2}]]></accountId> <content><![CDATA[{3}]]></content> </request> ", taskCode, application.Id, KernelContext.Current.User.Id, content); // 发送请求信息 AjaxRequestData reqeustData = new AjaxRequestData(); reqeustData.ActionUri = actionUri; reqeustData.Args.Add("xml", xml); AjaxRequest.RequestAsync(reqeustData, null); } } } } return("{\"message\":{\"returnCode\":\"0\",\"value\":\"" + message + "\"}}"); }
// ------------------------------------------------------- // 退出帐号 // ------------------------------------------------------- #region 函数:Quit(XmlDocument doc) /// <summary>退出</summary> public string Quit(XmlDocument doc) { string identityName = KernelContext.Current.AuthenticationManagement.IdentityName; // 获取当前用户信息 IAccountInfo account = KernelContext.Current.User; KernelContext.Current.AuthenticationManagement.Logout(); // ------------------------------------------------------- // Session // ------------------------------------------------------- HttpContext.Current.Session.Clear(); // Mono 2.10.9 版本的 InProc 模式下调用 Session.Abandon() 会引发如下错误 // System.NullReferenceException: Object reference not set to an instance of an object at // System.Web.SessionState.SessionInProcHandler.GetItemInternal (System.Web.HttpContext context, System.String id, System.Boolean& locked, System.TimeSpan& lockAge, System.Object& lockId, System.Web.SessionState.SessionStateActions& actions, Boolean exclusive) if (Environment.OSVersion.Platform == PlatformID.Win32NT) { HttpContext.Current.Session.Abandon(); } HttpAuthenticationCookieSetter.ClearUserCookies(); HttpContext.Current.Response.Cookies[identityName].Value = null; HttpContext.Current.Response.Cookies[identityName].Expires = DateTime.Now.AddDays(-1); // ------------------------------------------------------- // IIdentity // ------------------------------------------------------- if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated) { FormsAuthentication.SignOut(); } // 记录帐号操作日志 MembershipManagement.Instance.AccountLogService.Log(account.Id, "membership.member.quit", string.Format("【{0}】在 {1} 退出了系统。【IP:{2}】", account.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), IPQueryContext.GetClientIP())); return("{\"message\":{\"returnCode\":0,\"value\":\"已成功退出。\"}}"); }
// ------------------------------------------------------- // 接口地址:/api/connect.auth.authorize.aspx // ------------------------------------------------------- #region 函数:GetAuthorizeCode(XmlDocument doc) /// <summary>获取详细信息</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string GetAuthorizeCode(XmlDocument doc) { StringBuilder outString = new StringBuilder(); string clientId = XmlHelper.Fetch("clientId", doc); string redirectUri = XmlHelper.Fetch("redirectUri", doc); string responseType = XmlHelper.Fetch("responseType", doc); string scope = XmlHelper.Fetch("scope", doc); string style = XmlHelper.Fetch("style", doc); string loginName = XmlHelper.Fetch("loginName", doc); string password = XmlHelper.Fetch("password", doc); if (string.IsNullOrEmpty(loginName) || string.IsNullOrEmpty(password)) { HttpContentTypeHelper.SetValue("html"); return(CreateLoginPage(clientId, redirectUri, responseType, scope)); } else { // 当前用户信息 IAccountInfo account = MembershipManagement.Instance.AccountService.LoginCheck(loginName, password); if (account == null) { if (string.IsNullOrEmpty(responseType)) { outString.Append("{\"message\":{\"returnCode\":1,\"value\":\"帐号或者密码错误。\"}}"); return(outString.ToString()); } else { // 输出登录页面 // 设置输出的内容类型,默认为 html 格式。 HttpContentTypeHelper.SetValue("html"); return(CreateLoginPage(clientId, redirectUri, responseType, scope)); } } else { // 检验是否有授权码 if (!ConnectContext.Instance.ConnectAuthorizationCodeService.IsExist(clientId, account.Id)) { ConnectAuthorizationCodeInfo authorizationCode = new ConnectAuthorizationCodeInfo(); authorizationCode.Id = DigitalNumberContext.Generate("Key_32DigitGuid"); authorizationCode.AppKey = clientId; authorizationCode.AccountId = account.Id; authorizationCode.AuthorizationScope = string.IsNullOrEmpty(scope) ? "public" : scope; ConnectContext.Instance.ConnectAuthorizationCodeService.Save(authorizationCode); } // 设置访问令牌 ConnectContext.Instance.ConnectAccessTokenService.Write(clientId, account.Id); // 设置会话信息 ConnectAccessTokenInfo token = ConnectContext.Instance.ConnectAccessTokenService.FindOneByAccountId(clientId, account.Id); // 记录日志 string ip = IPQueryContext.GetClientIP(); MembershipManagement.Instance.AccountService.SetIPAndLoginDate(account.Id, ip, DateTime.Now); MembershipManagement.Instance.AccountLogService.Log(account.Id, "connect.auth.authorize", string.Format("【{0}】在 {1} 登录了系统。【IP:{2}】", account.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ip)); string sessionId = token.AccountId + "-" + token.Id; KernelContext.Current.AuthenticationManagement.AddSession(clientId, sessionId, account); HttpAuthenticationCookieSetter.SetUserCookies(sessionId); string code = ConnectContext.Instance.ConnectAuthorizationCodeService.GetAuthorizationCode(clientId, account); // responseType == null 则输出令牌信息 if (string.IsNullOrEmpty(responseType)) { outString.Append("{\"data\":" + AjaxUtil.Parse <ConnectAccessTokenInfo>(token) + ","); outString.Append("\"message\":{\"returnCode\":0,\"value\":\"验证成功。\"}}"); string callback = XmlHelper.Fetch("callback", doc); return(string.IsNullOrEmpty(callback) ? outString.ToString() : callback + "(" + outString.ToString() + ")"); } else if (responseType == "code") { HttpContext.Current.Response.Redirect(CombineUrlAndAuthorizationCode(redirectUri, code)); } else if (responseType == "token") { HttpContext.Current.Response.Redirect(CombineUrlAndAccessToken(redirectUri, token)); } else { HttpContext.Current.Response.Redirect(CombineUrlAndAuthorizationCode(redirectUri, code)); } } } outString.Append("{\"message\":{\"returnCode\":0,\"value\":\"执行成功。\"}}"); return(outString.ToString()); }
/// <summary></summary> public override string GetIdentityValue() { string accountIdentityProperty = MembershipConfigurationView.Instance.AccountIdentityCookieToken; if (HttpContext.Current.Request.Cookies[accountIdentityProperty] == null || string.IsNullOrEmpty(HttpContext.Current.Request.Cookies[accountIdentityProperty].Value)) { if (HttpContext.Current.User.Identity.IsAuthenticated) { string longinName = HttpContext.Current.User.Identity.Name; int index = longinName.IndexOf("\\") + 1; longinName = longinName.Substring(index, longinName.Length - index); IAccountInfo account = MembershipManagement.Instance.AccountService.FindOneByLoginName(longinName); if (account == null) { return(string.Empty); } else { string accountIdentity = string.Format("{0}-{1}", account.Id, DigitalNumberContext.Generate("Key_Session")); SessionContext.Instance.Write(this.strategy, accountIdentity, account); HttpAuthenticationCookieSetter.SetUserCookies(accountIdentity); // 记录登录时间 if (account.LoginDate.AddHours(8) < DateTime.Now) { MembershipManagement.Instance.AccountService.SetIPAndLoginDate(account.Id, IPQueryContext.GetClientIP(), DateTime.Now); } return(accountIdentity); } } else { return(string.Empty); } } else { return(HttpContext.Current.Request.Cookies[accountIdentityProperty].Value); } }