Create custom login system with FormsAuthentication and more in ASP.NET MVC 3 Razor? - asp.net-mvc-3

Sorry for the big title.
So I've been doing some research for making login systems. I've already made my own, but discovered a more secure way to do it.
As far as I know, the four basic components of this login system are:
FormsAuthentication
MembershipProvider
RoleProvider
Principal
I have this as my basic user model:
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Password { get; set; }
public string PictureUrl { get; set; }
public string Role { get; set; }
public string AccessToken { get; set; }
}
This is just for retaining the data from the database.
I still want to use this model with the components listed above.
Does anyone know a good and thorough tutorial that explains how to create a custom login system using the above components in MVC 3 Razor?
Thanks in advance.

You can build a custom 'login system' by implementing a custom version of MembershipProvider and RoleProvider that uses your own database. Then you can re-use all the rest of the built in authentication and authorization stuff.
MSDN has some details on how to build a MembershipProvider here and details on a custom RoleProvider here. Samples implementations are included.

You can use this open source project :
https://github.com/TroyGoode/MembershipStarterKit

Related

MVC3 + Simple Membership: Accessing User Profiles Through Entity Framework

I'm using the SimpleMembership.MVC3 package with my MVC3 application and I want to be able to access users from the table through Entity Framework
In examples for doing this with MVC4, you can simply create a POCO to mirror the User table that's been generated, add your DbSet in your DbContext implementation and then query the DbSet like you normally would, ie: context.Users.
This collection is always returning 0 items for me even though there are rows in the table. What am I doing wrong? Here's what I got so far:
[Table("User")]
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class TestContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
}
In my service:
model.Accounts = context.Users.ToList();
Thanks!
You do not create your a POCO that mirrors the User table in order to access it directly from EF. There is already a POCO created by the Internet template when you created the project, which you can customize as described here. This same article also shows how you can access the user information by accessing EF directly. You do not create your own context, there is one already in place that you use. Here is a code snippet from that article.
var context = new UsersContext();
var username = User.Identity.Name;
var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);
var email = user.Email;
The article also has links to download the source code that demonstrates the details on how to do this.
I circumvented the membership classes entirely and implemented a pure EF membership system. I leveraged the System.Web.Helpers Crypto helpers to handle password hashing and just create the AuthCookie when needed.

using i18n.DataAnnotations . How exactly does it work?

I am implementing a multilingual site with asp.net mvc 3.
A friend suggested me this project https://github.com/danielcrenna/i18n
Until now i have succeded to make it work in controllers and views (razor) but not in data annotation.
For example
public class LogOnModel
{
[i18n.DataAnnotations.Email]
[Required(ErrorMessage = "Required Field")]
[i18n.DataAnnotations.DataType(DataType.EmailAddress)]
public string Email { get; set; }
[i18n.DataAnnotations.Required(ErrorMessage = "Required Field")]
[DataType(DataType.Password)]
[i18n.DataAnnotations.Display(Name = "Password")]
public string Password { get; set; }
[i18n.DataAnnotations.Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
The above piece of code should produce new entries in .po files , whenever the build is successful. But nothing happens whatsoever.
Is there anybody that has knowledge of this?
Thanks in advance!
I can't comment on the i18n framework you're using from GitHub, but if it helps, there is something similar in .NET. The way you do this in .NET isn't based on .po but on resources compiled into satellite assemblies.
For MVC you can use the DisplayAttribute to specify the type which contains the resource string you wish to use. There are equivalent attributes for validation messages.
It seems that with i18n v1 is not possible to make working i18n.DataAnnotations, I asked as issue at github https://github.com/turquoiseowl/i18n/issues/104

How to assign my models to built-in users

I am trying to implement a foreign key connection between the built-in User model and my models in ASP.NET MVC 3.
How to assign ownership or some other roles to various entries represented with my models. Example of how my models look like:
public class Entry
{
public int Id { get; set; }
public string Value { get; set; }
public User Owner { get; set; }
public User SomeoneElse { get; set; }
}
Where to find the model for users, what do I need to import? Or is there a better approach to accomplish this?
Do you use Entity Framework ?? If so...
Simple solution
You could simply keep the Guid from the Built-In User model. You won't have a "real relationship" but it will do the trick for what you want to do. You can always get the UserId with Membership.GetUser().ProviderUserKey
Other more complex
Completely rewrite and override the MembershipProvider and login module. That way you can use your own User object and add other properties to it aswell.
Not Sure about this one
Not sure if this one will work with the auto generated tables from the MembershipProvider but you can add the Foreign Key Property this way:
[ForeignKey("User")]
public Guid UserId { get; set; }

What is the best practice for a service layer design where the business data has a 1 to 0..1 relationship?

Greetings all,
I have researched and found a number of discussions on designing a MVC service layer, but I haven't found an answer to my exact questions. The post on service layer interdependency has an image illustrating what I have in mind, but I have a further question that I don't believe is covered in the referenced post.
My application will track data for a non-profit that interacts with humans in multiple contexts. Maybe the human was a client, maybe they were an adviser, or maybe they were an adversary. They can be multiple. A client may later become an adversary (think lawyers' clients).
My idea is that the creation of a new client or a new adversary always creates two records: 1 record in the person table and one record in the ancillary table. My thoughts behind this is that there will be one place (the person table) to check to see if the business has had any past interaction with a given person.
My question is , when representing entities in a 1 to 0..1 relationship to the controller layer, (1) Should the controller be involved in combining and splitting classes before passing them to a view? (2) If not, should the service layer construct the viewmodel?
I've read the post about the 1800 line Controller here.
I've also read this post that says your service layer shouldn't know about the view model, which makes me think it lives and dies in the controller layer. If the service layer doesn't touch the viewmodel, for example, (3) is it good design for the workerService to return both Person and Worker objects to the Controller?
Here are my entity classes:
public class Record
{
public DateTime datecreated { get; set; }
public DateTime dateupdated { get; set; }
public string Createdby { get; set; }
public string Updatedby { get; set; }
}
public class Person : Record
{
public int ID { get; set; }
public virtual Worker Worker { get; set; }
publiv virtual Defendant defendant {get; set;}
...
}
public class Worker : Record
{
public int ID { get; set; }
public virtual Person person { get; set; }
...
}
public class Defendant : Record
{
public int ID { get; set; }
public virtual Person person { get; set; }
...
}
I think you should try and find a balance between whats "good design" and what works for you.
For instance, I have an MVC application that uses ASP.NET Membership, but I also have a custom User table, where I store things like a user's fiendly name, or OpenID. In that same application I have an IAdminService that handles everything concerning user administration.
What IAdminService returns to the controller is an AdminUser class, which looks like:
public class AdminUser
{
public string UserName { get; set; }
public User User { get; set; }
public MembershipUserWrapper MembershipUser { get; set; }
}
MembershipUserWrapper is just a wrapper around the default MembershipUser to allow for testing and more flexibility in general.
Anyway, you could argue that AdminUser is actually a view model and indeed I do have a couple of views strongly typed to AdminUser. It would be complicating matters unnecessarily to not let IAdminService return an AdminUser just because it is in the "service layer", and in this case, you don't want the controller performing the "transformation" from User and MembershipUserWrapper to AdminUser every time.
is it good design for the workerService to return both Person and Worker objects to the Controller?
I think in this case it probably is. You could have two separate services, but most of the logic for fetching a Worker and a Person is probably the same, so you'd be forcing yourself to either repeat a lot of code or create a third service that performs the common tasks.
You should pay attention to proper desing, but take also K.I.S.S. and YAGNI into account. Do what makes sense now, and refactor accordingly whenever needed.

loosely coupled development

I'm reading Sanderson's "Pro ASP.NET MVC Framework".
I'm confused a little with decoupling implementation.
He uses LinqToSql in the code sample and repository pattern to interact with database.
[Table(Name = "Products")]
public class Product
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync=AutoSync.OnInsert)]
public int ProductID { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Description { get; set; }
[Column]
public decimal Price { get; set; }
[Column]
public string Category { get; set; }
}
public class SqlProductsRepository : IProductsRepository
{
private Table<Product> productsTable;
public SqlProductsRepository(string connectionString)
{
productsTable = (new DataContext(connectionString)).GetTable<Product>();
}
public IQueryable<Product> Products
{
get { return productsTable; }
}
}
SqlProductsRepository is dataLayer here as it interacts with database.
1.However it is located in DomainModel project. Maybe it is just for demo?
So where is domain logic here?
2.I can't see full decoupling as Products property return IQueryable.
Is it assumed that if we change a component, it must contain Product class?
I seem that it is required to have one more project with abstractions:
Repository Interfaces such as IProductRepository and MappingClasses interfaces such as IProduct.
DataLayer component must implement these abastractions.
Is it right?
Maybe it is diffucult to explain it shortly, however how it is usually work in live projects?
IMHO, this must have been for demo purposes as it doesn't make sense (in real world environments) to separate your architecture in layers and keep these different layers in a single dll. I just came up with a valid reason. What if you want multiple applications to use your business layer without immediate access to the datalayer. You'd have to carefully consider access modifiers to your datalayer but it would be possible.
Whether you should expose IQueryable objects from your datalayer is a discussion that has been going on since the invention of the repository pattern. And there are quite a lot of resources to be found about it.
To list a few:
http://mikehadlow.blogspot.com/2009/01/should-my-repository-expose-iqueryable.html
How can I write a clean Repository without exposing IQueryable to the rest of my application?
To return IQueryable<T> or not return IQueryable<T>
http://www.weirdlover.com/2010/05/11/iqueryable-can-kill-your-dog-steal-your-wife-kill-your-will-to-live-etc/
... (google)

Resources