Set a Grails Domain Class as "No-Insert Mode" - grails

I need to use a complex query on my Grails application. Instead of using a complex criteriaBuilder(), I instead performed the following:
Created View on the database, say ParentChildView.
Mapped it into a domain class.
Use this ParentChildView domain class to perform a .list() operation.
I'm wondering if I can configure this domain class to something like "select-only mode" or "no-insert-allowed mode"?— you know, just to make sure an Exception will be thrown if some developer accidentally tries to insert to this domain.

As per my understanding of your question, you don't want insertion to happen or for sure updates as well.
Your action could be one from these.
User meta-programming and make save method throw an exception for domain. e.g.
User.metaClass.static.save = {
throw new IllegalStateException("Object is not in a state to be save.")
}
You could use hooks if not sure about meta-programming as below.
def beforeInsert() {
throw new IllegalStateException("Object is not in a state to be save.")
}
def beforeUpdate() {
throw new IllegalStateException("Object is not in a state to be updated.")
}
def beforeDelete() {
throw new IllegalStateException("Object is not in a state to be deleted.")
}
Haven't tried mapWith for inserts / updates as it actually don't allow creation of a table but everything like a domain is available.
static mapWith = "none"
Last but not least we could also use transactions but these won't be of that much help. Like in service you could use #Transactional(readOnly=true). But this will just help in services.
Also, you could disable versioning and want cache just only for reads.
static mapping = {
cache usage: 'read-only'
version false
}
I found this topic about read-only domain very helpful and worth.
I'm not sure about third bullet but you could try this as well.
Hope It would help!

Related

Jhipster, prevent user to update entities created by other users

I have been implementing Jhipster at my work and loving it. I was asked to implement a security validation that one user should not be allowed to edit the entity created by other user. For this I need two things:
First, in all entities, add a ManytoOne relation with User entity.
In Backend put a validation in controller while updating the entity to check if current logged in user is same as what is stored in DB. In front end also same logic to show/hide edit button.
I have done a POC for this and it works but is little ugly, check the code:
public ResponseEntity<Entry> updateEntry(#RequestBody Entry entry) throws URISyntaxException {
log.debug("REST request to update Entry : {}", entry);
if (entry.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
//here is my logic
Optional<Entry> entry_db = entryRepository.findOneWithEagerRelationships(entry.getId());
if(!entry_db.get().getUser().getId().equals(userService.getUserWithAuthorities().get().getId())) {
//throw someexception
}
//
Entry result = entryRepository.save(entry);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, entry.getId().toString()))
.body(result);
}
Is there any better or OOTB way of doing this??? may be something in spring security i am not aware of??
Thanks for help!!
This is a job for Spring Security Expression-Based Access Control, in particular you could annotate your method with #PreFilter and a custom PermissionEvaluator you would implement with similar logic as in your POC. The PermissionEvaluator could be generic and applied to several entity types if you define an Owned interface that models the ownership with a method like User getOwner() and that all your entity classes would implement.
See https://docs.spring.io/spring-security/site/docs/current/reference/html5/#el-access
The annotated method should be in a service rather than in a resource controller.
Also, UserService alone will not help you in finding the current authenticated user, you should use JHipster's SecurityUtils first and then ÙserService if you need more data about it.

Grails: how to retrieve a persistent value for the collection?

I'm writing a Grails application and I need to retrieve a persistent value for the collection of my domain class objects. Let's consider we have got the following domain object:
class UserGroup {
SortedSet<User> users
static hasMany = [ users: User ]
// ...
def beforeUpdate() {
println "BEFORE UPDATE: " + this.getPersistentValue('users');
}
}
class User implements Comparable<User> {
String name
}
And the controller which has the following action:
class UserGroupController {
def addUser() {
UserGroup group = UserGroup.get(params.long('gid'))
User user = User.get(params.long('uid'))
group.addToUsers(user)
group.save(failOnError:true, flush:true)
}
}
The problem is that when beforeUpdate() is called, the users collection already contains the recently added user. So, seems that addTo() method doesn't trigger the beforeUpdate() event.
The same problem occurs when we're talking about isDirty() method. As the changes are applied before the beforeUpdate() is called, the collection is not recognized as dirty field.
Does anyone know how to change this? I'm writing a feature which tracks the history of changes for lots of different object, so I need to have access to the previous value in order to understand whether its value was changed or not.
I have had a similar issue, where things are being updated when I wasn't expecting them when I used the .get() on domain classes. I like to use .read() now because it wont update the database when I'm not expecting it to. Grails does a lot of sneaky things behind the sense which are helpful I think but can be a bit confusing.

Grails - controllers and tight coupling with backend

When you generate controllers in grails, the controllers call methods on the domain layer directly - I quite don't understand this, every bit of me is telling me that this is kind of wrong because you are tightly coupling the backend with the frontend. I think this belongs to the service layer.
Since it would be pretty ugly to create an equivalent set of methods in the service layer for all the methods defined on domain objects, I created this AbstractService to delegate all (missing) method calls from the service layer to the domain layer:
abstract class AbstractService {
def entityType
/**
* By default, this method takes the name of the service that extends this
* class, removes the suffix 'Service' and tries to create the Class object
* from the resulting name. Override at will.
*/
protected Class getEntityType() {
if (!entityType) {
try {
entityType = Class.forName(this.class.name[0..-8], false, Thread.currentThread().contextClassLoader)
} catch (ClassNotFoundException e) {
throw new ClassNotFoundException("Class ${this.class.name[0..-8]} could not be found. Please "
+ "override AbstractService#getEntityType() for ${this.class}.")
}
}
entityType
}
def methodMissing(String name, args) {
try {
if (getEntityType()?.metaClass?.getStaticMetaMethod(name)) {
getEntityType().invokeMethod(name, args)
} else if (args?.last()?.metaClass?.getMetaMethod(name)) {
args.last().invokeMethod(name, args.take(args.size() - 1))
} else {
throw new MissingMethodException(name, this.class, args)
}
} catch (MissingMethodException e) {
throw new MissingMethodException(name, this.class, args)
}
}
}
Then I just extend this service e.g. like this:
class UserService extends AbstractService {
}
And my controllers then can look for example like this:
class UserController {
def userService
def create() {
userService.save(new User(params))
}
def list() {
userService.list(params)
}
// et cetera...
}
Don't you think this is better? Thanks to dependency injection, I can for example rewrite the whole business layer without the need to change the code in the controllers - which is kind of why we use dependency injection, isn't it?
Thanks for your answers, I would like to hear as much opinions as possible.
This model is very used in Java Web applications and all. The Rails (and Grails followed it) community just tried to break the paradigm here, leaving it more simple. I mean, why would you delegate a service class to manipulate an entity, if this entity can simply do the job? If it's natural to the entity to do the job, then don't bring someone else to do it. That way, you avoid the Anemic Model since your objects are not only data holders, but they also know how to operate its own business.
Having said that, there are times when you're better off using a service class to do operations on your entities. For example, if it involves different kind of entities at the same time and so on... So, when it's not "natural" (and you would have to force to make it work) for the entity itself to take care of the operation, then a service class is the way to go. This article based on Rails gives some tips about the use of a service class.
And you are not tightly coupling the controller with the models (you said backend and front end, but I guess that's what you mean). The controller will eventually need to use the model, be it the entity itself or a service class (also Model) manipulating it.
The scaffolded controller code does not really represent ideal application architecture. Keep in mind that the generated scaffold code is just a starting point for generating the CRUD portions of your application.
You are correct that in general, you don't want to put most of your GORM queries in Controllers, since controllers are supposed to be for interacting with the front end. You can certainly either put the query/business logic into Services or put the queries directly into Domain classes. That's why Grails Services support declarative transaction handling.

returning a default instance from a getter method that I don't want to persist

I have two domain objects:
Customer
CustomerConfig
Customer has a 1-1 association with CustomerConfig. There is a default CustomerConfig with default settings for Customers who do not have an explicitly saved CustomerConfig e.g.
def getConfig() {
if (!config) {
return new CustomerConfig() //the default settings
} else {
return config
}
}
The problem I am having is that when I return the default setting GORM saves the CustomerConfig instance to the database as it appears to GORM that it has changed.
In fact I do not want to save it to the database as I want to be able to control the default settings for customer and make updates for customers until they have an explicitly saved config.
I also am trying avoid using conditional logic as follows:
def config = customer.config?:new CustomerConfig()
And encapsulate it in the Customer domain object. It seems like there's a different pattern I should be following. Would welcome any advice.
Thanks,
cowper
IMHO, it's never a good idea to change behavior of default getter/setter as those are managed by GORM.
You can do something like this
class Customer {
static transients = ['setting']
public CustomerConfig getSetting(){
return getConfig()?:new CustomerConfig()
}

Grails Plugins Requiring External Relationships

I posted this on the Grails mailing list yesterday and haven't had any hits. Figured I'd try here as well today.
I'm considering writing a grails plugin but this plugin would require some sort of relationship to an account / user object. However, I don't want to force a particular security model on the plugin. For example, say was writing a comment system plugin (I'm not). I'd have a comment object...
class Comment {
String comment
Date dateCreated
// etc etc
}
The comment is missing a couple of things:
Who added the comment
What the comment was added to.
I'd like to first focus on #1. So someone might be using the Spring security plugin and use the default Person object, or maybe they changed that to User. Who knows. Is there any way that anyone can think of to configure that relationship without hard coding it in the plugin?
One thing I've thought about was to have the grails app extend the plugin's domain classes to add this relationship. so I might do something like...
class ArticleComment extends Comment {
static belongsTo = [user:User]
}
But in a larger plugin, that might be a lot of inheritance requirements. Not the end of the world, but just looking for other possible options.
You can use the same technique employed by the Commentable plugin:
The user of your plugin will need to declare a closure in Config.groovy to evaluate the logged user:
grails.myplugin.user.evaluator = { session.user }
And you can use something like this in your plugin's code to call the user configured closure:
def evaluateUser() {
def evaluator = grailsApplication.config.grails.myplugin.user.evaluator
def user
if(evaluator instanceof Closure) {
evaluator.delegate = this
evaluator.resolveStrategy = Closure.DELEGATE_ONLY
user = evaluator.call()
}
if(!user) {
throw new Exception("No [grails.myplugin.user.evaluator] setting defined or the evaluator doesn't evaluate to an entity. Please define the evaluator correctly in grails-app/conf/Config.groovy")
}
if(!user.id) {
throw new Exception("The evaluated user is not a persistent instance.")
}
return user
}
I think you can do it like SpringSecurity do. Instead of let people extend your Comment class, You can write 2 class CommentUser & CommentPlace; then let others extends them. I think it's more simple.

Resources