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 java.util.ArrayList;
19  import java.util.List;
20  import java.util.Map;
21  import java.util.UUID;
22  
23  import javax.servlet.http.Cookie;
24  import javax.servlet.http.HttpServletRequest;
25  import javax.servlet.http.HttpSession;
26  
27  import org.codelibs.core.collection.LruHashMap;
28  import org.codelibs.core.lang.StringUtil;
29  import org.codelibs.fess.Constants;
30  import org.codelibs.fess.mylasta.direction.FessConfig;
31  import org.codelibs.fess.util.ComponentUtil;
32  import org.lastaflute.core.security.PrimaryCipher;
33  import org.lastaflute.web.login.TypicalUserBean;
34  import org.lastaflute.web.servlet.session.SessionManager;
35  import org.lastaflute.web.util.LaRequestUtil;
36  import org.lastaflute.web.util.LaResponseUtil;
37  
38  public class UserInfoHelper {
39      protected static final String USER_BEAN = "lastaflute.action.USER_BEAN.FessUserBean";
40  
41      protected int resultDocIdsCacheSize = 20;
42  
43      protected String cookieName = "fsid";
44  
45      protected String cookieDomain;
46  
47      protected int cookieMaxAge = 30 * 24 * 60 * 60;// 1 month
48  
49      protected String cookiePath = "/";
50  
51      protected Boolean cookieSecure;
52  
53      protected boolean httpOnly = true;
54  
55      public String getUserCode() {
56          final HttpServletRequest request = LaRequestUtil.getRequest();
57  
58          String userCode = (String) request.getAttribute(Constants.USER_CODE);
59          if (StringUtil.isNotBlank(userCode)) {
60              return userCode;
61          }
62  
63          userCode = getUserCodeFromRequest(request);
64          if (StringUtil.isNotBlank(userCode)) {
65              return userCode;
66          }
67  
68          if (!request.isRequestedSessionIdValid()) {
69              return null;
70          }
71  
72          userCode = getUserCodeFromCookie(request);
73          if (StringUtil.isBlank(userCode)) {
74              userCode = getUserCodeFromUserBean(request);
75              if (StringUtil.isBlank(userCode)) {
76                  userCode = getId();
77              }
78          }
79  
80          if (StringUtil.isNotBlank(userCode)) {
81              updateUserSessionId(userCode);
82          }
83          return userCode;
84      }
85  
86      protected String getUserCodeFromUserBean(final HttpServletRequest request) {
87          final SessionManager sessionManager = ComponentUtil.getComponent(SessionManager.class);
88          String userCode =
89                  sessionManager.getAttribute(USER_BEAN, TypicalUserBean.class).filter(u -> !Constants.EMPTY_USER_ID.equals(u.getUserId()))
90                          .map(u -> u.getUserId().toString()).orElse(StringUtil.EMPTY);
91          if (StringUtil.isBlank(userCode)) {
92              return null;
93          }
94  
95          final PrimaryCipher cipher = ComponentUtil.getPrimaryCipher();
96          userCode = cipher.encrypt(userCode);
97          request.setAttribute(Constants.USER_CODE, userCode);
98          deleteUserCodeFromCookie(request);
99          return userCode;
100     }
101 
102     public void deleteUserCodeFromCookie(final HttpServletRequest request) {
103         final String cookieValue = getUserCodeFromCookie(request);
104         if (cookieValue != null) {
105             updateCookie(cookieValue, 0);
106         }
107     }
108 
109     protected String getUserCodeFromRequest(final HttpServletRequest request) {
110         final FessConfig fessConfig = ComponentUtil.getFessConfig();
111         final String userCode = request.getParameter(fessConfig.getUserCodeRequestParameter());
112         if (StringUtil.isBlank(userCode)) {
113             return null;
114         }
115 
116         final int length = userCode.length();
117         if (fessConfig.getUserCodeMinLengthAsInteger().intValue() > length
118                 || fessConfig.getUserCodeMaxLengthAsInteger().intValue() < length) {
119             return null;
120         }
121 
122         if (fessConfig.isValidUserCode(userCode)) {
123             request.setAttribute(Constants.USER_CODE, userCode);
124             return userCode;
125         }
126         return null;
127     }
128 
129     protected String getId() {
130         return UUID.randomUUID().toString().replace("-", StringUtil.EMPTY);
131     }
132 
133     protected void updateUserSessionId(final String userCode) {
134         ComponentUtil.getSearchLogHelper().getUserInfo(userCode);
135 
136         final HttpServletRequest request = LaRequestUtil.getRequest();
137         request.setAttribute(Constants.USER_CODE, userCode);
138 
139         updateCookie(userCode, cookieMaxAge);
140     }
141 
142     protected void updateCookie(final String userCode, final int age) {
143         final Cookie cookie = new Cookie(cookieName, userCode);
144         cookie.setMaxAge(age);
145         cookie.setHttpOnly(httpOnly);
146         if (StringUtil.isNotBlank(cookieDomain)) {
147             cookie.setDomain(cookieDomain);
148         }
149         if (StringUtil.isNotBlank(cookiePath)) {
150             cookie.setPath(cookiePath);
151         }
152         if (cookieSecure != null) {
153             cookie.setSecure(cookieSecure);
154         }
155         LaResponseUtil.getResponse().addCookie(cookie);
156     }
157 
158     protected String getUserCodeFromCookie(final HttpServletRequest request) {
159         final Cookie[] cookies = request.getCookies();
160         if (cookies != null) {
161             for (final Cookie cookie : cookies) {
162                 if (cookieName.equals(cookie.getName())) {
163                     return cookie.getValue();
164                 }
165             }
166         }
167         return null;
168     }
169 
170     public void storeQueryId(final String queryId, final List<Map<String, Object>> documentItems) {
171         final HttpSession session = LaRequestUtil.getRequest().getSession(false);
172         if (session != null) {
173             final FessConfig fessConfig = ComponentUtil.getFessConfig();
174 
175             final List<String> docIdList = new ArrayList<>();
176             for (final Map<String, Object> map : documentItems) {
177                 final Object docId = map.get(fessConfig.getIndexFieldDocId());
178                 if (docId != null && docId.toString().length() > 0) {
179                     docIdList.add(docId.toString());
180                 }
181             }
182 
183             if (!docIdList.isEmpty()) {
184                 final Map<String, String[]> resultDocIdsCache = getResultDocIdsCache(session);
185                 resultDocIdsCache.put(queryId, docIdList.toArray(new String[docIdList.size()]));
186             }
187         }
188     }
189 
190     public String[] getResultDocIds(final String queryId) {
191         final HttpSession session = LaRequestUtil.getRequest().getSession(false);
192         if (session != null) {
193             final Map<String, String[]> resultUrlCache = getResultDocIdsCache(session);
194             final String[] urls = resultUrlCache.get(queryId);
195             if (urls != null) {
196                 return urls;
197             }
198         }
199         return StringUtil.EMPTY_STRINGS;
200     }
201 
202     private Map<String, String[]> getResultDocIdsCache(final HttpSession session) {
203         @SuppressWarnings("unchecked")
204         Map<String, String[]> resultDocIdsCache = (Map<String, String[]>) session.getAttribute(Constants.RESULT_DOC_ID_CACHE);
205         if (resultDocIdsCache == null) {
206             resultDocIdsCache = new LruHashMap<>(resultDocIdsCacheSize);
207             session.setAttribute(Constants.RESULT_DOC_ID_CACHE, resultDocIdsCache);
208         }
209         return resultDocIdsCache;
210     }
211 
212     public void setResultDocIdsCacheSize(final int resultDocIdsCacheSize) {
213         this.resultDocIdsCacheSize = resultDocIdsCacheSize;
214     }
215 
216     public void setCookieName(final String cookieName) {
217         this.cookieName = cookieName;
218     }
219 
220     public void setCookieDomain(final String cookieDomain) {
221         this.cookieDomain = cookieDomain;
222     }
223 
224     public void setCookieMaxAge(final int cookieMaxAge) {
225         this.cookieMaxAge = cookieMaxAge;
226     }
227 
228     public void setCookiePath(final String cookiePath) {
229         this.cookiePath = cookiePath;
230     }
231 
232     public void setCookieSecure(final Boolean cookieSecure) {
233         this.cookieSecure = cookieSecure;
234     }
235 
236     public void setCookieHttpOnly(boolean httpOnly) {
237         this.httpOnly = httpOnly;
238     }
239 }