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.
 
 
 
 
 
 

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