您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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