So I want to create a login page where when you enter your login credentials as a admin you get acces. If you are not a admin you get redirected back to the login page. In my database I have a field of boolean type:
isAdmin <--datatype(byte")
So how can you the best way do this?! I would like to do this in the repository pattern way as it gets easier to unit test it then.
I have googled this a lot and starting to get a bit confused on the matter. How many classes, models etc should I have?! I'm guessing one controller would do. Anyone got any good ideas?! I've read some on the DCI pattern about user roles but as it basically "only" to check that boolean in the database maybe it is overkill? Thankful for all feedback.
Is your isAdmin column a bit or a byte? It should probably be a bit. You could just create a query that checks the credentials and the IsAdmin column. If a row is returned then the login was successful.
You should create a custom Membership Provider and check the user isAdmin as part of ValidateUser.
Alternatively if other users are allowed in, use a custom role provider.
The following link is a good place to start
http://theintegrity.co.uk/2010/11/asp-net-mvc-2-custom-membership-provider-tutorial-part-1/
If I understand correctly, I had a similar issue. It seems from your question that you are not using the default membership provider (at least as is). I didn't either. So what I did was create a new authorization attribute. In your case it could look something like this:
The repository method IsAdmin could be as simple as a query to check the boolean corresponding to the supplied user's ID. Something like this (please double check if
SingleOrDefault()
is necessary or not):And then use this in the action you want like so:
When this returns false, your ActionResult will be an HttpUnauthorizedResult which in theory should redirect to the login page.