private void unregisterJob(final String jobName) {
    try {
      scheduler.getScheduler().unscheduleJob(new TriggerKey(jobName, Scheduler.DEFAULT_GROUP));
      scheduler.getScheduler().deleteJob(new JobKey(jobName, Scheduler.DEFAULT_GROUP));
    } catch (SchedulerException e) {
      LOG.error("Could not remove job " + jobName, e);
    }

    if (ApplicationContextProvider.getBeanFactory().containsSingleton(jobName)) {
      ApplicationContextProvider.getBeanFactory().destroySingleton(jobName);
    }
  }
  @SuppressWarnings("unchecked")
  private <T> T createSpringBean(final Class<T> jobClass) {
    T jobInstance = null;
    for (int i = 0; i < 5 && jobInstance == null; i++) {
      LOG.debug("{} attempt to create Spring bean for {}", i, jobClass);
      try {
        jobInstance =
            (T)
                ApplicationContextProvider.getBeanFactory()
                    .createBean(jobClass, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
        LOG.debug("{} attempt to create Spring bean for {} succeeded", i, jobClass);
      } catch (BeanCreationException e) {
        LOG.error("Could not create Spring bean for {}", jobClass, e);
        try {
          Thread.sleep(1000);
        } catch (final InterruptedException ex) {
          // ignore
        }
      }
    }
    if (jobInstance == null) {
      throw new NotFoundException("Spring bean for " + jobClass);
    }

    return jobInstance;
  }
  @Override
  public void process(final Exchange exchange) {
    Long key = exchange.getProperty("userKey", Long.class);

    UserPatch userPatch = new UserPatch();
    userPatch.setKey(key);
    userPatch.setPassword(
        new PasswordPatch.Builder().value(exchange.getProperty("password", String.class)).build());

    List<PropagationTask> tasks =
        propagationManager.getUserUpdateTasks(
            new WorkflowResult<Pair<UserPatch, Boolean>>(
                new ImmutablePair<UserPatch, Boolean>(userPatch, null),
                null,
                "confirmPasswordReset"),
            true,
            null);
    PropagationReporter propReporter =
        ApplicationContextProvider.getBeanFactory().getBean(PropagationReporter.class);
    try {
      taskExecutor.execute(tasks, propReporter);
    } catch (PropagationException e) {
      LOG.error("Error propagation primary resource", e);
      propReporter.onPrimaryResourceFailure(tasks);
    }
  }
Example #4
0
  @Transactional(readOnly = true)
  @Override
  public Pair<Boolean, Boolean> enforcePolicies(final User user) {
    // ------------------------------
    // Verify password policies
    // ------------------------------
    LOG.debug("Password Policy enforcement");

    try {
      int maxPPSpecHistory = 0;
      for (PasswordPolicy policy : getPasswordPolicies(user)) {
        if (user.getPassword() == null && !policy.isAllowNullPassword()) {
          throw new PasswordPolicyException("Password mandatory");
        }

        for (PasswordRuleConf ruleConf : policy.getRuleConfs()) {
          Class<? extends PasswordRule> ruleClass =
              implementationLookup.getPasswordRuleClass(ruleConf.getClass());
          if (ruleClass == null) {
            LOG.warn("Could not find matching password rule for {}", ruleConf.getClass());
          } else {
            // fetch (or create) rule
            PasswordRule rule;
            if (ApplicationContextProvider.getBeanFactory()
                .containsSingleton(ruleClass.getName())) {
              rule =
                  (PasswordRule)
                      ApplicationContextProvider.getBeanFactory().getSingleton(ruleClass.getName());
            } else {
              rule =
                  (PasswordRule)
                      ApplicationContextProvider.getBeanFactory()
                          .createBean(ruleClass, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
              ApplicationContextProvider.getBeanFactory()
                  .registerSingleton(ruleClass.getName(), rule);
            }

            // enforce rule
            rule.enforce(ruleConf, user);
          }
        }

        if (user.verifyPasswordHistory(user.getClearPassword(), policy.getHistoryLength())) {
          throw new PasswordPolicyException("Password value was used in the past: not allowed");
        }

        if (policy.getHistoryLength() > maxPPSpecHistory) {
          maxPPSpecHistory = policy.getHistoryLength();
        }
      }

      // update user's password history with encrypted password
      if (maxPPSpecHistory > 0 && user.getPassword() != null) {
        user.getPasswordHistory().add(user.getPassword());
      }
      // keep only the last maxPPSpecHistory items in user's password history
      if (maxPPSpecHistory < user.getPasswordHistory().size()) {
        for (int i = 0; i < user.getPasswordHistory().size() - maxPPSpecHistory; i++) {
          user.getPasswordHistory().remove(i);
        }
      }
    } catch (Exception e) {
      LOG.error("Invalid password for {}", user, e);
      throw new InvalidEntityException(
          User.class, EntityViolationType.InvalidPassword, e.getMessage());
    } finally {
      // password has been validated, let's remove its clear version
      user.removeClearPassword();
    }

    // ------------------------------
    // Verify account policies
    // ------------------------------
    LOG.debug("Account Policy enforcement");

    boolean suspend = false;
    boolean propagateSuspension = false;
    try {
      if (adminUser.equals(user.getUsername()) || anonymousUser.equals(user.getUsername())) {
        throw new AccountPolicyException("Not allowed: " + user.getUsername());
      }

      for (AccountPolicy policy : getAccountPolicies(user)) {
        for (AccountRuleConf ruleConf : policy.getRuleConfs()) {
          Class<? extends AccountRule> ruleClass =
              implementationLookup.getAccountRuleClass(ruleConf.getClass());
          if (ruleClass == null) {
            LOG.warn("Could not find matching password rule for {}", ruleConf.getClass());
          } else {
            // fetch (or create) rule
            AccountRule rule;
            if (ApplicationContextProvider.getBeanFactory()
                .containsSingleton(ruleClass.getName())) {
              rule =
                  (AccountRule)
                      ApplicationContextProvider.getBeanFactory().getSingleton(ruleClass.getName());
            } else {
              rule =
                  (AccountRule)
                      ApplicationContextProvider.getBeanFactory()
                          .createBean(ruleClass, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
              ApplicationContextProvider.getBeanFactory()
                  .registerSingleton(ruleClass.getName(), rule);
            }

            // enforce rule
            rule.enforce(ruleConf, user);
          }
        }

        suspend |=
            user.getFailedLogins() != null
                && policy.getMaxAuthenticationAttempts() > 0
                && user.getFailedLogins() > policy.getMaxAuthenticationAttempts()
                && !user.isSuspended();
        propagateSuspension |= policy.isPropagateSuspension();
      }
    } catch (Exception e) {
      LOG.error("Invalid username for {}", user, e);
      throw new InvalidEntityException(
          User.class, EntityViolationType.InvalidUsername, e.getMessage());
    }

    return ImmutablePair.of(suspend, propagateSuspension);
  }
  private void registerJob(
      final String jobName,
      final Job jobInstance,
      final String cronExpression,
      final Date startAt,
      final Map<String, Object> jobMap)
      throws SchedulerException, ParseException {

    synchronized (scheduler.getScheduler()) {
      boolean jobAlreadyRunning = false;
      for (JobExecutionContext jobCtx : scheduler.getScheduler().getCurrentlyExecutingJobs()) {
        if (jobName.equals(jobCtx.getJobDetail().getKey().getName())
            && Scheduler.DEFAULT_GROUP.equals(jobCtx.getJobDetail().getKey().getGroup())) {

          jobAlreadyRunning = true;

          LOG.debug("Job {} already running, cancel", jobCtx.getJobDetail().getKey());
        }
      }

      if (jobAlreadyRunning) {
        return;
      }
    }

    // 0. unregister job
    unregisterJob(jobName);

    // 1. Job bean
    ApplicationContextProvider.getBeanFactory().registerSingleton(jobName, jobInstance);

    // 2. JobDetail bean
    JobBuilder jobDetailBuilder =
        JobBuilder.newJob(jobInstance.getClass())
            .withIdentity(jobName)
            .usingJobData(new JobDataMap(jobMap));

    // 3. Trigger
    if (cronExpression == null && startAt == null) {
      // Jobs added with no trigger must be durable
      scheduler.getScheduler().addJob(jobDetailBuilder.storeDurably().build(), true);
    } else {
      TriggerBuilder<?> triggerBuilder;

      if (cronExpression == null) {
        triggerBuilder =
            TriggerBuilder.newTrigger()
                .withIdentity(JobNamer.getTriggerName(jobName))
                .startAt(startAt);
      } else {
        triggerBuilder =
            TriggerBuilder.newTrigger()
                .withIdentity(JobNamer.getTriggerName(jobName))
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression));

        if (startAt == null) {
          triggerBuilder = triggerBuilder.startNow();
        } else {
          triggerBuilder = triggerBuilder.startAt(startAt);
        }
      }

      scheduler.getScheduler().scheduleJob(jobDetailBuilder.build(), triggerBuilder.build());
    }
  }