First, create the domain class:
grails create-domain-class info.shelfunit.Magazine
Next, add some fields and the SecUser class:
SecUser owner String title String topic
LInk it to SecUser:
static belongsTo = [SecUser]
Link SecUser to our new domain (we already had a Book class):
static hasMany = [books: Book, magazines: Magazine]
Add some constraints to our new domain:
static constraints = { title blank: false topic blank: false }
Next, generate the controller and the views:
grails generate-all info.shelfunit.Magazine
Add some imports in the MagazineController
import grails.plugin.springsecurity.annotation.Secured import grails.plugin.springsecurity.SpringSecurityService import info.shelfunit.SecUser
Add the Spring Security Service:
def springSecurityService
Add the following annotation to the index and show methods:
@Secured(['permitAll'])
Add the following annotation to everything else:
@Secured(['ROLE_USER'])
Change the save method to ensure the user ID is the logged in user:
def user = springSecurityService.currentUser magazineInstance.owner = springSecurityService.currentUser
Next, let’s change the views.
In index.gsp, wrap the link for the create action in a block to see if the user is logged in and has a “USER” role:
<sec:ifAllGranted roles="ROLE_USER"> <li><g:link action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></li> </sec:ifAllGranted>
In show.gsp, we should put an if block around the links to delete and edit a magazine
<g:if test="${magazineInstance?.owner?.id == currentLoggedInUser?.id}"> <g:form url="[resource:magazineInstance, action:'delete']" method="DELETE"> <fieldset> <g:link action="edit" resource="${magazineInstance}"><g:message code="default.button.edit.label" default="Edit" /></g:link> <g:actionSubmit action="delete" value="${message(code: 'default.button.delete.label', default: 'Delete')}" onclick="return confirm('${message(code: 'default.button.delete.confirm.message', default: 'Are you sure?')}');" /> </fieldset> </g:form> </g:if>
There is no change at this time to create.gsp or edit.gsp.