1
0
mirror of https://git.teknik.io/Teknikode/Teknik.git synced 2023-08-02 14:16:22 +02:00

Added ajax actionresult handler.

Added returning of json or view from register/login depending on caller.
This commit is contained in:
Uncled1023 2016-10-26 16:25:57 -07:00
parent f2e016d321
commit 96471f48a8
7 changed files with 95 additions and 94 deletions

View File

@ -222,7 +222,7 @@ namespace Teknik.Areas.Users.Controllers
if (string.IsNullOrEmpty(model.ReturnUrl))
{
return Json(new { result = returnUrl });
return GenerateActionResult(new { result = returnUrl }, Redirect(returnUrl));
}
else
{
@ -231,7 +231,10 @@ namespace Teknik.Areas.Users.Controllers
}
}
}
return Json(new { error = "Invalid Username or Password." });
model.Error = true;
model.ErrorMessage = "Invalid Username or Password.";
return GenerateActionResult(new { error = model.ErrorMessage }, View("/Areas/User/Views/User/ViewLogin.cshtml", model));
}
public ActionResult Logout()
@ -265,64 +268,81 @@ namespace Teknik.Areas.Users.Controllers
[AllowAnonymous]
public ActionResult Register([Bind(Prefix="Register")]RegisterViewModel model)
{
model.Error = false;
model.ErrorMessage = string.Empty;
if (ModelState.IsValid)
{
if (Config.UserConfig.RegistrationEnabled)
{
if (!UserHelper.ValidUsername(Config, model.Username))
if (!model.Error && !UserHelper.ValidUsername(Config, model.Username))
{
return Json(new { error = "That username is not valid" });
model.Error = true;
model.ErrorMessage = "That username is not valid";
}
if (!UserHelper.UsernameAvailable(db, Config, model.Username))
if (!model.Error && !UserHelper.UsernameAvailable(db, Config, model.Username))
{
return Json(new { error = "That username is not available" });
model.Error = true;
model.ErrorMessage = "That username is not available";
}
if (model.Password != model.ConfirmPassword)
if (!model.Error && model.Password != model.ConfirmPassword)
{
return Json(new { error = "Passwords must match" });
model.Error = true;
model.ErrorMessage = "Passwords must match";
}
// PGP Key valid?
if (!string.IsNullOrEmpty(model.PublicKey) && !PGP.IsPublicKey(model.PublicKey))
if (!model.Error && !string.IsNullOrEmpty(model.PublicKey) && !PGP.IsPublicKey(model.PublicKey))
{
return Json(new { error = "Invalid PGP Public Key" });
model.Error = true;
model.ErrorMessage = "Invalid PGP Public Key";
}
try
if (!model.Error)
{
User newUser = db.Users.Create();
newUser.JoinDate = DateTime.Now;
newUser.Username = model.Username;
newUser.UserSettings = new UserSettings();
newUser.SecuritySettings = new SecuritySettings();
newUser.BlogSettings = new BlogSettings();
newUser.UploadSettings = new UploadSettings();
if (!string.IsNullOrEmpty(model.PublicKey))
newUser.SecuritySettings.PGPSignature = model.PublicKey;
if (!string.IsNullOrEmpty(model.RecoveryEmail))
newUser.SecuritySettings.RecoveryEmail = model.RecoveryEmail;
UserHelper.AddAccount(db, Config, newUser, model.Password);
// If they have a recovery email, let's send a verification
if (!string.IsNullOrEmpty(model.RecoveryEmail))
try
{
string verifyCode = UserHelper.CreateRecoveryEmailVerification(db, Config, newUser);
string resetUrl = Url.SubRouteUrl("user", "User.ResetPassword", new { Username = model.Username });
string verifyUrl = Url.SubRouteUrl("user", "User.VerifyRecoveryEmail", new { Code = verifyCode });
UserHelper.SendRecoveryEmailVerification(Config, model.Username, model.RecoveryEmail, resetUrl, verifyUrl);
User newUser = db.Users.Create();
newUser.JoinDate = DateTime.Now;
newUser.Username = model.Username;
newUser.UserSettings = new UserSettings();
newUser.SecuritySettings = new SecuritySettings();
newUser.BlogSettings = new BlogSettings();
newUser.UploadSettings = new UploadSettings();
if (!string.IsNullOrEmpty(model.PublicKey))
newUser.SecuritySettings.PGPSignature = model.PublicKey;
if (!string.IsNullOrEmpty(model.RecoveryEmail))
newUser.SecuritySettings.RecoveryEmail = model.RecoveryEmail;
UserHelper.AddAccount(db, Config, newUser, model.Password);
// If they have a recovery email, let's send a verification
if (!string.IsNullOrEmpty(model.RecoveryEmail))
{
string verifyCode = UserHelper.CreateRecoveryEmailVerification(db, Config, newUser);
string resetUrl = Url.SubRouteUrl("user", "User.ResetPassword", new { Username = model.Username });
string verifyUrl = Url.SubRouteUrl("user", "User.VerifyRecoveryEmail", new { Code = verifyCode });
UserHelper.SendRecoveryEmailVerification(Config, model.Username, model.RecoveryEmail, resetUrl, verifyUrl);
}
}
catch (Exception ex)
{
model.Error = true;
model.ErrorMessage = ex.GetFullMessage(true);
}
if (!model.Error)
{
return Login(new LoginViewModel { Username = model.Username, Password = model.Password, RememberMe = false, ReturnUrl = model.ReturnUrl });
}
}
catch (Exception ex)
{
return Json(new { error = ex.GetFullMessage(true) });
}
return Login(new LoginViewModel { Username = model.Username, Password = model.Password, RememberMe = false, ReturnUrl = model.ReturnUrl });
}
return Json(new { error = "User Registration is Disabled" });
if (!model.Error)
{
model.Error = true;
model.ErrorMessage = "User Registration is Disabled";
}
}
return Json(new { error = "You must include all fields." });
return GenerateActionResult(new { error = model.ErrorMessage }, View("/Areas/User/Views/User/ViewRegistration.cshtml", model));
}
[HttpPost]

View File

@ -4,7 +4,12 @@
{
<div class="row">
<div class="col-sm-12 text-center">
<div id="loginStatus"></div>
<div id="loginStatus">
@if (Model.Error)
{
<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>@Model.ErrorMessage</div>
}
</div>
</div>
</div>
<form role="form" id="loginForm" action="@Url.SubRouteUrl("user", "User.Login")" method="post" accept-charset="UTF-8">

View File

@ -4,7 +4,12 @@
{
<div class="row">
<div class="col-sm-12 text-center">
<div id="registerStatus"></div>
<div id="registerStatus">
@if (Model.Error)
{
<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>@Model.ErrorMessage</div>
}
</div>
</div>
</div>
<form role="form" id="registrationForm" action="@Url.SubRouteUrl("user", "User.Register")" method="post" accept-charset="UTF-8">

View File

@ -11,6 +11,7 @@ using Teknik.Configuration;
using Piwik.Tracker;
using Teknik.Filters;
using Teknik.Helpers;
using Teknik.ViewModels;
namespace Teknik.Controllers
{
@ -77,6 +78,20 @@ namespace Teknik.Controllers
}
return null;
}
protected ActionResult GenerateActionResult(object json)
{
return GenerateActionResult(json, View());
}
protected ActionResult GenerateActionResult(object json, ActionResult result)
{
if (Request.IsAjaxRequest())
{
return Json(json);
}
return result;
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]

View File

@ -164,7 +164,7 @@ namespace Teknik
Response.TrySkipIisCustomErrors = true;
// If it is an Ajax request, we should respond with Json data, otherwise redirect
if (IsAjaxRequest())
if (new HttpRequestWrapper(Request).IsAjaxRequest())
{
string jsonResult = string.Empty;
if (httpException == null)
@ -185,57 +185,5 @@ namespace Teknik
new HttpContextWrapper(Context), routeData));
}
}
//This method checks if we have an AJAX request or not
private bool IsAjaxRequest()
{
//The easy way
bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest")
|| ((Request.Headers != null)
&& (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));
//If we are not sure that we have an AJAX request or that we have to return JSON
//we fall back to Reflection
if (!isAjaxRequest)
{
try
{
//The controller and action
string controllerName = Request.RequestContext.
RouteData.Values["controller"].ToString();
string actionName = Request.RequestContext.
RouteData.Values["action"].ToString();
//We create a controller instance
DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
Controller controller = controllerFactory.CreateController(
Request.RequestContext, controllerName) as Controller;
//We get the controller actions
ReflectedControllerDescriptor controllerDescriptor =
new ReflectedControllerDescriptor(controller.GetType());
ActionDescriptor[] controllerActions =
controllerDescriptor.GetCanonicalActions();
//We search for our action
foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
{
if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
{
//If the action returns JsonResult then we have an AJAX request
if (actionDescriptor.MethodInfo.ReturnType
.Equals(typeof(JsonResult)))
return true;
}
}
}
catch
{
}
}
return isAjaxRequest;
}
}
}

View File

@ -6,6 +6,7 @@ using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Teknik.ViewModels;
namespace Teknik.Helpers
{
@ -84,4 +85,10 @@ namespace Teknik.Helpers
_innerResult.ExecuteResult(context);
}
}
public enum ResultType
{
Passthrough,
Json
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Web;
using Teknik.Configuration;
using Teknik.Helpers;
namespace Teknik.ViewModels
{