1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.service.impl;
24  
25  import com.liferay.portal.DuplicateRoleException;
26  import com.liferay.portal.NoSuchRoleException;
27  import com.liferay.portal.PortalException;
28  import com.liferay.portal.RequiredRoleException;
29  import com.liferay.portal.RoleNameException;
30  import com.liferay.portal.SystemException;
31  import com.liferay.portal.kernel.annotation.Propagation;
32  import com.liferay.portal.kernel.annotation.Transactional;
33  import com.liferay.portal.kernel.util.GetterUtil;
34  import com.liferay.portal.kernel.util.OrderByComparator;
35  import com.liferay.portal.kernel.util.StringPool;
36  import com.liferay.portal.kernel.util.StringUtil;
37  import com.liferay.portal.kernel.util.Validator;
38  import com.liferay.portal.model.Group;
39  import com.liferay.portal.model.ResourceConstants;
40  import com.liferay.portal.model.Role;
41  import com.liferay.portal.model.RoleConstants;
42  import com.liferay.portal.security.permission.PermissionCacheUtil;
43  import com.liferay.portal.service.base.RoleLocalServiceBaseImpl;
44  import com.liferay.portal.util.PortalUtil;
45  import com.liferay.portal.util.PropsUtil;
46  
47  import java.util.HashMap;
48  import java.util.LinkedHashMap;
49  import java.util.List;
50  import java.util.Map;
51  
52  /**
53   * <a href="RoleLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
54   *
55   * @author Brian Wing Shun Chan
56   *
57   */
58  public class RoleLocalServiceImpl extends RoleLocalServiceBaseImpl {
59  
60      public Role addRole(
61              long userId, long companyId, String name, String description,
62              int type)
63          throws PortalException, SystemException {
64  
65          return addRole(userId, companyId, name, description, type, null, 0);
66      }
67  
68      public Role addRole(
69              long userId, long companyId, String name, String description,
70              int type, String className, long classPK)
71          throws PortalException, SystemException {
72  
73          // Role
74  
75          className = GetterUtil.getString(className);
76          long classNameId = PortalUtil.getClassNameId(className);
77  
78          validate(0, companyId, name);
79  
80          long roleId = counterLocalService.increment();
81  
82          if ((classNameId <= 0) || className.equals(Role.class.getName())) {
83              classNameId = PortalUtil.getClassNameId(Role.class);
84              classPK = roleId;
85          }
86  
87          Role role = rolePersistence.create(roleId);
88  
89          role.setCompanyId(companyId);
90          role.setClassNameId(classNameId);
91          role.setClassPK(classPK);
92          role.setName(name);
93          role.setDescription(description);
94          role.setType(type);
95  
96          rolePersistence.update(role, false);
97  
98          // Resources
99  
100         if (userId > 0) {
101             resourceLocalService.addResources(
102                 companyId, 0, userId, Role.class.getName(), role.getRoleId(),
103                 false, false, false);
104         }
105 
106         return role;
107     }
108 
109     public void addUserRoles(long userId, long[] roleIds)
110         throws SystemException {
111 
112         userPersistence.addRoles(userId, roleIds);
113 
114         PermissionCacheUtil.clearCache();
115     }
116 
117     @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
118     public void checkSystemRoles(long companyId)
119         throws PortalException, SystemException {
120 
121         for (Role role : roleFinder.findBySystem(companyId)) {
122             _systemRolesMap.put(companyId + role.getName(), role);
123         }
124 
125         // Regular roles
126 
127         String[] systemRoles = PortalUtil.getSystemRoles();
128 
129         for (String name : systemRoles) {
130             String description = PropsUtil.get(
131                 "system.role." + StringUtil.replace(name, " ", ".") +
132                     ".description");
133             int type = RoleConstants.TYPE_REGULAR;
134 
135             checkSystemRole(companyId, name, description, type);
136         }
137 
138         // Community roles
139 
140         String[] systemCommunityRoles = PortalUtil.getSystemCommunityRoles();
141 
142         for (String name : systemCommunityRoles) {
143             String description = PropsUtil.get(
144                 "system.community.role." +
145                     StringUtil.replace(name, " ", ".") + ".description");
146             int type = RoleConstants.TYPE_COMMUNITY;
147 
148             checkSystemRole(companyId, name, description, type);
149         }
150 
151         // Organization roles
152 
153         String[] systemOrganizationRoles =
154             PortalUtil.getSystemOrganizationRoles();
155 
156         for (String name : systemOrganizationRoles) {
157             String description = PropsUtil.get(
158                 "system.organization.role." +
159                     StringUtil.replace(name, " ", ".") + ".description");
160             int type = RoleConstants.TYPE_ORGANIZATION;
161 
162             checkSystemRole(companyId, name, description, type);
163         }
164     }
165 
166     public void deleteRole(long roleId)
167         throws PortalException, SystemException {
168 
169         Role role = rolePersistence.findByPrimaryKey(roleId);
170 
171         if (PortalUtil.isSystemRole(role.getName())) {
172             throw new RequiredRoleException();
173         }
174 
175         // Resources
176 
177         String className = role.getClassName();
178         long classNameId = role.getClassNameId();
179 
180         if ((classNameId <= 0) || className.equals(Role.class.getName())) {
181             resourceLocalService.deleteResource(
182                 role.getCompanyId(), Role.class.getName(),
183                 ResourceConstants.SCOPE_INDIVIDUAL, role.getRoleId());
184         }
185 
186         if ((role.getType() == RoleConstants.TYPE_COMMUNITY) ||
187             (role.getType() == RoleConstants.TYPE_ORGANIZATION)) {
188 
189             userGroupRoleLocalService.deleteUserGroupRolesByRoleId(
190                 role.getRoleId());
191         }
192 
193         // Role
194 
195         rolePersistence.remove(role);
196 
197         // Permission cache
198 
199         PermissionCacheUtil.clearCache();
200     }
201 
202     public Role getGroupRole(long companyId, long groupId)
203         throws PortalException, SystemException {
204 
205         long classNameId = PortalUtil.getClassNameId(Group.class);
206 
207         return rolePersistence.findByC_C_C(companyId, classNameId, groupId);
208     }
209 
210     public List<Role> getGroupRoles(long groupId) throws SystemException {
211         return groupPersistence.getRoles(groupId);
212     }
213 
214     public Map<String, List<String>> getResourceRoles(
215             long companyId, String name, int scope, String primKey)
216         throws SystemException {
217 
218         return roleFinder.findByC_N_S_P(companyId, name, scope, primKey);
219     }
220 
221     public Role getRole(long roleId) throws PortalException, SystemException {
222         return rolePersistence.findByPrimaryKey(roleId);
223     }
224 
225     public Role getRole(long companyId, String name)
226         throws PortalException, SystemException {
227 
228         Role role = _systemRolesMap.get(companyId + name);
229 
230         if (role != null) {
231             return role;
232         }
233 
234         return rolePersistence.findByC_N(companyId, name);
235     }
236 
237     public List<Role> getRoles(long companyId) throws SystemException {
238         return rolePersistence.findByCompanyId(companyId);
239     }
240 
241     public List<Role> getUserGroupRoles(long userId, long groupId)
242         throws SystemException {
243 
244         return roleFinder.findByUserGroupRole(userId, groupId);
245     }
246 
247     public List<Role> getUserRelatedRoles(long userId, long groupId)
248         throws SystemException {
249 
250         return roleFinder.findByU_G(userId, groupId);
251     }
252 
253     public List<Role> getUserRelatedRoles(long userId, long[] groupIds)
254         throws SystemException {
255 
256         return roleFinder.findByU_G(userId, groupIds);
257     }
258 
259     public List<Role> getUserRelatedRoles(long userId, List<Group> groups)
260         throws SystemException {
261 
262         return roleFinder.findByU_G(userId, groups);
263     }
264 
265     public List<Role> getUserRoles(long userId) throws SystemException {
266         return userPersistence.getRoles(userId);
267     }
268 
269     public boolean hasUserRole(long userId, long roleId)
270         throws SystemException {
271 
272         return userPersistence.containsRole(userId, roleId);
273     }
274 
275     /**
276      * Returns true if the user has the role.
277      *
278      * @param       userId the user id of the user
279      * @param       companyId the company id of the company
280      * @param       name the name of the role
281      * @param       inherited boolean value for whether to check roles inherited
282      *              from the community, organization, location, or user group
283      * @return      true if the user has the role
284      */
285     public boolean hasUserRole(
286             long userId, long companyId, String name, boolean inherited)
287         throws PortalException, SystemException {
288 
289         Role role = rolePersistence.findByC_N(companyId, name);
290 
291         if (inherited) {
292             if (roleFinder.countByR_U(role.getRoleId(), userId) > 0) {
293                 return true;
294             }
295             else {
296                 return false;
297             }
298         }
299         else {
300             return userPersistence.containsRole(userId, role.getRoleId());
301         }
302     }
303 
304     /**
305      * Returns true if the user has any one of the specified roles.
306      *
307      * @param       userId the user id of the user
308      * @param       companyId the company id of the company
309      * @param       names an array of role names
310      * @param       inherited boolean value for whether to check roles inherited
311      *              from the community, organization, location, or user group
312      * @return      true if the user has the role
313      */
314     public boolean hasUserRoles(
315             long userId, long companyId, String[] names, boolean inherited)
316         throws PortalException, SystemException {
317 
318         for (int i = 0; i < names.length; i++) {
319             if (hasUserRole(userId, companyId, names[i], inherited)) {
320                 return true;
321             }
322         }
323 
324         return false;
325     }
326 
327     public List<Role> search(
328             long companyId, String name, String description, Integer type,
329             int start, int end, OrderByComparator obc)
330         throws SystemException {
331 
332         return search(
333             companyId, name, description, type,
334             new LinkedHashMap<String, Object>(), start, end, obc);
335     }
336 
337     public List<Role> search(
338             long companyId, String name, String description, Integer type,
339             LinkedHashMap<String, Object> params, int start, int end,
340             OrderByComparator obc)
341         throws SystemException {
342 
343         return roleFinder.findByC_N_D_T(
344             companyId, name, description, type, params, start, end, obc);
345     }
346 
347     public int searchCount(
348             long companyId, String name, String description, Integer type)
349         throws SystemException {
350 
351         return searchCount(
352             companyId, name, description, type,
353             new LinkedHashMap<String, Object>());
354     }
355 
356     public int searchCount(
357             long companyId, String name, String description, Integer type,
358             LinkedHashMap<String, Object> params)
359         throws SystemException {
360 
361         return roleFinder.countByC_N_D_T(
362             companyId, name, description, type, params);
363     }
364 
365     public void setUserRoles(long userId, long[] roleIds)
366         throws SystemException {
367 
368         userPersistence.setRoles(userId, roleIds);
369 
370         PermissionCacheUtil.clearCache();
371     }
372 
373     public void unsetUserRoles(long userId, long[] roleIds)
374         throws SystemException {
375 
376         userPersistence.removeRoles(userId, roleIds);
377 
378         PermissionCacheUtil.clearCache();
379     }
380 
381     public Role updateRole(long roleId, String name, String description)
382         throws PortalException, SystemException {
383 
384         Role role = rolePersistence.findByPrimaryKey(roleId);
385 
386         validate(roleId, role.getCompanyId(), name);
387 
388         if (PortalUtil.isSystemRole(role.getName())) {
389             throw new RequiredRoleException();
390         }
391 
392         role.setName(name);
393         role.setDescription(description);
394 
395         rolePersistence.update(role, false);
396 
397         return role;
398     }
399 
400     protected void checkSystemRole(
401             long companyId, String name, String description, int type)
402         throws PortalException, SystemException {
403 
404         Role role = _systemRolesMap.get(companyId + name);
405 
406         try {
407             if (role == null) {
408                 role = rolePersistence.findByC_N(companyId, name);
409             }
410 
411             if (!role.getDescription().equals(description)) {
412                 role.setDescription(description);
413 
414                 roleLocalService.updateRole(role, false);
415             }
416         }
417         catch (NoSuchRoleException nsre) {
418             role = roleLocalService.addRole(
419                 0, companyId, name, description, type);
420         }
421 
422         _systemRolesMap.put(companyId + name, role);
423     }
424 
425     protected void validate(long roleId, long companyId, String name)
426         throws PortalException, SystemException {
427 
428         if ((Validator.isNull(name)) || (Validator.isNumber(name)) ||
429             (name.indexOf(StringPool.COMMA) != -1) ||
430             (name.indexOf(StringPool.STAR) != -1)) {
431 
432             throw new RoleNameException();
433         }
434 
435         try {
436             Role role = roleFinder.findByC_N(companyId, name);
437 
438             if (role.getRoleId() != roleId) {
439                 throw new DuplicateRoleException();
440             }
441         }
442         catch (NoSuchRoleException nsge) {
443         }
444     }
445 
446     private Map<String, Role> _systemRolesMap = new HashMap<String, Role>();
447 
448 }