|
- using Learun.Application.Base.SystemModule;
- using Learun.Util;
- using Nancy;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.IO;
- using System.Linq.Expressions;
- using System.Net;
- using System.Security.Cryptography;
- using System.Text;
- using System.Web.Mvc;
- using System.Web.WebSockets;
- using Learun.Application.Organization;
- using Learun.Application.TwoDevelopment.EducationalAdministration;
- using Learun.Application.TwoDevelopment.LR_Desktop;
- using Learun.Util.Operat;
- using Nancy.ModelBinding;
- using Nancy.Responses;
- using Newtonsoft.Json;
-
- namespace Learun.Application.WebApi.Modules
- {
- public class WeixinApi : BaseNoAuthentication
- {
- private UserIBLL userIbll = new UserBLL();
- private PostIBLL postIBLL = new PostBLL();
- private RoleIBLL roleIBLL = new RoleBLL();
- private StuInfoBasicIBLL stuInfoBasicIBLL = new StuInfoBasicBLL();
- private WeChatConfigIBLL weChatConfigIbll = new WeChatConfigBLL();
- LR_Base_LogoIBLL baseLogoIbll = new LR_Base_LogoBLL();
- CdMajorIBLL majorIbll = new CdMajorBLL();
- public WeixinApi()
- : base("/weixinapi")
- {
- Get["/weixinconfig"] = GetWeixinConfig;
- Post["/getweixinaccess_token"] = GetWeixinAccess_token;
- Post["/login"] = Login;
- Get["/getweixinwebaccess_token"] = GetWeixinWebaccess_token;
- //获取ACIp
- Get["/GetACIp"] = GetACIp;
- //获取logo
- Get["/GetLogo"] = GetImg;
- }
-
- public Response GetImg(dynamic _)
- {
- string code = Request.Query["code"];
- string rootPath = ConfigurationManager.AppSettings["AnnexesFile"] + "\\";
- string midPath = "Content/images/logo";
- try
- {
- LR_Base_LogoEntity logoEntity = baseLogoIbll.GetLR_Base_LogoEntityByCode(code);
- if (logoEntity != null)
- {
- return new GenericFileResponse(logoEntity.F_FileName, "image/jpeg");
- }
- else
- {
- switch (code)
- {
- case "default":
- return new GenericFileResponse(Path.Combine(rootPath, midPath, "default.png"), "image/jpeg");
- case "accordion":
- return new GenericFileResponse(Path.Combine(rootPath, midPath, "accordion.png"), "image/jpeg");
- case "windows":
- return new GenericFileResponse(Path.Combine(rootPath, midPath, "windows.png"), "image/jpeg");
- case "top":
- return new GenericFileResponse(Path.Combine(rootPath, midPath, "top.png"), "image/jpeg");
- case "applogo":
- return new GenericFileResponse(Path.Combine(rootPath, midPath, "applogo.png"), "image/jpeg");
- }
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- throw;
- }
- return null;
- }
-
- public Response GetACIp(dynamic _)
- {
- string Ip = GetIP();
- string ACIp = ConfigurationManager.AppSettings["ACIp"] ?? "";
- string ACIp2 = ConfigurationManager.AppSettings["ACIp2"] ?? "";
- return Success(new
- {
- Ip,
- ACIp,
- ACIp2
- });
- }
- public Response GetWeixinConfig(dynamic _)
- {
- var entity = weChatConfigIbll.GetEnableEntity();
- string appid = entity?.APPId;
- string secret = entity?.secret;
- return Success(new { appid, secret });
- }
-
- public Response GetWeixinAccess_token(dynamic _)
- {
- var entity = weChatConfigIbll.GetEnableEntity();
- string appid = entity?.APPId;
- string secret = entity?.secret;
-
- string code = Request.Query["code"];
- var responsejson = HttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code");
- if (!string.IsNullOrEmpty(responsejson))
- {
- var weixintokenobj = JsonConvert.DeserializeObject<dynamic>(responsejson);
- if (string.IsNullOrEmpty(weixintokenobj.errcode))
- {
- string openid = weixintokenobj.openid;
- var userEntity = userIbll.GetEntityByWeixinOpenId(openid);
- if (userEntity != null)
- {
- ReqParameter req = this.Bind<ReqParameter>();
- string token = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_App", req.loginMark, false);//写入缓存信息
- #region 写入日志
- LogEntity logEntity = new LogEntity();
- logEntity.F_CategoryId = 1;
- logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
- logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
- logEntity.F_OperateAccount = userEntity.F_Account + "(" + userEntity.F_RealName + ")";
- logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : userEntity.F_Account;
- logEntity.F_Module = Config.GetValue("SoftName");
- logEntity.F_Description = "移动端";
- #endregion
- //写入日志
- logEntity.F_ExecuteResult = 1;
- logEntity.F_ExecuteResultJson = "登录成功";
- logEntity.WriteLog();
-
- OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
- res.userInfo.password = null;
- res.userInfo.secretkey = null;
- var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
- if (studententity != null)
- {
- res.userInfo.grade = studententity.Grade;
- var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
- if (majorinfo != null)
- {
- res.userInfo.majorno = majorinfo.ID ?? "";
- }
-
- }
- var jsonData = new
- {
- logined = true,
- baseinfo = res.userInfo,
- post = postIBLL.GetListByPostIds(res.userInfo.postIds),
- role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds)
- };
- return Success(jsonData);
- }
- else
- {
- return Success(JsonConvert.DeserializeObject(responsejson));
- }
- }
- else
- {
- return Fail("微信授权失败,请重试。");
- }
- }
- return Fail("微信授权失败,请重试。");
- }
-
- private Response Login(dynamic _)
- {
- LoginModel loginModel = this.GetReqData<LoginModel>();
-
- #region 内部账户验证
- UserEntity userEntity = userIbll.CheckLogin(loginModel.username, loginModel.password);
-
- #region 写入日志
- LogEntity logEntity = new LogEntity();
- logEntity.F_CategoryId = 1;
- logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
- logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
- logEntity.F_OperateAccount = loginModel.username + "(" + userEntity.F_RealName + ")";
- logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : loginModel.username;
- logEntity.F_Module = Config.GetValue("SoftName");
- logEntity.F_Description = "移动端";
- #endregion
-
- if (!userEntity.LoginOk)//登录失败
- {
- //写入日志
- logEntity.F_ExecuteResult = 0;
- logEntity.F_ExecuteResultJson = "登录失败:" + userEntity.LoginMsg;
- logEntity.WriteLog();
- return Fail(userEntity.LoginMsg);
- }
- else
- {
- ReqParameter req = this.Bind<ReqParameter>();
- string token = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_App", req.loginMark, false);//写入缓存信息
- //写入日志
- logEntity.F_ExecuteResult = 1;
- logEntity.F_ExecuteResultJson = "登录成功";
- logEntity.WriteLog();
- OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
- res.userInfo.password = null;
- res.userInfo.secretkey = null;
- var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
- if (studententity != null)
- {
- res.userInfo.grade = studententity.Grade;
- var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
- if (majorinfo != null)
- {
- res.userInfo.majorno = majorinfo.ID ?? "";
- }
-
- }
- //是否强密码验证
- bool pwd = false;
- if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["verifypwd"]) && ConfigurationManager.AppSettings["verifypwd"] == "true" && loginModel.up == false)
- {
- pwd = true;
- }
- else
- {
- //保存用户设备号
- userIbll.UpdateWeixinOpenId(userEntity.F_UserId, loginModel.openid);
- }
- var jsonData = new
- {
- baseinfo = res.userInfo,
- post = postIBLL.GetListByPostIds(res.userInfo.postIds),
- role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds),
- pwd = pwd
- };
- return Success(jsonData);
- }
- #endregion
- }
-
- public Response GetWeixinWebaccess_token(dynamic _)
- {
- var entity = weChatConfigIbll.GetEnableEntity();
- string appid = entity?.APPId;
- string secret = entity?.secret;
- string url = Request.Query["url"];
- var responsejson = HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
- if (!string.IsNullOrEmpty(responsejson))
- {
- var weixintokenobj = JsonConvert.DeserializeObject<dynamic>(responsejson);
- if (string.IsNullOrEmpty(weixintokenobj.errcodeValue))
- {
- string access_token = weixintokenobj.access_token;
- string jsapi_ticket = HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi");
- var weixinjsapiticketobj = JsonConvert.DeserializeObject<dynamic>(jsapi_ticket);
- if (weixinjsapiticketobj.errcode == 0)
- {
- string ticket = weixinjsapiticketobj.ticket;
- //生成签名
- string noncestr = Util.CommonHelper.CreateNo();
- string timestamp = GetTimeStamp(true);
- string param = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url;
- string certificate = SHA1(param).ToLower();
- return Success(new { appid, noncestr, timestamp, certificate });
- }
- else
- {
- return Fail("2.getticket 微信授权失败,请重试。" + weixinjsapiticketobj.errcode + weixinjsapiticketobj.errmsg+ ",access_tokenjson:" + responsejson);
- }
- }
- else
- {
- return Fail("1.token 微信授权失败,请重试。" + weixintokenobj.errcode + weixintokenobj.errmsg+weixintokenobj.errcodeValue);
- }
- }
- else
- {
- return Fail("微信授权失败,请重试。");
- }
- }
-
- /// <summary>
- /// 发起一个HTTP请求(以GET方式)
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public string HttpGet(string url)
- {
- WebRequest myWebRequest = WebRequest.Create(url);
- WebResponse myWebResponse = myWebRequest.GetResponse();
- Stream ReceiveStream = myWebResponse.GetResponseStream();
- string responseStr = "";
- if (ReceiveStream != null)
- {
- StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
- responseStr = reader.ReadToEnd();
- reader.Close();
- }
- myWebResponse.Close();
- return responseStr;
- }
- /// <summary>
- /// 获取当前时间戳
- /// </summary>
- /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.bool bflag = true</param>
- /// <returns></returns>
- public static string GetTimeStamp(bool bflag)
- {
- TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
- string ret = string.Empty;
- if (bflag)
- ret = Convert.ToInt64(ts.TotalSeconds).ToString();
- else
- ret = Convert.ToInt64(ts.TotalMilliseconds).ToString();
-
- return ret;
- }
- // <summary>
- /// SHA1 加密,返回大写字符串
- /// </summary>
- /// <param name="content">需要加密字符串</param>
- /// <returns>返回40位UTF8 大写</returns>
- public static string SHA1(string content)
- {
- return SHA1(content, Encoding.UTF8);
- }
- /// <summary>
- /// SHA1 加密,返回大写字符串
- /// </summary>
- /// <param name="content">需要加密字符串</param>
- /// <param name="encode">指定加密编码</param>
- /// <returns>返回40位大写字符串</returns>
- public static string SHA1(string content, Encoding encode)
- {
- try
- {
- SHA1 sha1 = new SHA1CryptoServiceProvider();
- byte[] bytes_in = encode.GetBytes(content);
- byte[] bytes_out = sha1.ComputeHash(bytes_in);
- sha1.Dispose();
- string result = BitConverter.ToString(bytes_out);
- result = result.Replace("-", "");
- return result;
- }
- catch (Exception ex)
- {
- throw new Exception("SHA1加密出错:" + ex.Message);
- }
- }
- /// <summary>
- /// 获取IP
- /// </summary>
- /// <returns></returns>
- private string GetIP()
- {
- //string ip = string.Empty;
- //if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
- // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
- //if (string.IsNullOrEmpty(ip))
- // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
- //return ip;
- string userIP = "未获取用户IP";
-
- try
- {
- if (System.Web.HttpContext.Current == null
- || System.Web.HttpContext.Current.Request == null
- || System.Web.HttpContext.Current.Request.ServerVariables == null)
- {
- return "";
- }
-
- string CustomerIP = "";
-
- //CDN加速后取到的IP simone 090805
- CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
- if (!string.IsNullOrEmpty(CustomerIP))
- {
- return CustomerIP;
- }
-
- CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
-
- if (!string.IsNullOrEmpty(CustomerIP))
- {
- return CustomerIP;
- }
-
- if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
- {
- CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
-
- if (CustomerIP == null)
- {
- CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
- }
- }
- else
- {
- CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
- }
-
- if (string.Compare(CustomerIP, "unknown", true) == 0 || string.IsNullOrEmpty(CustomerIP))
- {
- return System.Web.HttpContext.Current.Request.UserHostAddress;
- }
- return CustomerIP;
- }
- catch { }
-
- return userIP;
- }
- }
- }
|