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