View Javadoc
1   /*
2    * Copyright 2012-2019 CodeLibs Project and the Others.
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,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.helper;
17  
18  import static org.codelibs.core.stream.StreamUtil.stream;
19  
20  import java.util.ArrayList;
21  import java.util.HashMap;
22  import java.util.HashSet;
23  import java.util.List;
24  import java.util.Map;
25  import java.util.Set;
26  
27  import javax.annotation.PostConstruct;
28  import javax.servlet.http.Cookie;
29  import javax.servlet.http.HttpServletRequest;
30  
31  import org.codelibs.core.crypto.CachedCipher;
32  import org.codelibs.core.lang.StringUtil;
33  import org.codelibs.fess.app.service.AccessTokenService;
34  import org.codelibs.fess.entity.SearchRequestParams.SearchRequestType;
35  import org.codelibs.fess.exception.InvalidAccessTokenException;
36  import org.codelibs.fess.mylasta.action.FessUserBean;
37  import org.codelibs.fess.mylasta.direction.FessConfig;
38  import org.codelibs.fess.util.ComponentUtil;
39  import org.lastaflute.web.servlet.request.RequestManager;
40  import org.lastaflute.web.util.LaRequestUtil;
41  import org.slf4j.Logger;
42  import org.slf4j.LoggerFactory;
43  
44  /**
45   * This class returns a list of a role from a request parameter,
46   * a request header and a cookie. The format of the default value
47   * is "[\d]+\nrole1,role2,role3", which you can encrypt.
48   *
49   * @author shinsuke
50   *
51   */
52  public class RoleQueryHelper {
53  
54      private static final Logger logger = LoggerFactory.getLogger(RoleQueryHelper.class);
55  
56      protected static final String USER_ROLES = "userRoles";
57  
58      protected CachedCipher cipher;
59  
60      protected String valueSeparator = "\n";
61  
62      protected String roleSeparator = ",";
63  
64      protected String parameterKey;
65  
66      protected boolean encryptedParameterValue = true;
67  
68      protected String headerKey;
69  
70      protected boolean encryptedHeaderValue = true;
71  
72      protected String cookieKey;
73  
74      protected boolean encryptedCookieValue = true;
75  
76      protected Map<String, String> cookieNameMap;
77  
78      protected final List<String> defaultRoleList = new ArrayList<>();
79  
80      @PostConstruct
81      public void init() {
82          stream(ComponentUtil.getFessConfig().getSearchDefaultPermissionsAsArray()).of(stream -> stream.forEach(name -> {
83              defaultRoleList.add(name);
84          }));
85      }
86  
87      public Set<String> build(final SearchRequestType searchRequestType) {
88          final Set<String> roleSet = new HashSet<>();
89          final HttpServletRequest request = LaRequestUtil.getOptionalRequest().orElse(null);
90          final FessConfig fessConfig = ComponentUtil.getFessConfig();
91          final boolean isApiRequest =
92                  !SearchRequestType.SEARCH.equals(searchRequestType) && !SearchRequestType.ADMIN_SEARCH.equals(searchRequestType);
93  
94          if (request != null) {
95              @SuppressWarnings("unchecked")
96              final Set<String> list = (Set<String>) request.getAttribute(USER_ROLES);
97              if (list != null) {
98                  return list;
99              }
100 
101             // request parameter
102             if (StringUtil.isNotBlank(parameterKey)) {
103                 processParameter(request, roleSet);
104             }
105 
106             // request header
107             if (StringUtil.isNotBlank(headerKey)) {
108                 processHeader(request, roleSet);
109             }
110 
111             // cookie
112             if (StringUtil.isNotBlank(cookieKey)) {
113                 processCookie(request, roleSet);
114             }
115 
116             // cookie mapping
117             if (cookieNameMap != null) {
118                 buildByCookieNameMapping(request, roleSet);
119             }
120 
121             final boolean hasAccessToken = processAccessToken(request, roleSet, isApiRequest);
122 
123             final RequestManager requestManager = ComponentUtil.getRequestManager();
124             try {
125                 requestManager.findUserBean(FessUserBean.class)
126                         .ifPresent(fessUserBean -> stream(fessUserBean.getPermissions()).of(stream -> stream.forEach(roleSet::add)))
127                         .orElse(() -> {
128                             if (isApiRequest && ComponentUtil.getFessConfig().getApiAccessTokenRequiredAsBoolean()) {
129                                 throw new InvalidAccessTokenException("invalid_token", "Access token is requried.");
130                             }
131                             if (!hasAccessToken || roleSet.isEmpty()) {
132                                 roleSet.addAll(fessConfig.getSearchGuestPermissionList());
133                             }
134                         });
135             } catch (final RuntimeException e) {
136                 try {
137                     requestManager.findLoginManager(FessUserBean.class).ifPresent(manager -> manager.logout());
138                 } catch (final Exception e1) {
139                     // ignore
140                 }
141                 throw e;
142             }
143         }
144 
145         if (defaultRoleList != null) {
146             roleSet.addAll(defaultRoleList);
147         }
148 
149         if (logger.isDebugEnabled()) {
150             logger.debug("roleSet: " + roleSet);
151         }
152 
153         if (request != null) {
154             request.setAttribute(USER_ROLES, roleSet);
155         }
156         return roleSet;
157     }
158 
159     protected boolean processAccessToken(final HttpServletRequest request, final Set<String> roleSet, final boolean isApiRequest) {
160         if (isApiRequest) {
161             return ComponentUtil.getComponent(AccessTokenService.class).getPermissions(request).map(p -> {
162                 p.forEach(roleSet::add);
163                 return true;
164             }).orElse(false);
165         }
166         return false;
167     }
168 
169     protected void processParameter(final HttpServletRequest request, final Set<String> roleSet) {
170         final String parameter = request.getParameter(parameterKey);
171         if (logger.isDebugEnabled()) {
172             logger.debug(parameterKey + ":" + parameter);
173         }
174         if (StringUtil.isNotEmpty(parameter)) {
175             parseRoleSet(parameter, encryptedParameterValue, roleSet);
176         }
177 
178     }
179 
180     protected void processHeader(final HttpServletRequest request, final Set<String> roleSet) {
181 
182         final String parameter = request.getHeader(headerKey);
183         if (logger.isDebugEnabled()) {
184             logger.debug(headerKey + ":" + parameter);
185         }
186         if (StringUtil.isNotEmpty(parameter)) {
187             parseRoleSet(parameter, encryptedHeaderValue, roleSet);
188         }
189 
190     }
191 
192     protected void processCookie(final HttpServletRequest request, final Set<String> roleSet) {
193 
194         final Cookie[] cookies = request.getCookies();
195         if (cookies != null) {
196             for (final Cookie cookie : cookies) {
197                 if (cookieKey.equals(cookie.getName())) {
198                     final String value = cookie.getValue();
199                     if (logger.isDebugEnabled()) {
200                         logger.debug(cookieKey + ":" + value);
201                     }
202                     if (StringUtil.isNotEmpty(value)) {
203                         parseRoleSet(value, encryptedCookieValue, roleSet);
204                     }
205                 }
206             }
207         }
208 
209     }
210 
211     protected void buildByCookieNameMapping(final HttpServletRequest request, final Set<String> roleSet) {
212         final Cookie[] cookies = request.getCookies();
213         if (cookies != null) {
214             for (final Cookie cookie : cookies) {
215                 addRoleFromCookieMapping(roleSet, cookie);
216             }
217         }
218 
219     }
220 
221     protected void addRoleFromCookieMapping(final Set<String> roleNameList, final Cookie cookie) {
222         final String roleName = cookieNameMap.get(cookie.getName());
223         if (StringUtil.isNotBlank(roleName)) {
224             roleNameList.add(roleName);
225         }
226     }
227 
228     protected void parseRoleSet(final String value, final boolean encrypted, final Set<String> roleSet) {
229         String rolesStr = value;
230         if (encrypted && cipher != null) {
231             rolesStr = cipher.decryptoText(rolesStr);
232         }
233 
234         if (valueSeparator.length() > 0) {
235             final String[] values = rolesStr.split(valueSeparator);
236             if (values.length > 1) {
237                 final String[] roles = values[1].split(roleSeparator);
238                 for (final String role : roles) {
239                     if (StringUtil.isNotEmpty(role)) {
240                         roleSet.add(role);
241                     }
242                 }
243             }
244         } else {
245             final String[] roles = rolesStr.split(roleSeparator);
246             for (final String role : roles) {
247                 if (StringUtil.isNotEmpty(role)) {
248                     roleSet.add(role);
249                 }
250             }
251         }
252     }
253 
254     public void addCookieNameMapping(final String cookieName, final String roleName) {
255         if (cookieNameMap == null) {
256             cookieNameMap = new HashMap<>();
257         }
258         cookieNameMap.put(cookieName, roleName);
259     }
260 
261     public void setCipher(final CachedCipher cipher) {
262         this.cipher = cipher;
263     }
264 
265     public void setValueSeparator(final String valueSeparator) {
266         this.valueSeparator = valueSeparator;
267     }
268 
269     public void setRoleSeparator(final String roleSeparator) {
270         this.roleSeparator = roleSeparator;
271     }
272 
273     public void setParameterKey(final String parameterKey) {
274         this.parameterKey = parameterKey;
275     }
276 
277     public void setEncryptedParameterValue(final boolean encryptedParameterValue) {
278         this.encryptedParameterValue = encryptedParameterValue;
279     }
280 
281     public void setHeaderKey(final String headerKey) {
282         this.headerKey = headerKey;
283     }
284 
285     public void setEncryptedHeaderValue(final boolean encryptedHeaderValue) {
286         this.encryptedHeaderValue = encryptedHeaderValue;
287     }
288 
289     public void setCookieKey(final String cookieKey) {
290         this.cookieKey = cookieKey;
291     }
292 
293     public void setEncryptedCookieValue(final boolean encryptedCookieValue) {
294         this.encryptedCookieValue = encryptedCookieValue;
295     }
296 
297 }