public IActionResult GetValidateCode() { byte[] data = null; string code = CaptchaHelper.RandomCode(5); HttpContext.Session.SetString("code", code); //TempData["code"] = code; //定义一个画板 MemoryStream ms = new MemoryStream(); using (Bitmap map = new Bitmap(80, 32)) { //画笔,在指定画板画板上画图 //g.Dispose(); using (Graphics g = Graphics.FromImage(map)) { g.Clear(Color.White); g.DrawString(code, new Font("黑体", 18.0F), Brushes.Blue, new Point(4, 3)); //绘制干扰线 CaptchaHelper.PaintInterLine(g, 6, map.Width, map.Height); } map.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); } data = ms.GetBuffer(); //存在session中 return(File(data, "image/jpeg")); }
public IActionResult Get(string id) { if (!string.IsNullOrEmpty(id)) { _cacheService.Remove(id); } string code = CaptchaHelper.GetSingleObj().CreateCode(); string captoken = "V_" + Guid.NewGuid().ToString(); TimeSpan timeSpan = new TimeSpan(0, 0, 30); _cacheService.Add(captoken, code, timeSpan); var bitmap = CaptchaHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40); MemoryStream ms = new MemoryStream(); bitmap.Save(ms, ImageFormat.Gif); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); String strbaser64 = Convert.ToBase64String(arr); var send = new CacheM { Token = captoken, Img = strbaser64 }; return(Json(send)); }
/// <summary> /// Generation CAPTCHA /// </summary> /// <param name="encryptText">The text for captcha</param> public void Create(string encryptText) { try { if (Request.UrlReferrer.AbsolutePath == Request.Url.AbsolutePath) { throw new Exception(); } var encryptorModel = CaptchaHelper.GetEncryptorModel(); var generateImage = CaptchaHelper.GetGenerateImage(); if (string.IsNullOrEmpty(encryptText) || (encryptorModel == null)) { throw new ArgumentException(); } var captchaText = CaptchaHelper.GetEncryption().Decrypt(encryptText, encryptorModel.Password, encryptorModel.Salt); var capthaBmp = generateImage.Generate(captchaText); Response.ContentType = "image/gif"; capthaBmp.Save(Response.OutputStream, ImageFormat.Gif); } catch (Exception) { Response.ContentType = "image/gif"; ErrorBitmap().Save(Response.OutputStream, ImageFormat.Gif); } }
public async Task <ActionResult> Register(RegisterViewModel model) { CaptchaResponse response = CaptchaHelper.ValidateCaptcha(Request["g-recaptcha-response"]); if (!response.Success) { return(RedirectToAction("CaptchaInvalid", "Home")); } if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { UserManager.AddToRole(user.Id, "Owner"); //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); this.RegisterOwner(user.Id, model.FirstName, model.LastName, model.Email); //await SendConfirmationEmailAsync(user.Id); await SendConfirmationEmailAsync(user.Id, model.FirstName, model.LastName, model.Email, model.Password); return(RedirectToAction("AccountRegistered")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model) { if (!CaptchaHelper.Validate()) { ModelState.AddModelError("", "Invalid Captcha"); return(View(model)); } if (!ModelState.IsValid) { return(View(model)); } var user = await UserManager.FindByEmailAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return(RedirectToAction(nameof(ResetPasswordConfirmation))); } var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); if (result.Succeeded) { return(RedirectToAction(nameof(ResetPasswordConfirmation))); } AddErrors(result); return(View()); }
public IActionResult SendContactMessage([FromBody] ContactDto contact) { var secret = _webConfiguration.RecaptchaSecret; contact.Subject = "Contact Form Submission"; var captchaResponse = CaptchaHelper.GetCaptchaResponse( secret, contact?.ClientResponse, HttpContext.Connection.RemoteIpAddress.ToString()); if (!captchaResponse.Success) { return(BadRequest()); } var email = new SendGridTransactionalMessageDto { ApiKey = _webConfiguration.SendGridApiKey, Recipients = SendGridConstants.SendGrid_DevelopmentRecipientEmail, FromAddress = SendGridConstants.SendGrid_DevelopmentRecipientEmail, Subject = "Gray Wolf Contact Form", HtmlMessage = $@"Name: {contact.Name} <br/> Phone: {contact.PhoneNumber} <br/> Email: {contact.Email} <br/> Type: {contact.HelpYou} <br/> Message: {contact.Comments}" }; var response = _sendGridService.SendSingleEmail(email); return(Ok()); }
public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (!CaptchaHelper.Validate()) { ModelState.AddModelError("", "Invalid Captcha"); return(View(model)); } if (ModelState.IsValid) { var user = await UserManager.FindByEmailAsync(model.Email); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { // Don't reveal that the user does not exist or is not confirmed return(RedirectToAction(nameof(ForgotPasswordConfirmation))); } string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrl = Url.Action(nameof(ResetPassword), "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); await EmailService.SendEmail(Enums.EmailTemplateType.PasswordReset, user.Id, user.Email, user.UserName, callbackUrl); return(RedirectToAction(nameof(ForgotPasswordConfirmation))); } return(View(model)); }
/// <summary> /// 批量生成验证码 /// </summary> /// <param name="captcha">验证码帮助类</param> /// <param name="row">生成的行数</param> /// <param name="column">生成的列数</param> /// <param name="filePath">保存的图片的完整路径</param> private void BatchGenerateCaptcha(CaptchaHelper captcha, int row, int column, string filePath) { var hasChinese = captcha.Mode == CaptchaMode.Chinese || captcha.Mode == CaptchaMode.QuestionBank; int sigleWidth = captcha.StringLength * captcha.FontSize * (hasChinese ? 2 : 1); int sigleHeight = Convert.ToInt32(0.6 * captcha.FontSize + captcha.FontSize); int width = sigleWidth * column; //总图片宽度 int height = sigleHeight * row; //总图片高度 var image = new Bitmap(width, height); using Graphics graphics = Graphics.FromImage(image); graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.Clear(Color.White); for (int j = 0; j < 20; j++) { for (int i = 0; i < 10; i++) { graphics.DrawImage( captcha.GetCaptcha().Image, //生成的验证码 i * sigleWidth, //X位置 j * sigleHeight, //Y位置 sigleWidth, //单张验证码长度 sigleHeight //单张验证码高度 ); } } using FileStream stream = new(filePath, FileMode.OpenOrCreate); image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); }
/// <summary> /// 获取绑定账户的额外信息 /// </summary> /// <param name="userContext"></param> /// <returns></returns> public ResponseModel GetWithdrawingExtraInfo(UserContext userContext) { var result = CaptchaHelper.GetWithdrawingExtraInfo(userContext.AccId); var responseModel = new ResponseModel(); var youPaiSdk = new UploadCalculationInfo(); var payLoad = new YouPaiImgParams(); if (result.Code == ResponseErrorcode.C200) { if (result.Data != null) { var model = JsonConvert.DeserializeObject <WithdrawOtherData>( Helper.JsonSerializeObject(result.Data)); if (model.youPaiSDK != null) { payLoad.Policy = model.youPaiSDK.Policy; payLoad.Prefix = model.youPaiSDK.ImgHostUrl; payLoad.Signature = model.youPaiSDK.SignStr; payLoad.BucketName = model.youPaiSDK.BucketName; youPaiSdk.HasBusinessLicense = model.IsHasBusinessUrl; youPaiSdk.Payload = payLoad; } } } responseModel.Data = youPaiSdk; responseModel.Code = Convert.ToInt32(result.Code); responseModel.Message = result.Message; return(responseModel); }
private void Button_Click(object sender, RoutedEventArgs e) { if (!int.TryParse(TxtCaptchaCodeLength.Text, out int length)) { length = 4; } var captchaCode = CaptchaHelper.GenerateCaptchaCode(length); TxtCaptchaCode.Text = captchaCode; if (!int.TryParse(TxtImageWidth.Text, out int imageWidth)) { imageWidth = 200; } if (!int.TryParse(TxtImageHeight.Text, out int imageHeight)) { imageHeight = 50; } var captcha = CaptchaHelper.GenerateCaptcha(captchaCode, imageWidth, imageHeight); var bmp = new BitmapImage(); bmp.BeginInit(); bmp.StreamSource = new MemoryStream(captcha.ByteData); bmp.EndInit(); ImgCaptcha.Source = bmp; ImgCaptcha.Width = imageWidth; ImgCaptcha.Height = imageHeight; }
/// <summary> /// 得到验证码 /// </summary> /// <param name="emailTo"></param> /// <returns></returns> public async Task <string> GetRegisterCaptchaAsync(string emailTo) { if (await ExistUserAsync(emailTo)) { return("该邮箱已存在,请切换或找回密码"); } var key = $"{CacheKeys.REGISTERCAPTCHA}{emailTo}"; var expireMinutes = 5; if (await FrequentlyGetCaptchaAsync(key, expireMinutes, 2)) { return("获取验证码过于频繁,请稍后再获取"); } var captchaNumber = CaptchaHelper.CreateRandomNumber(6); var htmlEmail = SystemBll.GetMailContent("注册账号", captchaNumber, expireMinutes); var result = await SystemBll.SendSystemMailAsync("LionFrame-注册账号", htmlEmail, emailTo); if (result.Contains("发送成功")) { await RedisClient.SetAsync(key, captchaNumber, new TimeSpan(0, expireMinutes, 0)); } return(result); }
/// <summary> /// 根據新增學習圈建立驗證碼 /// </summary> /// <param name="circleKey"></param> /// <returns></returns> public bool CreateFromCreateLearningCircle(string circleKey) { var learningCircleService = new LearningCircleService(); var learningCircleInfo = learningCircleService.GetDetailByOuterKey(circleKey.ToLower()); if (learningCircleInfo == null) { return(false); } var codeService = new CaptchaHelper(); var code = codeService.GenerateRandomText(10); var checkHadCode = _uow.MemberInviteRepo.GetFirst(t => t.CircleKey.ToLower() == circleKey.ToLower() && t.Enable == true && t.IsCourseCode == true); if (checkHadCode == null) { var entity = new MemberInvite() { CircleKey = circleKey.ToLower(), Code = code.ToLower(), CreateDate = DateTime.UtcNow, Enable = true, InviteEmail = null, InviteUrl = null, IsCourseCode = true, Type = 0 }; _uow.DbContext.MemberInvite.Add(entity); _uow.SaveChanges(); } return(true); }
/// <summary> /// 验证登录信息 /// </summary> /// <param name="query"></param> /// <param name="rm"></param> /// <returns></returns> public bool CheckLoginInfo(SysUsrMstrQuery query, ref ReturnMsg rm) { if (string.IsNullOrEmpty(query.USR_NAME)) { rm.msg = "请输入用户名"; return(false); } if (string.IsNullOrEmpty(query.USR_PWD)) { rm.msg = "请输入密码"; return(false); } if (string.IsNullOrEmpty(query.code)) { rm.msg = "请输入验证码"; return(false); } var vch = new CaptchaHelper(); if (!vch.VerifyCode(query.cookie, query.code)) { rm.msg = "验证码错误"; return(false); } return(true); }
public async Task <RegisterOutput> Register(RegisterInput input) { // 检查验证码 await CaptchaHelper.CheckVierificationCode( this._cacheManager, this.SettingManager, CaptchaType.TenantUserRegister, input.UserName, input.VerificationCode, AbpSession.TenantId); var user = await _userRegistrationManager.RegisterAsync( input.UserName, input.UserName, input.EmailAddress, input.UserName, input.Password, true // Assumed email address is always confirmed. Change this if you want to implement email confirmation. ); var isEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueAsync <bool>(AbpZeroSettingNames.UserManagement .IsEmailConfirmationRequiredForLogin); return(new RegisterOutput { // 是否可以登陆 1、用户已激活 并且 2、用户邮箱已确认或未启用邮箱校验 并且 3、没有启用登陆验证码 CanLogin = user.IsActive && (user.IsEmailConfirmed || !isEmailConfirmationRequiredForLogin) && !await UseCaptchaOnLogin() }); }
//controller function to generate image //returns image file (through url.action in img src attribute) public ActionResult GetCaptcha(string prefix, bool noisy = true) { var rand = new Random((int)DateTime.Now.Ticks); //generate new question int a = rand.Next(10, 99); int b = rand.Next(0, 9); var captcha = string.Format("{0} + {1} = ?", a, b); //store answer Session["Captcha" + prefix] = a + b; //image stream FileContentResult img = null; try { img = this.File(CaptchaHelper.GenerateCaptchaImg(captcha, true), "image/Jpeg"); } catch (Exception e) { Logger.Error(e); } return(img); }
public ActionResult ResetPassword(RegisteredUserVM currentUser, string passwordToken, string userID) { CaptchaHelper captchaHelper = new CaptchaHelper(); string captchaResponse = captchaHelper.CheckRecaptcha(); ViewBag.CaptchaResponse = captchaResponse; if (captchaResponse == "Valid") { var userStore = new UserStore <IdentityUser>(); UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore); var user = manager.FindById(userID); CreateTokenProvider(manager, PASSWORD_RESET); if (currentUser.Password == currentUser.ConfirmPassword) { IdentityResult result = manager.ResetPassword(userID, passwordToken, currentUser.Password); if (result.Succeeded) { ViewBag.Result = "The password has been reset."; } else { ViewBag.Result = "Failed, password has to be at least 6 characters!"; } } } else { ViewBag.Result = "The password has not been reset."; } return(View()); }
public async Task <FileContentResult> GenerateCaptcha(string name, CaptchaType?t, int?tid) { if (!t.HasValue || t.Value == CaptchaType.Defulat || name.IsNullOrWhiteSpace()) { return(null); } var captchaConfig = await SettingManager.GetCaptchaConfig(t.Value, tid); if (!captchaConfig.Enabled) { return(null); } var imgStream = _vierificationCodeService.Create(out string code, (ValidateCodeType)captchaConfig.Type, captchaConfig.Length); // 分租户获取缓存 var cacheKey = CaptchaHelper.CreateCacheKey(t.Value, tid); var cache = _cacheManager.GetCache(cacheKey); // 存值,过期时间3分钟 await cache.SetAsync(name, code.ToLower(), null, TimeSpan.FromMinutes(3)); // Response.Body.Dispose(); return(File(imgStream.ToArray(), MimeTypeNames.ImagePng)); }
public ActionResult Login(LoginViewModel model) { bool isValidCaptcha = CaptchaHelper.ValidateCaptchaCode(model.CaptchaCode, HttpContext); if (!isValidCaptcha) { ViewBag.Error = "Captcha Code Is Not Valid"; return(View(model)); } SessionLoginResult result = SessionHelper.Login(model.UserName, model.Password, _memberService, _profileDetailService, _profileMemberService); if (result.IsSuccess) { if (ModelState.IsValid) { return(RedirectToAction("Index", "Home")); } return(View(model)); } else { ViewBag.Error = result.Message; return(View(model)); } }
public IActionResult GetCaptcha() { CaptchaResponseDto dto = new CaptchaResponseDto(); dto = CaptchaHelper.GenerateCaptcha(); return(Ok(dto)); }
/// <summary> /// 发送验证码 - 找回密码 /// </summary> /// <param name="email"></param> /// <returns></returns> public async Task <ResponseModel <string> > SendEmailAsync(string email) { var response = new ResponseModel <string>(); if (!email.IsEmail()) { return(response.Fail("邮箱格式错误")); } var key = $"{CacheKeys.RETRIEVEPWDCAPTCHA}{email}"; var expireMinutes = 5; if (await FrequentlyGetCaptchaAsync(key, expireMinutes, 2)) { return(response.Fail("获取验证码过于频繁,请稍后再获取")); } if (!await ExistUserAsync(email)) { return(response.Fail("该邮箱尚未注册或无效")); } var captchaNumber = CaptchaHelper.CreateRandomNumber(6); var htmlEmail = SystemBll.GetMailContent("找回密码", captchaNumber, expireMinutes); var result = await SystemBll.SendSystemMailAsync("LionFrame-找回密码", htmlEmail, email); if (result.Contains("发送成功")) { await RedisClient.SetAsync(key, captchaNumber, new TimeSpan(0, expireMinutes, 0)); } return(response.Succeed("发送成功")); }
public FileResult Get() { var imgPath = Server.MapPath(SystemSettings.CaptchaBackgroundImagePath); var captchaLenght = SystemSettings.CaptchaLenght; return(File(CaptchaHelper.GetCaptchaBytes(imgPath, captchaLenght), "image/jpeg")); }
/// <summary> /// The get response captcha. /// </summary> /// <param name="context"> /// The context. /// </param> public void GetResponseCaptcha([NotNull] HttpContext context) { #if (!DEBUG) try { #endif var captchaImage = new CaptchaImage( CaptchaHelper.GetCaptchaText(new HttpSessionStateWrapper(context.Session), context.Cache, true), 250, 50, "Century Schoolbook"); context.Response.Clear(); context.Response.ContentType = "image/jpeg"; captchaImage.Image.Save(context.Response.OutputStream, ImageFormat.Jpeg); #if (!DEBUG) } catch (Exception x) { this.Get <ILogger>().Log(this.Get <IUserDisplayName>().GetName(BoardContext.Current.CurrentUser), this, x); context.Response.Write( "Error: Resource has been moved or is unavailable. Please contact the forum admin."); } #endif }
/// <summary> /// 检查图形验证码功能 /// </summary> /// <param name="type">图形验证码的类型</param> /// <param name="code">待验证的code</param> protected async Task <bool> VerifyImgCodeAsync(CaptchaType type, string code) { if (string.IsNullOrWhiteSpace(code)) { throw new UserFriendlyException("验证码不能为空!"); } //租户Id var tenantId = AbpSession.TenantId; // 分租户获取缓存 var cacheKey = CaptchaHelper.CreateCacheKey(type, tenantId); //图形验证码缓存管理器 var captchaCacheManager = CacheManager.GetCache(cacheKey); var sessionId = HttpContext.Request.Cookies[cacheKey]; //获取缓存中的值 var cacheCode = await captchaCacheManager.GetOrDefaultAsync(sessionId); if (cacheCode != null && code == cacheCode.ToString()) { await captchaCacheManager.RemoveAsync(sessionId); return(true); } await captchaCacheManager.RemoveAsync(sessionId); throw new UserFriendlyException("验证码错误!"); }
public IActionResult GetCaptchaImage() { string captchaCode = CaptchaHelper.GenerateCaptchaCode(); var result = CaptchaHelper.GetImage(116, 36, captchaCode); HttpContext.Session.SetString(CaptchaCodeSessionName, captchaCode); return(new FileStreamResult(new MemoryStream(result.CaptchaByteData), "image/png")); }
/// <summary> /// 验证码 /// </summary> /// <returns></returns> public ActionResult VerifyCode() { string vcode = CaptchaHelper.CreateRandomCode(4); SessionHelper.Set("vcode", vcode); return(File(CaptchaHelper.DrawImage(vcode), @"image/jpeg")); }
/// <summary> /// 生成图形验证码 /// </summary> /// <returns>图形验证码</returns> public ActionResult Captcha() { var code = CaptchaHelper.GetRandomCode(4); var codeStream = CaptchaHelper.IdentifyImg(code, 20, 30); Session[CAPTCHA] = code; return(File(codeStream.ToArray(), @"image/jpeg")); }
public FileContentResult Generate() { var captchaResult = new CaptchaHelper(12).Generate(); Session[CaptchaConst.REG_CAPTCHA_SESSION] = captchaResult.CaptchaCode; return(File(captchaResult.CaptchaImage, "image/Gif")); }
/// <summary> /// 获取验证码 /// </summary> /// <returns></returns> public IActionResult CheckCode() { string captchaCode = CaptchaHelper.GenerateCaptchaCode(); var result = CaptchaHelper.GetImage(116, 36, captchaCode); HttpContext.Session.SetString("CheckCode", captchaCode); return(File(new MemoryStream(result.CaptchaByteData), "image/png")); }
public object GetCaptchaImage(string key) { string captchaCode = CaptchaHelper.GenerateCaptchaCode(); var result = CaptchaHelper.GetImage(116, 36, captchaCode); MemoryCacheService.Default.SetCache(key, captchaCode, 5); return(new FileStreamResult(new MemoryStream(result.CaptchaByteData), "image/png")); }
public object GifHybridCode() { var ch = new CaptchaHelper(); var code = ch.GetRandomEnDigitalText(4); var imgbyte = ch.GetGifEnDigitalCodeByte(code); return(File(imgbyte, "image/gif")); }