vgquotes/Src/VideoGameQuotes.Web/Controllers/HomeController.cs

87 lines
2.3 KiB
C#

using System;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Web.Mvc;
using VideoGameQuotes.Web.Models;
namespace VideoGameQuotes.Web.Controllers {
public class HomeController : Controller {
private static readonly string[] answers = new[] {
"I AM ERROR.",
"shyron",
"our princess is in another castle",
"the cake is a lie",
"all your base",
"ganon not gannon",
"thunderbird",
"'glad you came, pit!",
"ryu huyabasa"
};
public ActionResult Index() {
return View();
}
public ActionResult About() {
return View();
}
public ActionResult Contact() {
var randomAnswer = GetRandomAnswer();
var model = new ContactModel {
UnhashedCaptchaAnswer = randomAnswer,
HashedCaptchaAnswer = GetHashedCaptcha(randomAnswer)
};
return View(model);
}
private static string GetRandomAnswer() {
return answers[new Random().Next(answers.Length)];
}
private static string GetHashedCaptcha(string value) {
return Convert.ToBase64String(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(value ?? string.Empty)));
}
private static void ResetModel(ContactModel model) {
model.UnhashedCaptchaAnswer = GetRandomAnswer();
model.HashedCaptchaAnswer = GetHashedCaptcha(model.UnhashedCaptchaAnswer);
model.CaptchaAnswer = null;
}
[HttpPost]
public ActionResult Contact(ContactModel model) {
if (GetHashedCaptcha(model.CaptchaAnswer) != model.HashedCaptchaAnswer) {
ModelState.AddModelError("CaptchaAnswer", "You are not human");
}
if (!ModelState.IsValid) {
ResetModel(model);
return View(model);
}
//send email
var fromAddress = new MailAddress("contact@tommymontgomery.com", "Contact Bot");
var subject = string.Format("[tommymontgomery.com] Message from {0}", model.Name);
var client = new SmtpClient {
Host = "localhost"
};
var message = new MailMessage(fromAddress, new MailAddress("tmont@tmont.com")) { Subject = subject, Body = model.Message };
message.ReplyToList.Add(new MailAddress(model.Email, model.Name));
try {
client.Send(message);
} catch (Exception e) {
ModelState.AddModelError("client", e.Message);
ResetModel(model);
return View(model);
}
return View("ContactSuccess");
}
}
}