Inclusion and Exclusion of Model Properties in Entity Framework - entity-framework

I have a user model and there are different properties I want to be obtainable in different circumstances,
I have a WebAPI that handles the User Model, and for different actions, I need certain properties excluded.
E.g.
When I do /API/Users -> I want to omit the passwords as this will enable someone to see the hashes of all the passwords.
However I can't outright omit the passwords as the password is required by actions such as login.
What is the best solution to enable omission of certain fields depending on the circumstances?
As a work around I added this code to my API Action
// GET: api/Users
public List<User> GetUsers()
{
return db.Users.ToList().Select(u => { u.password = ""; return u; }).ToList();
}
but surely there is a more elegant solution than this. Ideally I would like to add an annotation to the action that precludes certain properties from the result set

Related

REST - Updating partial data

I am currently programming a REST service and a website that mostly uses this REST service.
Model:
public class User {
private String realname;
private String username;
private String emailAddress;
private String password;
private Role role;
..
}
View:
One form to update
realname
email address
username
Another form to update the role
And a third form to change the password
.
Focussing on the first view, which pattern would be a good practice?
PUT /user/{userId}
imho not because the form contains only partial data (not role, not password). So it cannot send a whole user object.
PATCH /user/{userId}
may be ok. Is a good way to implement it like:
1) read current user entity
2)
if(source.getRealname() != null) // Check if field was set (partial update)
dest.setRealname(source.getRealname());
.. for all available fields
3) save dest
POST /user/{userId}/generalInformation
as summary for realname, email, username
.
Thank you!
One problem with this approach is that user cannot nullify optional fields since code is not applying the value if (input is empty and value) is null.
This might be ok for password or other required entity field but for example if you have an optional Note field then the user cannot "clean" the field.
Also, if you are using a plain FORM you cannot use PATCH method, only GET or POST.
If you are using Ajax you might be interested in JSON Merge Patch (easier) and/or JavaScript Object Notation (JSON) Patch (most complete); for an overview of the problems that one can find in partial updates and in using PATCH see also this page.
A point is that a form can only send empty or filled value, while a JSON object property can have three states: value (update), null (set null) and no-property (ignore).
An implementation I used with success is ZJSONPATCH
Focussing on the first view, which pattern would be a good practice?
My suggestion starts from a simple idea: how would you do this as web pages in HTML?
You probably start from a page that offers a view of the user, with hyperlinks like "Update profile", "Update role", "Change password". Clicking on update profile would load an html form, maybe with a bunch of default values already filled in. The operator would make changes, then submit the form, which would send a message to an endpoint that knows how to decode the message body and update the model.
The first two steps are "safe" -- the operator isn't proposing any changes. In the last step, the operator is proposing a change, so safe methods would not be appropriate.
HTML, as a hypermedia format, is limited to two methods (GET, POST), so we might see the browser do something like
GET /user/:id
GET /forms/updateGeneralInformation?:id
POST /updates/generalInformation/:id
There are lots of different spellings you can use, depending on how to prefer to organize your resources. The browser doesn't care, because it's just following links.
You have that same flexibility in your API. The first trick in the kit should always be "can I solve this with a new resource?".
Ian S Robinson observed: specialization and innovation depend on an open set. If you restrict yourself to a closed vocabulary of HTTP methods, then the open set you need to innovate needs to lie elsewhere: the RESTful approach is to use an open set of resources.
Update of a profile really does sound like an operation that should be idempotent, so you'd like to use PUT if you can. Is there anything wrong with:
GET /user/:id/generalInformation
PUT /user/:id/generalInformation
It's a write, it's idempotent, it's a complete replacement of the generalInformation resource, so the HTTP spec is happy.
Yes, changing the current representation of multiple resources with a single request is valid HTTP. In fact, this is one of the approaches described by RFC 7231
Partial content updates are possible by targeting a separately identified resource with state that overlaps a portion of the larger resource
If you don't like supporting multiple views of a resource and supporting PUT on each, you can apply the same heuristic ("add more resources") by introducing a command queue to handle changes to the underlying model.
GET /user/:id/generalInformation
PUT /changeRequests/:uuid
Up to you whether you want to represent all change requests as entries in the same collection, or having specialized collections of change requests for subsets of operations. Tomato, tomahto.

Why Include Record Key in WebAPI PUT Parameters

In all the ASP.NET WebAPI examples I have seen for implementing the HTTP PUT method, the record's key is passed as a separate parameter to the model updates. For example:
[HttpPut]
public HttpResponseMessage Put(int id, UserEditViewModel model)
{
// Look up existing record
User user = await db.Users.FindAsync(id);
// Apply changes
// user.Name = model.Name;
// Commit updated record to data store
db.SaveChanges();
}
I am curious as to why this approach is used rather than to define the key value on the model and simplify the call?
public HttpResponseMessage Put(UserEditViewModel model)
{
// Look up existing record
User user = await db.Users.FindAsync(model.UserId);
// Apply changes
// user.Name = model.Name;
// Commit updated record to data store
db.SaveChanges();
}
In most cases that I can think of the View will require the UserId anyway, so I don't see how/why it would complicated the model from the View's perspective, but I am sure there must be a good reason.
Depending on what level of RESTfulness we're talking about, I think it might be more about convenience. Looking at Richardson's Maturity Model level 3, the workflow could be something like this:
GET /api/users/{id}
Once the client navigates to a user, the server will have built the link uri, filling it with the unique resource identifier, so it could look something like this:
"api:user-edit": {
"href": "http://apiname:port/api/user/{id}"
},
So the client will have to just do a
PUT /api/users/{id}
with the appropriate payload (which theoretically should be the resource in full, but more often than not the server will only choose to look at just a couple of fields - almost like a PATCH).

How to represent a read-only property in a REST Api

if you have a REST API that is hypermedia-driven (HATEOAS) you can easily change a client's behavior by including or omitting links in the response (_links). That enables a client to completely forget about testing permissions for the operations that are possible in the current state of a resource (the link to the operation is present or not).
Additionally you can leave out properties in the response if the current user doesn't have permission to see it.
That way authorization is done entirely on the server (and controls actions and properties that are eligible to execute/view).
But what if I want to a have a read-only property? It is no problem for the REST API to ignore the property if it is present in the request (_POST_ OR _PUT_). it just won't get saved. But how can a client distinguish between write and read-only properties to present the user appropriate controls (like a disabled input field in HTML)?
The goal is to never ever have the client request a user's permissions, but to have a completely resource driven client/frontend.
Any help is greatly appreciated :-)
If I misunderstood your question, I apologize upfront. With that being said...
But how can a client distinguish between write and read-only
properties to present the user appropriate controls (like a disabled
input field in HTML)
Well, there are multiple solutions to this. The simplest one I can personally think of is to make each property an object having a simple structure of something like:
...
someProperty: {
value: 'some value',
access: 'read-only'
},
someOtherProperty: {
value: 'some value',
access: 'write'
}
...
You can obviously get as creative as you want with how you represent the "access" level of the property (using enums, booleans, changing access to be isReadOnly or whatever).
After that, the person using the API now knows they are read-only or not. If they submit a "write" value for a "read-only" property as part of the POST payload, then they should expect nothing less than a 403 response.
Edit:
In case you can't alter the properties in this manner, there are a number of other ways you can still achieve this:
write documentation that explains what access each property has
create a route that the user can submit 1 or more properties to in order to receive a response that indicates the access level of each property (response: { propName: 'read-only', propName2: 'write', etc.)
Return a propertyAccess map as part of the response (mapping properties to access levels).
end of the day, you just need a way to map a property with an access level. however that's done depends on what your restrictions and requirements are for the api, what changes you can make, and what is acceptable to both your client(s) and the business requirements.

ServiceStack Routing with ravendb ids

I've an entity with an ID of
public string ID {get;set;}
activities/1
(which comes from RavenDB).
I'm registering the following routes in my ServiceStack AppHost
Routes
.Add<Activity>("/activities")
.Add<Activity("/activities/{id}");
I'm using a backbone app to POST and PUT to my REST Service.
What happens out-of-the-box:
id property is serialized into the json as "activities/1"
id property is encoded into route as "activities%2F1"
ServiceStack gives precedence to the URL based id property, so my string gets the encoded value which is no use to RavenDb directly.
The options I'm aware of:
Change backbone to post to "/activities" and let the JSON Serialiser kick in
Change RavenDb ID generation to use hyphens rather than slashes
Make my Id property parse for the encoded %2F on set and convert to a slash
Both have disadvantages in that I either lose RESTfulness in my API, which is undesirable, or I don't follow RavenDb conventions, which are usually sensible out-of-the-fox. Also, I've a personal preference for having slashes.
So I'm wondering if there are any other options in servicestack that I could use to sort this issue that involve less compromise? Either Serialiser customisation or wildcard routing are in my head....
I have the same problem with ASP.Net WebAPI, so I don't think this is so much a ServiceStack issue, but just a general concern with dealing with Raven style id's on a REST URL.
For example, let's say I query GET: /api/users and return a result like:
[{
Id:"users/1",
Name:"John"
},
{
Id:"users/2",
Name:"Mary"
}]
Now I want to get a specific user. If I follow pure REST approach, the Id would be gathered from this document, and then I would pass it in the id part of the url. The problem here is that this ends up looking like GET: /api/users/users/1 which is not just confusing, but the slash gets in the way of how WebAPI (and ServiceStack) route url parameters to action methods.
The compromise I made was to treat the id as an integer from the URL's perspective only. So the client calls GET: /api/users/1, and I define my method as public User Get(int id).
The cool part is that Raven's session.Load(id) has overloads that take either the full string form, or the integer form, so you don't have to translate most of the time.
If you DO find yourself needing to translate the id, you can use this extension method:
public static string GetStringIdFor<T>(this IDocumentSession session, int id)
{
var c = session.Advanced.DocumentStore.Conventions;
return c.FindFullDocumentKeyFromNonStringIdentifier(id, typeof (T), false);
}
Calling it is simple as session.GetStringIdFor<User>(id). I usually only have to translate manually if I'm doing something with the id other than immediately loading a document.
I understand that by translating the ids like this, that I'm breaking some REST purist conventions, but I think this is reasonable given the circumstances. I'd be interested in any alternative approaches anyone comes up with.
I had this problem when trying out Durandal JS with RavenDB.
My workaround was to change the URL very slightly to get it to work. So in your example:
GET /api/users/users/1
Became
GET /api/users/?id=users/1
From jQuery, this becomes:
var vm = {};
vm.users = [];
$.get("/api/users/?" + $.param( { id: "users/1" })
.done(function(data) {
vm.users = data;
});

Data Security using Entity Framework

What options/solutions are there for securing data using Entity Framework?
I do not talk about forms login and such here, just assume that the users are authenticated or not.
To illustrate, i attached one of my web api controllers and i wonder if this is the way to do it. The reason why i ask is that i wonder if there are easier ways to do this than writing all this logic to what data to expose in all my controllers.
Also, when looking into a system like breezejs and odata where i can add $expand=TrafficImages to my queries, i would not want users to be able to get my hole database.
So to summarize, what ways are there to securing the data exposed such the users cant download sensible data.
[AllowAnonymous]
public object GetTheoryTests()
{
var identity = ((ClaimsIdentity)((ClaimsPrincipal)HttpContext.Current.User).Identity);
//if (HttpContext.Current.User.Identity.IsAuthenticated)
if (!identity.IsAuthenticated)
return db.TheoryTests.Include(t=>t.TrafficImages).Where(t=>t.PublicAvalible)
.Select(t => new { Id = t.Id, Title = t.Title, Images = t.TrafficImages }).AsEnumerable();
if (User.IsInRole("WebAdmins"))
return db.TheoryTests.AsEnumerable();
var key = identity.GetProvider();
var member = db.Members.Include(m=>m.PayedTheoryTests).SingleOrDefault(m=>m.Identities.Any(
i=>i.identityprovider == key.provider &&
i.nameidentifier == key.id));
if(member!=null)
return db.TheoryTests.Include(t => t.TrafficImages).Where(t => t.PublicAvalible).Select(t => new { Id = t.Id, Title = t.Title, Images = t.TrafficImages }).AsEnumerable();
else
return db.TheoryTests.Include(t => t.TrafficImages).Where(t => t.PublicAvalible)
.Union(member.PayedTheoryTests).Select(t => new { Id = t.Id, Title = t.Title, Images = t.TrafficImages }).AsEnumerable();
}
When thinking about it, what i miss is something like a viewmodel untop of my database depending on the state of the user. Would it be a solution to create two entity frameworks ontop of the same database, one for limited data display and one for more advanced operations?
Meanwhile, until QueryInterceptors arrive, you should take other steps. First, you should look into the techniques for securing a Web API controller or method, a subject beyond the scope of this answer.
Second, w/r/t $expand, you are quite right to be wary of that feature. You may want to inspect which expansions are requested for some controller methods and/or disallow it altogether for others.
Fortunately, this is relatively easy to do. You have access to the request query string. You can detect the presence of "$expand" in that string and analyze it if you want to allow certain expansions and forbid others.
Breeze will add helpers for this in future. You'll have to process the string until then.
You may want to create your own action filter for this purpose if you're up to it.
Great question!. We are currently working on something called QueryInterceptors that will allow you to examine and possibly change or reject the query that was submitted to the server. The "Principal" would be a available context object within each QueryInterceptor method. Please vote for this feature on the "Breeze" website at www.breezejs.com.