using System.ComponentModel.DataAnnotations; using System.Net; using System.Web.Mvc; using Portoa.Persistence; using Portoa.Web.Results; using Portoa.Web.Util; using VideoGameQuotes.Api; using VideoGameQuotes.Api.Persistence; using VideoGameQuotes.Web.Models; using VideoGameQuotes.Web.Security; namespace VideoGameQuotes.Web.Controllers { public class UserController : Controller { private readonly IUserService userService; public UserController(IUserService userService) { this.userService = userService; } protected new ActionResult Json(object data) { return this.SerializeToJson(data); } [HttpGet, VerifyUser(Group = UserGroup.Admin)] public ActionResult Edit([Required]string usernameOrIp) { if (!ModelState.IsValid) { return GetUsernameNotFoundResult(usernameOrIp); } var user = userService.FindByUsernameOrIp(usernameOrIp); if (user == null) { return GetUsernameNotFoundResult(usernameOrIp); } return View(new EditUserModel { Id = user.Id, Username = user.Username, IpAddress = user.IpAddress, Group = user.Group }); } [HttpPost, VerifyUser(Group = UserGroup.Admin)] public ActionResult Edit(EditUserModel model) { if (!ModelState.IsValid) { return View(model); } try { var user = userService.FindById(model.Id); user.Username = model.Username; user.IpAddress = model.IpAddress; user.Group = model.Group; user = userService.Save(user); return RedirectToAction("Edit", new { usernameOrIp = user.Username ?? user.IpAddress }); } catch (EntityNotFoundException) { ModelState.AddModelError("Id", "Invalid user ID"); return View(model); } } private ActionResult GetUsernameNotFoundResult(string usernameOrIp) { return new StatusOverrideResult(View("InvalidUsername", new InvalidUsernameModel { UsernameOrIp = usernameOrIp })) { StatusCode = HttpStatusCode.NotFound }; } } }