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.
 
 
 
 
 
 

417 lines
18 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. OperatorResult res = OperatorHelper.Instance.IsOnLine(token, req.loginMark);
  197. res.userInfo.password = null;
  198. res.userInfo.secretkey = null;
  199. var studententity = stuInfoBasicIBLL.GetStuInfoBasicEntityByStuNo(userEntity.F_Account);
  200. if (studententity != null)
  201. {
  202. res.userInfo.grade = studententity.Grade;
  203. var majorinfo = majorIbll.GetCdMajorEntityByMajorNo(studententity.MajorNo);
  204. if (majorinfo != null)
  205. {
  206. res.userInfo.majorno = majorinfo.ID ?? "";
  207. }
  208. }
  209. //是否强密码验证
  210. bool pwd = false;
  211. if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["verifypwd"]) && ConfigurationManager.AppSettings["verifypwd"] == "true" && loginModel.up == false)
  212. {
  213. pwd = true;
  214. }
  215. else
  216. {
  217. //保存用户设备号
  218. userIbll.UpdateWeixinOpenId(userEntity.F_UserId, loginModel.openid);
  219. }
  220. var jsonData = new
  221. {
  222. baseinfo = res.userInfo,
  223. post = postIBLL.GetListByPostIds(res.userInfo.postIds),
  224. role = roleIBLL.GetListByRoleIds(res.userInfo.roleIds),
  225. pwd = pwd
  226. };
  227. return Success(jsonData);
  228. }
  229. #endregion
  230. }
  231. public Response GetWeixinWebaccess_token(dynamic _)
  232. {
  233. var entity = weChatConfigIbll.GetEnableEntity();
  234. string appid = entity?.APPId;
  235. string secret = entity?.secret;
  236. string url = Request.Query["url"];
  237. var responsejson = HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
  238. if (!string.IsNullOrEmpty(responsejson))
  239. {
  240. var weixintokenobj = JsonConvert.DeserializeObject<dynamic>(responsejson);
  241. if (string.IsNullOrEmpty(weixintokenobj.errcodeValue))
  242. {
  243. string access_token = weixintokenobj.access_token;
  244. string jsapi_ticket = HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi");
  245. var weixinjsapiticketobj = JsonConvert.DeserializeObject<dynamic>(jsapi_ticket);
  246. if (weixinjsapiticketobj.errcode == 0)
  247. {
  248. string ticket = weixinjsapiticketobj.ticket;
  249. //生成签名
  250. string noncestr = Util.CommonHelper.CreateNo();
  251. string timestamp = GetTimeStamp(true);
  252. string param = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
  253. string certificate = SHA1(param).ToLower();
  254. return Success(new { appid, noncestr, timestamp, certificate });
  255. }
  256. else
  257. {
  258. return Fail("2.getticket 微信授权失败,请重试。" + weixinjsapiticketobj.errcode + weixinjsapiticketobj.errmsg+ ",access_tokenjson:" + responsejson);
  259. }
  260. }
  261. else
  262. {
  263. return Fail("1.token 微信授权失败,请重试。" + weixintokenobj.errcode + weixintokenobj.errmsg+weixintokenobj.errcodeValue);
  264. }
  265. }
  266. else
  267. {
  268. return Fail("微信授权失败,请重试。");
  269. }
  270. }
  271. /// <summary>
  272. /// 发起一个HTTP请求(以GET方式)
  273. /// </summary>
  274. /// <param name="url"></param>
  275. /// <returns></returns>
  276. public string HttpGet(string url)
  277. {
  278. WebRequest myWebRequest = WebRequest.Create(url);
  279. WebResponse myWebResponse = myWebRequest.GetResponse();
  280. Stream ReceiveStream = myWebResponse.GetResponseStream();
  281. string responseStr = "";
  282. if (ReceiveStream != null)
  283. {
  284. StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
  285. responseStr = reader.ReadToEnd();
  286. reader.Close();
  287. }
  288. myWebResponse.Close();
  289. return responseStr;
  290. }
  291. /// <summary>
  292. /// 获取当前时间戳
  293. /// </summary>
  294. /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.bool bflag = true</param>
  295. /// <returns></returns>
  296. public static string GetTimeStamp(bool bflag)
  297. {
  298. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  299. string ret = string.Empty;
  300. if (bflag)
  301. ret = Convert.ToInt64(ts.TotalSeconds).ToString();
  302. else
  303. ret = Convert.ToInt64(ts.TotalMilliseconds).ToString();
  304. return ret;
  305. }
  306. // <summary>
  307. /// SHA1 加密,返回大写字符串
  308. /// </summary>
  309. /// <param name="content">需要加密字符串</param>
  310. /// <returns>返回40位UTF8 大写</returns>
  311. public static string SHA1(string content)
  312. {
  313. return SHA1(content, Encoding.UTF8);
  314. }
  315. /// <summary>
  316. /// SHA1 加密,返回大写字符串
  317. /// </summary>
  318. /// <param name="content">需要加密字符串</param>
  319. /// <param name="encode">指定加密编码</param>
  320. /// <returns>返回40位大写字符串</returns>
  321. public static string SHA1(string content, Encoding encode)
  322. {
  323. try
  324. {
  325. SHA1 sha1 = new SHA1CryptoServiceProvider();
  326. byte[] bytes_in = encode.GetBytes(content);
  327. byte[] bytes_out = sha1.ComputeHash(bytes_in);
  328. sha1.Dispose();
  329. string result = BitConverter.ToString(bytes_out);
  330. result = result.Replace("-", "");
  331. return result;
  332. }
  333. catch (Exception ex)
  334. {
  335. throw new Exception("SHA1加密出错:" + ex.Message);
  336. }
  337. }
  338. /// <summary>
  339. /// 获取IP
  340. /// </summary>
  341. /// <returns></returns>
  342. private string GetIP()
  343. {
  344. //string ip = string.Empty;
  345. //if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
  346. // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
  347. //if (string.IsNullOrEmpty(ip))
  348. // ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
  349. //return ip;
  350. string userIP = "未获取用户IP";
  351. try
  352. {
  353. if (System.Web.HttpContext.Current == null
  354. || System.Web.HttpContext.Current.Request == null
  355. || System.Web.HttpContext.Current.Request.ServerVariables == null)
  356. {
  357. return "";
  358. }
  359. string CustomerIP = "";
  360. //CDN加速后取到的IP simone 090805
  361. CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
  362. if (!string.IsNullOrEmpty(CustomerIP))
  363. {
  364. return CustomerIP;
  365. }
  366. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  367. if (!string.IsNullOrEmpty(CustomerIP))
  368. {
  369. return CustomerIP;
  370. }
  371. if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
  372. {
  373. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  374. if (CustomerIP == null)
  375. {
  376. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  377. }
  378. }
  379. else
  380. {
  381. CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  382. }
  383. if (string.Compare(CustomerIP, "unknown", true) == 0 || string.IsNullOrEmpty(CustomerIP))
  384. {
  385. return System.Web.HttpContext.Current.Request.UserHostAddress;
  386. }
  387. return CustomerIP;
  388. }
  389. catch { }
  390. return userIP;
  391. }
  392. }
  393. }