Reputation: 3957
I am new to MVC. I have added reCAPTCHA to a test website and it works, but I need to include a check for whether or not the user has selected the checkbox. I then want a failure to display in the @html.ValidationSummary list so as to keep everything clean on the website, as opposed to adding a separate message via a ViewBag.
Please note that I created an MVC project template, so a lot of code has already been generated by VS2013. Thus, I need to integrate this in with the website. Also, one of Microsoft's example shows how to do it in the controller, even though they recommend that you not do it in the controller because a controller should contain only logic related to application flow control - Microsoft just took a shortcut to keep things simple (SMH).
AccountController.cs
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
//Validate Google reCAPTCHA here
var response = Request["g-recaptcha-response"];
string secretKey = "SITE SECRET";
var client = new WebClient();
var recaptchaResult = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
var obj = JObject.Parse(recaptchaResult);
var status = (bool)obj.SelectToken("success");
//ViewBag.Message = status ? "Google reCaptcha validation success" : "Google reCaptcha validation failed";
if (ModelState.IsValid && status)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
Register.cshtml
@model WebApp1.Models.RegisterViewModel
@{
ViewBag.Title = "Register";
}
<h2>@ViewBag.Title.</h2>
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="g-recaptcha" data-sitekey="SITE SECRET"></div>
<br />
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
@section Scripts {
<script type="text/javascript" src='https://www.google.com/recaptcha/api.js' async></script>
@Scripts.Render("~/bundles/jqueryval")
}
Upvotes: 1
Views: 969
Reputation: 11317
Just add an error on the ModelState when the captcha validation fails :
....
var status = (bool)obj.SelectToken("success");
if (!status)
ModelState.AddModelError("", "Captcha entered is not valid");
// This will make automatically ModelState.IsValid to false
if (ModelState.IsValid)
{
..........
"Captcha entered is not valid" will be displayed in the validation summary
Upvotes: 3