1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    *
5    *
6    *
7    * The contents of this file are subject to the terms of the Liferay Enterprise
8    * Subscription License ("License"). You may not use this file except in
9    * compliance with the License. You can obtain a copy of the License by
10   * contacting Liferay, Inc. See the License for the specific language governing
11   * permissions and limitations under the License, including but not limited to
12   * distribution rights 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.sharepoint;
24  
25  import com.liferay.portal.kernel.log.Log;
26  import com.liferay.portal.kernel.log.LogFactoryUtil;
27  import com.liferay.portal.kernel.servlet.HttpHeaders;
28  import com.liferay.portal.kernel.servlet.HttpMethods;
29  import com.liferay.portal.kernel.util.Base64;
30  import com.liferay.portal.kernel.util.GetterUtil;
31  import com.liferay.portal.kernel.util.StringPool;
32  import com.liferay.portal.model.Company;
33  import com.liferay.portal.model.CompanyConstants;
34  import com.liferay.portal.model.User;
35  import com.liferay.portal.security.auth.Authenticator;
36  import com.liferay.portal.security.auth.PrincipalException;
37  import com.liferay.portal.security.auth.PrincipalThreadLocal;
38  import com.liferay.portal.security.permission.PermissionChecker;
39  import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
40  import com.liferay.portal.security.permission.PermissionThreadLocal;
41  import com.liferay.portal.service.UserLocalServiceUtil;
42  import com.liferay.portal.servlet.filters.BasePortalFilter;
43  import com.liferay.portal.util.PortalUtil;
44  import com.liferay.portal.util.WebKeys;
45  
46  import java.io.IOException;
47  
48  import java.util.HashMap;
49  import java.util.Map;
50  import java.util.StringTokenizer;
51  
52  import javax.servlet.FilterChain;
53  import javax.servlet.http.HttpServletRequest;
54  import javax.servlet.http.HttpServletResponse;
55  import javax.servlet.http.HttpSession;
56  
57  /**
58   * <a href="SharepointFilter.java.html"><b><i>View Source</i></b></a>
59   *
60   * @author Bruno Farache
61   */
62  public class SharepointFilter extends BasePortalFilter {
63  
64      protected boolean isSharepointRequest(String uri) {
65          if (uri == null) {
66              return false;
67          }
68  
69          if (uri.endsWith("*.asmx")) {
70              return true;
71          }
72  
73          for (String prefix : _PREFIXES) {
74              if (uri.startsWith(prefix)) {
75                  return true;
76              }
77          }
78  
79          return false;
80      }
81  
82      protected User login(
83              HttpServletRequest request, HttpServletResponse response)
84          throws Exception {
85  
86          User user = null;
87  
88          // Get the Authorization header, if one was supplied
89  
90          String authorization = request.getHeader("Authorization");
91  
92          if (authorization == null) {
93              return user;
94          }
95  
96          StringTokenizer st = new StringTokenizer(authorization);
97  
98          if (!st.hasMoreTokens()) {
99              return user;
100         }
101 
102         String basic = st.nextToken();
103 
104         // We only handle HTTP Basic authentication
105 
106         if (!basic.equalsIgnoreCase(HttpServletRequest.BASIC_AUTH)) {
107             return user;
108         }
109 
110         String encodedCredentials = st.nextToken();
111 
112         if (_log.isDebugEnabled()) {
113             _log.debug("Encoded credentials are " + encodedCredentials);
114         }
115 
116         String decodedCredentials = new String(
117             Base64.decode(encodedCredentials));
118 
119         if (_log.isDebugEnabled()) {
120             _log.debug("Decoded credentials are " + decodedCredentials);
121         }
122 
123         int pos = decodedCredentials.indexOf(StringPool.COLON);
124 
125         if (pos == -1) {
126             return user;
127         }
128 
129         Company company = PortalUtil.getCompany(request);
130 
131         String login = GetterUtil.getString(
132             decodedCredentials.substring(0, pos));
133         long userId = GetterUtil.getLong(login);
134         String password = decodedCredentials.substring(pos + 1);
135 
136         Map<String, String[]> headerMap = new HashMap<String, String[]>();
137         Map<String, String[]> parameterMap = new HashMap<String, String[]>();
138 
139         int authResult = Authenticator.FAILURE;
140 
141         if (company.getAuthType().equals(CompanyConstants.AUTH_TYPE_EA)) {
142             authResult = UserLocalServiceUtil.authenticateByEmailAddress(
143                 company.getCompanyId(), login, password, headerMap,
144                 parameterMap);
145 
146             userId = UserLocalServiceUtil.getUserIdByEmailAddress(
147                 company.getCompanyId(), login);
148         }
149         else if (company.getAuthType().equals(CompanyConstants.AUTH_TYPE_SN)) {
150             authResult = UserLocalServiceUtil.authenticateByScreenName(
151                 company.getCompanyId(), login, password, headerMap,
152                 parameterMap);
153 
154             userId = UserLocalServiceUtil.getUserIdByScreenName(
155                 company.getCompanyId(), login);
156         }
157         else if (company.getAuthType().equals(CompanyConstants.AUTH_TYPE_ID)) {
158             authResult = UserLocalServiceUtil.authenticateByUserId(
159                 company.getCompanyId(), userId, password, headerMap,
160                 parameterMap);
161         }
162 
163         if (authResult == Authenticator.SUCCESS) {
164             user = UserLocalServiceUtil.getUser(userId);
165         }
166 
167         return user;
168     }
169 
170     protected void processFilter(
171             HttpServletRequest request, HttpServletResponse response,
172             FilterChain filterChain)
173         throws Exception {
174 
175         String method = request.getMethod();
176 
177         String userAgent = GetterUtil.getString(
178             request.getHeader(HttpHeaders.USER_AGENT));
179 
180         if ((userAgent.startsWith(
181                 "Microsoft Data Access Internet Publishing") ||
182              userAgent.startsWith("Microsoft Office Protocol Discovery")) &&
183             method.equals(HttpMethods.OPTIONS)) {
184 
185             setOptionsHeaders(response);
186 
187             return;
188         }
189 
190         if (!isSharepointRequest(request.getRequestURI())) {
191             processFilter(
192                 SharepointFilter.class, request, response, filterChain);
193 
194             return;
195         }
196 
197         if (method.equals(HttpMethods.GET) || method.equals(HttpMethods.HEAD)) {
198             setGetHeaders(response);
199         }
200         else if (method.equals(HttpMethods.POST)) {
201             setPostHeaders(response);
202         }
203 
204         HttpSession session = request.getSession();
205 
206         User user = (User)session.getAttribute(WebKeys.USER);
207 
208         try {
209             if (user == null) {
210                 user = login(request, response);
211 
212                 if (user == null) {
213                     throw new PrincipalException("User is null");
214                 }
215 
216                 session.setAttribute(WebKeys.USER, user);
217             }
218 
219             PrincipalThreadLocal.setName(user.getUserId());
220 
221             PermissionChecker permissionChecker =
222                 PermissionCheckerFactoryUtil.create(user, false);
223 
224             PermissionThreadLocal.setPermissionChecker(permissionChecker);
225         }
226         catch (Exception e) {
227             sendUnauthorized(response);
228 
229             return;
230         }
231 
232         try {
233             processFilter(
234                 SharepointFilter.class, request, response, filterChain);
235         }
236         catch (Exception e) {
237             _log.error(e, e);
238         }
239     }
240 
241     protected void sendUnauthorized(HttpServletResponse response)
242         throws IOException {
243 
244         response.setHeader("WWW-Authenticate", "BASIC realm=\"Liferay\"");
245 
246         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
247 
248         response.flushBuffer();
249     }
250 
251     protected void setGetHeaders(HttpServletResponse response) {
252         response.setContentType("text/html");
253 
254         response.setHeader(
255             "Public-Extension", "http://schemas.microsoft.com/repl-2");
256         response.setHeader(
257             "MicrosoftSharePointTeamServices", SharepointUtil.VERSION);
258         response.setHeader("Cache-Control", "no-cache");
259     }
260 
261     protected void setOptionsHeaders(HttpServletResponse response) {
262         response.setHeader("MS-Author-Via", "MS-FP/4.0,DAV");
263         response.setHeader("MicrosoftOfficeWebServer", "5.0_Collab");
264         response.setHeader(
265             "MicrosoftSharePointTeamServices", SharepointUtil.VERSION);
266         response.setHeader("DAV", "1,2");
267         response.setHeader("Accept-Ranges", "none");
268         response.setHeader("Cache-Control", "no-cache");
269         response.setHeader(
270             "Allow",
271             "COPY, DELETE, GET, GETLIB, HEAD, LOCK, MKCOL, MOVE, OPTIONS, " +
272                 "POST, PROPFIND, PROPPATCH, PUT, UNLOCK");
273     }
274 
275     protected void setPostHeaders(HttpServletResponse response) {
276         response.setContentType("application/x-vermeer-rpc");
277 
278         response.setHeader(
279             "MicrosoftSharePointTeamServices", SharepointUtil.VERSION);
280         response.setHeader("Cache-Control", "no-cache");
281         response.setHeader("Connection", "close");
282     }
283 
284     private static final String[] _PREFIXES =
285         new String[] {
286             "/_vti_inf.html", "/_vti_bin", "/sharepoint", "/history",
287             "/resources"};
288 
289     private static Log _log = LogFactoryUtil.getLog(SharepointFilter.class);
290 
291 }