123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266 |
- 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<String>(id.ToString(), out signtoken);
- if (signtoken == null)
- {
- //var payload = new Dictionary<string, object>()
- //{
- // { "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<List<Object>> parameters = new List<List<Object>>();
- if (username != null)
- parameters.Add(new List<Object>() { "username", username });
- if (password != null)
- parameters.Add(new List<Object>() { "password", password });
- DataAccess.GetValues(commandText, ref dt, DataAccess.ToParameters(parameters).ToArray(), out result);
- #endregion
- IList<Account> users = new List<Account>();
- AccessToken restoken = null;
- if (dt != null&& dt.Rows.Count>0)
- {
- users = ModelConvertHelper<Account>.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<List<Object>> parametersUpdate = new List<List<Object>>();
- parametersUpdate.Add(new List<Object>() { "LastLoginIp", ip });
- parametersUpdate.Add(new List<Object>() { "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 = "" });
- }
- }
- }
|