using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System.Web; using MySystem.Models; using MySystem.MainModels; using LitJson; using Library; using Microsoft.IdentityModel.Tokens; using System.Text; using System.Security.Claims; using System.IdentityModel.Tokens.Jwt; namespace MySystem.Areas.Api.Controllers { [Area("Api")] [Route("Api/[controller]/[action]")] public class SystemSetController : BaseController { public SystemSetController(IHttpContextAccessor accessor, ILogger logger, IOptions setting) : base(accessor, logger, setting) { } #region APP启动初始数据 public JsonResult Detail(string value) { value = HttpUtility.UrlDecode(value); JsonData data = JsonMapper.ToObject(value); string apptype = data["apptype"].ToString(); string version = data["version"].ToString(); string CheckSignResult = CheckSign(value, new string[] { }); if (CheckSignResult != "1") { return Json(new AppResultJson() { Status = "-1", Info = CheckSignResult }); } else { return DetailDo(value); } } public JsonResult DetailDo(string value) { JsonData data = JsonMapper.ToObject(value); string apptype = data["apptype"].ToString(); string version = data["version"].ToString(); Dictionary Obj = new Dictionary(); List> PageSDK = new List>(); Models.SystemSet set = RedisDbconn.Instance.Get("SystemSet"); List files = RedisDbconn.Instance.GetList("FileUpdateInfo", 1, 1000).OrderBy(m => m.Path).OrderBy(m => m.FileName).ToList(); foreach (FileUpdateInfo subfile in files) { string Tag = function.MD5_16(subfile.Id.ToString()); string Url = subfile.Path; string FileName = subfile.FileName; int ver = subfile.Version; Dictionary row = new Dictionary(); row.Add("Url", Url); row.Add("DownloadUrl", "/skin/app/default/" + Url); row.Add("FileName", FileName); row.Add("Version", ver); row.Add("Tag", Tag); PageSDK.Add(row); } List> AfterStartPhotos = new List>(); string StartAdPhoto = "static/images/startadphoto.png"; if (!string.IsNullOrEmpty(set.StartAdPhoto)) { StartAdPhoto = set.StartAdPhoto; StartAdPhoto = StartAdPhoto.Substring(StartAdPhoto.IndexOf("static")); } string StartAdUrl = ""; Dictionary after = new Dictionary(); after.Add("Url", ""); after.Add("Photo", "static/images/afterstartphoto1.png"); AfterStartPhotos.Add(after); after = new Dictionary(); after.Add("Url", ""); after.Add("Photo", "static/images/afterstartphoto2.png"); AfterStartPhotos.Add(after); after = new Dictionary(); after.Add("Url", ""); after.Add("Photo", "static/images/afterstartphoto3.png"); AfterStartPhotos.Add(after); Obj.Add("PageSDK", PageSDK); //页面所需资源引用 List> HtmlVersion = new List>(); List pages = RedisDbconn.Instance.GetList("PageUpdateInfo", 1, 1000).ToList(); foreach (PageUpdateInfo page in pages) { Dictionary item = new Dictionary(); string DataId = function.MD5_16(page.ModulePath); item.Add("Id", page.Id.ToString()); item.Add("DataId", DataId); item.Add("ModuleVersion", page.ModuleVersion.ToString()); item.Add("FileName", page.ModulePath); HtmlVersion.Add(item); } Obj.Add("HtmlVersion", HtmlVersion); Obj.Add("IsPageSDKZip", "0"); Obj.Add("PageSDKZip", "/Areas/Admin/Assets/TemplateFile/Areas.zip"); Obj.Add("StartAdPhoto", string.IsNullOrEmpty(set.StartAdPhoto) ? "" : StartAdPhoto); Obj.Add("StartAdUrl", StartAdUrl); Obj.Add("AfterStartPhotos", AfterStartPhotos); Obj.Add("IsLeftSide", "0"); //是否侧滑 Obj.Add("LeftSideUrl", "http://www.baidu.com/"); //侧滑页面地址 if (apptype == "ios") { Obj.Add("AppClose", "0"); int check = RedisDbconn.Instance.GetList("AppVersion", 1, 1000).Count(m => m.TerminalKind == "ios"); if (check > 0) { AppVersion ver = RedisDbconn.Instance.GetList("AppVersion", 1, 1000).Where(m => m.TerminalKind == "ios").OrderByDescending(m => m.Id).FirstOrDefault(); if (ver.Status == 1 && versionToNumber(version) < versionToNumber(ver.VersionNum)) { Obj.Add("AppStatus", "1"); Obj.Add("AppTitle", ver.Title); Obj.Add("AppInfo", ver.Info); Obj.Add("AppBtn1", ver.ConfirmText); Obj.Add("AppBtn2", ver.CancelText); Obj.Add("AppBtn1Url", ver.DownloadUrl); } else { Obj.Add("AppStatus", "0"); } } else { Obj.Add("AppStatus", "0"); } } else { int check = RedisDbconn.Instance.GetList("AppVersion", 1, 1000).Count(m => m.TerminalKind == "android"); if (check > 0) { AppVersion ver = RedisDbconn.Instance.GetList("AppVersion", 1, 1000).Where(m => m.TerminalKind == "android").OrderByDescending(m => m.Id).FirstOrDefault(); if (ver.Status == 1 && versionToNumber(version) < versionToNumber(ver.VersionNum)) { Obj.Add("AppStatus", "1"); Obj.Add("AppTitle", ver.Title); Obj.Add("AppInfo", ver.Info); Obj.Add("AppBtn1", ver.ConfirmText); Obj.Add("AppBtn2", ver.CancelText); Obj.Add("AppBtn1Url", ver.DownloadUrl); } else { Obj.Add("AppStatus", "0"); } } else { Obj.Add("AppStatus", "0"); } } Obj.Add("ConnectErrUrl", ""); //网络错误页面 return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj }); } #endregion #region 附加方法 List SystemFilesV2; private void GetSystemFilesV2() { SystemFilesV2 = new List(); string dataFilePath = function.getPath("/wwwroot/skin/app/default/"); System.IO.FileSystemInfo info = new System.IO.DirectoryInfo(dataFilePath); scanV2(info); } private void scanV2(System.IO.FileSystemInfo info) { if (!info.Exists) return; System.IO.DirectoryInfo dir = info as System.IO.DirectoryInfo; //不是目录 if (dir == null) return; System.IO.FileSystemInfo[] files = dir.GetFileSystemInfos(); for (int i = 0; i < files.Length; i++) { System.IO.FileInfo file = files[i] as System.IO.FileInfo; //是文件 if (file != null) { string filename = file.FullName.Replace("\\", "/"); SystemFilesV2.Add(filename.Substring(filename.LastIndexOf("/"))); } else scanV2(files[i]); } } private int versionToNumber(string version) { string[] versionlist = version.Split('.'); string left = versionlist[0]; string mid = versionlist[1]; if (mid.Length == 1) mid = "00" + mid; if (mid.Length == 2) mid = "0" + mid; string right = versionlist[2]; if (right.Length == 1) right = "00" + right; if (right.Length == 2) right = "0" + right; string result = left + mid + right; return int.Parse(result); } #endregion #region 生成APP配置文件 public string makeAppInitData(string version, string apptype) { Models.SystemSet set = RedisDbconn.Instance.Get("SystemSet") ?? new Models.SystemSet(); string url = Host + "Api/APPSetInfo/List?value={\"Kind\":\"1\",\"PageSize\":\"10\",\"PageNum\":\"1\",\"version\":\"" + version + "\",\"apptype\":\"" + apptype + "\"}"; string AppInfoList = function.GetWebRequest(url); string SystemSet = function.GetWebRequest(Host + "Api/SystemSet/DetailDo?value={\"version\":\"" + version + "\",\"apptype\":\"" + apptype + "\"}"); string GotoPages = "{"; string PageInfoList = "{"; string LibFile = "{"; List newpages = RedisDbconn.Instance.GetList("PageUpdateInfo", 1, 1000).OrderBy(m => m.Id).ToList(); foreach (PageUpdateInfo page in newpages) { string FileName = page.ModulePath.Split('.')[0]; PageInfoList += "\"page" + FileName + "\":" + function.GetWebRequest(Host + "Api/PageUpdateInfo/CheckDo?value={\"Url\":\"" + FileName + "\",\"version\":\"" + version + "\",\"apptype\":\"" + apptype + "\"}&ismakefile=0") + ","; GotoPages += "\"page" + FileName + "\":\"" + function.CheckNull(page.GotoPages).Trim(',') + "\","; string PagePath = function.ReadInstance("/WebRootPath.txt") + "/template/app/default/" + page.ModulePath; string pageContent = function.ReadInstanceByFull(PagePath); pageContent = dbconn.Encrypt3DES(pageContent, "*ga34|^7"); LibFile += "\"page" + FileName + "\":\"" + pageContent + "\","; } PageInfoList = PageInfoList.TrimEnd(','); PageInfoList += "}"; GotoPages = GotoPages.TrimEnd(','); GotoPages += "}"; LibFile = LibFile.TrimEnd(','); LibFile += "}"; return AppInfoList + "#cut#" + SystemSet + "#cut#" + PageInfoList + "#cut#" + GotoPages + "#cut#" + dbconn.Encrypt3DES(LibFile, "*ga34|^7"); } #endregion #region 验证获取jwt的token public JsonResult AppCheck(string value) { value = DesDecrypt(value); JsonData data = JsonMapper.ToObject(value); string CheckSignResult = CheckSign(value, new string[] { "uuid", "salt" }); if (CheckSignResult != "1") { return Json(new AppResultJson() { Status = "-1", Info = CheckSignResult }); } else { string uuid = data["uuid"].ToString(); string salt = data["salt"].ToString(); string u = function.MD5_16(uuid + salt); Dictionary Obj = new Dictionary(); //生成jwt令牌 Obj.Add("Token", AppToken(u)); return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj }); } } public JsonResult AppCheckTest(string value) { value = DesDecrypt(value); JsonData data = JsonMapper.ToObject(value); string uuid = data["uuid"].ToString(); string salt = data["salt"].ToString(); string u = function.MD5_16(uuid + salt); Dictionary Obj = new Dictionary(); //生成jwt令牌 Obj.Add("Token", AppToken(u)); return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj }); } public string AppToken(string u) { u = "old_" + u; string test = function.get_Random(10); var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtSecret)), SecurityAlgorithms.HmacSha256); var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Iss,JwtIss), new Claim(JwtRegisteredClaimNames.Aud,test), new Claim("Guid", Guid.NewGuid().ToString("D")), new Claim(ClaimTypes.Role, "system"), new Claim(ClaimTypes.Role, "admin"), }; SecurityToken securityToken = new JwtSecurityToken( signingCredentials: securityKey, expires: DateTime.Now.AddDays(10),//过期时间 claims: claims, audience: test, issuer: u ); RedisDbconn.Instance.Set("utoken:" + u, test); RedisDbconn.Instance.SetExpire("utoken:" + u, 3600 * 24 * 10); //生成jwt令牌 return new JwtSecurityTokenHandler().WriteToken(securityToken); } public string AppTokenV2(int UserId, string DeviceId, string DeviceType) { string Token = RedisDbconn.Instance.Get("apptoken:" + DeviceId + ":" + DeviceType + ":" + UserId); if(!string.IsNullOrEmpty(Token)) { return Token; } string issuer = "new_" + UserId + "_" + DeviceId + "_" + DeviceType; string test = function.get_Random(10); var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtSecret)), SecurityAlgorithms.HmacSha256); var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Iss,JwtIss), new Claim(JwtRegisteredClaimNames.Aud,test), new Claim("Guid", Guid.NewGuid().ToString("D")), new Claim(ClaimTypes.Role, "system"), new Claim(ClaimTypes.Role, "admin"), }; SecurityToken securityToken = new JwtSecurityToken( signingCredentials: securityKey, expires: DateTime.Now.AddDays(10),//过期时间 claims: claims, audience: test, issuer: issuer ); RedisDbconn.Instance.Set("utoken:" + issuer, test); RedisDbconn.Instance.SetExpire("utoken:" + issuer, 3600 * 24 * 10); //生成jwt令牌 Token = new JwtSecurityTokenHandler().WriteToken(securityToken); RedisDbconn.Instance.Set("apptoken:" + DeviceId + ":" + DeviceType + ":" + UserId, Token); RedisDbconn.Instance.SetExpire("apptoken:" + DeviceId + ":" + DeviceType + ":" + UserId, 3600 * 24 * 10 - 60); return Token; } #endregion #region 获取OSS参数 public JsonResult OssParam(string value) { Dictionary Obj = new Dictionary(); Obj.Add("AccessId", "LTAI5t7ivibdYZTro4SRVZ9M"); Obj.Add("AccessKey", "nfr1bmbJbMhLuaj10iBORkuFfIAX7M"); return Json(new AppResultJson() { Status = "-1", Info = "", Data = Obj }); } #endregion #region 检查签名是否合法,合法返回1,不合法返回提示信息 /// /// 检查签名是否合法,合法返回1,不合法返回提示信息 /// /// 请求的参数(json字符串) /// 要签名的字段 /// private string CheckSign(string value, string[] signField) { JsonData json = JsonMapper.ToObject(value); Dictionary dic = new Dictionary(); for (int i = 0; i < signField.Length; i++) { dic.Add(signField[i], json[signField[i]].ToString()); } string sign = json["sign"].ToString(); //客户端签名字符串 return new Sign().sign(dic, sign); } #endregion } }