using JCSoft.WX.Framework.Api; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Common.Wechat; using Common; using ZcPeng.PublicLibrary; using ZcPeng.weixin.PublicAccount; using JCSoft.WX.Framework.Models.ApiResponses; using JCSoft.WX.Framework.Models.ApiRequests; using JCSoft.WX.Framework.Models; using System.Security.Claims; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication; using System.IO; using System.Text; using Newtonsoft.Json; using Microsoft.AspNetCore.Cors; using SupplierWeb.Codes.mvc; using Newtonsoft.Json.Converters; using Microsoft.Extensions.Caching.Memory; using SupplierWeb.Codes.Auth; using System.Threading; using CoreEntity.Entity; using System.Data; using Common.Model; using CoreEntity.DAL; using log4net; using Common.Config; namespace SupplierWeb.Controllers { [Route("web/login")] //[AutoValidateAntiforgeryToken] //[IgnoreAntiforgeryToken] public class LoginController : BaseController { public LoginController(IMemoryCache cache, IApiClient client) : base(cache, client) { } [HttpGet, Route("getOperationToken")] public ActionResult Token(string staffId) { //var resultMsg = new { Success = true, Msg = "", Code = 0, Data = new Token() }; Guid id; string ids = string.Empty; //判断参数是否合法 if (string.IsNullOrEmpty(staffId) || (!Guid.TryParse(staffId, out id))) { //resultMsg = new { Success = true, Msg = "非法参数", Code = 1, Data = new Token() }; return Content( "" + ids + ""); } //插入缓存 String signtoken; _cache.TryGetValue(id.ToString(), out signtoken); if (signtoken == null) { //var payload = new Dictionary() //{ // { "roleid", 1 }, // { "", "the-value" } //}; //var secretKey = Config.SecretKey; //string SignToken = Jwt.JsonWebToken.Encode(payload, secretKey, Jwt.JwtHashAlgorithm.HS256); //Token token = new Token(); //token.StaffId = Guid.NewGuid(); //token.SignToken = SignToken; //token.ExpireTime = DateTime.Now.AddSeconds(60); //_cache.GetOrCreate(token.StaffId.ToString(), entry => //{ // //entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120); // entry.SetAbsoluteExpiration(token.ExpireTime); // return DateTime.Now.ToString(); //}); } else { //延长token有效期 Token token = new Token(); token.StaffId = new Guid(staffId); token.SignToken = signtoken; token.ExpireTime = DateTime.Now.AddSeconds(TokenConfig.ExpireTime); var signtokenr = _cache.GetOrCreate(token.StaffId.ToString(), entry => { //entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120); entry.SetAbsoluteExpiration(token.ExpireTime); return token.SignToken; }); ids = staffId; } //返回token信息 //resultMsg = new { Success = true, Msg = "", Code = 0, Data = token }; //IsoDateTimeConverter timejson = new IsoDateTimeConverter //{ // DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss" //}; //var jsonData = JsonConvert.SerializeObject(token, timejson); return Content(""+ ids +""); } //[HttpOptions] //public JsonResult Options() //{ // return Json(""); //} private ILog log = LogManager.GetLogger(Startup.Repository.Name, typeof(LoginController)); ////登陆,根据供应商,采购,供应商业务员挂靠,资料管理员,财务,仓库 等角色设置权限 //[IgnoreAntiforgeryToken] //[EnableCors("CorsSample")] [HttpPost, Route("index")] public JsonResult index(string username, string password) { #region 获取user string commandText = "Select RoleId,AccountName,AccountPassWord,Id,PurStaffId From " + Config.TablePrefix+"Account Where AccountName=@username And accountPassWord=@password"; string result; DataTable dt = new DataTable(); HttpRequest req = HttpContext.Request; using (Stream stream = HttpContext.Request.Body) { byte[] buffer = new byte[HttpContext.Request.ContentLength.Value]; stream.Read(buffer, 0, buffer.Length); string content = Encoding.UTF8.GetString(buffer); var jsonData = JsonConvert.DeserializeAnonymousType(content, new { username = "", password = "" }); if (jsonData != null) { username = jsonData.username; password = jsonData.password; } } List> parameters = new List>(); if (username != null) parameters.Add(new List() { "username", username }); if (password != null) parameters.Add(new List() { "password", password }); DataAccess.GetValues(commandText, ref dt, DataAccess.ToParameters(parameters).ToArray(), out result); #endregion IList users = new List(); AccessToken restoken = null; if (dt != null&& dt.Rows.Count>0) { users = ModelConvertHelper.ConvertToModel(dt).ToArray(); var roleid = users[0].RoleId; if (roleid == 1 || roleid == 6 || roleid == 7) { //var restoken = WechatHelper.getAccessToken(_client); //加入公众号 AccountInfo account = new AccountInfo(Config.WeChatAppName, Config.WeChatAppKey, Config.WeChatAppSecret, null, null, null); AccountInfoCollection.SetAccountInfo(account); restoken = ZcPeng.weixin.PublicAccount.AccessToken.Get(Config.WeChatAppName); if (restoken != null) { var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaim(new Claim("appid", Config.WeChatAppKey)); identity.AddClaim(new Claim("appSecret", Config.WeChatAppSecret)); identity.AddClaim(new Claim("token", restoken.access_token)); var authProperties = new AuthenticationProperties { ExpiresUtc = new DateTimeOffset(DateTime.UtcNow.AddSeconds(restoken.expires_in)) }; HttpContext?.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), authProperties); } else { log.Error("获取微信token失败"); } } Token token = SupplierWeb.Codes.Auth.Token.genAndSaveToken(users,_cache,out var roleName,restoken); #region 更新登陆时间和ip string ip = HttpContext.Connection.RemoteIpAddress.ToString(); if (Request.Headers.ContainsKey("X-Real-IP")) { ip = Request.Headers["X-Real-IP"].ToString(); } if ((ip == "" || ip == null )&&Request.Headers.ContainsKey("X-Forwarded-For")) { ip = Request.Headers["X-Forwarded-For"].ToString(); } string commandTextUpdate = "UPDATE " + Config.TablePrefix + "Account " + " SET LastLoginTime = getdate()," + "LastLoginIp = @LastLoginIp " + " WHERE id= @Id "; string resultUpdate; //准备参数 List> parametersUpdate = new List>(); parametersUpdate.Add(new List() { "LastLoginIp", ip }); parametersUpdate.Add(new List() { "Id", users[0].Id }); int successUpdate = DataAccess.ExecuteCommand(commandTextUpdate, DataAccess.ToParameters(parametersUpdate), out resultUpdate); #endregion return Json(new { success = true, msg = resultUpdate, user = new { id = users[0].Id, username = username, staffid = token.StaffId, roleid = roleid, rolename = roleName, wxresponse = restoken /*, permissions = permission*/ } }); } else { return Json(new { success = false, msg = "登陆错误,请检查用户名密码", user = new { id = "", username = username, password = password } }); } } [HttpGet, Route("index")] public ActionResult getIndex(string username, string password, string callback) { var json = index(username, password); string jsonData = JsonConvert.SerializeObject(json.Value); return Content(callback + "(" + jsonData + ")"); } [HttpPost, Route("logout")] public JsonResult LogOut(string staffId) { _cache.Remove(staffId); HttpContext?.SignOutAsync(); return Json(new { success = true, msg = "" }); } } }