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.
 
 
 
 
 
 

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