I need to check that a user is allowed to save/retrieve contacts to/from the database by calling a web service, and return an HTTP403 with an explanation if it is not the case.
So for the sake of factorizing the code, I decided to use a boolean method that "never" returns false
and is there only to check this, and throws a corresponding exception.
public boolean canPerformAction(User authenticatedUser) throws ForbiddenActionException{
if(authenticatedUser == null){
throw new ForbiddenActionException("There must be a user to perform an action !");
}
if(!authenticatedUser.BelongToCompany(company)){
throw new ForbiddenActionException("The user doesn't belong to the company, therefore he can't perform the action");
}
return true;
}
Then in saveContact
, I call it as follows:
public Person saveContact(User user, Person contact) throws ForbiddenActionException{
canPerformAction(user);
contact= persistContact(contact);
return contact;
}
I do the same thing in retrieveContact
:
public Person retrieveContact(User user, String contactId) throws ForbiddenActionException{
canPerformAction(user);
return fetchContact(contactId);
}
And finally these methods are called in the web service:
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveContact(@PathParam("contactId") String contactId) {
try{
Person contact= retrieveContact(getUser(), contactId);
return Response.status(Response.Status.OK).entity(contact).build();
}catch(ForbiddenActionException e){
return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build();
}
}
@POST
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response saveContact(@PathParam("id") String id, Person contact) {
try{
Person contact= saveContact(getUser(), contact);
return Response.status(Response.Status.OK).entity(contact).build();
}catch(ForbiddenActionException e){
return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build();
}
}
Do you think that this is an acceptable approach of dealing with the problem ?
void
since you're not doing anything with thetrue
value anyway? \$\endgroup\$void
is more suitable in this case. But is it a good practice / common to put checks invoid
methods ? Won't it be consided as bad code ? \$\endgroup\$void
signals that the function is run to execute commands. I'm specifically thinking of Command Query Separation when I say that. \$\endgroup\$