jeudi 3 décembre 2015

Validation on my MVC Login

I've created a login page for my application, which takes the following parameters:

  • Server - Text box helper
  • User - Drop down list helper
  • Password - Text box helper
  • Database - Drop down helper
  • Company - Drop down helper

End user enters a a SQL server instance named or default, which populates the user drop down list and a user selects a relevant user name and then that populates the database (from the instance) and company (internal companys in a database) drop down list to what the user has access to, then they choose from those company and database drop down list, then finally enter their password to complete the submission into the application, which works fine.

In need of some help on the validation side,

Firstly i need the server to have a default time out, to which if a user enters an incorrect SQL server instance it throws an validation error after a specified time of 60 seconds as an example.

Second, i need throw a validation error if the password is incorrect after submitting the form.

Login Controller:

using System;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using BusinessIntelligenceHub.Models;
using PSFNetObjects;


namespace BusinessIntelligenceHub.Controllers
{
public class LoginController : BaseController
{
    [AllowAnonymous]
    public ActionResult LogOn()
    {
        if (LogOnInfo != null)
            return RedirectToAction("Index", "Home");

        var model = new LogOnModel();
        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [AllowAnonymous]
    public ActionResult LogOn(LogOnModel model, string returnUrl = "")
    {
        if (model == null)
            throw new ArgumentNullException("model");

        //ensure the model has been completed
        if (model.IsComplete == false)
            return View(model);

        model.Password = string.Empty;

        //login was successful, redirect the user to the requested page.
        Session.Add("LOGONINFO", model);

        if (string.IsNullOrEmpty(returnUrl))
            return RedirectToAction("Index", "Home");

        return Redirect(Server.UrlDecode(returnUrl));
    }

    public ActionResult LoadUsers(string server)
    {
        DataTable dt = PSFNetSystem.UserList(server, true).Tables[0];
        var list = dt.Rows.Cast<DataRow>().Select(r => r["USERID"].ToString()).ToList();
        return Json(list, JsonRequestBehavior.AllowGet);
    }

    public ActionResult LoadDatabases(string server, string user)
    {
        string userGroup = PSFNetSystem.GetUsersGroup(server, user);

        DataTable dt = PSFNetSystem.DatabaseList(server, "Accounting", userGroup).Tables[0];
        var list = dt.Rows.Cast<DataRow>().Select(r => r["NAME"].ToString()).ToList();
        return Json(list, JsonRequestBehavior.AllowGet);
    }

    public ActionResult LoadCompanies(string server, string database)
    {
        DataTable dt = PSFNetSystem.CompanyList(server, database).Tables[0];
        var list = dt.Rows.Cast<DataRow>().Select(r => r["CODE"].ToString()).ToList();
        return Json(list, JsonRequestBehavior.AllowGet);
    }

    /// <summary>
    /// Logs out the current user.
    /// GET: Admin/Logoff
    /// </summary>
    /// <returns></returns>
    public ActionResult LogOff()
    {
        Session.Remove("LOGONINFO");
        return RedirectToAction("LogOn");
    }
}
}

Base Controller:

using System;
using System.Web.Mvc;
using System.Web.Routing;
using BusinessIntelligenceHub.Models;

namespace BusinessIntelligenceHub.Controllers
{
public class BaseController : Controller
{
    private LogOnModel _logOnInfo;

    /// <summary>
    /// Gets the log on information.
    /// </summary>
    /// <value>
    /// The log on information.
    /// </value>
    public LogOnModel LogOnInfo
    {
        get { return _logOnInfo; }
    }

    #region Overrides

    /// <summary>
    /// Initializes data that might not be available when the constructor is called.
    /// </summary>
    /// <param name="requestContext">The HTTP context and route data.</param>
    protected override void Initialize(RequestContext requestContext)
    {
        if (requestContext == null)
            throw new ArgumentNullException("requestContext");

        //extract the model from the session
        _logOnInfo = requestContext.HttpContext.Session["LOGONINFO"] as LogOnModel;
        if (LogOnInfo != null)
            ViewBag.LogOnInfo = LogOnInfo;


        base.Initialize(requestContext);
    }

    #endregion
}
}

Logon Model:

using System.ComponentModel.DataAnnotations;

namespace BusinessIntelligenceHub.Models
{
public class LogOnModel
{
    [Required]
    public string Server { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string Database { get; set; }
    public string Company { get; set; }

    /// <summary>
    /// Gets a value indicating whether this login attempt has been completed.
    /// </summary>
    /// <value>
    /// <c>true</c> if this login attempt is complete; otherwise, <c>false</c>.
    /// </value>
    public bool IsComplete
    {
        get
        {
            return string.IsNullOrEmpty(this.Server) == false
                && string.IsNullOrEmpty(this.Username) == false
                && string.IsNullOrEmpty(this.Database) == false
                && string.IsNullOrEmpty(this.Company) == false;
        }
    }
    public bool IsntComplete
    {
        get
        {
            return string.IsNullOrEmpty(this.Server) == true
                && string.IsNullOrEmpty(this.Username) == true
                && string.IsNullOrEmpty(this.Database) == true
                && string.IsNullOrEmpty(this.Company) == true;
        }
    }
}
}

Login View:

@model BusinessIntelligenceHub.Models.LogOnModel

@{
ViewBag.Title = "Log On";
Layout = "~/Views/Shared/_LoginLayout.cshtml";
}
@using (@Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-group">
    @Html.LabelFor(model => model.Server)
    @Html.TextBoxFor(model => model.Server, new { @class = "form-control", id             = "serverTextbox" })
</div>
<div class="form-group">
    @Html.LabelFor(model => model.Username)
    @Html.DropDownListFor(model => model.Username, Enumerable.Empty<SelectListItem>(), new { @class = "form-control", id = "usersCombo" })
</div>
<div class="form-group">
    @Html.LabelFor(model => model.Password)
    @Html.PasswordFor(model => model.Password, new { @class = "form-control" })
</div>
<div class="form-group">
    @Html.LabelFor(model => model.Database)
    @Html.DropDownListFor(model => model.Database, Enumerable.Empty<SelectListItem>(), new { @class = "form-control", id = "databaseCombo" })
</div>
<div class="form-group">
    @Html.LabelFor(model => model.Company)
    @Html.DropDownListFor(model => model.Company, Enumerable.Empty<SelectListItem>(), new { @class = "form-control", id = "companyCombo" })
</div>


<div class="form-group">
    <input type="submit" id="LogOn" value="Log In" class="btn btn-default" />
</div>
<div>
    @Html.ValidationSummary()
</div>
}

@section scripts {
<script type="text/javascript">

function populateDropdown(dropdownId, requestPath, requestData,      valueFunction, textFunction) {
    var dropDown = $("#" + dropdownId);
    dropDown.empty();

    $.getJSON(requestPath, requestData, function (items) {
        $.each(items, function (index, object) {
            dropDown.append($("<option />").val(valueFunction(object)).text(textFunction(object)));
        });
    });
}

$(document).ready(function () {
    $("#serverTextbox").blur(function () {
        var server = $.trim($(this).val());
        populateDropdown('usersCombo', 'LoadUsers', { server: server },
            function (object) { return object; },
            function (object) { return object; });
    });

    $("#usersCombo").change(function () {
        var server = $.trim($("#serverTextbox").val());
        var user = $.trim($(this).val());
        populateDropdown('databaseCombo', 'LoadDatabases', { server: server, user: user },
            function (object) { return object; },
            function (object) { return object; });
    });

    $("#databaseCombo").change(function () {
        var server = $.trim($("#serverTextbox").val());
        var database = $.trim($(this).val());
        populateDropdown('companyCombo', 'LoadCompanies', { server: server, database: database },
            function (object) { return object; },
            function (object) { return object; });
    });

});
</script>

}

Grateful for any information on validation I'm trying to get.




Aucun commentaire:

Enregistrer un commentaire