25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

497 satır
21 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. Post["/loginbyweixinopenid"] = LoginByWeixinOpenId;
  39. Get["/getweixinwebaccess_token"] = GetWeixinWebaccess_token;
  40. //获取ACIp
  41. Get["/GetACIp"] = GetACIp;
  42. //获取logo
  43. Get["/GetLogo"] = GetImg;
  44. }
  45. public Response GetImg(dynamic _)
  46. {
  47. string code = Request.Query["code"];
  48. string rootPath = ConfigurationManager.AppSettings["AnnexesFile"] + "\\";
  49. string midPath = "Content/images/logo";
  50. try
  51. {
  52. LR_Base_LogoEntity logoEntity = baseLogoIbll.GetLR_Base_LogoEntityByCode(code);
  53. if (logoEntity != null)
  54. {
  55. return new GenericFileResponse(logoEntity.F_FileName, "image/jpeg");
  56. }
  57. else
  58. {
  59. switch (code)
  60. {
  61. case "default":
  62. return new GenericFileResponse(Path.Combine(rootPath, midPath, "default.png"), "image/jpeg");
  63. case "accordion":
  64. return new GenericFileResponse(Path.Combine(rootPath, midPath, "accordion.png"), "image/jpeg");
  65. case "windows":
  66. return new GenericFileResponse(Path.Combine(rootPath, midPath, "windows.png"), "image/jpeg");
  67. case "top":
  68. return new GenericFileResponse(Path.Combine(rootPath, midPath, "top.png"), "image/jpeg");
  69. case "applogo":
  70. return new GenericFileResponse(Path.Combine(rootPath, midPath, "applogo.png"), "image/jpeg");
  71. }
  72. }
  73. }
  74. catch (Exception e)
  75. {
  76. Console.WriteLine(e);
  77. throw;
  78. }
  79. return null;
  80. }
  81. public Response GetACIp(dynamic _)
  82. {
  83. string Ip = GetIP();
  84. string ACIp = ConfigurationManager.AppSettings["ACIp"] ?? "";
  85. string ACIp2 = ConfigurationManager.AppSettings["ACIp2"] ?? "";
  86. return Success(new
  87. {
  88. Ip,
  89. ACIp,
  90. ACIp2
  91. });
  92. }
  93. public Response GetWeixinConfig(dynamic _)
  94. {
  95. var entity = weChatConfigIbll.GetEnableEntity();
  96. string appid = entity?.APPId;
  97. string secret = entity?.secret;
  98. return Success(new { appid, secret });
  99. }
  100. public Response GetWeixinAccess_token(dynamic _)
  101. {
  102. var entity = weChatConfigIbll.GetEnableEntity();
  103. string appid = entity?.APPId;
  104. string secret = entity?.secret;
  105. string code = Request.Query["code"];
  106. var responsejson = HttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code");
  107. if (!string.IsNullOrEmpty(responsejson))
  108. {
  109. var weixintokenobj = JsonConvert.DeserializeObject<dynamic>(responsejson);
  110. if (string.IsNullOrEmpty(weixintokenobj.errcode))
  111. {
  112. string openid = weixintokenobj.openid;
  113. var userEntity = userIbll.GetEntityByWeixinOpenId(openid);
  114. if (userEntity != null)
  115. {
  116. ReqParameter req = this.Bind<ReqParameter>();
  117. string token = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_App", req.loginMark, false);//写入缓存信息
  118. #region 写入日志
  119. LogEntity logEntity = new LogEntity();
  120. logEntity.F_CategoryId = 1;
  121. logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
  122. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
  123. logEntity.F_OperateAccount = userEntity.F_Account + "(" + userEntity.F_RealName + ")";
  124. logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : userEntity.F_Account;
  125. logEntity.F_Module = Config.GetValue("SoftName");
  126. logEntity.F_Description = "移动端";
  127. #endregion
  128. //写入日志
  129. logEntity.F_ExecuteResult = 1;
  130. logEntity.F_ExecuteResultJson = "登录成功";
  131. logEntity.WriteLog();
  132. OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
  133. res.userInfo.password = null;
  134. res.userInfo.secretkey = null;
  135. var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
  136. if (studententity != null)
  137. {
  138. res.userInfo.grade = studententity.Grade;
  139. var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
  140. if (majorinfo != null)
  141. {
  142. res.userInfo.majorno = majorinfo.ID ?? "";
  143. }
  144. }
  145. var jsonData = new
  146. {
  147. logined = true,
  148. baseinfo = res.userInfo,
  149. post = postIBLL.GetListByPostIds(res.userInfo.postIds),
  150. role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds)
  151. };
  152. return Success(jsonData);
  153. }
  154. else
  155. {
  156. return Success(JsonConvert.DeserializeObject(responsejson));
  157. }
  158. }
  159. else
  160. {
  161. return Fail("微信授权失败,请重试。");
  162. }
  163. }
  164. return Fail("微信授权失败,请重试。");
  165. }
  166. private Response Login(dynamic _)
  167. {
  168. LoginModel loginModel = this.GetReqData<LoginModel>();
  169. #region 内部账户验证
  170. UserEntity userEntity = userIbll.CheckLogin(loginModel.username, loginModel.password);
  171. #region 写入日志
  172. LogEntity logEntity = new LogEntity();
  173. logEntity.F_CategoryId = 1;
  174. logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
  175. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
  176. logEntity.F_OperateAccount = loginModel.username + "(" + userEntity.F_RealName + ")";
  177. logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : loginModel.username;
  178. logEntity.F_Module = Config.GetValue("SoftName");
  179. logEntity.F_Description = "移动端";
  180. #endregion
  181. if (!userEntity.LoginOk)//登录失败
  182. {
  183. //写入日志
  184. logEntity.F_ExecuteResult = 0;
  185. logEntity.F_ExecuteResultJson = "登录失败:" + userEntity.LoginMsg;
  186. logEntity.WriteLog();
  187. return Fail(userEntity.LoginMsg);
  188. }
  189. else
  190. {
  191. ReqParameter req = this.Bind<ReqParameter>();
  192. string token = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_App", req.loginMark, false);//写入缓存信息
  193. //写入日志
  194. logEntity.F_ExecuteResult = 1;
  195. logEntity.F_ExecuteResultJson = "登录成功";
  196. logEntity.WriteLog();
  197. OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
  198. res.userInfo.password = null;
  199. res.userInfo.secretkey = null;
  200. var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
  201. if (studententity != null)
  202. {
  203. res.userInfo.grade = studententity.Grade;
  204. var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
  205. if (majorinfo != null)
  206. {
  207. res.userInfo.majorno = majorinfo.ID ?? "";
  208. }
  209. }
  210. //是否强密码验证
  211. bool pwd = false;
  212. if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["verifypwd"]) && ConfigurationManager.AppSettings["verifypwd"] == "true" && loginModel.up == false)
  213. {
  214. pwd = true;
  215. }
  216. else
  217. {
  218. //保存用户设备号
  219. userIbll.UpdateWeixinOpenId(userEntity.F_UserId, loginModel.openid);
  220. }
  221. var jsonData = new
  222. {
  223. baseinfo = res.userInfo,
  224. post = postIBLL.GetListByPostIds(res.userInfo.postIds),
  225. role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds),
  226. pwd = pwd
  227. };
  228. return Success(jsonData);
  229. }
  230. #endregion
  231. }
  232. private Response LoginByWeixinOpenId(dynamic _)
  233. {
  234. LoginModel loginModel = this.GetReqData<LoginModel>();
  235. #region 内部账户验证
  236. //UserEntity userEntity = userIbll.CheckLogin(loginModel.username, loginModel.password);
  237. UserEntity userEntity = userIbll.GetEntityByWeixinOpenId(loginModel.openid);
  238. if (userEntity == null)
  239. {
  240. userEntity = new UserEntity()
  241. {
  242. LoginMsg = "账户不存在!",
  243. LoginOk = false
  244. };
  245. }
  246. else
  247. {
  248. userEntity.LoginOk = true;
  249. }
  250. #region 写入日志
  251. LogEntity logEntity = new LogEntity();
  252. logEntity.F_CategoryId = 1;
  253. logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
  254. logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
  255. logEntity.F_OperateAccount = loginModel.openid + "(" + userEntity.F_RealName + ")";
  256. logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : loginModel.openid;
  257. logEntity.F_Module = Config.GetValue("SoftName");
  258. logEntity.F_Description = "移动端";
  259. #endregion
  260. if (!userEntity.LoginOk)//登录失败
  261. {
  262. //写入日志
  263. logEntity.F_ExecuteResult = 0;
  264. logEntity.F_ExecuteResultJson = "登录失败:" + userEntity.LoginMsg;
  265. logEntity.WriteLog();
  266. return Fail(userEntity.LoginMsg);
  267. }
  268. else
  269. {
  270. ReqParameter req = this.Bind<ReqParameter>();
  271. string token = OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_App", req.loginMark, false);//写入缓存信息
  272. //写入日志
  273. logEntity.F_ExecuteResult = 1;
  274. logEntity.F_ExecuteResultJson = "登录成功";
  275. logEntity.WriteLog();
  276. OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
  277. res.userInfo.password = null;
  278. res.userInfo.secretkey = null;
  279. var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
  280. if (studententity != null)
  281. {
  282. res.userInfo.grade = studententity.Grade;
  283. var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
  284. if (majorinfo != null)
  285. {
  286. res.userInfo.majorno = majorinfo.ID ?? "";
  287. }
  288. }
  289. //是否强密码验证
  290. bool pwd = false;
  291. if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["verifypwd"]) && ConfigurationManager.AppSettings["verifypwd"] == "true" && loginModel.up == false)
  292. {
  293. pwd = true;
  294. }
  295. var jsonData = new
  296. {
  297. baseinfo = res.userInfo,
  298. post = postIBLL.GetListByPostIds(res.userInfo.postIds),
  299. role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds),
  300. pwd = pwd
  301. };
  302. return Success(jsonData);
  303. }
  304. #endregion
  305. }
  306. public Response GetWeixinWebaccess_token(dynamic _)
  307. {
  308. var entity = weChatConfigIbll.GetEnableEntity();
  309. string appid = entity?.APPId;
  310. string secret = entity?.secret;
  311. string url = Request.Query["url"];
  312. var responsejson = HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
  313. if (!string.IsNullOrEmpty(responsejson))
  314. {
  315. var weixintokenobj = JsonConvert.DeserializeObject<dynamic>(responsejson);
  316. if (string.IsNullOrEmpty(weixintokenobj.errcode))
  317. {
  318. string access_token = weixintokenobj.access_token;
  319. string jsapi_ticket = HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi");
  320. var weixinjsapiticketobj = JsonConvert.DeserializeObject<dynamic>(jsapi_ticket);
  321. if (weixinjsapiticketobj.errcode == 0)
  322. {
  323. string ticket = weixinjsapiticketobj.ticket;
  324. //生成签名
  325. string noncestr = Util.CommonHelper.CreateNo();
  326. string timestamp = GetTimeStamp(true);
  327. string param = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
  328. string certificate = SHA1(param).ToLower();
  329. return Success(new { appid, noncestr, timestamp, certificate });
  330. }
  331. else
  332. {
  333. return Fail("微信授权失败,请重试。" + weixinjsapiticketobj.errcode + weixinjsapiticketobj.errmsg);
  334. }
  335. }
  336. else
  337. {
  338. return Fail("微信授权失败,请重试。" + weixintokenobj.errcode + weixintokenobj.errmsg);
  339. }
  340. }
  341. else
  342. {
  343. return Fail("微信授权失败,请重试。");
  344. }
  345. }
  346. /// <summary>
  347. /// 发起一个HTTP请求(以GET方式)
  348. /// </summary>
  349. /// <param name="url"></param>
  350. /// <returns></returns>
  351. public string HttpGet(string url)
  352. {
  353. WebRequest myWebRequest = WebRequest.Create(url);
  354. WebResponse myWebResponse = myWebRequest.GetResponse();
  355. Stream ReceiveStream = myWebResponse.GetResponseStream();
  356. string responseStr = "";
  357. if (ReceiveStream != null)
  358. {
  359. StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
  360. responseStr = reader.ReadToEnd();
  361. reader.Close();
  362. }
  363. myWebResponse.Close();
  364. return responseStr;
  365. }
  366. /// <summary>
  367. /// 获取当前时间戳
  368. /// </summary>
  369. /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.bool bflag = true</param>
  370. /// <returns></returns>
  371. public static string GetTimeStamp(bool bflag)
  372. {
  373. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  374. string ret = string.Empty;
  375. if (bflag)
  376. ret = Convert.ToInt64(ts.TotalSeconds).ToString();
  377. else
  378. ret = Convert.ToInt64(ts.TotalMilliseconds).ToString();
  379. return ret;
  380. }
  381. // <summary>
  382. /// SHA1 加密,返回大写字符串
  383. /// </summary>
  384. /// <param name="content">需要加密字符串</param>
  385. /// <returns>返回40位UTF8 大写</returns>
  386. public static string SHA1(string content)
  387. {
  388. return SHA1(content, Encoding.UTF8);
  389. }
  390. /// <summary>
  391. /// SHA1 加密,返回大写字符串
  392. /// </summary>
  393. /// <param name="content">需要加密字符串</param>
  394. /// <param name="encode">指定加密编码</param>
  395. /// <returns>返回40位大写字符串</returns>
  396. public static string SHA1(string content, Encoding encode)
  397. {
  398. try
  399. {
  400. SHA1 sha1 = new SHA1CryptoServiceProvider();
  401. byte[] bytes_in = encode.GetBytes(content);
  402. byte[] bytes_out = sha1.ComputeHash(bytes_in);
  403. sha1.Dispose();
  404. string result = BitConverter.ToString(bytes_out);
  405. result = result.Replace("-", "");
  406. return result;
  407. }
  408. catch (Exception ex)
  409. {
  410. throw new Exception("SHA1加密出错:" + ex.Message);
  411. }
  412. }
  413. /// <summary>
  414. /// 获取IP
  415. /// </summary>
  416. /// <returns></returns>
  417. private string GetIP()
  418. {
  419. //string ip = string.Empty;
  420. //if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
  421. // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
  422. //if (string.IsNullOrEmpty(ip))
  423. // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
  424. //return ip;
  425. string userIP = "未获取用户IP";
  426. try
  427. {
  428. if (System.Web.HttpContext.Current == null
  429. || System.Web.HttpContext.Current.Request == null
  430. || System.Web.HttpContext.Current.Request.ServerVariables == null)
  431. {
  432. return "";
  433. }
  434. string CustomerIP = "";
  435. //CDN加速后取到的IP simone 090805
  436. CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
  437. if (!string.IsNullOrEmpty(CustomerIP))
  438. {
  439. return CustomerIP;
  440. }
  441. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  442. if (!string.IsNullOrEmpty(CustomerIP))
  443. {
  444. return CustomerIP;
  445. }
  446. if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
  447. {
  448. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  449. if (CustomerIP == null)
  450. {
  451. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  452. }
  453. }
  454. else
  455. {
  456. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  457. }
  458. if (string.Compare(CustomerIP, "unknown", true) == 0 || string.IsNullOrEmpty(CustomerIP))
  459. {
  460. return System.Web.HttpContext.Current.Request.UserHostAddress;
  461. }
  462. return CustomerIP;
  463. }
  464. catch { }
  465. return userIP;
  466. }
  467. }
  468. }