source: trunk/grails-app/controllers/PersonController.groovy @ 403

Last change on this file since 403 was 403, checked in by gav, 14 years ago

Change all controllers to use default.optimistic.locking.failure.

File size: 7.4 KB
Line 
1import org.codehaus.groovy.grails.plugins.springsecurity.Secured
2
3@Secured(['ROLE_Manager','ROLE_AppAdmin'])
4class PersonController extends BaseAppAdminController {
5
6    def authenticateService
7    def filterService
8
9    // the delete, save and update actions only accept POST requests
10    static Map allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']
11
12    def index = {
13        redirect action: list, params: params
14    }
15
16    def list = {
17        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100 )
18
19        if(!params.filter) {
20            return [personList: Person.list(params),
21                            personTotal: Person.count(),
22                            filterParams: params]
23        }
24
25        // filterPane:
26        return[ personList: filterService.filter( params, Person ),
27            personTotal: filterService.count( params, Person ),
28            filterParams: com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params),
29            params:params ]
30    }
31
32    def show = {
33
34        // In the case of an actionSubmit button, rewrite action name from 'index'.
35        if(params._action_Show)
36            params.action='show'
37
38        def person = Person.get(params.id)
39        if (!person) {
40            flash.message = "Person not found with id $params.id"
41            redirect action: list
42            return
43        }
44        def authorityList = person.authorities.sort { p1, p2 -> p1.id <=> p2.id }
45        [person: person, authorityList: authorityList]
46    }
47
48    /**
49    * Person delete action. Before removing an existing person,
50    * they should be removed from those authorities which they are involved.
51    */
52    def delete = {
53
54        def person = Person.get(params.id)
55        if (person) {
56            def authPrincipal = authenticateService.principal()
57            // Avoid self-delete.
58            if (!(authPrincipal instanceof String) && authPrincipal.username == person.loginName) {
59                flash.message = "You cannot delete yourself, please login as another manager and try again."
60                redirect(action:show,id:params.id)
61            }
62            else {
63                //first, delete this person from Persons_Authorities table.
64                Authority.findAll().each { it.removeFromPersons(person) }
65                person.isActive = false
66                person.save(flush: true)
67
68                try {
69                    person.delete(flush: true)
70                    flash.message = "Person $params.id deleted."
71                    redirect(action:list)
72                }
73                catch(org.springframework.dao.DataIntegrityViolationException e) {
74                    flash.message = "Could not delete '$person.loginName' due to database constraints, but all authorities have been removed."
75                    redirect(action:show,id:params.id)
76                }
77            }
78        }
79        else {
80            flash.message = "Person not found with id $params.id"
81        }
82    }
83
84    def edit = {
85
86        // In the case of an actionSubmit button, rewrite action name from 'index'.
87        if(params._action_Edit)
88            params.action='edit'
89
90        def person = Person.get(params.id)
91        if (!person) {
92            flash.message = "Person not found with id $params.id"
93            redirect action: list
94            return
95        }
96        params.message = "To allow login at least the 'ROLE_AppUser' authority must be given."
97        return buildPersonModel(person)
98    }
99
100    /**
101    * Person update action.
102    */
103    def update = {
104        Person.withTransaction { status ->
105
106            def person = Person.get(params.id)
107            if (!person) {
108                flash.message = "Person not found with id $params.id"
109                redirect action: edit, id: params.id
110                return
111            }
112
113            long version = params.version.toLong()
114            if (person.version > version) {
115                person.errors.rejectValue 'version', "default.optimistic.locking.failure"
116                render view: 'edit', model: buildPersonModel(person)
117                return
118            }
119
120            person.properties = params
121            person.setPersonGroupsFromCheckBoxList(params.personGroups)
122
123            if(params.pass == "") {
124                person.pass = "InsertNothingToClearValidation"
125            }
126            else {
127                if (person.validate()) {
128                    person.password = authenticateService.encodePassword(params.pass)
129                }
130            }
131
132            if (!person.hasErrors() && person.save(flush: true)) {
133                addRemoveAuthorities(person)
134                flash.message = "Person '$params.id - $params.loginName' updated."
135                redirect action: show, id: person.id
136            }
137            else {
138                render view: 'edit', model: buildPersonModel(person)
139            }
140
141        } //end withTransaction
142    } // update()
143
144    def create = {
145        params.message = "To allow login at least the 'ROLE_AppUser' authority must be given."
146        [person: new Person(params), authorityList: getLimitedAuthorityList()]
147    }
148
149    /**
150    * Person save action.
151    */
152    def save = {
153        Person.withTransaction { status ->
154
155            def person = new Person()
156            person.properties = params
157            person.password = authenticateService.encodePassword(params.pass)
158            person.setPersonGroupsFromCheckBoxList(params.personGroups)
159            if (person.save(flush: true)) {
160                addRemoveAuthorities(person)
161                redirect action: show, id: person.id
162            }
163            else {
164                render view: 'create', model: [person: person, authorityList: getLimitedAuthorityList()]
165            }
166
167        } //end withTransaction
168    }
169
170    /**
171    * Add or remove authorities from person as indicated in params.
172    */
173    private void addRemoveAuthorities(person) {
174        def authMap = [:]
175
176        // Build authMap from params.
177        for (key in params.keySet()) {
178            if(key.startsWith("ROLE")) {
179                authMap.(key.toString()) = "add"
180            }
181            else if(key.startsWith("_ROLE")) {
182                if( !authMap.(key.substring(1)) ) authMap.(key.substring(1)) = "remove"
183            }
184        }
185
186        // Add or remove authorities.
187        for(a in authMap) {
188            if(a.value == "add")
189                Authority.findByAuthority(a.key.toString()).addToPersons(person)
190            else
191                Authority.findByAuthority(a.key.toString()).removeFromPersons(person)
192        }
193    }
194
195    private Map buildPersonModel(person) {
196
197        List roles = getLimitedAuthorityList()
198        Set userRoleNames = []
199        for (role in person.authorities) {
200            userRoleNames << role.authority
201        }
202        LinkedHashMap<Authority, Boolean> roleMap = [:]
203        for (role in roles) {
204            roleMap[(role)] = userRoleNames.contains(role.authority)
205        }
206
207        return [person: person, roleMap: roleMap]
208    }
209
210    /**
211    * Get the full authorityList if current user is an App Admin else leave that authority off the list.
212    */
213    private List getLimitedAuthorityList() {
214        def authorityList = []
215        if(authenticateService.ifAnyGranted('ROLE_AppAdmin'))
216            authorityList = Authority.list().sort { p1, p2 -> p1.id <=> p2.id }
217        else
218            authorityList = Authority.withCriteria { gt("id", 1L) }.sort { p1, p2 -> p1.id <=> p2.id }
219
220        return authorityList
221    }
222} // end class
Note: See TracBrowser for help on using the repository browser.