Jon Bellamy

Jon Bellamy

  • 0
  • 47
  • 0

MVC3 and LinqToSQL User Logon

May 3 2011 9:38 AM
Good day to you all,

Firstly, allow me to apologise in advance for my simple understanding of what I am about to ask.  I am fairly competent in C#, LinqToSQL, WPF, but am a complete "newbie" at web-development and despite looking at numerous forums and performing countless google searches, I am still at a loss.

I have a requirement to create a user login screen for an MVC3 Rzor Application.  My requirement is as simple as this.

  • Users are stored in a SQL 2008 database, in a table called users that has the following columns / attributes:
  • UserID (int, Primary Key)
  • CompanyID (int)
  • FirstName (nvarchar 50)
  • LastName (nvarchar 50)
  • UserName (nvarchar 100) << Will hold e-mail addresses as the user name
  • Password (nvarchar 50)
  • ActiveUser (bit)
  • CanEdit (bit)
  • LimitedView (bit)
  • LimitedViewLimits (nvarchar MAX)
  • CanChangeStatus (bit)
  • IsAdmin (bit)
  • The MVC application should show the login page initially, authenticate the user, and if successful display the home page.  If authentication fails, just show the login page.
  • Users should be authenticated by the UserName and Password columns.
  • User should be "stored" until browser session closed.
  • All other application methods are available once logged in only.
  • The LinqToSQL class is called AMDataContext (it's a .dbml file)
I am completely and utterly at a loss of how to implement this, everything seems so heavyweight, and yet I don't think it needs to be complex and in my view nothing more than a simple login form that accepts a username and password, authenticates them, and displays the home view if successful.  The User object from the database needs to be stored at a level accessible to the home view as the properties (columns in the database) are used to limited access to certain methods and to personalised the app to the user and their permissions.

The class for the authentication part would be something like:

public User AuthenticateUser(string _username, string _password)
{
        using(AMDataContext db = new AMDataContext())
        {
                User theUser =   db.Users
                                       .Where(u => u.UserName == _username)
                                       .Where(u => u.Password == _password)
                                       .SingleOrDefault();
                if (theUser == null)
                        return null;
                else
                        return theUser;
        }
}


If null, advise user and diaply login view, if a user is returned, store where the User object can be accessed at any time by other views (namely the home view) and display the home view.

Any help / advice would be greatly appreciated.

Many thanks,

Jon

Brought to you by: JavaScript SDK for Bold BI dashboard and analytics embedding. Free trial.

Answers (7)