View Javadoc
1   package com.atlassian.refapp.sal.websudo;
2   
3   import com.atlassian.oauth.util.RequestAnnotations;
4   import com.atlassian.plugin.spring.scanner.annotation.export.ExportAsService;
5   import com.atlassian.refapp.auth.external.WebSudoSessionManager;
6   import com.atlassian.sal.api.websudo.WebSudoManager;
7   import com.atlassian.sal.api.websudo.WebSudoSessionException;
8   
9   import javax.inject.Inject;
10  import javax.inject.Named;
11  import javax.servlet.http.HttpServletRequest;
12  import javax.servlet.http.HttpServletResponse;
13  import java.io.IOException;
14  import java.net.URLEncoder;
15  
16  import static com.google.common.base.Preconditions.checkNotNull;
17  
18  @ExportAsService
19  @Named("salWebSudoManager")
20  public final class RefImplWebSudoManager implements WebSudoManager {
21      private static final String WEBSUDO_PATH = "/plugins/servlet/websudo";
22      private static final String WEBSUOD_REQUEST_ATTR = WebSudoManager.class.getName() + "-websudo-resource";
23  
24      private final WebSudoSessionManager webSudoAuthenticator;
25  
26      @Inject
27      public RefImplWebSudoManager(final WebSudoSessionManager webSudoAuthenticator) {
28          this.webSudoAuthenticator = checkNotNull(webSudoAuthenticator);
29      }
30  
31      public boolean canExecuteRequest(HttpServletRequest request) {
32          return RequestAnnotations.isOAuthRequest(request) || webSudoAuthenticator.isWebSudoSession(request);
33      }
34  
35      public void enforceWebSudoProtection(HttpServletRequest request, HttpServletResponse response) {
36          try {
37              final String queryString = request.getQueryString();
38              final String requestURI = request.getServletPath();
39              final String pathInfo = request.getPathInfo();
40              response.sendRedirect(request.getContextPath()
41                      + WEBSUDO_PATH
42                      + "?redir="
43                      + URLEncoder.encode(requestURI +
44                      ((null != pathInfo) ? pathInfo : "") +
45                      ((null != queryString) ? "?" + queryString : ""), "UTF-8"));
46          } catch (IOException e) {
47              throw new SecurityException("Failed to redirect to " + WEBSUDO_PATH);
48          }
49      }
50  
51      public void willExecuteWebSudoRequest(HttpServletRequest request) throws WebSudoSessionException {
52          if (null == request || !canExecuteRequest(request)) {
53              throw new WebSudoSessionException();
54          }
55          request.setAttribute(WEBSUOD_REQUEST_ATTR, Boolean.TRUE);
56      }
57  }