@Transactional(readOnly = true)
  @Test
  public void testGetWidgetDefinitionsByCategory() throws IOException, Exception {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(auth);

    MultiMap widgetDefinitionsByCategoryMap = uIService.getWidgetDefinitionsByCategory();
    Assert.notNull(widgetDefinitionsByCategoryMap);
    //			Assert.isTrue(widgetDefinitionsByCategoryMap.size() == 3);
    //			Assert.isTrue(widgetDefinitionsByCategoryMap.values().size() == 4);

    org.junit.Assert.assertTrue(
        "testGetWidgetDefinitionsByCategory() widgetDefinitionsByCategoryMap.size() failed test, "
            + "expected value 3, actually got: "
            + widgetDefinitionsByCategoryMap.size(),
        widgetDefinitionsByCategoryMap.size() == 4);
    org.junit.Assert.assertTrue(
        "testGetWidgetDefinitionsByCategory() widgetDefinitionsByCategoryMap.values().size() failed test, "
            + "expected value 4, actually got: "
            + widgetDefinitionsByCategoryMap.values().size(),
        widgetDefinitionsByCategoryMap.values().size() >= 5);

    securityContext.setAuthentication(null);
  }
  @Test
  public void testGetCanvasesByCategories() throws Exception {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(auth);
    LinkedHashMap<String, List<Canvas>> canvasesByCategory = uIService.getCanvasesByCategories();
    Assert.notNull(canvasesByCategory, "Canvases by category service call returns null");
    Assert.isTrue(
        canvasesByCategory.size() == 2,
        "Canvases by category service call does not return all three types of canvases");
    Assert.isTrue(
        canvasesByCategory.values().size() == 2,
        "Canvases by category service call does not return expected number of canvases (=5)");
    securityContext.setAuthentication(null);
  }
 private void useAuthentication(
     HttpServletRequest request,
     HttpServletResponse response,
     FilterChain chain,
     Authentication authentication,
     SecurityContext securityContext)
     throws IOException, ServletException {
   try {
     securityContext.setAuthentication(authentication);
     chain.doFilter(request, response);
     addToUserChange(authentication);
   } finally {
     securityContext.setAuthentication(null);
   }
 }
示例#4
0
  @After
  public void resetSecurity() {
    SecurityContext securityContext = new SecurityContextImpl();
    securityContext.setAuthentication(null);

    SecurityContextHolder.setContext(securityContext);
  }
  @Test
  public void testAddUserAsAdmin() throws Exception {
    SecurityContext securityContext = new SecurityContextImpl();
    User user = new User("admin");
    user.setId(2L);
    user.setPassword("password");
    user.addRole(new Role(Constants.ADMIN_ROLE));
    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), user.getPassword(), user.getAuthorities());
    token.setDetails(user);
    securityContext.setAuthentication(token);
    SecurityContextHolder.setContext(securityContext);

    UserManager userManager = makeInterceptedTarget();
    final User adminUser = new User("admin");
    adminUser.setId(2L);

    context.checking(
        new Expectations() {
          {
            one(userDao).saveUser(with(same(adminUser)));
          }
        });

    userManager.saveUser(adminUser);
  }
  @Before
  public void setup() {
    logger.info("setup");

    this.mockMvc =
        MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    User user = null;
    try {
      user = userService.findByLogin("johndoe");
    } catch (ServiceException e) {
      logger.error(e.getLocalizedMessage());
    }

    Authentication authentication = null;
    if (user != null) {
      authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword());
    }
    Authentication result = authenticationManager.authenticate(authentication);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(result);
    session = new MockHttpSession();
    session.setAttribute(
        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);
  }
  @Ignore
  @Test
  public void testGetSearchUserGridWidgetDefinitionWithoutAuthentication()
      throws IllegalArgumentException, IllegalAccessException, InvocationTargetException,
          SecurityException, NoSuchMethodException, IOException {
    AbstractLicensableWidget searchUserGridWidget =
        uIService.getWidgetDefinition(SearchUserGridWidgetName);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(null);
    Assert.notNull(searchUserGridWidget);
    Assert.notNull(searchUserGridWidget.getDataURL());

    Assert.isTrue(
        searchUserGridWidget.getActionConfig().getActionConfig().size() == 2,
        "Search user grid widget action config does not have expected # of permissions values");

    Assert.isTrue(
        searchUserGridWidget
                .getActionConfig()
                .getActionConfig()
                .get("widget-actions")
                .get(new Permission("delete-user"))
            == Boolean.FALSE,
        "Search user grid widget action config does not have delete-user permission false");

    Assert.isTrue(
        searchUserGridWidget
                .getActionConfig()
                .getActionConfig()
                .get("widget-actions")
                .get(new Permission("disable-user"))
            == Boolean.FALSE,
        "Search user grid widget action config does not have disable-user permission false");
  }
 @Transactional
 @Test
 public void getGroupMaintenanceWidget() throws Exception {
   final User jackUser = this.userService.getUser(JACK_USERNAME);
   final SecurityContext securityContext = SecurityContextHolder.getContext();
   securityContext.setAuthentication(
       new UsernamePasswordAuthenticationToken(
           jackUser,
           null,
           Arrays.asList(
               new SimpleGrantedAuthority("group-maintenance-create"),
               new SimpleGrantedAuthority("group-maintenance-edit"))));
   final GroupMaintenanceWidget groupMaintenanceWidget =
       this.uIService.getGroupMaintenanceWidgetDefinition();
   Assert.notNull(groupMaintenanceWidget, "GroupMaintenanceWidget is Null");
   Assert.isTrue(
       groupMaintenanceWidget.getId() == 12, "Id is not Proper for GroupMaintenanceWidget");
   Assert.isTrue(groupMaintenanceWidget.isActive() == true, "GroupMaintenanceWidget isn't active");
   Assert.notNull(
       groupMaintenanceWidget.getBroadcastList(), "GroupMaintenanceWidget BroadCast List is Null");
   Assert.isTrue(
       groupMaintenanceWidget.getBroadcastList().contains("groupName"),
       "GroupMaintenanceWidget Doesn't Contain GroupName in BroadCast List");
   Assert.isTrue(
       groupMaintenanceWidget.getShortName().equals("GroupMaintenance"),
       "GroupMaintenanceWidget Doesn't Contain Proper Short Name");
   Assert.isTrue(
       groupMaintenanceWidget.getName().equals("group-maintenance-widget"),
       "GroupMaintenanceWidget Doesn't Contain Proper Name");
   Assert.isTrue(
       groupMaintenanceWidget.getTitle().equals("Group Maintenance"),
       "GroupMaintenanceWidget Doesn't Contain Proper Title");
   Assert.notNull(
       groupMaintenanceWidget.getWidgetType(), "GroupMaintenanceWidget WidgetType is Null");
 }
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader("Authorization");

    if (header == null || !header.startsWith(AUTH_TOKEN)) {
      chain.doFilter(request, response);
      return;
    }

    try {
      final String[] tokens = this.extractAndDecodeHeader(header, request);
      final String username = tokens[0];

      if (authenticationIsRequired(username)) {

        final String access_token = tokens[1];
        final String provider = tokens[2];
        String usernameToken = null;
        String profileName = null;

        if (provider.equals(FACEBOOK)) {
          UserOperations userOperations = new FacebookTemplate(access_token).userOperations();
          usernameToken = userOperations.getUserProfile().getEmail();
          profileName = userOperations.getUserProfile().getName();
        } else if (provider.equals(GOOGLEPLUS)) {
          PlusOperations plusOperations = new GoogleTemplate(access_token).plusOperations();
          usernameToken = plusOperations.getGoogleProfile().getAccountEmail();
          profileName = plusOperations.getGoogleProfile().getDisplayName();
        }

        if (usernameToken == null || !usernameToken.equals(username)) {
          throw new BadCredentialsException("Invalid access authentication token");
        }

        User user = this.loginService.findUserByEmail(username);

        if (user != null && user.isEnabled() == false) {
          throw new BadCredentialsException("Invalid credentials - User disabled");
        } else if (user == null) {
          user = this.loginService.insertSocialUser(new User(profileName, username));
        }

        final SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(
            new UsernamePasswordAuthenticationToken(
                user, user.getPassword(), user.getAuthorities()));
      }
    } catch (AuthenticationException failed) {
      SecurityContextHolder.clearContext();
      authenticationEntryPoint.commence(request, response, failed);
      return;
    }

    chain.doFilter(request, response);
  }
示例#10
0
 @Test
 public void testgetCurrentUserLogin() {
   SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
   securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
   SecurityContextHolder.setContext(securityContext);
   String login = SecurityUtils.getCurrentUserLogin();
   assertThat(login).isEqualTo("admin");
 }
示例#11
0
 @Test
 public void testIsAuthenticated() {
   SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
   securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
   SecurityContextHolder.setContext(securityContext);
   boolean isAuthenticated = SecurityUtils.isAuthenticated();
   assertThat(isAuthenticated).isTrue();
 }
示例#12
0
  public void authenticate(String customername) {
    UserDetails userDetails;
    TestingAuthenticationToken authenticationToken;
    SecurityContext context;

    userDetails = loginService.loadUserByUsername(customername);
    authenticationToken = new TestingAuthenticationToken(userDetails, null);
    context = SecurityContextHolder.getContext();
    context.setAuthentication(authenticationToken);
  }
示例#13
0
 @Test
 public void testAnonymousIsNotAuthenticated() {
   SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
   Collection<GrantedAuthority> authorities = new ArrayList<>();
   authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
   securityContext.setAuthentication(
       new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
   SecurityContextHolder.setContext(securityContext);
   boolean isAuthenticated = SecurityUtils.isAuthenticated();
   assertThat(isAuthenticated).isFalse();
 }
  @Test
  @Transactional(readOnly = true)
  public void testGetEventGridWidgetDefinitionWithAuthentication()
      throws IllegalArgumentException, IllegalAccessException, InvocationTargetException,
          SecurityException, NoSuchMethodException, IOException {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(auth);
    AbstractLicensableWidget eventGridWidget = uIService.getWidgetDefinition(EventGridWidgetName);
    Assert.notNull(eventGridWidget);
    Assert.isTrue(
        eventGridWidget.getActionConfig().getActionConfig().size() == 2,
        "Event grid widget action config does not have expected # of permissions values");
    Assert.isTrue(
        eventGridWidget
                .getActionConfig()
                .getActionConfig()
                .get("widget-actions")
                .get(new Permission("create-event"))
            == Boolean.TRUE,
        "Event grid widget action config does not have create-event permission true");
    Assert.isTrue(
        eventGridWidget
                .getActionConfig()
                .getActionConfig()
                .get("widget-actions")
                .get(new Permission("edit-event"))
            == Boolean.TRUE,
        "Event grid widget action config does not have edit-event permission true");

    // Assertions for AutoRefreshConfig
    JSONObject defaultViewConfigJSON = new JSONObject(eventGridWidget.getDefaultViewConfig());
    Assert.isTrue(
        defaultViewConfigJSON.has("autoRefreshConfig"),
        "Could not find property 'AutoRefreshConfig'");

    JSONObject autoRefreshConfigJSON =
        new JSONObject(defaultViewConfigJSON.get("autoRefreshConfig").toString());
    Assert.isTrue(
        autoRefreshConfigJSON.has("globalOverride"), "Could not find property 'globalOverride'");
    Assert.isTrue(autoRefreshConfigJSON.has("enabled"), "Could not find property 'enabled'");
    Assert.isTrue(autoRefreshConfigJSON.has("interval"), "Could not find property 'interval'");

    Assert.isTrue(
        autoRefreshConfigJSON.getBoolean("globalOverride") == false,
        "Incorrect value for property 'globalOverride'");
    Assert.isTrue(
        autoRefreshConfigJSON.getBoolean("enabled") == true,
        "Incorrect value for property 'enabled'");
    Assert.isTrue(
        autoRefreshConfigJSON.getInt("interval") == 120, "Incorrect value for property 'interval'");
  }
示例#15
0
  private void setUpSecurityContext() {
    SimpleGrantedAuthority authority = new SimpleGrantedAuthority("mdsSchemaAccess");
    List<SimpleGrantedAuthority> authorities = asList(authority);

    User principal = new User("motech", "motech", authorities);

    Authentication authentication =
        new UsernamePasswordAuthenticationToken(principal, "motech", authorities);

    SecurityContext securityContext = new SecurityContextImpl();
    securityContext.setAuthentication(authentication);

    SecurityContextHolder.setContext(securityContext);
  }
  @Before
  public void setUp() throws Exception {
    // store initial security context for later restoration
    initialSecurityContext = SecurityContextHolder.getContext();

    SecurityContext context = new SecurityContextImpl();
    User user = new User("user");
    user.setId(1L);
    user.setPassword("password");
    user.addRole(new Role(Constants.USER_ROLE));

    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), user.getPassword(), user.getAuthorities());
    token.setDetails(user);
    context.setAuthentication(token);
    SecurityContextHolder.setContext(context);
  }
示例#17
0
 private void authenticateAndExecute(
     HttpServletRequest request,
     HttpServletResponse response,
     FilterChain chain,
     SecurityContext securityContext)
     throws IOException, ServletException {
   // Try to see if authentication in cache based on the hashed header and client ip
   Authentication authentication = getNonUiCachedAuthentication(request);
   if (authentication != null
       && authentication.isAuthenticated()
       && !reAuthenticationRequired(request, authentication)) {
     log.debug("Header authentication {} found in cache.", authentication);
     useAuthentication(request, response, chain, authentication, securityContext);
     // Add to user change cache the login state
     addToUserChange(authentication);
     return;
   }
   try {
     authFilter.doFilter(request, response, chain);
   } finally {
     Authentication newAuthentication = securityContext.getAuthentication();
     if (newAuthentication != null && newAuthentication.isAuthenticated()) {
       // Add to user change cache the login state
       addToUserChange(newAuthentication);
       // Save authentication like in Wicket Session (if session exists)
       if (RequestUtils.setAuthentication(request, newAuthentication, false)) {
         log.debug("Added authentication {} in Http session.", newAuthentication);
       } else {
         // If it did not work use the header cache
         // An authorization cache key with no header can only be used for Anonymous authentication
         AuthCacheKey authCacheKey =
             new AuthCacheKey(authFilter.getCacheKey(request), request.getRemoteAddr());
         String username = newAuthentication.getName();
         if ((UserInfo.ANONYMOUS.equals(username) && authCacheKey.hasEmptyHeader())
             || (!UserInfo.ANONYMOUS.equals(username) && !authCacheKey.hasEmptyHeader())) {
           nonUiAuthCache.put(authCacheKey, newAuthentication);
           userChangedCache.get(username).addAuthCacheKey(authCacheKey);
           log.debug("Added authentication {} in cache.", newAuthentication);
         }
       }
     }
     securityContext.setAuthentication(null);
   }
 }
  /** @param args */
  public static void main(String[] args) {
    if (args.length < 1) {
      System.out.println("Usage: Initializer " + "<spring-configuration-classname> ");
      System.exit(1);
    }
    ConfigurableApplicationContext applicationContext = null;
    try {
      SpringConfiguration springConfig =
          (SpringConfiguration) BeanUtils.instantiateClass(Class.forName(args[0]));
      applicationContext =
          new ClassPathXmlApplicationContext(
              springConfig.getRootApplicationContextConfigLocations());

      CreateDefaultUsers createDefaultUsers = new CreateDefaultUsers(applicationContext);
      createDefaultUsers.createRoles(applicationContext);
      User adminUser = createDefaultUsers.createAdministrator(applicationContext, "admin", "pass");

      // createDefaultOfferings requires security context so that ACL
      // entries can be created for the default offerings.
      // this also means that the only user allowed to "see" offerings at
      // the initial login will be the admin user.
      Authentication authority =
          new UsernamePasswordAuthenticationToken(
              adminUser.getUserDetails(),
              new GrantedAuthority[] {new SimpleGrantedAuthority(UserDetailsService.ADMIN_ROLE)});
      SecurityContext securityContext = new SecurityContextImpl();
      securityContext.setAuthentication(authority);
      SecurityContextHolder.setContext(securityContext);

      CreateDefaultOfferings createDefaultOfferings =
          new CreateDefaultOfferings(applicationContext);
      Curnit[] curnits = createDefaultOfferings.createDefaultCurnits(applicationContext);
      Jnlp[] jnlps = createDefaultOfferings.createDefaultJnlps(applicationContext);
      createDefaultOfferings.createDefaultOfferings(applicationContext, curnits, jnlps);

    } catch (Exception all) {
      System.err.println(all.getLocalizedMessage());
      all.printStackTrace(System.out);
      System.exit(2);
    } finally {
      applicationContext.close();
    }
  }
  @Before
  public void setup() {
    logger.info("setup");

    this.mockMvc =
        MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    User user = null;
    try {
      user = userService.findByLogin("johndoe");
    } catch (ServiceException e) {
      logger.error(e.getLocalizedMessage());
    }

    Authentication authentication =
        new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword());
    Authentication result = authenticationManager.authenticate(authentication);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(result);
    session = new MockHttpSession();
    session.setAttribute(
        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);

    try {
      logger.info("Create Tomcat server");
      String jsonString =
          "{\"applicationName\":\"" + applicationName + "\", \"serverName\":\"" + release + "\"}";
      ResultActions resultats =
          mockMvc.perform(
              post("/application")
                  .session(session)
                  .contentType(MediaType.APPLICATION_JSON)
                  .content(jsonString));
      resultats.andExpect(status().isOk());

    } catch (Exception e) {
      logger.error(e.getMessage());
    }
  }
  // Test fix to http://issues.appfuse.org/browse/APF-96
  @Test
  public void testAddUserRoleWhenHasAdminRole() throws Exception {
    SecurityContext securityContext = new SecurityContextImpl();
    User user1 = new User("user");
    user1.setId(1L);
    user1.setPassword("password");
    user1.addRole(new Role(Constants.ADMIN_ROLE));
    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(
            user1.getUsername(), user1.getPassword(), user1.getAuthorities());
    token.setDetails(user1);
    securityContext.setAuthentication(token);
    SecurityContextHolder.setContext(securityContext);

    UserManager userManager = makeInterceptedTarget();
    final User user = new User("user");
    user.setId(1L);
    user.getRoles().add(new Role(Constants.ADMIN_ROLE));
    user.getRoles().add(new Role(Constants.USER_ROLE));

    given(userDao.saveUser(user)).willReturn(user);

    userManager.saveUser(user);
  }
 public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
   SecurityContext context = SecurityContextHolder.getContext();
   context.setAuthentication(authentication);
   save(authentication, request);
   return request;
 }
  @Test
  @Transactional(readOnly = true)
  public void testGetSearchUserGridWidgetDefinitionWithAuthentication()
      throws IllegalArgumentException, IllegalAccessException, InvocationTargetException,
          SecurityException, NoSuchMethodException, IOException {
    String listenForListString = "\"listensForList\":[\"userName\"]";
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(auth);
    AbstractLicensableWidget searchUserGridWidget =
        uIService.getWidgetDefinition(SearchUserGridWidgetName);
    Assert.notNull(searchUserGridWidget);
    Assert.isTrue(
        searchUserGridWidget.getActionConfig().getActionConfig().size() == 2,
        "Search user grid widget action config does not have expected # of permissions values");
    Assert.isTrue(
        searchUserGridWidget
                .getActionConfig()
                .getActionConfig()
                .get("widget-actions")
                .get(new Permission("delete-user"))
            == Boolean.TRUE,
        "Search user grid widget action config does not have delete-user permission true");
    Assert.isTrue(
        searchUserGridWidget
                .getActionConfig()
                .getActionConfig()
                .get("widget-actions")
                .get(new Permission("disable-user"))
            == Boolean.TRUE,
        "Search user grid widget action config does not have disable-user permission true");
    Assert.notNull(
        searchUserGridWidget.getReactToList(),
        "Search user grid widget definition does not have react to map");
    Assert.notNull(
        searchUserGridWidget.getBroadcastList(),
        "Search user grid widget definition does not have the broadcast list");
    Assert.isTrue(
        searchUserGridWidget.getBroadcastList().size() == 1,
        "Search user grid widget definition does not have the required broadcast list size");
    String defaultViewConfig = searchUserGridWidget.getDefaultViewConfig();
    Assert.isTrue(
        defaultViewConfig.contains(listenForListString),
        "Default view config does not have the expected listen for list");

    // Assertions for AutoRefreshConfig
    JSONObject defaultViewConfigJSON = new JSONObject(searchUserGridWidget.getDefaultViewConfig());
    Assert.isTrue(
        defaultViewConfigJSON.has("autoRefreshConfig"),
        "Could not find property 'AutoRefreshConfig'");

    JSONObject autoRefreshConfigJSON =
        new JSONObject(defaultViewConfigJSON.get("autoRefreshConfig").toString());
    Assert.isTrue(
        autoRefreshConfigJSON.has("globalOverride"), "Could not find property 'globalOverride'");
    Assert.isTrue(autoRefreshConfigJSON.has("enabled"), "Could not find property 'enabled'");
    Assert.isTrue(autoRefreshConfigJSON.has("interval"), "Could not find property 'interval'");

    Assert.isTrue(
        autoRefreshConfigJSON.getBoolean("globalOverride") == false,
        "Incorrect value for property 'globalOverride'");
    Assert.isTrue(
        autoRefreshConfigJSON.getBoolean("enabled") == true,
        "Incorrect value for property 'enabled'");
    Assert.isTrue(
        autoRefreshConfigJSON.getInt("interval") == 120, "Incorrect value for property 'interval'");
  }
 /**
  * Saves the specified {@link Authentication} into an empty {@link SecurityContext} using the
  * {@link SecurityContextRepository}.
  *
  * @param authentication the {@link Authentication} to save
  * @param request the {@link HttpServletRequest} to use
  */
 final void save(Authentication authentication, HttpServletRequest request) {
   SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
   securityContext.setAuthentication(authentication);
   save(securityContext, request);
 }
示例#24
0
  public String login() {
    StringBuffer msg = new StringBuffer("{msg:'");

    SysConfig sysConfig = this.sysConfigService.findByKey("codeConfig");

    Captcha captcha = (Captcha) getSession().getAttribute("simpleCaptcha");
    Boolean login = Boolean.valueOf(false);

    String newPassword = null;

    if ((!"".equals(this.username)) && (this.username != null)) {
      setUser(this.userService.findByUserName(this.username));

      if (this.user != null) {
        if (org.apache.commons.lang.StringUtils.isNotEmpty(this.password)) {
          newPassword = StringUtil.encryptSha256(this.password);
          if (this.user.getPassword().equalsIgnoreCase(newPassword)) {
            if (sysConfig.getDataValue().equals("1")) {
              if (captcha == null) {
                msg.append("请刷新验证码再登录.'");
              } else if (captcha.isCorrect(this.checkCode)) {
                if (this.user.getStatus().shortValue() == 1) login = Boolean.valueOf(true);
                else msg.append("此用户已被禁用.'");
              } else msg.append("验证码不正确.'");

            } else if (this.user.getStatus().shortValue() == 1) login = Boolean.valueOf(true);
            else msg.append("此用户已被禁用.'");
          } else msg.append("密码不正确.'");
        } else {
          msg.append("密码不能为空.'");
        }
      } else msg.append("用户不存在.'");
    }
    if (login.booleanValue()) {
      UsernamePasswordAuthenticationToken authRequest =
          new UsernamePasswordAuthenticationToken(this.username, this.password);
      SecurityContext securityContext = SecurityContextHolder.getContext();
      securityContext.setAuthentication(this.authenticationManager.authenticate(authRequest));
      SecurityContextHolder.setContext(securityContext);
      getSession().setAttribute("SPRING_SECURITY_LAST_USERNAME", this.username);
      String rememberMe = getRequest().getParameter("_spring_security_remember_me");
      if ((rememberMe != null) && (rememberMe.equals("on"))) {
        long tokenValiditySeconds = 1209600L;
        long tokenExpiryTime = System.currentTimeMillis() + tokenValiditySeconds * 1000L;

        String signatureValue =
            DigestUtils.md5Hex(
                this.username
                    + ":"
                    + tokenExpiryTime
                    + ":"
                    + this.user.getPassword()
                    + ":"
                    + this.key);

        String tokenValue = this.username + ":" + tokenExpiryTime + ":" + signatureValue;
        String tokenValueBase64 = new String(Base64.encodeBase64(tokenValue.getBytes()));
        getResponse().addCookie(makeValidCookie(tokenExpiryTime, tokenValueBase64));
      }

      setJsonString("{success:true}");
    } else {
      msg.append(",failure:true}");
      setJsonString(msg.toString());
      return "login";
    }
    return "index";
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String requestURI = httpRequest.getRequestURI();

    SecurityContext context = getSecurityContext();

    Authentication authentication = context.getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()) {
      String token = httpRequest.getHeader(INTERNAL_TOKEN_HEADER);
      if (token != null) {
        context.setAuthentication(new InternalAuthenticationToken(token));
      } else {
        // for view access, we should redirect to the Ambari login
        if (requestURI.matches(VIEWS_CONTEXT_ALL_PATTERN)) {
          String queryString = httpRequest.getQueryString();
          String requestedURL = queryString == null ? requestURI : (requestURI + '?' + queryString);
          String redirectURL = httpResponse.encodeRedirectURL(LOGIN_REDIRECT_BASE + requestedURL);

          httpResponse.sendRedirect(redirectURL);
          return;
        }
      }
    } else {
      boolean authorized = false;

      for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
        if (grantedAuthority instanceof AmbariGrantedAuthority) {

          AmbariGrantedAuthority ambariGrantedAuthority = (AmbariGrantedAuthority) grantedAuthority;

          PrivilegeEntity privilegeEntity = ambariGrantedAuthority.getPrivilegeEntity();
          Integer permissionId = privilegeEntity.getPermission().getId();

          // admin has full access
          if (permissionId.equals(PermissionEntity.AMBARI_ADMIN_PERMISSION)) {
            authorized = true;
            break;
          }

          // clusters require permission
          if (requestURI.matches(API_CLUSTERS_ALL_PATTERN)) {
            if (permissionId.equals(PermissionEntity.CLUSTER_READ_PERMISSION)
                || permissionId.equals(PermissionEntity.CLUSTER_OPERATE_PERMISSION)) {
              authorized = true;
              break;
            }
          } else if (STACK_ADVISOR_REGEX.matcher(requestURI).matches()) {
            // TODO permissions model doesn't manage stacks api, but we need access to stack advisor
            // to save configs
            if (permissionId.equals(PermissionEntity.CLUSTER_OPERATE_PERMISSION)) {
              authorized = true;
              break;
            }
          } else if (requestURI.matches(API_VIEWS_ALL_PATTERN)) {
            // views require permission
            if (permissionId.equals(PermissionEntity.VIEW_USE_PERMISSION)) {
              authorized = true;
              break;
            }
          } else if (requestURI.matches(API_PERSIST_ALL_PATTERN)) {
            if (permissionId.equals(PermissionEntity.CLUSTER_OPERATE_PERMISSION)) {
              authorized = true;
              break;
            }
          }
        }
      }

      if (!authorized && requestURI.matches(VIEWS_CONTEXT_PATH_PATTERN)) {
        final ViewInstanceVersionDTO dto = parseViewInstanceInfo(requestURI);
        authorized =
            getViewRegistry()
                .checkPermission(dto.getViewName(), dto.getVersion(), dto.getInstanceName(), true);
      }

      // allow all types of requests for /users/{current_user}
      if (!authorized && requestURI.matches(API_USERS_USERNAME_PATTERN)) {
        final SecurityContext securityContext = getSecurityContext();
        final String currentUserName = securityContext.getAuthentication().getName();
        final String urlUserName = parseUserName(requestURI);
        authorized = currentUserName.equalsIgnoreCase(urlUserName);
      }

      // allow GET for everything except /views, /api/v1/users, /api/v1/groups,
      // /api/v1/ldap_sync_events
      if (!authorized
          && (!httpRequest.getMethod().equals("GET")
              || requestURI.matches(VIEWS_CONTEXT_ALL_PATTERN)
              || requestURI.matches(API_USERS_ALL_PATTERN)
              || requestURI.matches(API_GROUPS_ALL_PATTERN)
              || requestURI.matches(API_LDAP_SYNC_EVENTS_ALL_PATTERN))) {

        httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
        httpResponse.sendError(
            HttpServletResponse.SC_FORBIDDEN,
            "You do not have permissions to access this resource.");
        httpResponse.flushBuffer();
        return;
      }
    }

    chain.doFilter(request, response);
  }