View Javadoc
1   /*
2    * Copyright (c) 2002-2022, City of Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.portal.web.features;
35  
36  import java.util.ArrayList;
37  import java.util.Collection;
38  import java.util.Collections;
39  import java.util.HashMap;
40  import java.util.List;
41  import java.util.Map;
42  import java.util.stream.Collectors;
43  
44  import javax.servlet.http.HttpServletRequest;
45  
46  import org.apache.commons.lang3.StringUtils;
47  
48  import fr.paris.lutece.portal.business.right.Level;
49  import fr.paris.lutece.portal.business.right.LevelHome;
50  import fr.paris.lutece.portal.business.right.Right;
51  import fr.paris.lutece.portal.business.right.RightHome;
52  import fr.paris.lutece.portal.business.user.AdminUser;
53  import fr.paris.lutece.portal.business.user.AdminUserHome;
54  import fr.paris.lutece.portal.service.admin.AccessDeniedException;
55  import fr.paris.lutece.portal.service.admin.AdminUserService;
56  import fr.paris.lutece.portal.service.i18n.I18nService;
57  import fr.paris.lutece.portal.service.security.SecurityTokenService;
58  import fr.paris.lutece.portal.service.template.AppTemplateService;
59  import fr.paris.lutece.portal.service.util.AppPathService;
60  import fr.paris.lutece.portal.service.util.AppPropertiesService;
61  import fr.paris.lutece.portal.web.admin.AdminFeaturesPageJspBean;
62  import fr.paris.lutece.portal.web.constants.Parameters;
63  import fr.paris.lutece.portal.web.util.LocalizedPaginator;
64  import fr.paris.lutece.util.ReferenceItem;
65  import fr.paris.lutece.util.ReferenceList;
66  import fr.paris.lutece.util.html.AbstractPaginator;
67  import fr.paris.lutece.util.html.HtmlTemplate;
68  import fr.paris.lutece.util.html.ItemNavigator;
69  import fr.paris.lutece.util.sort.AttributeComparator;
70  import fr.paris.lutece.util.url.UrlItem;
71  
72  /**
73   * This class provides the user interface to manage rights features ( manage, create, modify )
74   */
75  public class RightJspBean extends AdminFeaturesPageJspBean
76  {
77      private static final long serialVersionUID = 8074788265698162631L;
78  
79      // Right
80      public static final String RIGHT_MANAGE_RIGHTS = "CORE_RIGHT_MANAGEMENT";
81  
82      // Properties
83      private static final String PROPERTY_MANAGE_RIGHTS_PAGETITLE = "portal.features.manage_rights.pageTitle";
84      private static final String PROPERTY_ASSIGN_USERS_PAGETITLE = "portal.features.assign_users.pageTitle";
85      private static final String PROPERTY_USERS_PER_PAGE = "paginator.user.itemsPerPage";
86  
87      // Markers
88      private static final String MARK_RIGHTS_LIST = "rights_list";
89      private static final String MARK_RIGHT = "right";
90      private static final String MARK_AVAILABLE_USERS_LIST = "available_users_list";
91      private static final String MARK_ASSIGNED_USERS_LIST = "assigned_users_list";
92      private static final String MARK_ASSIGNED_USERS_NUMBER = "assigned_users_number";
93      private static final String MARK_USER_LEVELS_LIST = "user_levels";
94      private static final String MARK_ITEM_NAVIGATOR = "item_navigator";
95      private static final String MARK_PAGINATOR = "paginator";
96      private static final String MARK_NB_ITEMS_PER_PAGE = "nb_items_per_page";
97  
98      // Parameters
99      private static final String PARAMETER_ID_RIGHT = "id_right";
100     private static final String PARAMETER_AVAILABLE_USER_LIST = "available_users_list";
101     private static final String PARAMETER_ID_USER = "id_user";
102     private static final String PARAMETER_ANCHOR = "anchor";
103 
104     // Templates files path
105     private static final String TEMPLATE_MANAGE_RIGHTS = "admin/features/manage_rights.html";
106     private static final String TEMPLATE_ASSIGN_USERS = "admin/features/assign_users_right.html";
107 
108     // JSP
109     private static final String JSP_URL_ASSIGN_USERS_TO_RIGHT = "jsp/admin/features/AssignUsersRight.jsp";
110     private static final String JSP_ASSIGN_USERS_TO_RIGHT = "AssignUsersRight.jsp";
111     private int _nItemsPerPage;
112     private String _strCurrentPageIndex;
113     private ItemNavigator _itemNavigator;
114 
115     /**
116      * Returns the list of rights
117      *
118      * @param request
119      *            The Http request
120      * @return the html code for display the rights list
121      */
122     public String getManageRights( HttpServletRequest request )
123     {
124         setPageTitleProperty( PROPERTY_MANAGE_RIGHTS_PAGETITLE );
125 
126         // Reinit session
127         reinitItemNavigator( );
128 
129         Map<String, Object> model = new HashMap<>( );
130         model.put( MARK_RIGHTS_LIST, I18nService.localizeCollection( RightHome.getRightsList( ), getLocale( ) ) );
131 
132         HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_MANAGE_RIGHTS, getLocale( ), model );
133 
134         return getAdminPage( template.getHtml( ) );
135     }
136 
137     /**
138      * Returns the users assignation form
139      *
140      * @param request
141      *            The Http request
142      * @return the html code for display the modes list
143      */
144     public String getAssignUsers( HttpServletRequest request )
145     {
146         Map<String, Object> model = new HashMap<>( );
147         setPageTitleProperty( PROPERTY_ASSIGN_USERS_PAGETITLE );
148 
149         String strBaseUrl = AppPathService.getBaseUrl( request ) + JSP_URL_ASSIGN_USERS_TO_RIGHT;
150         UrlItem/url/UrlItem.html#UrlItem">UrlItem url = new UrlItem( strBaseUrl );
151 
152         // RIGHT
153         String strIdRight = request.getParameter( PARAMETER_ID_RIGHT );
154         Right right = RightHome.findByPrimaryKey( strIdRight );
155 
156         if ( right == null )
157         {
158             return getManageRights( request );
159         }
160 
161         right.setLocale( getLocale( ) );
162 
163         // ASSIGNED USERS
164         // Add users with higher level then connected user or add all users if connected
165         // user is administrator
166         List<AdminUser> listAssignedUsers = AdminUserHome.findByRight( strIdRight ).stream( ).filter( this::isUserHigherThanConnectedUser )
167                 .collect( Collectors.toList( ) );
168 
169         List<AdminUser> listFilteredUsers = AdminUserService.getFilteredUsersInterface( listAssignedUsers, request, model, url );
170 
171         // AVAILABLE USERS
172         ReferenceListeferenceList">ReferenceList listAvailableUsers = new ReferenceList( );
173 
174         for ( AdminUser user : AdminUserHome.findUserList( ) )
175         {
176             final ReferenceItemtem.html#ReferenceItem">ReferenceItem itemUser = new ReferenceItem( );
177             itemUser.setCode( Integer.toString( user.getUserId( ) ) );
178             itemUser.setName( user.getFirstName( ) + " " + user.getLastName( ) + "(" + user.getAccessCode( ) + ")" );
179 
180             boolean bAssigned = listAssignedUsers.stream( )
181                     .anyMatch( assignedUser -> Integer.toString( assignedUser.getUserId( ) ).equals( itemUser.getCode( ) ) );
182 
183             // Add users with higher level then connected user or add all users if connected
184             // user is administrator
185             if ( !bAssigned && isUserHigherThanConnectedUser( user ) && ( user.getUserLevel( ) <= right.getLevel( ) ) )
186             {
187                 listAvailableUsers.add( itemUser );
188             }
189         }
190 
191         // SORT
192         String strSortedAttributeName = request.getParameter( Parameters.SORTED_ATTRIBUTE_NAME );
193         String strAscSort = null;
194 
195         if ( strSortedAttributeName != null )
196         {
197             strAscSort = request.getParameter( Parameters.SORTED_ASC );
198 
199             boolean bIsAscSort = Boolean.parseBoolean( strAscSort );
200 
201             Collections.sort( listFilteredUsers, new AttributeComparator( strSortedAttributeName, bIsAscSort ) );
202         }
203 
204         _strCurrentPageIndex = AbstractPaginator.getPageIndex( request, AbstractPaginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex );
205         int defaultItemsPerPage = AppPropertiesService.getPropertyInt( PROPERTY_USERS_PER_PAGE, 50 );
206         _nItemsPerPage = AbstractPaginator.getItemsPerPage( request, AbstractPaginator.PARAMETER_ITEMS_PER_PAGE, _nItemsPerPage, defaultItemsPerPage );
207 
208         if ( strSortedAttributeName != null )
209         {
210             url.addParameter( Parameters.SORTED_ATTRIBUTE_NAME, strSortedAttributeName );
211         }
212 
213         if ( strAscSort != null )
214         {
215             url.addParameter( Parameters.SORTED_ASC, strAscSort );
216         }
217 
218         // ITEM NAVITATOR
219         setItemNavigator( strIdRight, url.getUrl( ) );
220 
221         // PAGINATOR
222         url.addParameter( PARAMETER_ID_RIGHT, right.getId( ) );
223 
224         LocalizedPaginator<AdminUser> paginator = new LocalizedPaginator<>( listFilteredUsers, _nItemsPerPage, url.getUrl( ),
225                 AbstractPaginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex, getLocale( ) );
226 
227         // USER LEVEL
228         Collection<Level> filteredLevels = LevelHome.getLevelsList( ).stream( )
229                 .filter( level -> getUser( ).isAdmin( ) || getUser( ).hasRights( level.getId( ) ) ).collect( Collectors.toList( ) );
230 
231         model.put( MARK_RIGHT, right );
232         model.put( MARK_USER_LEVELS_LIST, filteredLevels );
233         model.put( MARK_AVAILABLE_USERS_LIST, listAvailableUsers );
234         model.put( MARK_ASSIGNED_USERS_LIST, paginator.getPageItems( ) );
235         model.put( MARK_ASSIGNED_USERS_NUMBER, listAssignedUsers.size( ) );
236         model.put( MARK_ITEM_NAVIGATOR, _itemNavigator );
237         model.put( MARK_PAGINATOR, paginator );
238         model.put( MARK_NB_ITEMS_PER_PAGE, Integer.toString( _nItemsPerPage ) );
239         model.put( SecurityTokenService.MARK_TOKEN, SecurityTokenService.getInstance( ).getToken( request, TEMPLATE_ASSIGN_USERS ) );
240 
241         HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_ASSIGN_USERS, getLocale( ), model );
242 
243         return getAdminPage( template.getHtml( ) );
244     }
245 
246     /**
247      * Process the data capture form for assign users to a role
248      *
249      * @param request
250      *            The HTTP Request
251      * @return The Jsp URL of the process result
252      * @throws AccessDeniedException
253      *             if the security token is invalid
254      */
255     public String doAssignUsers( HttpServletRequest request ) throws AccessDeniedException
256     {
257         if ( !SecurityTokenService.getInstance( ).validate( request, TEMPLATE_ASSIGN_USERS ) )
258         {
259             throw new AccessDeniedException( ERROR_INVALID_TOKEN );
260         }
261         String strIdRight = request.getParameter( PARAMETER_ID_RIGHT );
262 
263         // retrieve the selected portlets ids
264         String [ ] arrayUsersIds = request.getParameterValues( PARAMETER_AVAILABLE_USER_LIST );
265 
266         if ( ( arrayUsersIds != null ) )
267         {
268             for ( String arrayUsersId : arrayUsersIds )
269             {
270                 int nUserId = Integer.parseInt( arrayUsersId );
271                 AdminUser user = AdminUserHome.findByPrimaryKey( nUserId );
272                 if ( !AdminUserHome.hasRight( user, strIdRight ) )
273                 {
274                     AdminUserHome.createRightForUser( nUserId, strIdRight );
275                 }
276             }
277         }
278 
279         return JSP_ASSIGN_USERS_TO_RIGHT + "?" + PARAMETER_ID_RIGHT + "=" + strIdRight;
280     }
281 
282     /**
283      * unassigns user from role
284      * 
285      * @param request
286      *            The HttpRequest
287      * @return the HTML code of list assignations
288      * @throws AccessDeniedException
289      *             if the security token is invalid
290      */
291     public String doUnAssignUser( HttpServletRequest request ) throws AccessDeniedException
292     {
293         if ( !SecurityTokenService.getInstance( ).validate( request, TEMPLATE_ASSIGN_USERS ) )
294         {
295             throw new AccessDeniedException( ERROR_INVALID_TOKEN );
296         }
297         String strIdRight = request.getParameter( PARAMETER_ID_RIGHT );
298         int nIdUser = Integer.parseInt( request.getParameter( PARAMETER_ID_USER ) );
299         String strAnchor = request.getParameter( PARAMETER_ANCHOR );
300 
301         AdminUser adminUser = AdminUserHome.findByPrimaryKey( nIdUser );
302 
303         if ( adminUser != null )
304         {
305             AdminUserHome.removeRightForUser( nIdUser, strIdRight );
306         }
307 
308         return JSP_ASSIGN_USERS_TO_RIGHT + "?" + PARAMETER_ID_RIGHT + "=" + strIdRight + "#" + strAnchor;
309     }
310 
311     /**
312      * Get the item navigator
313      * 
314      * @param strIdRight
315      *            the id right
316      * @param strUrl
317      *            the url
318      */
319     private void setItemNavigator( String strIdRight, String strUrl )
320     {
321         if ( _itemNavigator == null )
322         {
323             List<String> listIdsRight = new ArrayList<>( );
324             int nCurrentItemId = 0;
325             int nIndex = 0;
326 
327             for ( Right right : RightHome.getRightsList( ) )
328             {
329                 if ( ( right != null ) && StringUtils.isNotBlank( right.getId( ) ) )
330                 {
331                     listIdsRight.add( right.getId( ) );
332 
333                     if ( right.getId( ).equals( strIdRight ) )
334                     {
335                         nCurrentItemId = nIndex;
336                     }
337 
338                     nIndex++;
339                 }
340             }
341 
342             _itemNavigator = new ItemNavigator( listIdsRight, nCurrentItemId, strUrl, PARAMETER_ID_RIGHT );
343         }
344         else
345         {
346             _itemNavigator.setCurrentItemId( strIdRight );
347         }
348     }
349 
350     /**
351      * Reinit the item navigator
352      */
353     private void reinitItemNavigator( )
354     {
355         _itemNavigator = null;
356     }
357 }