private byte[] Serialize(T obj) { byte[] data; using (var ms = new MemoryStream()) { Serializer.Serialize(ms, obj); data = ms.ToArray(); } if (_isCompressed) { data = QuickLZ.compress(data, 3); } if (_isEncrypted) { data = AesHelper.AesEncrypt(data, GetBytes(_encKey)); } var body = data; var header = BitConverter.GetBytes(body.Length); var payload = header.Concat(body).ToArray(); return(payload); }
/// <summary> /// 登录凭证校验(用作测试的) /// </summary> /// <param name="appid"></param> /// <param name="js_code"></param> /// <returns>{"session_key":"gAtKIuM6mn8F50iSUCZE9w==","openid":"o0LDq4njwCCuQuj3FOIZeLFDrc9o"}</returns> public IActionResult Jscode2session_Test(string appid, string secret, string js_code) { var url = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", appid, secret, js_code); var response = HttpHelper.Get(url); //return response; //var response = AllPublicServices.WechatHelper.Jscode2session((Enums.Wechat.AppKey)appKey, js_code); if (response.IndexOf("invalid") > -1) { //记录错误日志 AllLogServices.SysExceptionLogService.AddLog(M.Log.Services.Enum.ExceptionType.Exception, new Exception(response), "CatErrorFilterAttribute"); //记录请求日志 AllLogServices.SysHttpRequestLogService.AddLog(); } if (response.IndexOf("session_key") > -1 && response.IndexOf("openid") > -1) { var tempModel = Serializer.JsonDeserialize <TempModel>(response); tempModel.token = AesHelper.AesEncrypt(new Cat.M.Book.Models.ModelBinder.ReturnModels.BookAuth() { Openid = tempModel.openid, LoginTime = DateTime.Now }.ToJson()); response = Serializer.JsonSerialize(tempModel); } return(Content(response)); }
/// <summary> /// 测试aes加密 /// </summary> public void TestAesHelper() { var testStr = "FreshMan"; var enCodeStr = AesHelper.AesEncrypt(testStr); var deCodeStr = AesHelper.AesDecrypt(enCodeStr); deCodeStr.IsEqualTo(testStr); }
public ActionResult ChangePassword(string firstpwd) { var resultMode = new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Success, Message = "响应成功" }; if (string.IsNullOrEmpty(firstpwd)) { resultMode.ResultCode = ResponceCodeEnum.Fail; resultMode.Message = "新密码为空"; } else { var newPassword = AesHelper.AesEncrypt(firstpwd); var server = new AccountService(); try { var currentModel = server.GetSysUser(CurrentModel.Id); if (currentModel == null) { resultMode.Message = "登录超时,请退出重新登录"; resultMode.ResultCode = ResponceCodeEnum.Fail; return(Json(resultMode, JsonRequestBehavior.AllowGet)); } var resetUser = server.GetSysUser(CurrentModel.Id); if (resetUser == null) { resultMode.Message = "用户无效"; resultMode.ResultCode = ResponceCodeEnum.Fail; return(Json(resultMode, JsonRequestBehavior.AllowGet)); } resetUser.Password = newPassword; server.SaveUserModel(resetUser); return(Json(resultMode, JsonRequestBehavior.AllowGet)); } catch (Exception e) { Trace.WriteLine(e); } } return(Json(resultMode, JsonRequestBehavior.AllowGet)); }
public ActionResult ResetPassword(int id) { var resultMode = new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Success, Message = "响应成功" }; var newPassword = AesHelper.AesEncrypt("123456"); var server = new AccountService(); try { var currentModel = server.GetSysUser(CurrentModel.Id); if (currentModel == null) { resultMode.Message = "登录超时,请退出重新登录"; resultMode.ResultCode = ResponceCodeEnum.Fail; return(Json(resultMode, JsonRequestBehavior.AllowGet)); } if (currentModel.UserType == UserTypeEnum.SuperAdmin || currentModel.UserType == UserTypeEnum.UsuallyAdmin) { var resetUser = server.GetSysUser(id); if (resetUser == null) { resultMode.Message = "用户无效"; resultMode.ResultCode = ResponceCodeEnum.Fail; return(Json(resultMode, JsonRequestBehavior.AllowGet)); } resetUser.Password = newPassword; server.SaveUserModel(resetUser); return(Json(resultMode, JsonRequestBehavior.AllowGet)); } resultMode.Message = "还不是管理员,不能重置密码"; resultMode.ResultCode = ResponceCodeEnum.Fail; return(Json(resultMode, JsonRequestBehavior.AllowGet)); } catch (Exception e) { Trace.WriteLine(e); } return(Json(resultMode, JsonRequestBehavior.AllowGet)); }
public ActionResult Login(string username, string password, string checkcode) { var code = Session["ValidateCode"]?.ToString(); if (string.IsNullOrEmpty(code) || !code.Equals(checkcode, StringComparison.CurrentCultureIgnoreCase)) { ModelState.AddModelError("error", "验证码错误"); Session["ValidateCode"] = null; return(View()); } password = AesHelper.AesEncrypt(password); var loginInfo = _accountService.UserLogin(username, password); if (loginInfo != null && loginInfo.IsLogin) { string data = JsonConvert.SerializeObject(loginInfo); CookieHelper.SetCookie(StaticFileHelper.UserCookieStr, AesHelper.AesEncrypt(DesHelper.DesEnCode(data))); return(Redirect(ViewBag.RootNode + "/Home/WelCome")); } ModelState.AddModelError("error", "用户名或密码错误"); return(View()); }
private static byte[] GetByteMsg(string msg) { byte[] msgBytes = null; switch (EncryptType) { case EncryptDecryptType.Aes: msgBytes = AesHelper.AesEncrypt(_encoding.GetBytes(msg), "Jlfc_QQh.2018@11!~^$#GRqB++(())1"); break; case EncryptDecryptType.Rsa: //msgBytes = RsaHelper.RsaEncryptToBytes(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["RsaPublicKey"]), msg); break; case EncryptDecryptType.None: msgBytes = _encoding.GetBytes(msg); break; default: throw new ArgumentOutOfRangeException(); } return(msgBytes); }
/// <summary> /// 登录凭证校验 /// </summary> /// <param name="appKey">对应数据库表Wechat_App_Config中的Mark_Key配置值</param> /// <param name="js_code"></param> /// <returns>{"session_key":"gAtKIuM6mn8F50iSUCZE9w==","openid":"o0LDq4njwCCuQuj3FOIZeLFDrc9o"}</returns> public IActionResult Jscode2session(int appKey, string js_code) { var response = AllPublicServices.WechatHelper.Jscode2session((Enums.Wechat.AppKey)appKey, js_code); if (response.IndexOf("invalid") > -1) { //记录错误日志 AllLogServices.SysExceptionLogService.AddLog(M.Log.Services.Enum.ExceptionType.Exception, new Exception(response), "CatErrorFilterAttribute"); //记录请求日志 AllLogServices.SysHttpRequestLogService.AddLog(); } if (response.IndexOf("session_key") > -1 && response.IndexOf("openid") > -1) { var tempModel = Serializer.JsonDeserialize <TempModel>(response); tempModel.token = AesHelper.AesEncrypt(new Cat.M.Book.Models.ModelBinder.ReturnModels.BookAuth() { Openid = tempModel.openid, LoginTime = DateTime.Now }.ToJson()); response = Serializer.JsonSerialize(tempModel); } return(Content(response)); }
public ResponseBaseModel <WeChatAuthResponseModel> GetUserOpenId([FromBody] WeChatLoginInfo loginInfo) { var data = RedisCacheHelper.Get <WeChatAuthResponseModel>(RedisCacheKey.AuthInfoKey + loginInfo.code); if (data != null) { return(new ResponseBaseModel <WeChatAuthResponseModel> { ResultCode = ResponceCodeEnum.Success, Message = "微信认证成功", Data = data }); } var weChatCheck = new WeChatAppDecrypt( string.IsNullOrEmpty(loginInfo.sys) ? AppConfigurationHelper.GetString("XcxAppID", "") : AppConfigurationHelper.GetString("XcxAppID" + loginInfo.sys), string.IsNullOrEmpty(loginInfo.sys) ? AppConfigurationHelper.GetString("XcxAppSecrect", "") : AppConfigurationHelper.GetString("XcxAppSecrect" + loginInfo.sys, "")); var openIdAndSessionKeyModel = weChatCheck.DecodeOpenIdAndSessionKey(loginInfo); if (openIdAndSessionKeyModel == null) { return(new ResponseBaseModel <WeChatAuthResponseModel> { ResultCode = ResponceCodeEnum.Fail, Message = "微信认证失败" }); } var isValidData = weChatCheck.VaildateUserInfo(loginInfo, openIdAndSessionKeyModel); if (!isValidData) { return(new ResponseBaseModel <WeChatAuthResponseModel> { ResultCode = ResponceCodeEnum.Fail, Message = "请求信息验签失败" }); } var responseData = weChatCheck.Decrypt(loginInfo.encryptedData, loginInfo.iv, openIdAndSessionKeyModel.session_key); if (responseData == null) { return(new ResponseBaseModel <WeChatAuthResponseModel> { ResultCode = ResponceCodeEnum.Fail, Message = "微信认证失败" }); } var server = new WechatAccountService(); var searchOpenIdModel = server.GetByOpenId(responseData.openId); //TODO:新的访问者 if (searchOpenIdModel == null) { var newModel = new WeChatAccountModel { AvatarUrl = responseData.avatarUrl, CreateTime = DateTime.Now, Gender = DataTypeConvertHelper.ToInt(responseData.gender, 1), IsDel = FlagEnum.HadZore.GetHashCode(), NickName = responseData.nickName, OpenId = responseData.openId, Remarks = "新访问用户", FamilyCode = "", HadBindFamily = FlagEnum.HadZore }; server.SaveModel(newModel); var newSysModel = new SysUser { Birthday = "1900-01-01 00:00:00", CreateTime = DateTime.Now, IsDel = FlagEnum.HadZore, CreateAuth = 1, HeadUrl = newModel.AvatarUrl, Password = AesHelper.AesEncrypt("123456"), Sex = EnumHelper.GetEnumByValue <SexEnum>(newModel.Gender), UpdateAuth = 1, UpdateTime = DateTime.Now, UserType = UserTypeEnum.Usually, UserName = Guid.NewGuid().ToString() }; var accountService = new AccountService(); var resultId = accountService.InsertWeChatUserAndBind(newSysModel, newModel.OpenId); newModel.AccountId = resultId; searchOpenIdModel = newModel; } //TODO:未绑定用户,自动注册绑定 else if (searchOpenIdModel.AccountId < 1) { var newSysModel = new SysUser { Birthday = "1900-01-01 00:00:00", CreateTime = DateTime.Now, IsDel = FlagEnum.HadZore, CreateAuth = 1, HeadUrl = searchOpenIdModel.AvatarUrl, Password = AesHelper.AesEncrypt("123456"), Sex = EnumHelper.GetEnumByValue <SexEnum>(searchOpenIdModel.Gender), UpdateAuth = 1, UpdateTime = DateTime.Now, UserType = UserTypeEnum.Usually, UserName = Guid.NewGuid().ToString() }; var accountService = new AccountService(); var resultId = accountService.InsertWeChatUserAndBind(newSysModel, searchOpenIdModel.OpenId); searchOpenIdModel.AccountId = resultId; } //TODO:更新用户的昵称,头像 else { searchOpenIdModel.AvatarUrl = responseData.avatarUrl; searchOpenIdModel.NickName = responseData.nickName; searchOpenIdModel.UpDateTime = DateTime.Now; server.SaveModel(searchOpenIdModel); } //TODO:获取家庭成员信息 var userIds = new List <long>(); if (searchOpenIdModel.HadBindFamily == FlagEnum.HadOne && !string.IsNullOrEmpty(searchOpenIdModel.FamilyCode)) { var members = _familyServer.GetFamilyMembers(searchOpenIdModel.FamilyCode); if (members != null && members.Count > 0) { userIds.AddRange(members.Select(f => f.UserId)); } } var weChatMemberList = new List <WeChatAuthResponseModel>(); if (userIds.Count > 0) { var weChatMembers = server.Get(userIds); if (weChatMembers != null && weChatMembers.Count > 0) { weChatMemberList = weChatMembers.Select(f => new WeChatAuthResponseModel { AvatarUrl = f.AvatarUrl, AccountId = f.AccountId, NickName = f.NickName }).ToList(); } } var resultModel = new WeChatAuthResponseModel { Token = Guid.NewGuid().ToString(), CodeTimeSpan = responseData.watermark?.timestamp, AvatarUrl = responseData.avatarUrl, AccountId = searchOpenIdModel.AccountId, NickName = responseData.nickName, WechatMemberList = weChatMemberList }; //TODO:记录Token信息 RedisCacheHelper.AddSet(RedisCacheKey.AuthInfoKey + loginInfo.code, resultModel, DateTime.Now.AddHours(2)); RedisCacheHelper.AddSet(RedisCacheKey.AuthTokenKey + resultModel.Token, searchOpenIdModel, DateTime.Now.AddHours(2)); return(new ResponseBaseModel <WeChatAuthResponseModel> { ResultCode = ResponceCodeEnum.Success, Message = "微信认证成功", Data = resultModel }); }
public ResponseBaseModel <dynamic> BindWeChatUser(string name, string password, string checkcode, string token) { if (string.IsNullOrEmpty(token)) { return(new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Fail, Message = "token失效" }); } var userData = RedisCacheHelper.Get <WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token); if (userData == null || userData.AccountId > 0) { return(new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Fail, Message = "token失效或者已经绑定过信息" }); } if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(password)) { return(new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Fail, Message = "用户名和密码不能为空" }); } if (string.IsNullOrEmpty(checkcode)) { return(new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Fail, Message = "验证码不能为空" }); } var oldCheckCode = RedisCacheHelper.Get <string>(RedisCacheKey.AuthCheckCodeKey + token); RedisCacheHelper.Remove(RedisCacheKey.AuthCheckCodeKey + token); if (oldCheckCode != checkcode) { return(new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Fail, Message = "验证码错误" }); } var accountService = new AccountService(); password = AesHelper.AesEncrypt(password); var loginInfo = accountService.GetSysUsersByUserName(name)?.FirstOrDefault(); //没有该用户则注册一个用户 if (loginInfo == null || loginInfo.Id < 1) { var newModel = new SysUser { Birthday = "1900-01-01 00:00:00", CreateTime = DateTime.Now, IsDel = FlagEnum.HadZore, CreateAuth = 1, HeadUrl = userData.AvatarUrl, Password = password, Sex = EnumHelper.GetEnumByValue <SexEnum>(userData.Gender), UpdateAuth = 1, UpdateTime = DateTime.Now, UserType = UserTypeEnum.Usually, UserName = name }; var resultId = accountService.InsertWeChatUserAndBind(newModel, userData.OpenId); //处理成功 if (resultId > 0) { userData.AccountId = resultId; RedisCacheHelper.AddSet(RedisCacheKey.AuthTokenKey + token, userData, DateTime.Now.AddDays(1)); } var resultModel = new WeChatAuthResponseModel { Token = token, CodeTimeSpan = DateTime.Now.AddDays(1).ToLongTimeString(), AvatarUrl = userData.AvatarUrl, AccountId = resultId }; return(new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Success, Message = "", Data = resultModel }); } //有该用户,查看是否已经绑定过别人 else { if (loginInfo.Password != password) { return(new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Fail, Message = "密码错误" }); } var wechatServer = new WechatAccountService(); var otherData = wechatServer.GetByAccountId(loginInfo.Id); //有人已经绑定了 if (otherData != null) { if (otherData.OpenId == userData.OpenId) { var resultModeltemp = new WeChatAuthResponseModel { Token = token, CodeTimeSpan = DateTime.Now.AddDays(1).ToLongTimeString(), AvatarUrl = userData.AvatarUrl, AccountId = loginInfo.Id }; RedisCacheHelper.AddSet(RedisCacheKey.AuthTokenKey + token, userData, DateTime.Now.AddDays(1)); return(new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Success, Message = "", Data = resultModeltemp }); } return(new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Fail, Message = "非法绑定" }); } userData.AccountId = loginInfo.Id; var oldModel = wechatServer.GetByOpenId(userData.OpenId); if (oldModel == null) { wechatServer.SaveModel(userData); } else { oldModel.AccountId = userData.AccountId; wechatServer.SaveModel(oldModel); } RedisCacheHelper.AddSet(RedisCacheKey.AuthTokenKey + token, userData, DateTime.Now.AddDays(1)); var resultModel = new WeChatAuthResponseModel { Token = token, CodeTimeSpan = DateTime.Now.AddDays(1).ToLongTimeString(), AvatarUrl = userData.AvatarUrl, AccountId = loginInfo.Id }; return(new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Success, Message = "", Data = resultModel }); } }
public ActionResult SaveDataInfo(SysUser model) { var resultMode = new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Success, Message = "响应成功" }; var server = new AccountService(); var saveModel = new SysUser(); if (model == null) { Debug.WriteLine("请求参数为空"); resultMode.Message = "保存失败"; resultMode.ResultCode = ResponceCodeEnum.Fail; return(Json(resultMode, JsonRequestBehavior.AllowGet)); } if (model.Id > 0) { saveModel = server.GetSysUser(model.Id); if (saveModel == null) { resultMode.Message = "该菜单已经被删除"; resultMode.ResultCode = ResponceCodeEnum.Fail; return(Json(resultMode, JsonRequestBehavior.AllowGet)); } if (saveModel.UserName != model.UserName) { resultMode.Message = "登录名不允许修改"; resultMode.ResultCode = ResponceCodeEnum.Fail; return(Json(resultMode, JsonRequestBehavior.AllowGet)); } } else { var list = server.GetSysUsersByUserName(model.UserName); if (list != null && list.Count > 0) { resultMode.Message = "用户名已经被占用"; resultMode.ResultCode = ResponceCodeEnum.Fail; return(Json(resultMode, JsonRequestBehavior.AllowGet)); } saveModel.CreateAuth = CurrentModel.Id; saveModel.CreateTime = DateTime.Now; saveModel.Password = AesHelper.AesEncrypt("123456"); } saveModel.Id = model.Id; saveModel.Birthday = model.Birthday; saveModel.Sex = model.Sex; saveModel.TelPhone = model.TelPhone; saveModel.IsDel = FlagEnum.HadZore; saveModel.TrueName = model.TrueName; saveModel.UserType = model.UserType; saveModel.UpdateAuth = CurrentModel.Id; saveModel.UpdateTime = DateTime.Now; saveModel.UserName = model.UserName; try { server.SaveUserModel(saveModel); return(Json(resultMode, JsonRequestBehavior.AllowGet)); } catch (Exception e) { Debug.WriteLine(e.Message); resultMode.Message = "保存失败"; resultMode.ResultCode = ResponceCodeEnum.Fail; resultMode.Data = e.Message; return(Json(resultMode, JsonRequestBehavior.AllowGet)); } }
public async Task <ResultEx> InitDataBase(InstallSqlServerModel sqlServerModel) { var result = CheckSqlServerParameter(sqlServerModel); if (result.Flag) { _dataBaseName = result.Data.ToString(); string connectionString; if (!string.IsNullOrEmpty(sqlServerModel.ConnectionString)) { sqlServerModel.ConnectionString = sqlServerModel.ConnectionString.Trim(); } if (sqlServerModel.ConnectionType == ConnectionType.String) { connectionString = sqlServerModel.ConnectionString; } else { connectionString = CreateConnectionString( sqlServerModel.AuthenticationType == AuthenticationType.Windows, sqlServerModel.ServerName, sqlServerModel.DatabaseName, sqlServerModel.Username, sqlServerModel.Password); } //创建新的DBContext对象只是数据库创建操作 var builder = new DbContextOptionsBuilder(); builder.UseSqlServer(connectionString); var dbContext = new Kj1012Context(builder.Options); var dataBase = dbContext.Database; var databaseCreator = dataBase.GetService <IRelationalDatabaseCreator>(); sqlServerModel.ConnectionString = connectionString; var isCreateDatabase = false; if (sqlServerModel.AlwaysCreate) { if (databaseCreator.Exists()) { await databaseCreator.DeleteAsync(); } await CreateDataBase(databaseCreator, dataBase); isCreateDatabase = true; } else if (sqlServerModel.NotExistCreate) { if (!databaseCreator.Exists()) { await CreateDataBase(databaseCreator, dataBase); isCreateDatabase = true; } } else { if (!databaseCreator.Exists()) { return(ResultEx.Init(false, "数据库名称不存在,请核对")); } } var version = GetSqlServerVersion(sqlServerModel.ConnectionString); if (version < 10) { return(ResultEx.Init(false, "创建数据表失败,Sql Server 数据库版本至少需要Sql Server 2008及以上")); } if (version > 0) { //SQL Server2016 及以上执行2016脚本 if (version >= 13 && isCreateDatabase) { //执行2016脚本 ExecuteSqlScriptFromFile(dataBase, $"{SqlServerScriptPath}\\SqlServer_2016.sql"); } //保存数据库配置信息 _appSettingService.SaveDataSetting(new DataSettings { DataProvider = DataProviderType.SqlServer, Version = version, ConnectionString = AesHelper.AesEncrypt(sqlServerModel.ConnectionString, ConstDefine.DataSettingAesKey) }); } else { return(ResultEx.Init(false, "创建数据表失败,未知SQL SERVER数据库版本")); } } return(result); }