LoginController.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using JCSoft.WX.Framework.Api;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.AspNetCore.Http;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. using Common.Wechat;
  9. using Common;
  10. using ZcPeng.PublicLibrary;
  11. using ZcPeng.weixin.PublicAccount;
  12. using JCSoft.WX.Framework.Models.ApiResponses;
  13. using JCSoft.WX.Framework.Models.ApiRequests;
  14. using JCSoft.WX.Framework.Models;
  15. using System.Security.Claims;
  16. using Microsoft.AspNetCore.Authentication.Cookies;
  17. using Microsoft.AspNetCore.Authentication;
  18. using System.IO;
  19. using System.Text;
  20. using Newtonsoft.Json;
  21. using Microsoft.AspNetCore.Cors;
  22. using SupplierWeb.Codes.mvc;
  23. using Newtonsoft.Json.Converters;
  24. using Microsoft.Extensions.Caching.Memory;
  25. using SupplierWeb.Codes.Auth;
  26. using System.Threading;
  27. using CoreEntity.Entity;
  28. using System.Data;
  29. using Common.Model;
  30. using CoreEntity.DAL;
  31. using log4net;
  32. using Common.Config;
  33. namespace SupplierWeb.Controllers
  34. {
  35. [Route("web/login")]
  36. //[AutoValidateAntiforgeryToken]
  37. //[IgnoreAntiforgeryToken]
  38. public class LoginController : BaseController
  39. {
  40. public LoginController(IMemoryCache cache, IApiClient client) : base(cache, client)
  41. {
  42. }
  43. [HttpGet, Route("getOperationToken")]
  44. public ActionResult Token(string staffId)
  45. {
  46. //var resultMsg = new { Success = true, Msg = "", Code = 0, Data = new Token() };
  47. Guid id;
  48. string ids = string.Empty;
  49. //判断参数是否合法
  50. if (string.IsNullOrEmpty(staffId) || (!Guid.TryParse(staffId, out id)))
  51. {
  52. //resultMsg = new { Success = true, Msg = "非法参数", Code = 1, Data = new Token() };
  53. return
  54. Content( "" +
  55. ids
  56. + "");
  57. }
  58. //插入缓存
  59. String signtoken;
  60. _cache.TryGetValue<String>(id.ToString(), out signtoken);
  61. if (signtoken == null)
  62. {
  63. //var payload = new Dictionary<string, object>()
  64. //{
  65. // { "roleid", 1 },
  66. // { "", "the-value" }
  67. //};
  68. //var secretKey = Config.SecretKey;
  69. //string SignToken = Jwt.JsonWebToken.Encode(payload, secretKey, Jwt.JwtHashAlgorithm.HS256);
  70. //Token token = new Token();
  71. //token.StaffId = Guid.NewGuid();
  72. //token.SignToken = SignToken;
  73. //token.ExpireTime = DateTime.Now.AddSeconds(60);
  74. //_cache.GetOrCreate(token.StaffId.ToString(), entry =>
  75. //{
  76. // //entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120);
  77. // entry.SetAbsoluteExpiration(token.ExpireTime);
  78. // return DateTime.Now.ToString();
  79. //});
  80. }
  81. else
  82. {
  83. //延长token有效期
  84. Token token = new Token();
  85. token.StaffId = new Guid(staffId);
  86. token.SignToken = signtoken;
  87. token.ExpireTime = DateTime.Now.AddSeconds(TokenConfig.ExpireTime);
  88. var signtokenr = _cache.GetOrCreate(token.StaffId.ToString(), entry =>
  89. {
  90. //entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120);
  91. entry.SetAbsoluteExpiration(token.ExpireTime);
  92. return token.SignToken;
  93. });
  94. ids = staffId;
  95. }
  96. //返回token信息
  97. //resultMsg = new { Success = true, Msg = "", Code = 0, Data = token };
  98. //IsoDateTimeConverter timejson = new IsoDateTimeConverter
  99. //{
  100. // DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"
  101. //};
  102. //var jsonData = JsonConvert.SerializeObject(token, timejson);
  103. return Content(""+
  104. ids
  105. +"");
  106. }
  107. //[HttpOptions]
  108. //public JsonResult Options()
  109. //{
  110. // return Json("");
  111. //}
  112. private ILog log = LogManager.GetLogger(Startup.Repository.Name, typeof(LoginController));
  113. ////登陆,根据供应商,采购,供应商业务员挂靠,资料管理员,财务,仓库 等角色设置权限
  114. //[IgnoreAntiforgeryToken]
  115. //[EnableCors("CorsSample")]
  116. [HttpPost, Route("index")]
  117. public JsonResult index(string username, string password)
  118. {
  119. #region 获取user
  120. string commandText = "Select RoleId,AccountName,AccountPassWord,Id,PurStaffId From " + Config.TablePrefix+"Account Where AccountName=@username And accountPassWord=@password";
  121. string result;
  122. DataTable dt = new DataTable();
  123. HttpRequest req = HttpContext.Request;
  124. using (Stream stream = HttpContext.Request.Body)
  125. {
  126. byte[] buffer = new byte[HttpContext.Request.ContentLength.Value];
  127. stream.Read(buffer, 0, buffer.Length);
  128. string content = Encoding.UTF8.GetString(buffer);
  129. var jsonData = JsonConvert.DeserializeAnonymousType(content, new { username = "", password = "" });
  130. if (jsonData != null)
  131. {
  132. username = jsonData.username;
  133. password = jsonData.password;
  134. }
  135. }
  136. List<List<Object>> parameters = new List<List<Object>>();
  137. if (username != null)
  138. parameters.Add(new List<Object>() { "username", username });
  139. if (password != null)
  140. parameters.Add(new List<Object>() { "password", password });
  141. DataAccess.GetValues(commandText, ref dt, DataAccess.ToParameters(parameters).ToArray(), out result);
  142. #endregion
  143. IList<Account> users = new List<Account>();
  144. AccessToken restoken = null;
  145. if (dt != null&& dt.Rows.Count>0)
  146. {
  147. users = ModelConvertHelper<Account>.ConvertToModel(dt).ToArray();
  148. var roleid = users[0].RoleId;
  149. if (roleid == 1 || roleid == 6 || roleid == 7)
  150. {
  151. //var restoken = WechatHelper.getAccessToken(_client);
  152. //加入公众号
  153. AccountInfo account = new AccountInfo(Config.WeChatAppName, Config.WeChatAppKey, Config.WeChatAppSecret, null, null, null);
  154. AccountInfoCollection.SetAccountInfo(account);
  155. restoken = ZcPeng.weixin.PublicAccount.AccessToken.Get(Config.WeChatAppName);
  156. if (restoken != null)
  157. {
  158. var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
  159. identity.AddClaim(new Claim("appid", Config.WeChatAppKey));
  160. identity.AddClaim(new Claim("appSecret", Config.WeChatAppSecret));
  161. identity.AddClaim(new Claim("token", restoken.access_token));
  162. var authProperties = new AuthenticationProperties
  163. {
  164. ExpiresUtc = new DateTimeOffset(DateTime.UtcNow.AddSeconds(restoken.expires_in))
  165. };
  166. HttpContext?.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), authProperties);
  167. }
  168. else
  169. {
  170. log.Error("获取微信token失败");
  171. }
  172. }
  173. Token token = SupplierWeb.Codes.Auth.Token.genAndSaveToken(users,_cache,out var roleName,restoken);
  174. #region 更新登陆时间和ip
  175. string ip = HttpContext.Connection.RemoteIpAddress.ToString();
  176. if (Request.Headers.ContainsKey("X-Real-IP"))
  177. {
  178. ip = Request.Headers["X-Real-IP"].ToString();
  179. }
  180. if ((ip == "" || ip == null )&&Request.Headers.ContainsKey("X-Forwarded-For"))
  181. {
  182. ip = Request.Headers["X-Forwarded-For"].ToString();
  183. }
  184. string commandTextUpdate = "UPDATE " + Config.TablePrefix + "Account " +
  185. " SET LastLoginTime = getdate()," +
  186. "LastLoginIp = @LastLoginIp " +
  187. " WHERE id= @Id ";
  188. string resultUpdate;
  189. //准备参数
  190. List<List<Object>> parametersUpdate = new List<List<Object>>();
  191. parametersUpdate.Add(new List<Object>() { "LastLoginIp", ip });
  192. parametersUpdate.Add(new List<Object>() { "Id", users[0].Id });
  193. int successUpdate = DataAccess.ExecuteCommand(commandTextUpdate, DataAccess.ToParameters(parametersUpdate), out resultUpdate);
  194. #endregion
  195. return Json(new
  196. {
  197. success = true,
  198. msg = resultUpdate,
  199. user = new
  200. {
  201. id = users[0].Id,
  202. username = username,
  203. staffid = token.StaffId,
  204. roleid = roleid,
  205. rolename = roleName,
  206. wxresponse = restoken
  207. /*, permissions = permission*/
  208. }
  209. });
  210. }
  211. else
  212. {
  213. return Json(new { success = false, msg = "登陆错误,请检查用户名密码", user = new { id = "", username = username, password = password } });
  214. }
  215. }
  216. [HttpGet, Route("index")]
  217. public ActionResult getIndex(string username, string password, string callback)
  218. {
  219. var json = index(username, password);
  220. string jsonData = JsonConvert.SerializeObject(json.Value);
  221. return Content(callback + "("
  222. + jsonData +
  223. ")");
  224. }
  225. [HttpPost, Route("logout")]
  226. public JsonResult LogOut(string staffId)
  227. {
  228. _cache.Remove(staffId);
  229. HttpContext?.SignOutAsync();
  230. return Json(new { success = true, msg = "" });
  231. }
  232. }
  233. }