source: branches/TaskRewrite/src/plugins/acegi-0.5.1/src/groovy/org/codehaus/groovy/grails/plugins/springsecurity/GrailsDaoImpl.groovy @ 58

Last change on this file since 58 was 58, checked in by gav, 15 years ago

Configure BootStrap? with latest concepts.
Install and setup Acegi plugin with custom views.
Test Fixture plugin in a test app but couldn't get it to work with Acegi encodePassword() so gave up.

File size: 5.4 KB
Line 
1/**
2/* Copyright 2006-2009 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.codehaus.groovy.grails.plugins.springsecurity
17
18import org.apache.log4j.Logger
19
20import org.springframework.security.GrantedAuthority
21import org.springframework.security.GrantedAuthorityImpl
22import org.springframework.security.userdetails.UserDetails
23import org.springframework.security.userdetails.UserDetailsService
24import org.springframework.security.userdetails.UsernameNotFoundException
25import org.springframework.dao.DataAccessException
26
27/**
28 * {@link UserDetailsService} with {@link GrailsDomainClass} Data Access Object.
29 * @author Tsuyoshi Yamamoto
30 * @author <a href='mailto:beckwithb@studentsonly.com'>Burt Beckwith</a>
31 */
32class GrailsDaoImpl extends GrailsWebApplicationObjectSupport implements UserDetailsService {
33
34        private final Logger logger = Logger.getLogger(getClass())
35
36        def authenticateService
37
38        // dependency-injected fields
39        String loginUserDomainClass
40        String usernameFieldName
41        String passwordFieldName
42        String enabledFieldName
43        String relationalAuthoritiesField
44        String authorityFieldName
45        String authoritiesMethodName
46
47        /**
48         * {@inheritDoc}
49         * @see org.springframework.security.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
50         */
51        UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
52                return loadUserByUsername(username, true)
53        }
54
55        /**
56         * Load a user by username, optionally not loading roles.
57         * @param username  the login name
58         * @param loadRoles  if <code>true</code> load roles from the database
59         * @return the user if found, otherwise throws {@link UsernameNotFoundException}
60         * @throws UsernameNotFoundException  if the user isn't found
61         * @throws DataAccessException  if there's a database problem
62         */
63        UserDetails loadUserByUsername(String username, boolean loadRoles)
64                        throws UsernameNotFoundException, DataAccessException {
65
66                if (authenticateService.securityConfig.security.useNtlm) {
67                        username = username.toLowerCase()
68                }
69
70                GrailsWebApplicationObjectSupport.SessionContainer container = setUpSession()
71                try {
72                        def user = loadDomainUser(username, container.session)
73                        GrantedAuthority[] authorities = loadAuthorities(user, username, loadRoles)
74                        return createUserDetails(
75                                        username, user."$passwordFieldName", user."$enabledFieldName",
76                                        authorities, user)
77                }
78                finally {
79                        releaseSession(container)
80                }
81    }
82
83        protected GrantedAuthority[] loadAuthorities(user, String username, boolean loadRoles) {
84                if (!loadRoles) {
85                        return []
86                }
87
88                if (relationalAuthoritiesField) {
89                        return createRolesByRelationalAuthorities(user, username)
90                }
91
92                if (authoritiesMethodName) {
93                        return createRolesByAuthoritiesMethod(user, username)
94                }
95
96                logger.error("User [${username}] has no GrantedAuthority")
97                throw new UsernameNotFoundException("User has no GrantedAuthority")
98        }
99
100        protected def loadDomainUser(username, session) throws UsernameNotFoundException, DataAccessException {
101
102                List users = session.createQuery(
103                                "from $loginUserDomainClass where $usernameFieldName=:username")
104                                .setString('username', username)
105                                .setCacheable(true)
106                                .list()
107
108                if (users.empty) {
109                        logger.error "User not found: $username"
110                        throw new UsernameNotFoundException("User not found", username)
111                }
112
113                return users[0]
114    }
115
116        /**
117         * Create the {@link UserDetails} instance. Subclasses can override to inherit core functionality
118         * but determine the concrete class without reimplementing the entire class.
119         * @param username the username
120         * @param password the password
121         * @param enabled set to <code>true</code> if the user is enabled
122         * @param authorities the authorities that should be granted to the caller
123         * @param user  the user domain instance
124         * @return  the instance
125         */
126        protected UserDetails createUserDetails(
127                        String username, String password, boolean enabled,
128                        GrantedAuthority[] authorities, Object user) {
129                new GrailsUserImpl(
130                                username, password, enabled,
131                                true, true, true, authorities, user)
132        }
133
134        protected GrantedAuthority[] createRolesByAuthoritiesMethod(user, String username) {
135                Set authorities = user."$authoritiesMethodName"()
136                assertNotEmpty authorities, username
137
138                authorities.collect { roleName -> new GrantedAuthorityImpl(roleName) } as GrantedAuthority[]
139        }
140
141        protected GrantedAuthority[] createRolesByRelationalAuthorities(user, String username) {
142                // get authorities from LoginUser [LoginUser]--M:M--[Authority]
143
144                Set authorities = user."$relationalAuthoritiesField"
145                assertNotEmpty authorities, username
146
147                authorities.collect { item -> new GrantedAuthorityImpl(item."$authorityFieldName") } as GrantedAuthority[]
148        }
149
150        protected void assertNotEmpty(Collection authorities, String username) {
151                if (authorities == null || authorities.empty) {
152                        logger.error("User [${username}] has no GrantedAuthority")
153                        throw new UsernameNotFoundException("User has no GrantedAuthority")
154                }
155        }
156
157        protected Logger getLog() {
158                return logger
159        }
160}
Note: See TracBrowser for help on using the repository browser.