Implementing Company, Division, Department User Access Control in MVC4 with EF - asp.net-mvc

This is my first question on stackoverflow, so please be gentle. I am writing a customer portal to a warehouse application using MVC4, Entity Framework and SimpleMembership. The warehouse hosts contents for multiple companies. Each company has divisions and departments. The users will have varying access to the information for their company, divisions, and departments. I am looking for an elegant solution for access control. So far, my model looks like this:
public class UserProfile
{
UserProfile()
{
this.AccessControl = new HashSet<AccessControl>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public Nullable<int> CompanyId { get; set; }
public virtual ICollection<AccessControl> { get; set; }
public virtual Company Company { get; set; }
}
public class AccessControl
{
public int AccessControlId { get; set; }
public int UserId { get; set; }
public int CompanyId { get; set; }
public Nullable<int> DivisionId { get; set; }
public Nullable<int> DepartmentId { get; set; }
public Boolean ReadAccess { get; set; }
public Boolean WriteAccess { get; set; }
// other properties for access control
public virtual UserProfile UserProfile { get; set; }
public virtual Company Company { get; set; }
public virtual Division Division { get; set; }
public virtual Department Department { get; set; }
}
public class Content
{
public int ContentId { get; set; }
public int CompanyId { get; set; }
public int DivisionId { get; set; }
public int DepartmentId { get; set; }
// Various other properties
public virtual Company Company { get; set; }
public virtual Division Division { get; set; }
public virtual Department { get; set; }
}
My thought was that a NULL Division means all divisions and a NULL Department means all departments. My questions are:
What is an elegant way to write the repository method to retrieve a list of Content objects for a user based on their access control list as well as populating division and department select lists in CRUD views?
Is there a better way to model this access control list?

I don't think this addresses all of your questions yet, but I think a repository that looks something like this:
public class accessRepository
{
accessContext context = new accessContext();
public IQueryable<Content> GetAccessibleContentFor(int userId)
{
var up = context.UserProfiles.Single(u => u.UserId == userId);
var companyId = up.CompanyId;
return from c in context.Content
where c.CompanyId == companyId
&& (up.AccessControl.Any(
a=>
a.CompanyId == c.CompanyId &&
a.DivisionId == c.DivisionId &&
a.DepartmentId == c.DepartmentId)
|| up.AccessControl.Any(
a=>a.CompanyId == c.CompanyId &&
a.DivisionId == c.DivisionId &&
a.DepartmentId == null)
|| up.AccessControl.Any(
a=>
a.CompanyId == c.CompanyId &&
a.DivisionId == null)
select c;
}
}
would allow you get back the content that is accessible if:
The content belongs to the user's Company.
The user Can access content for the Company, Division, and Department
Or the user can access content for the Company and Division (all Departments)
Or the user can access content for the Company (all divisions) [ all departments, is assumed in this case.]

You should look into a policy- and attribute-based solution that's independent of your app where you can write authorization policies e.g.
a user can access content in the warehouse if the content.department==user.department && content.company==user.company.
XACML sounds like the perfect model. I wrote this demo where I do access control on purchase orders based on the purchaser, the amount, the location and the status of the PO. I don't need to change the app code because I use XACML externally.

Related

How to filter tolist query results based on a foreign key in ASP.NET MVC

I have two Classes Task & User. I want to be able to filter the tasks based on the value of the User class attribute "Name".
public class Task
{
[Key]
public int ID { get; set; }
public int UserID { get; set; }
public virtual User User { get; set; }
}
public class User
{
public int UserID { get; set; }
public string Name { get; set; }
public virtual ICollection<Task> Tasks { get; set; }
}
////UsersController
public ActionResult UserTasks()
{
return View(db.Tasks.Where(Task => Task.User == User.Name).ToList());
}
Also tried the UserTasks functions with == User.UserID, also didn't work.

Need help trying to create a one-to-many relationship using EF7, Asp.NET and SQLite

I am new to Entity Framework and Asp.NET, and therefore, struggling with creating database relationships within the Entity Framework.
I have two SQLite tables (Ticket and User) and have setup my entity models as follows:
public class Users
{
[ForeignKey("id")]
public int id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string email { get; set; }
public virtual ICollection<Tickets> Tickets { get; set; }
}
public class Tickets
{
public int id { get; set; }
public string summary { get; set; }
public string description { get; set; }
public string c_location { get; set; }
public string c_store_device { get; set; }
public string category { get; set; }
public DateTime? created_at { get; set; }
public DateTime? closed_at { get; set; }
public int priority { get; set; }
public int? assigned_to { get; set; }
public DateTime? due_at { get; set; }
public DateTime? updated_at { get; set; }
public string status { get; set; }
public virtual Users Users { get; set; }
}
I am trying to use Entity Framework 7 to export an IEnumerable<Tickets> that includes the User assigned to each Ticket.
I have tried to create my model relationship in MyDBContext as a single User can have multiple Tickets, and also has a foreign key associated in my Sqlite database (Tickets.assigned_to = User.id):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Users - > many Tickets
modelBuilder.Entity<Users>()
.HasMany(p => p.Tickets)
.WithOne(e => e.Users)
.HasForeignKey(p => p.assigned_to);
}
My result ends up with Ticket data being exported, but against every ticket I see a null value for User:
[{"id":10002,...,"Users":null}]
When I use .Include() within my Repository to include each User like this:
public IEnumerable<Tickets> GetAll()
{
return _db.Tickets.Include(t => t.Users).ToList();
}
It results in the error
HTTP Error 502.3 - Bad Gateway
The specified CGI application encountered an error and the server terminated the process.
What I'm trying to retrieve is data that looks like:
{"Ticket";[{"id":10002,..."status":"closed"}],"Users":[{"id":"1"..."email":"johndoe#someplace.com"}]}
I know it probably has something to do with my relationship model, but I cannot work out what I am doing wrong.
First you should really derive your Users from IdentityUser. It helps when trying to wire up the relationship, but I will give you the answer based on your current models. Your ForeignKey property should be on the child entity. By naming conventions, which is what EF uses by default, your public Users Users works better if you put a public int UsersId. Then essentially what EF will do is from your public Users Users it will go to the Users table. Then it looks for the ForeignKey which is set to Id, so now we are in the Users Table looking at the id property. Then it looks for the naming convention UsersId and if it sees it, it will set that property to the value that it saw from the Users Table Id column.
Try using this
public class Users
{
public int id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string email { get; set; }
public virtual ICollection<Tickets> Tickets { get; set; }
}
public class Tickets
{
public int id { get; set; }
public string summary { get; set; }
public string description { get; set; }
public string c_location { get; set; }
public string c_store_device { get; set; }
public string category { get; set; }
public DateTime? created_at { get; set; }
public DateTime? closed_at { get; set; }
public int priority { get; set; }
public DateTime? due_at { get; set; }
public DateTime? updated_at { get; set; }
public string status { get; set; }
[ForeignKey("Id")]
public int UsersId { get; set; }
public virtual Users Users { get; set; }
}
and for your Fluent API configuring
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Users - > many Tickets
modelBuilder.Entity<Users>()
.HasMany(p => p.Tickets)
.WithOne();
}
Now all that does is create the relationship. In order to view the specific items you want to view, use a ViewModel. So, pull the two lists you want from where you want. Then use logic to separate the list how you want them to display.
public class UsersViewModel()
{
public UsersViewModel(Users user, List<Tickets> tickets)
{
this.first_name = user.first_name;
this.last_name = user.last_name;
this.email = user.email;
this.Tickets = new List<Tickets>();
foreach(var ticket in tickets)
{
if(ticket.UserId == user.Id)
{
this.Tickets.Add(ticket)
}
}
}
public string first_name { get; set; }
public string last_name { get; set; }
public string email { get; set; }
public List<Tickets> Tickets { get; set;}
}
then in your controller make your list
public IActionResult Index()
{
var usersList = _repository.Users.ToList();
var ticketsList = _repository.Tickets.ToList();
var model = new List<UsersViewModel>();
foreach(var user in usersList)
{
var listItem = new UsersViewModel(user, ticketsList);
model.Add(listItem);
}
return View(model);
}
or use a Linq query
public IActionResult Index()
{
var usersList = _repository.Users.ToList();
var model = new List<UsersViewModel>();
foreach(var user in usersList)
{
var ticketsList = from x in _repository.Tickets where x.UserId.Equals(user.Id) select x;
var listItem = new UsersViewModel(user, ticketsList);
model.Add(listItem);
}
return View(model);
}
then at the top of your view you should have
#model IEnumerable<UsersViewModel>

mvc4 get results in controller from joining tables (entity framework)

I am not sure how to get the results from joining the tables in controllers.
There're 3 tables 'Groups' 'Users' 'GroupUser' (bridge table).
public class Group
{
[Key]
public int GroupID { get; set; }
public string Group_Name { get; set; }
public ICollection<User> Users { get; set; }
}
public class User
{
[Key]
public int UserID { get; set; }
public string User_Name { get; set; }
public ICollection<Group> Groups { get; set; }
}
I also have this EFContext class
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Group>()
.HasMany(g => g.Users)
.WithMany(u => u.Groups)
.Map(m =>
{
m.MapLeftKey("UserID");
m.MapRightKey("GroupID");
m.ToTable("GroupUSer");
});
Do I also need to build a GroupUser class (to represent the GroupUser bridge table)?
Then how do I get the results when joining the 3 tables to get list of groups and users?
GroupViewModel model = new GroupViewModel
{
Groups = .... // this should be a linq statement that get results
that contains all groups and users
};
The equal sql statemen would be
select *
from Group g
join GroupUser gu on g.GroupID=gu.GroupID
join User u on u.UserID=gu.UserID
No, intermediate class is not needed.
The main point of an ORM (Object-Relational Mapper, which is what Entity Framework is) is to abstract away the database and let you work in a pure object-oriented way. Intermediate tables are definitely a database term and are not needed here.
The only reason I can think of that may lead you to create an intermediate class is when you need a "payload" (an extra meta-data) on the association. For example:
public class User
{
public int Id { get; set; }
public int Email { get; set; }
public virtual ICollection<Account> Accounts { get; set; }
}
public class Account
{
public int Id { get; set; }
public virtual ICollection<User> Users { get; set; }
}
Now, if you want the user-to-account association to define whether the association is of "Own the account" type (Administrator), you can do something like:
public class User
{
public int Id { get; set; }
public int Email { get; set; }
public virtual ICollection<AccountUserAssociation> Accounts { get; set; }
}
public class Account
{
public int Id { get; set; }
public virtual ICollection<AccountUserAssociation> Users { get; set; }
}
public class AccountUserAssociation
{
public virtual User User { get; set; }
public virtual Account Account { get; set; }
public AssociationType AssociationType { get; set; }
}
public enum AssociationType { Regular, Administrator }

get Membership user object from another model

i want something like this :
public class Order
{
public Guid OrderID { get; set; }
public Guid UserId { get; set; }
public DateTime OrderDate { get; set; }
public decimal Amount { get; set; }
public virtual ICollection<OrderDetail> orderDetailByOrderID { get; set; }
public virtual MembershipUser userByOrderID { get; }
}
so from above code i want membership user to be access from Order object ....
however i tried it but its not working.
so please suggest some solution if you have come across this type situation
It sounds like you might be using Entity Framework Code First. If this is the case you'd probably want:
public virtual aspnet_Membership userByOrderID { get; set; }
instead of
public virtual MembershipUser userByOrderID { get; }
That would grab the aspnet_Membership entity that is tied to the UserId foreign key. The aspnet_Membership class is not quite the same as the MembershipUser entity, but they have many of the same properties.
If that won't work, you can always use your Order model as is, and generate a ViewModel that has the MembershipUser object.
public class OrderViewModel
{
public Order Order { get; set; }
public MembershipUser User { get; set; }
}
and create the ViewModel like this before passing it into a view
Order order = EntityDataContext.Orders.First();
var model = new OrderViewModel { Order = order, User = Membership.GetUser(order.UserId) }

Navigation property of entity is not loading

I am building a reservation system. I have users in roles('admin', 'client', 'employee', 'student').
Each reservation must be associated with a user of role client, it might be assigned to user of role employee and might also be assigned to user of role student.
So in my reservation class I have properties of type User and I have marked them with [ForeignKey("AnytypeId")] attribute to hint EF for relations.
I have seen code like this at http://blog.stevensanderson.com/2011/01/28/mvcscaffolding-one-to-many-relationships/
public class Reservation
{
public int ReservationID
{
get;
set;
}
[Required(ErrorMessage="Please provide a valid date")]
public DateTime ReservationDate
{
get;
set;
}
public DateTime ReservationEnd { get; set; }
public DateTime EntryDate
{
get;
set;
}
public DateTime UpdatedOn
{
get;
set;
}
public decimal Ammount
{
get;
set;
}
public decimal? Discount { get; set; }
[DataType(DataType.MultilineText)]
public string ServiceDetails { get; set; }
[DataType(DataType.MultilineText)]
public string Remarks { get; set; }
public String PaymentMethod { get; set; }
public string VoucherNumber { get; set; }
public int ServiceID
{
get;
set;
}
public virtual Service Service
{
get;
set;
}
public string EmployeeID { get; set; }
[ForeignKey("EmployeeID")]
public virtual User Employee { get; set; }
public string ClientID { get; set; }
[ForeignKey("ClientID")]
public virtual User Client { get; set; }
public string StudentID { get; set; }
[ForeignKey("StudentID")]
public virtual User Student { get; set; }
}
public class ReservationMap : EntityTypeConfiguration<Reservation>
{
public ReservationMap()
{
this.HasOptional(r => r.Client).WithMany().WillCascadeOnDelete(true);
this.HasOptional(r => r.Employee).WithMany().WillCascadeOnDelete(false);
this.HasOptional(r=>r.Student).WithMany().WillCascadeOnDelete(false);
}
}
Now as I run my mvc3 EF code first app database created for me on the fly with following ERD and edmx model.
Now few problems that I am having:
1. When I am listing all the users of role clients in view their reservation property is showing always 0 even if their are reservations available in database. I don't know why this collection property marked with virtual is not loading??
Please I am stuck with this help me out here this is the last thing remaining.
There are couple of problems in your model. You have configured the one to many relationship in such a way that the many end(Reservations property) is excluded from the mapping. Hence the Reservations will not be loaded by EF.
The other problem is if you are going to map the Reservations property as the many end of the relationship, what will be the navigational property? is it Employee, Client, Student? Because only one of these properties can participate in the relationship with Reservations property.
It is not clear as to how these relationships should be modeled by your description. One way would be to have 3 collection properties.
public class ReservationMap : EntityTypeConfiguration<Reservation>
{
public ReservationMap()
{
HasOptional(r => r.Client).WithMany(u => u.ClientReservations).WillCascadeOnDelete(true);
HasOptional(r => r.Employee).WithMany(u => u.EmployeeReservations).WillCascadeOnDelete(false);
HasOptional(r=>r.Student).WithMany(u => u.StudentReservations).WillCascadeOnDelete(false);
}
}

Resources