@Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
      response.getWriter().print(HttpServletResponse.SC_UNAUTHORIZED);
      return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession session = httpRequest.getSession();

    if (!httpRequest.getServletPath().matches(excludeUrlPattern)) {
      String requireTMforOrg = null;
      String controllerId = null;

      String path = httpRequest.getServletPath();
      if (path != null && path.startsWith("/controller/")) {
        controllerId = httpRequest.getParameter(SessionConstants.SESSION_CTRL_ID);
        if (controllerId == null || controllerId.trim().isEmpty()) {
          controllerId = (String) session.getAttribute(SessionConstants.SESSION_CTRL_ID);
        }
        HashMap<String, String> organizations = configService.getControllerOrganizations();
        if (!organizations.containsKey(controllerId) || organizations.get(controllerId) == null) {
          httpResponse.setStatus(404);
          return;
        }
        requireTMforOrg = organizations.get(controllerId);
      }

      Object loggedInUserId = session.getAttribute(SessionConstants.SESSION_USER_ID);
      if (loggedInUserId != null) {
        if (requireTMforOrg != null) {
          Object loggedInUserOrgId = session.getAttribute(SessionConstants.SESSION_USER_ORG_ID);
          Object loggedInUserRoles = session.getAttribute(SessionConstants.SESSION_USER_ROLES);
          if (!requireTMforOrg.equals(loggedInUserOrgId)
              || loggedInUserRoles == null
              || !(loggedInUserRoles instanceof Set)
              || !((Set<?>) loggedInUserRoles).contains(UserRoleType.TECHNOLOGY_MANAGER)) {

            send401(httpRequest, httpResponse, session, true);
            return;
          }
        } else {
          if (!Boolean.parseBoolean(
              "" + session.getAttribute(SessionConstants.SESSION_USER_IS_ADMIN))) {
            send401(httpRequest, httpResponse, session, false);
            return;
          }
        }

        // logged in with valid org and role => continue normally
        session.setAttribute(SessionConstants.SESSION_CTRL_ID, controllerId);
        chain.doFilter(httpRequest, response);
        return;
      }

      // Check HTTP Basic authentication
      String authHeader = httpRequest.getHeader("Authorization");
      if (authHeader != null) {
        StringTokenizer st = new StringTokenizer(authHeader);
        if (st.hasMoreTokens()) {
          String basic = st.nextToken();

          // only handle HTTP Basic authentication
          if (basic.equalsIgnoreCase("basic")) {
            String credentials = st.nextToken();
            String userPass = new String(Base64.decodeBase64(credentials));

            // The decoded string is in the form "userID:password".
            int p = userPass.indexOf(":");
            if (p != -1) {
              String userName = userPass.substring(0, p);
              String password = userPass.substring(p + 1);
              PasswordAuthentication auth = new PasswordAuthentication(userName, password);

              try {

                // Check authority
                VOUserDetails voUser = null;
                if (requireTMforOrg != null) {
                  voUser = authService.getAuthenticatedTMForController(controllerId, auth);
                  session.removeAttribute(SessionConstants.SESSION_USER_IS_ADMIN);
                  session.setAttribute(SessionConstants.SESSION_CTRL_ID, controllerId);
                  session.setAttribute("loggedInUserOrgId", voUser.getOrganizationId());
                  session.setAttribute("loggedInUserRoles", voUser.getUserRoles());
                } else {
                  voUser = authService.authenticateAdministrator(auth);
                  session.setAttribute(SessionConstants.SESSION_USER_IS_ADMIN, "true");
                  session.setAttribute("loggedInUserOrgId", voUser.getOrganizationId());
                  session.setAttribute("loggedInUserRoles", voUser.getUserRoles());
                }
                session.setAttribute(SessionConstants.SESSION_USER_LOCALE, voUser.getLocale());

                // Valid => store data in session
                session.setAttribute(SessionConstants.SESSION_USER_ID, userName);
                session.setAttribute(SessionConstants.SESSION_USER_PASSWORD, password);

                // And continue
                chain.doFilter(httpRequest, response);
                return;

              } catch (Exception e) {
                if (null != logger) {
                  logger.error("doFilter: " + e.getMessage());
                }
              }
            }
          }
        }
      }
      send401(httpRequest, httpResponse, session, requireTMforOrg != null);
    } else {
      chain.doFilter(request, response);
    }
  }