User can only call methods if the object belongs the user - java

In a CRUD jsf application, owners have objects, like records.
I want that owners can only view/edit/delete objects created by themselves. One way to achieve this, in every method to check if object has been created by the logged user.
There can be many similar methods and objects, so I would like to use another elegant/automatic way instead of using
if (selectedObject.owner == loggedUser)
phrases in every methods.
Is it possible,if possible how?

You could use aspect oriented programming for access protection.
I'd write an aspect to intercept all method calls to the access restricted methods, apply the check in a before advice and throw an exception if it fails. Depending on the structure of the program either by looking for an explicit annotation or by using a rather generic pointcut.
This would move your if (obj.owner.equals(loggedUser)) to one central place, but of course you'd still need to take care not to include other users' items in lists etc.
"The" Java aspect implementation is AspectJ. It is also used and supported by the Spring framework, which you may already use anyway: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html

If I were you I would show the component only if the user is authorized, by using
rendered={user.isOwner}
You will use this as an attribute in your component.

Related

Spring Controller with two methods differentiated by argument

I'm trying to write a REST interface to manage one of the resources in my application. Following best practice only I want to only use nouns as resource names.
I need the ability update the resource (a PUT operation) in one of several different ways. I imagine my user would call something like:
/resource/{name}?Operation=DO&time=1&Unit=HOUR
/resource/{name}?Operation=REDO&time=1&Unit=HOUR
/resource/{name}?Operation=UNDO
(I'll probably have more then 3 operations, but this is enough to show what's going on). One of the important things that the operations have different arguments. Logically time and Unit do not make sense to the UNDO operation.
In my Java back end I'd like to implement this with two different methods each of which will have it's own #RequestMapping annotation. The differentiator will be the value of the Operation parameter. I can't find any documentation that tells me how to do this
The alternative is to have a single method at the backend, but this is really ugly as I'll have to work out what combination of parameters is valid and throw my own 404 errors if they don't match!
If you absolutely need 2 controllers then do something like
/resource/do/{name}/{time}/{unit}
/resource/undo/{name}

Class structure for client library

I need to make a couple of services that will talk to both Amazon S3 and Riak CS.
They will handle the same operations, e.g. retrieve images.
Due to them returning different objects, in S3's case an S3Object. Is the proper way to design this to have a different class for each without a common interface?
I've been thinking on how to apply a common interface to both, but the return type of the methods is what's causing me some issues, due to them being different. I might just be going wrong about this and probably should just separate them but I am hoping to get some clarification here.
Thanks all!
Typically, you do this by wrapping the responses from the various external services with your own classes that have a common interface. You also wrap the services themselves, so when you call your service wrappers they all return your wrapped data classes. You've then isolated all references to the external service into one package. This also makes it easy to add or remove services.
A precise answer to your question would require knowing the language you are using and/or the platform. Eric in his answer above is correct that wrapping the data inside one of you own class is one way to handle this. However, depending on the language, the details of the final implementation will vary and the amount of work required when adding possible return value type will also vary.
In Java for example one way to handle this would be to return an heterogeneous container. Take a look at this thread:
Type safe heterogeneous container pattern to store lists of items

"Container" classes, good or bad practice, why?

I'm curious as to which is the better practice and the reasoning behind it, for this example I'm going to be using a social application which contains a 'friends' and a 'ignore' list with some custom logic based on them, (For sending messages directly, etc)
Which would be the better practice, and why?
Scenario 1:
class user {
List<> friends;
List<> ignores;
...
logical methods here
}
Scenario 2:
class User {
Social social;
...
}
class Social {
List<> friends;
List<> ignores;
...
logical methods here
}
I've seen both scenarios used throughout numerous applications and I'm curious as to which is the "Correct" way to lay it out in java, these will have methods such as
#addFriend(User user)
check ignore
check valid user
check other info
add to list
end
#getFriend(int id)
find friend by id
check online status
return friend
It seems like while have a 'Social' class may be a cleaner approach, does it really follow good practices? Seems like it'd use more memory/user just for cleaner code.
The reason why you have such constructs as your Social, most of the time, is that they represent a logical set of data and operations which is needed for different entities in your application.
If nothing other than User has those properties and actions, then there is no point in doing it separately from User. But you may design it separately anyway, for future uses (for example, if you want to be able to expand it later and you believe there will be other entities which will need Social functionality).
Looking at this from an object-oriented viewpoint, it means that the Social is a type. And then you have to ask yourself, is whether your User is_a Social or whether your User has_a Social. Does it make sense to say that the user has a "social subsystem" or is the user a "social object"? If the correct relation is is_a, then User should extend Social. If not, it should have a Social member, such as you described.
However, in Java, since you can't have multiple inheritance of implementation, sometimes your type may inherit from several types, and you have to decide which of them to extend. Many times, you simulate multiple inheritance of implementation, by having a member of what should have been the "second parent class", declare all the methods in your class, and delegate them to that member.
So the general guidelines are, more or less:
If in your application's domain, the only class where it will make sense to have friends and ignores and their operations is User, and no other conceivable entity would ever need them, then implement them directly in User.
If other entities may need similar functionality, and not all of them extend User anyway, you may consider this functionality to be an entity or class in its own right, and then you should have every class which has an is_a relationship to this entity extend it.
If Java's limitations of multiple inheritance don't allow extending directly, as it makes more sense for the class to extend some other class, you should embed an object and delegate the operations.
There may be other practical reasons to separate the Social entity from User, despite User being the only class to use them. For example, if you have several different possible implementations of "social" behavior, you may want to be able to use various Social subclasses as "plug-ins" inside User, rather than subclassing User.
Don't worry about memory so early. Go for readable/cleaner code. Premature optimization is root of all evil.
This is really based on the logic of your program. But consider that increasing the number of classes unnecessarily, is not good practice.
In your example, if the User class only contains a Social field, and you will just delegate all the method calls to the Social class, then go with scenario one.
On the other hand, if the User class has many more fields, like name, date of joining ... then it would be even better to create a separate class for such fields such as UserInfo in order to better structure your program and enhance code readability.
Now the main concerns are not the memory or performance costs of class structure.
Way more important are readability and clean code, AND the possibility to persist domain classes in a DB in the most simple and efficient way.
The later include composition or aggregation concern which is specific for different DB's.
You should care about the design aspects becoz with this you will have maintainable,scalable and readable code.
Now going by your example , i find second scenario as good case as it follows the SRP(Single Responsibilty Principle)
Don't worry about memory here as it wont make iota of difference here.
So do you want to do something like:
for(Connection connection : userSocialConnections ){
sendMessageTo(connection);
}
If so, then the method sendMessageTo would need to accept a connection (friend or ignored, basically a user) and probably if the runtype connection is ignored (or has blocked the user) then the sendMessageTo will return without sending a message polymorphically. This would require that in java that the IgnoredPeople And Friends are subtypes of something called as Connection(or people or anything you like; in fact, a connection is also a user - current or potential, isn't it?). This approach seems (to me) more like thinking in problem domain. Storing as two list inside user or inside social inside user does not matter much as long as they both (ignored and friends) have a common interface.
I would ask, what all other scenarios can be there for user's friends or ignored list. Do they need to be loaded lazily or stored separately.

Good Idea to do Spring Validation in Domain Objects Builder?

I am writing some helper code to add builders to my domain model using the Builder Pattern. I have the basic portion of the code built, but I want to added another build method that will validate the newly built object. I envision this new method would accept a class to match up with the groups in my bean validation. Therefore, when I get the object back from the builder I know it is a valid object for the state I want. I have two questions concerning this approach.
First, does this sound like a good approach? I have not seen anything on the net about doing this, but I think it would be a good idea to have it in the builder.
Next question, What is a good way to get a validator into the builder? Should I try to auotwire it in or something else?
Using the builder pattern is a nice way to construct objects, so it should work well for your purposes. You said you want to add another build method. Is this implying that you would have 2 build methods - one that validates and one that doesn't? I would only have one method so you can be sure your object validates.
For how to validate, the Spring docs discuss validating using JSR-303 http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/validation.html
Just something to keep in mind as you're building a Spring app. Consider if grails might be something of interest to you. One part of it is domain object validation and it has capabilities to build objects for testing that will validate. Obviously you would want to use more features than just that if you're going to use grails, but just wanted to note it.

Best Practice (Design Pattern) for copying and augmenting Objects

I'm using an API providing access to a special server environment. This API has a wide range of Data objects you can retrieve from it. For Example APICar
Now I'd like to have "my own" data object (MyCar) containing all information of that data object but i'd like to either leave out some properties, augment it, or simply rename some of them.
This is because i need those data objects in a JSON driven client application. So when someone changes the API mentioned above and changes names of properties my client application will break immediatly.
My question is:
Is there a best practice or a design pattern to copy objects like this? Like when you have one Object and want to transfer it into another object of another class? I've seen something like that in eclipse called "AdapterFactory" and was wondering if it's wide used thing.
To make it more clear: I have ObjectA and i need ObjectB. ObjectA comes from the API and its class can change frequently. I need a method or an Object or a Class somewhere which is capable of turning an ObjectA into ObjectB.
I think you are looking for Design Pattern Adapter
It's really just wrapping an instance of class A in an instance of class B, to provide a different way of using it / different type.
"I think" because you mention copying issues, so it may not be as much a class/type thing as a persistence / transmission thing.
Depending on your situation you may also be interested in dynamic proxying, but that's a Java feature.

Categories