using PdmAlert.Util; using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Reflection; namespace PdmAlert { public class LoginUser { public static LoginUser CurrentUser { get; private set; } private static readonly Encryptor encryptor = new Encryptor("12345678123456781234567812345678", "1234567812345678"); public string id { get; set; } public string realName { get; set; } public string username { get; set; } public string password { get; set; } public string appId { get; set; } public string pluginVersion { get; set; } public bool rememberMe { get; set; } public static bool TryAutoLogin() { string fileContent = null; if (LoadStrFromBin(ref fileContent)) { try { string jsonStr = encryptor.Decrypt(fileContent); Dictionary user = JsonUtil.Deserialize>(jsonStr); return Login(user["username"], user["password"], true); } catch (Exception ex) { RemoveCacheBin(); return false; } } return false; } public static bool Login(string username, string password, bool rememberMe) { using (HttpClient client = new HttpClient { BaseAddress = new Uri("http://localhost:8888/pdm-web/"), }) { try { Result res = client.PostSyncAction(new LoginUser { username = username, password = password, appId = "sockettool", pluginVersion = "0.0.0.1" }, "openApi/wpf/login"); CurrentUser = res.HandleResult(); CurrentUser.password = password; CurrentUser.rememberMe = rememberMe; if (rememberMe) { string userInfo = JsonUtil.Stringfiy(CurrentUser); SaveStrToBin(encryptor.Encrypt(userInfo)); } return true; } catch (Exception ex) { RemoveCacheBin(); } } return false; } public static void SaveStrToBin(string content) { string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().FullName), "bin"); byte[] bytes = Convert.FromBase64String(content); using (Stream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Write(bytes); } } public static bool LoadStrFromBin(ref string content) { string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().FullName), "bin"); if (!File.Exists(filePath)) { return false; } using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) using (BinaryReader reader = new BinaryReader(stream)) { byte[] bytes = new byte[stream.Length]; reader.Read(bytes, 0, bytes.Length); content = Convert.ToBase64String(bytes); return true; } } public static void RemoveCacheBin() { string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().FullName), "bin"); File.Delete(filePath); } } }