Accessing entities in EF on basis of userID - entity-framework

I want to be able to define a logic for accessing entities using EF5 . Like my order entity has UserId so i want from any where in code if query hits Orders it needs to get filter by currently logged in user.
I am using database first approach.

Usually this is a two-phase process.
First, having the username of your user, you retrieve the user record from the data source:
string UserName = HttpContext.Current.User.Identity.Name;
User user = context.Users.FirstOrDefault( u => u.UserName == UserName );
Then, you filter your data for specific user:
IEnumerable<Order> orders = context.Orders.Where( o => o.UserId == user.Id );
You can further optimize the process so that the user record doesn't have to be retrieved upon each request, instead you could store the UserId in the authentication cookie.

Related

Is there a better way to perform a query like this in Entity Framework

I have a model called User and each user has a list of another model called Hobbies. I want to retrieve a User who has a hobby with a certain ID, is there anything better using Entity Framework than just retrieving all users then searching inside each user's hobbies list and match it with the hobby id, a pseudo code would look like the following
UserList = select all users from db
targetUser = null;
for User in UsersList:
for Hobby in User.HobbiesList:
if(Hobby.ID == currentHobby.ID)
{
targetUser = User;
}
First of all, EF won't automatically get all the linked entities, you need to explicitly Include everything you want to see in the end result.
As for the question, yes of course, you can use all the standard LINQ filters when working with EF. In your case
db.Userlist.Where(user => user.HobbiesList.Any(hobby => hobby.ID == currentHobby.ID))
Don't forget to Include(user => user.HobbiesList) if you want to see it in the results.

Loopback extending built in User model issues

I am inheriting the builtin User model in my own Customer model. The Customer model is having extra parameters like first-name, last-name etc. To create an User and Customer I am using the following code:
// create a Customer
User.create({
email: email,
password: userPassword,
cellnumber: cellDetails.cellnumber
},
function (error, userDet) {
I get an id in response to this call: 59c4c5845dc8de4730645963. But when I am trying to get the account by id i.e. accounts/{id} and pass it the above id, it gives the following error:
the "Unknown \"customer\" id \"59c4c5845dc8de4730645963\"."
So this means that id of the User model and Customer model are somehow not same. How do I resolve this ? Also, in the mongo db database all the properties are getting visible under the User model and not under the Customer model. What am I doing wrong here ? Could anyone let me know.
Thanks
I believe you should create like this: Account.create({ email, password, ... }) , using the Account model rather than User model.
You should use the model you created document with, Account in this case. The thing is, each model works only with it's own MongoDB collection and they are isolated from each other.

moodle : How is parent/child mentor/mentee role relationship stored?

How or where does moodle store how a parent/mentor is related to a student. I don't see how the system is tying the user and role assignment and whatever else it's using (context, etc).
I jut want to be able to query for a list of users who have supervisor/parent role and get their corresponding students.
Thanks
I assume you have configured the parent role as defined here: https://docs.moodle.org/en/Parent_role
If so, the connection is as follows:
Each user has a 'context' record, related to their userid. This can be retrieved via context_user::instance($userid) or from the database by
SELECT *
FROM mdl_context
WHERE instanceid = [userid] AND contextlevel = 30
(Where 30 is CONTEXT_USER and assuming your DB prefix is the default 'mdl_')
Parent/mentors have an appropriate role assigned to them at this user's context.
You can find this in the database by the following query:
SELECT userid
FROM mdl_role_assignments
WHERE contextid = [usercontextid]
Optionally, this could be restricted to only retrieve specific roleids (with "AND roleid = [parentroleid]"). However, most sites will only have parent/mentor roles assigned in the user context, so you can probably get away without checking the roleid.
The following query will perfectly answer your parent child relationship.
This query will return the parent id when you will pass the child id in query
SELECT userid as parent FROM mdl_role_assignments
join mdl_context on mdl_context.id = mdl_role_assignments.contextid
where mdl_context.contextlevel = 30 and mdl_context.instanceid = 162
here 162 is the child id

How to hide properties on Azure Mobile Service responses?

I have a Mobile Service with Model classes and DTO classes. I mapped these using Fluent API and got it to work to perform CRUD operations, but I have a problem with the JSON responses returned in some instances.
Take for example a User entity with user name and password. To register a user I have my PostUserDTO method like this:
// POST tables/UserDTO
public async Task<IHttpActionResult> PostUserDTO(UserDTO item)
{
string hashString = PasswordHash.CreateHash(item.Password);
item.Password = hashString;
UserDTO current = await InsertAsync(item);
current.Password = "";
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
On the method I read the password property sent from the client and then proceed to hash it with a salt, replace the value in the object sent and save it to the database, then I proceed to empty the password so the hashed result isn't returned.
In this case the best practice would be to omit the password property from the response, this also should happen when retrieving all of the users in the table, I only want to return specific information, some information generated by my server should stay out from the response.
How can I select or alter the information from the responses? Do I have to create other DTOs for every kind of response I desire?

Extend User authentication object in Azure Mobile Services

Is it possible to add additional properties to the User object on the server in WAMS? I would like to store the Id primary key of my User table for (secure) use in my table scripts. At the moment the only id is the vendor specific authentication Id, but I'd like to be able to allow users to choose an authentication method. Currently my (simplified) table design is as follows:
User table:
id
googleId
twitterId
facebookId
name, etc...
League table
id
userId
name, etc
I'd like to store the user primary key in the userId field on the league table, and then query it to ensure that users only get to see leagues they created. At the moment, the user object in table scripts sends through a User object with the Google/Twitter/Windows authentication token and I have to do a query to get the primary key userID, everytime I want to carry out an operation on a table with a userId column.
Ideal solution would be that when the Insert script on my User table is called on registrations and logins I can do:
// PSEUDO CODE
function insert(item, user, request) {
var appUserId;
Query the user table using the user.userId Google/Twitter/Facebook id
If user exists {
// Set a persisted appUserId to use in all subsequent table scripts.
user.appUserId = results.id;
} else {
Set the GooTwitFace columns on the user table, from user.userId
insert the user then get the inserted record id
// Set a persisted appUserId to use in all subsequent table scripts
user.appUserId = insertUserPK;
}
}
Then, in subsequent table scripts, I'd like to use user.appUserId in queries
If all you are trying to do is authorize users to only have access to their own data, I'm not sure you even need the "user" table. Just use the provider-specific userId on the user object to query your "league" table (making sure the userId column is indexed). The values will be provider-specific, but that shouldn't make any difference.
If you are trying to maintain a notion of a single user identity across the user's Google/Facebook/Twitter logins, that's a more complicated problem where you would need a "user" table and the kind of lookup you are describing. We hope to ship support for this scenario as a feature out of the box. It is possible (but fairly messy) to do this yourself, let me know if that's what you're trying to do.