You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

411 lines
17 KiB

  1. using Learun.Application.Base.SystemModule;
  2. using Learun.Util;
  3. using Nancy;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Configuration;
  7. using System.IO;
  8. using System.Linq.Expressions;
  9. using System.Net;
  10. using System.Security.Cryptography;
  11. using System.Text;
  12. using System.Web.Mvc;
  13. using System.Web.WebSockets;
  14. using Learun.Application.Organization;
  15. using Learun.Application.TwoDevelopment.EducationalAdministration;
  16. using Learun.Application.TwoDevelopment.LR_Desktop;
  17. using Learun.Util.Operat;
  18. using Nancy.ModelBinding;
  19. using Nancy.Responses;
  20. using Newtonsoft.Json;
  21. namespace Learun.Application.WebApi.Modules
  22. {
  23. public class WeixinApi : BaseNoAuthentication
  24. {
  25. private UserIBLL userIbll = new UserBLL();
  26. private PostIBLL postIBLL = new PostBLL();
  27. private RoleIBLL roleIBLL = new RoleBLL();
  28. private StuInfoBasicIBLL stuInfoBasicIBLL = new StuInfoBasicBLL();
  29. private WeChatConfigIBLL weChatConfigIbll = new WeChatConfigBLL();
  30. LR_Base_LogoIBLL baseLogoIbll = new LR_Base_LogoBLL();
  31. CdMajorIBLL majorIbll = new CdMajorBLL();
  32. public WeixinApi()
  33. : base("/weixinapi")
  34. {
  35. Get["/weixinconfig"] = GetWeixinConfig;
  36. Post["/getweixinaccess_token"] = GetWeixinAccess_token;
  37. Post["/login"] = Login;
  38. Get["/getweixinwebaccess_token"] = GetWeixinWebaccess_token;
  39. //获取ACIp
  40. Get["/GetACIp"] = GetACIp;
  41. //获取logo
  42. Get["/GetLogo"] = GetImg;
  43. }
  44. public Response GetImg(dynamic _)
  45. {
  46. string code = Request.Query["code"];
  47. string rootPath = ConfigurationManager.AppSettings["AnnexesFile"] + "\\";
  48. string midPath = "Content/images/logo";
  49. try
  50. {
  51. LR_Base_LogoEntity logoEntity = baseLogoIbll.GetLR_Base_LogoEntityByCode(code);
  52. if (logoEntity != null)
  53. {
  54. return new GenericFileResponse(logoEntity.F_FileName, "image/jpeg");
  55. }
  56. else
  57. {
  58. switch (code)
  59. {
  60. case "default":
  61. return new GenericFileResponse(Path.Combine(rootPath, midPath, "default.png"), "image/jpeg");
  62. case "accordion":
  63. return new GenericFileResponse(Path.Combine(rootPath, midPath, "accordion.png"), "image/jpeg");
  64. case "windows":
  65. return new GenericFileResponse(Path.Combine(rootPath, midPath, "windows.png"), "image/jpeg");
  66. case "top":
  67. return new GenericFileResponse(Path.Combine(rootPath, midPath, "top.png"), "image/jpeg");
  68. case "applogo":
  69. return new GenericFileResponse(Path.Combine(rootPath, midPath, "applogo.png"), "image/jpeg");
  70. }
  71. }
  72. }
  73. catch (Exception e)
  74. {
  75. Console.WriteLine(e);
  76. throw;
  77. }
  78. return null;
  79. }
  80. public Response GetACIp(dynamic _)
  81. {
  82. string Ip = GetIP();
  83. string ACIp = ConfigurationManager.AppSettings["ACIp"] ?? "";
  84. string ACIp2 = ConfigurationManager.AppSettings["ACIp2"] ?? "";
  85. return Success(new
  86. {
  87. Ip,
  88. ACIp,
  89. ACIp2
  90. });
  91. }
  92. public Response GetWeixinConfig(dynamic _)
  93. {
  94. var entity = weChatConfigIbll.GetEnableEntity();
  95. string appid = entity?.APPId;
  96. string secret = entity?.secret;
  97. return Success(new { appid, secret });
  98. }
  99. public Response GetWeixinAccess_token(dynamic _)
  100. {
  101. var entity = weChatConfigIbll.GetEnableEntity();
  102. string appid = entity?.APPId;
  103. string secret = entity?.secret;
  104. string code = Request.Query["code"];
  105. var responsejson = HttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code");
  106. if (!string.IsNullOrEmpty(responsejson))
  107. {
  108. var weixintokenobj = JsonConvert.DeserializeObject<dynamic>(responsejson);
  109. if (string.IsNullOrEmpty(weixintokenobj.errcode))
  110. {
  111. string openid = weixintokenobj.openid;
  112. var userEntity = userIbll.GetEntityByWeixinOpenId(openid);
  113. if (userEntity != null)
  114. {
  115. ReqParameter req = this.Bind<ReqParameter>();
  116. string token = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_App", req.loginMark, false);//写入缓存信息
  117. #region 写入日志
  118. LogEntity logEntity = new LogEntity();
  119. logEntity.F_CategoryId = 1;
  120. logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
  121. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
  122. logEntity.F_OperateAccount = userEntity.F_Account + "(" + userEntity.F_RealName + ")";
  123. logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : userEntity.F_Account;
  124. logEntity.F_Module = Config.GetValue("SoftName");
  125. logEntity.F_Description = "移动端";
  126. #endregion
  127. //写入日志
  128. logEntity.F_ExecuteResult = 1;
  129. logEntity.F_ExecuteResultJson = "登录成功";
  130. logEntity.WriteLog();
  131. OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
  132. res.userInfo.password = null;
  133. res.userInfo.secretkey = null;
  134. var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
  135. if (studententity != null)
  136. {
  137. res.userInfo.grade = studententity.Grade;
  138. var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
  139. if (majorinfo != null)
  140. {
  141. res.userInfo.majorno = majorinfo.ID ?? "";
  142. }
  143. }
  144. var jsonData = new
  145. {
  146. logined = true,
  147. baseinfo = res.userInfo,
  148. post = postIBLL.GetListByPostIds(res.userInfo.postIds),
  149. role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds)
  150. };
  151. return Success(jsonData);
  152. }
  153. else
  154. {
  155. return Success(JsonConvert.DeserializeObject(responsejson));
  156. }
  157. }
  158. else
  159. {
  160. return Fail("微信授权失败,请重试。");
  161. }
  162. }
  163. return Fail("微信授权失败,请重试。");
  164. }
  165. private Response Login(dynamic _)
  166. {
  167. LoginModel loginModel = this.GetReqData<LoginModel>();
  168. #region 内部账户验证
  169. UserEntity userEntity = userIbll.CheckLogin(loginModel.username, loginModel.password);
  170. #region 写入日志
  171. LogEntity logEntity = new LogEntity();
  172. logEntity.F_CategoryId = 1;
  173. logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
  174. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
  175. logEntity.F_OperateAccount = loginModel.username + "(" + userEntity.F_RealName + ")";
  176. logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : loginModel.username;
  177. logEntity.F_Module = Config.GetValue("SoftName");
  178. logEntity.F_Description = "移动端";
  179. #endregion
  180. if (!userEntity.LoginOk)//登录失败
  181. {
  182. //写入日志
  183. logEntity.F_ExecuteResult = 0;
  184. logEntity.F_ExecuteResultJson = "登录失败:" + userEntity.LoginMsg;
  185. logEntity.WriteLog();
  186. return Fail(userEntity.LoginMsg);
  187. }
  188. else
  189. {
  190. ReqParameter req = this.Bind<ReqParameter>();
  191. string token = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_App", req.loginMark, false);//写入缓存信息
  192. //写入日志
  193. logEntity.F_ExecuteResult = 1;
  194. logEntity.F_ExecuteResultJson = "登录成功";
  195. logEntity.WriteLog();
  196. //保存用户设备号
  197. userIbll.UpdateWeixinOpenId(userEntity.F_UserId, loginModel.openid);
  198. OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
  199. res.userInfo.password = null;
  200. res.userInfo.secretkey = null;
  201. var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
  202. if (studententity != null)
  203. {
  204. res.userInfo.grade = studententity.Grade;
  205. var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
  206. if (majorinfo != null)
  207. {
  208. res.userInfo.majorno = majorinfo.ID ?? "";
  209. }
  210. }
  211. var jsonData = new
  212. {
  213. baseinfo = res.userInfo,
  214. post = postIBLL.GetListByPostIds(res.userInfo.postIds),
  215. role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds)
  216. };
  217. return Success(jsonData);
  218. }
  219. #endregion
  220. }
  221. public Response GetWeixinWebaccess_token(dynamic _)
  222. {
  223. var entity = weChatConfigIbll.GetEnableEntity();
  224. string appid = entity?.APPId;
  225. string secret = entity?.secret;
  226. string url = Request.Query["url"];
  227. var responsejson = HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
  228. if (!string.IsNullOrEmpty(responsejson))
  229. {
  230. var weixintokenobj = JsonConvert.DeserializeObject<dynamic>(responsejson);
  231. if (string.IsNullOrEmpty(weixintokenobj.errcode))
  232. {
  233. string access_token = weixintokenobj.access_token;
  234. string jsapi_ticket = HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi");
  235. var weixinjsapiticketobj = JsonConvert.DeserializeObject<dynamic>(jsapi_ticket);
  236. if (weixinjsapiticketobj.errcode == 0)
  237. {
  238. string ticket = weixinjsapiticketobj.ticket;
  239. //生成签名
  240. string noncestr = Util.CommonHelper.CreateNo();
  241. string timestamp = GetTimeStamp(true);
  242. string param = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
  243. string certificate = SHA1(param).ToLower();
  244. return Success(new { appid, noncestr, timestamp, certificate });
  245. }
  246. else
  247. {
  248. return Fail("微信授权失败,请重试。" + weixinjsapiticketobj.errcode + weixinjsapiticketobj.errmsg);
  249. }
  250. }
  251. else
  252. {
  253. return Fail("微信授权失败,请重试。" + weixintokenobj.errcode + weixintokenobj.errmsg);
  254. }
  255. }
  256. else
  257. {
  258. return Fail("微信授权失败,请重试。");
  259. }
  260. }
  261. /// <summary>
  262. /// 发起一个HTTP请求(以GET方式)
  263. /// </summary>
  264. /// <param name="url"></param>
  265. /// <returns></returns>
  266. public string HttpGet(string url)
  267. {
  268. WebRequest myWebRequest = WebRequest.Create(url);
  269. WebResponse myWebResponse = myWebRequest.GetResponse();
  270. Stream ReceiveStream = myWebResponse.GetResponseStream();
  271. string responseStr = "";
  272. if (ReceiveStream != null)
  273. {
  274. StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
  275. responseStr = reader.ReadToEnd();
  276. reader.Close();
  277. }
  278. myWebResponse.Close();
  279. return responseStr;
  280. }
  281. /// <summary>
  282. /// 获取当前时间戳
  283. /// </summary>
  284. /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.bool bflag = true</param>
  285. /// <returns></returns>
  286. public static string GetTimeStamp(bool bflag)
  287. {
  288. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  289. string ret = string.Empty;
  290. if (bflag)
  291. ret = Convert.ToInt64(ts.TotalSeconds).ToString();
  292. else
  293. ret = Convert.ToInt64(ts.TotalMilliseconds).ToString();
  294. return ret;
  295. }
  296. // <summary>
  297. /// SHA1 加密,返回大写字符串
  298. /// </summary>
  299. /// <param name="content">需要加密字符串</param>
  300. /// <returns>返回40位UTF8 大写</returns>
  301. public static string SHA1(string content)
  302. {
  303. return SHA1(content, Encoding.UTF8);
  304. }
  305. /// <summary>
  306. /// SHA1 加密,返回大写字符串
  307. /// </summary>
  308. /// <param name="content">需要加密字符串</param>
  309. /// <param name="encode">指定加密编码</param>
  310. /// <returns>返回40位大写字符串</returns>
  311. public static string SHA1(string content, Encoding encode)
  312. {
  313. try
  314. {
  315. SHA1 sha1 = new SHA1CryptoServiceProvider();
  316. byte[] bytes_in = encode.GetBytes(content);
  317. byte[] bytes_out = sha1.ComputeHash(bytes_in);
  318. sha1.Dispose();
  319. string result = BitConverter.ToString(bytes_out);
  320. result = result.Replace("-", "");
  321. return result;
  322. }
  323. catch (Exception ex)
  324. {
  325. throw new Exception("SHA1加密出错:" + ex.Message);
  326. }
  327. }
  328. /// <summary>
  329. /// 获取IP
  330. /// </summary>
  331. /// <returns></returns>
  332. private string GetIP()
  333. {
  334. //string ip = string.Empty;
  335. //if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
  336. // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
  337. //if (string.IsNullOrEmpty(ip))
  338. // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
  339. //return ip;
  340. string userIP = "未获取用户IP";
  341. try
  342. {
  343. if (System.Web.HttpContext.Current == null
  344. || System.Web.HttpContext.Current.Request == null
  345. || System.Web.HttpContext.Current.Request.ServerVariables == null)
  346. {
  347. return "";
  348. }
  349. string CustomerIP = "";
  350. //CDN加速后取到的IP simone 090805
  351. CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
  352. if (!string.IsNullOrEmpty(CustomerIP))
  353. {
  354. return CustomerIP;
  355. }
  356. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  357. if (!string.IsNullOrEmpty(CustomerIP))
  358. {
  359. return CustomerIP;
  360. }
  361. if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
  362. {
  363. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  364. if (CustomerIP == null)
  365. {
  366. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  367. }
  368. }
  369. else
  370. {
  371. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  372. }
  373. if (string.Compare(CustomerIP, "unknown", true) == 0 || string.IsNullOrEmpty(CustomerIP))
  374. {
  375. return System.Web.HttpContext.Current.Request.UserHostAddress;
  376. }
  377. return CustomerIP;
  378. }
  379. catch { }
  380. return userIP;
  381. }
  382. }
  383. }