1. Project Clover database Tue Dec 20 2016 21:24:09 CET
  2. Package com.xpn.xwiki.user.impl.xwiki

File MyFormAuthenticator.java

 

Coverage histogram

../../../../../../img/srcFileCovDistChart6.png
69% of files have more coverage

Code metrics

56
90
9
1
287
184
45
0.5
10
9
5

Classes

Class Line # Actions
MyFormAuthenticator 41 90 0% 45 63
0.5935483659.4%
 

Contributing tests

No tests hitting this source file were found.

Source view

1    /*
2    * See the NOTICE file distributed with this work for additional
3    * information regarding copyright ownership.
4    *
5    * This is free software; you can redistribute it and/or modify it
6    * under the terms of the GNU Lesser General Public License as
7    * published by the Free Software Foundation; either version 2.1 of
8    * the License, or (at your option) any later version.
9    *
10    * This software is distributed in the hope that it will be useful,
11    * but WITHOUT ANY WARRANTY; without even the implied warranty of
12    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13    * Lesser General Public License for more details.
14    *
15    * You should have received a copy of the GNU Lesser General Public
16    * License along with this software; if not, write to the Free
17    * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
18    * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
19    */
20    package com.xpn.xwiki.user.impl.xwiki;
21   
22    import java.io.IOException;
23    import java.net.URLEncoder;
24    import java.security.Principal;
25   
26    import javax.servlet.http.HttpServletRequest;
27    import javax.servlet.http.HttpServletResponse;
28   
29    import org.apache.commons.lang3.StringUtils;
30    import org.securityfilter.authenticator.FormAuthenticator;
31    import org.securityfilter.filter.SecurityRequestWrapper;
32    import org.securityfilter.filter.URLPatternMatcher;
33    import org.securityfilter.realm.SimplePrincipal;
34    import org.slf4j.Logger;
35    import org.slf4j.LoggerFactory;
36    import org.xwiki.container.servlet.filters.SavedRequestManager;
37   
38    import com.xpn.xwiki.XWikiContext;
39    import com.xpn.xwiki.XWikiException;
40   
 
41    public class MyFormAuthenticator extends FormAuthenticator implements XWikiAuthenticator
42    {
43    private static final Logger LOGGER = LoggerFactory.getLogger(MyFormAuthenticator.class);
44   
45    /**
46    * Show the login page.
47    *
48    * @param request the current request
49    * @param response the current response
50    */
 
51  0 toggle @Override
52    public void showLogin(HttpServletRequest request, HttpServletResponse response, XWikiContext context)
53    throws IOException
54    {
55  0 if ("1".equals(request.getParameter("basicauth"))) {
56  0 String realmName = context.getWiki().Param("xwiki.authentication.realmname");
57  0 if (realmName == null) {
58  0 realmName = "XWiki";
59    }
60  0 MyBasicAuthenticator.showLogin(request, response, realmName);
61    } else {
62  0 showLogin(request, response);
63    }
64    }
65   
 
66  0 toggle @Override
67    public void showLogin(HttpServletRequest request, HttpServletResponse response) throws IOException
68    {
69  0 String savedRequestId = request.getParameter(SavedRequestManager.getSavedRequestIdentifier());
70  0 if (StringUtils.isEmpty(savedRequestId)) {
71    // Save this request
72  0 savedRequestId = SavedRequestManager.saveRequest(request);
73    }
74  0 String sridParameter = SavedRequestManager.getSavedRequestIdentifier() + "=" + savedRequestId;
75   
76    // Redirect to login page
77  0 StringBuilder redirectBack = new StringBuilder(request.getRequestURI());
78  0 redirectBack.append('?');
79  0 String delimiter = "";
80  0 if (StringUtils.isNotEmpty(request.getQueryString())) {
81  0 redirectBack.append(request.getQueryString());
82  0 delimiter = "&";
83    }
84  0 if (!request.getParameterMap().containsKey(SavedRequestManager.getSavedRequestIdentifier())) {
85  0 redirectBack.append(delimiter);
86  0 redirectBack.append(sridParameter);
87    }
88  0 response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + this.loginPage + "?"
89    + sridParameter + "&xredirect=" + URLEncoder.encode(redirectBack.toString(), "UTF-8")));
90   
91  0 return;
92    }
93   
 
94  0 toggle @Override
95    public boolean processLogin(SecurityRequestWrapper request, HttpServletResponse response) throws Exception
96    {
97  0 return processLogin(request, response, null);
98    }
99   
 
100  2484 toggle private String convertUsername(String username, XWikiContext context)
101    {
102  2484 return context.getWiki().convertUsername(username, context);
103    }
104   
105    /**
106    * Process any login information that was included in the request, if any. Returns true if SecurityFilter should
107    * abort further processing after the method completes (for example, if a redirect was sent as part of the login
108    * processing).
109    *
110    * @param request
111    * @param response
112    * @return true if the filter should return after this method ends, false otherwise
113    */
 
114  13035 toggle @Override
115    public boolean processLogin(SecurityRequestWrapper request, HttpServletResponse response, XWikiContext context)
116    throws Exception
117    {
118  13032 try {
119  13027 Principal principal = MyBasicAuthenticator.checkLogin(request, response, context);
120  13017 if (principal != null) {
121  6306 return false;
122    }
123  6729 if ("1".equals(request.getParameter("basicauth"))) {
124  0 return true;
125    }
126    } catch (Exception e) {
127    // in case of exception we continue on Form Auth.
128    // we don't want this to interfere with the most common behavior
129    }
130   
131    // process any persistent login information, if user is not already logged in,
132    // persistent logins are enabled, and the persistent login info is present in this request
133  6725 if (this.persistentLoginManager != null) {
134  6724 Principal principal = request.getUserPrincipal();
135   
136    // If cookies are turned on:
137    // 1) if user is not already authenticated, authenticate
138    // 2) if xwiki.authentication.always is set to 1 in xwiki.cfg file, authenticate
139  6731 if (principal == null || context.getWiki().ParamAsLong("xwiki.authentication.always", 0) == 1) {
140  2424 String username =
141    convertUsername(this.persistentLoginManager.getRememberedUsername(request, response), context);
142  2422 String password = this.persistentLoginManager.getRememberedPassword(request, response);
143   
144  2423 principal = authenticate(username, password, context);
145   
146  2424 if (principal != null) {
147  0 if (LOGGER.isDebugEnabled()) {
148  0 LOGGER.debug("User " + principal.getName() + " has been authentified from cookie");
149    }
150   
151    // make sure the Principal contains wiki name information
152  0 if (!StringUtils.contains(principal.getName(), ':')) {
153  0 principal = new SimplePrincipal(context.getWikiId() + ":" + principal.getName());
154    }
155   
156  0 request.setUserPrincipal(principal);
157    } else {
158    // Failed to authenticate, better cleanup the user stored in the session
159  2423 request.setUserPrincipal(null);
160  2423 if (username != null || password != null) {
161    // Failed authentication with remembered login, better forget login now
162  0 this.persistentLoginManager.forgetLogin(request, response);
163    }
164    }
165    }
166    }
167   
168    // process login form submittal
169  6715 if ((this.loginSubmitPattern != null) && request.getMatchableURL().endsWith(this.loginSubmitPattern)) {
170  61 String username = convertUsername(request.getParameter(FORM_USERNAME), context);
171  61 String password = request.getParameter(FORM_PASSWORD);
172  61 String rememberme = request.getParameter(FORM_REMEMBERME);
173  61 rememberme = (rememberme == null) ? "false" : rememberme;
174  61 return processLogin(username, password, rememberme, request, response, context);
175    }
176  6660 return false;
177    }
178   
179    /**
180    * Process any login information passed in parameter (username, password). Returns true if SecurityFilter should
181    * abort further processing after the method completes (for example, if a redirect was sent as part of the login
182    * processing).
183    *
184    * @param request
185    * @param response
186    * @return true if the filter should return after this method ends, false otherwise
187    */
 
188  61 toggle @Override
189    public boolean processLogin(String username, String password, String rememberme, SecurityRequestWrapper request,
190    HttpServletResponse response, XWikiContext context) throws Exception
191    {
192  61 Principal principal = authenticate(username, password, context);
193  61 if (principal != null) {
194    // login successful
195  60 if (LOGGER.isInfoEnabled()) {
196  0 LOGGER.info("User " + principal.getName() + " has been logged-in");
197    }
198   
199    // invalidate old session if the user was already authenticated, and they logged in as a different user
200  60 if (request.getUserPrincipal() != null && !username.equals(request.getRemoteUser())) {
201  25 request.getSession().invalidate();
202    }
203   
204    // manage persistent login info, if persistent login management is enabled
205  60 if (this.persistentLoginManager != null) {
206    // did the user request that their login be persistent?
207  60 if (rememberme != null) {
208    // remember login
209  60 this.persistentLoginManager.rememberLogin(request, response, username, password);
210    } else {
211    // forget login
212  0 this.persistentLoginManager.forgetLogin(request, response);
213    }
214    }
215   
216    // make sure the Principal contains wiki name information
217  60 if (!StringUtils.contains(principal.getName(), ':')) {
218  60 principal = new SimplePrincipal(context.getWikiId() + ":" + principal.getName());
219    }
220   
221  60 request.setUserPrincipal(principal);
222  60 Boolean bAjax = (Boolean) context.get("ajax");
223  60 if ((bAjax == null) || (!bAjax.booleanValue())) {
224  60 String continueToURL = getContinueToURL(request);
225    // This is the url that the user was initially accessing before being prompted for login.
226  60 response.sendRedirect(response.encodeRedirectURL(continueToURL));
227    }
228    } else {
229    // login failed
230    // set response status and forward to error page
231  1 if (LOGGER.isInfoEnabled()) {
232  0 LOGGER.info("User " + username + " login has failed");
233    }
234   
235  1 String returnCode = context.getWiki().Param("xwiki.authentication.unauthorized_code");
236  1 int rCode = HttpServletResponse.SC_UNAUTHORIZED;
237  1 if ((returnCode != null) && (!returnCode.equals(""))) {
238  1 try {
239  1 rCode = Integer.parseInt(returnCode);
240    } catch (Exception e) {
241  0 rCode = HttpServletResponse.SC_UNAUTHORIZED;
242    }
243    }
244  1 response.setStatus(rCode); // TODO: Does this work? (200 in case of error)
245    }
246   
247  61 return true;
248    }
249   
250    /**
251    * FormAuthenticator has a special case where the user should be sent to a default page if the user spontaneously
252    * submits a login request.
253    *
254    * @param request
255    * @return a URL to send the user to after logging in
256    */
 
257  60 toggle private String getContinueToURL(HttpServletRequest request)
258    {
259  60 String savedURL = request.getParameter("xredirect");
260  60 if (StringUtils.isEmpty(savedURL)) {
261  1 savedURL = SavedRequestManager.getOriginalUrl(request);
262    }
263   
264  60 if (!StringUtils.isEmpty(savedURL)) {
265  59 return savedURL;
266    }
267  1 return request.getContextPath() + this.defaultPage;
268    }
269   
 
270  2484 toggle public static Principal authenticate(String username, String password, XWikiContext context) throws XWikiException
271    {
272  2485 return context.getWiki().getAuthService().authenticate(username, password, context);
273    }
274   
 
275  12962 toggle @Override
276    public boolean processLogout(SecurityRequestWrapper securityRequestWrapper,
277    HttpServletResponse httpServletResponse, URLPatternMatcher urlPatternMatcher) throws Exception
278    {
279  12967 boolean result = super.processLogout(securityRequestWrapper, httpServletResponse, urlPatternMatcher);
280  12973 if (result == true) {
281  1 if (this.persistentLoginManager != null) {
282  1 this.persistentLoginManager.forgetLogin(securityRequestWrapper, httpServletResponse);
283    }
284    }
285  12970 return result;
286    }
287    }