index
int64
repo_id
string
file_path
string
content
string
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/JobStatus.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.v3.oas.annotations.media.Schema; /** * The enumeration giving the possible statuses for a job. * * @author Marcus Portmann */ @Schema(description = "The job status") public enum JobStatus { /** Unscheduled. */ UNSCHEDULED("unscheduled", "Unscheduled"), /** Scheduled. */ SCHEDULED("scheduled", "Scheduled"), /** Executing. */ EXECUTING("executing", "Executing"), /** Executed. */ EXECUTED("executed", "Executed"), /** Aborted. */ ABORTED("aborted", "Aborted"), /** Failed. */ FAILED("failed", "Failed"), /** Once-off. */ ONCE_OFF("once_off", "Once-Off"); private final String code; private final String description; JobStatus(String code, String description) { this.code = code; this.description = description; } /** * Returns the job status given by the specified code value. * * @param code the code for the job status * @return the job status given by the specified code value */ @JsonCreator public static JobStatus fromCode(String code) { switch (code) { case "unscheduled": return JobStatus.UNSCHEDULED; case "scheduled": return JobStatus.SCHEDULED; case "executing": return JobStatus.EXECUTING; case "executed": return JobStatus.EXECUTED; case "aborted": return JobStatus.ABORTED; case "failed": return JobStatus.FAILED; case "once_off": return JobStatus.ONCE_OFF; default: throw new RuntimeException( "Failed to determine the job status with the invalid code (" + code + ")"); } } /** * Returns the job status for the specified numeric code. * * @param numericCode the numeric code for the job status * @return the job status given by the specified numeric code value */ public static JobStatus fromNumericCode(int numericCode) { switch (numericCode) { case 1: return JobStatus.UNSCHEDULED; case 2: return JobStatus.SCHEDULED; case 3: return JobStatus.EXECUTING; case 4: return JobStatus.EXECUTED; case 5: return JobStatus.ABORTED; case 6: return JobStatus.FAILED; case 7: return JobStatus.ONCE_OFF; default: throw new RuntimeException( "Failed to determine the job status for the numeric code (" + numericCode + ")"); } } /** * Returns the numeric code for the job status. * * @param jobStatus the job status * @return the numeric code for the job status */ public static int toNumericCode(JobStatus jobStatus) { switch (jobStatus) { case UNSCHEDULED: return 1; case SCHEDULED: return 2; case EXECUTING: return 3; case EXECUTED: return 4; case ABORTED: return 5; case FAILED: return 6; case ONCE_OFF: return 7; default: throw new RuntimeException( "Failed to determine the numeric code for the job status (" + jobStatus.code() + ")"); } } /** * Returns the code for the job status. * * @return the code for the job status */ @JsonValue public String code() { return code; } /** * Returns the description for the job status. * * @return the description for the job status */ public String description() { return description; } /** * Return the string representation of the job status enumeration value. * * @return the string representation of the job status enumeration value */ public String toString() { return description; } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/JobStatusConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import javax.persistence.AttributeConverter; import javax.persistence.Converter; /** * The <b>JobStatusConverter</b> class implements the custom JPA converter for the <b> JobStatus</b> * enumeration. * * @author Marcus Portmann */ @Converter(autoApply = true) public class JobStatusConverter implements AttributeConverter<JobStatus, Integer> { /** * Converts the value stored in the entity attribute into the data representation to be stored in * the database. * * @param attribute the entity attribute value to be converted * @return the converted data to be stored in the database column */ @Override public Integer convertToDatabaseColumn(JobStatus attribute) { if (attribute == null) return null; return JobStatus.toNumericCode(attribute); } /** * Converts the data stored in the database column into the value to be stored in the entity * attribute. Note that it is the responsibility of the converter writer to specify the correct * dbData type for the corresponding column for use by the JDBC driver: i.e., persistence * providers are not expected to do such type conversion. * * @param dbData the data from the database column to be converted * @return the converted value to be stored in the entity attribute */ @Override public JobStatus convertToEntityAttribute(Integer dbData) { if (dbData == null) return null; return JobStatus.fromNumericCode(dbData); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/JobStatusToStringConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.WritingConverter; import org.springframework.stereotype.Component; /** * The <b>JobStatusToStringConverter</b> class implements the Spring converter that converts a * <b>JobStatus</b> type into a <b>String</b> type. * * @author Marcus Portmann */ @Component @WritingConverter public class JobStatusToStringConverter implements Converter<JobStatus, String> { /** Constructs a new <b>JobStatusToStringConverter</b>. */ public JobStatusToStringConverter() {} @Override public String convert(JobStatus source) { return source.code(); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/Predictor.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; /** * The <b>Predictor</b> class provides the capability to predict when a scheduling pattern will be * matched. * * <p>Suppose you want to know when the scheduler will execute a job scheduled with the pattern * <em>0 3 * jan-jun,sep-dec mon-fri</em>. You can predict the next <em>n</em> execution of the job * using a Predictor instance: * * <pre> * String pattern = &quot;0 3 * jan-jun,sep-dec mon-fri&quot;; * Predictor p = new Predictor(pattern); * for (int i = 0; i &lt; n; i++) { * System.out.println(p.nextMatchingDate()); * } * </pre> * * @author Carlo Pelliccia * @author Marcus Portmann */ @SuppressWarnings({"unused", "WeakerAccess"}) public class Predictor { /** The scheduling pattern on which the predictor works. */ private final SchedulingPattern schedulingPattern; /** The start time for the next prediction. */ private long time; /** The time zone for the prediction. */ private TimeZone timeZone = TimeZone.getDefault(); /** * Constructs a new <b>SchedulingPattern</b>. * * @param schedulingPattern the scheduling pattern on which the prediction will be based */ public Predictor(SchedulingPattern schedulingPattern) { this(schedulingPattern, System.currentTimeMillis()); } /** * Constructs a new <b>SchedulingPattern</b>. * * @param schedulingPattern the scheduling pattern on which the prediction will be based * @throws InvalidSchedulingPatternException if the scheduling pattern is invalid */ public Predictor(String schedulingPattern) throws InvalidSchedulingPatternException { this(schedulingPattern, System.currentTimeMillis()); } /** * Constructs a new <b>SchedulingPattern</b>. * * @param schedulingPattern the scheduling pattern on which the prediction will be based * @param start the start time of the prediction */ public Predictor(SchedulingPattern schedulingPattern, Date start) { this(schedulingPattern, start.getTime()); } /** * It builds a predictor with the given scheduling pattern and start time. * * @param schedulingPattern the scheduling pattern on which the prediction will be based * @param start the start time of the prediction as a milliseconds value */ public Predictor(SchedulingPattern schedulingPattern, long start) { this.schedulingPattern = schedulingPattern; this.time = (start / (1000 * 60)) * 1000 * 60; } /** * It builds a predictor with the given scheduling pattern and start time. * * @param schedulingPattern the pattern on which the prediction will be based * @param start the start time of the prediction * @throws InvalidSchedulingPatternException if the scheduling pattern is invalid */ public Predictor(String schedulingPattern, Date start) throws InvalidSchedulingPatternException { this(schedulingPattern, start.getTime()); } /** * It builds a predictor with the given scheduling pattern and start time. * * @param schedulingPattern the pattern on which the prediction will be based * @param start the start time of the prediction * @throws InvalidSchedulingPatternException if the scheduling pattern is invalid */ public Predictor(String schedulingPattern, long start) throws InvalidSchedulingPatternException { this.schedulingPattern = new SchedulingPattern(schedulingPattern); this.time = (start / (1000 * 60)) * 1000 * 60; } /** * Returns the next matching moment as a {@link Date} object. * * @return the next matching moment as a {@link Date} object */ public synchronized Date nextMatchingDate() { return new Date(nextMatchingTime()); } /** * Returns the next matching moment as a {@link LocalDateTime} object. * * @return the next matching moment as a {@link LocalDateTime} object */ public synchronized LocalDateTime nextMatchingLocalDateTime() { return LocalDateTime.ofInstant( Instant.ofEpochMilli(nextMatchingTime()), ZoneId.systemDefault()); } /** * Returns the next matching moment as a milliseconds value. * * @return the next matching moment as a milliseconds value */ public synchronized long nextMatchingTime() { // Go a minute ahead. time += 60000; // Is it matching? if (schedulingPattern.match(time)) { return time; } // Go through the matcher groups. int size = schedulingPattern.matcherSize; long[] times = new long[size]; for (int k = 0; k < size; k++) { // Ok, split the time! GregorianCalendar c = new GregorianCalendar(); c.setTimeInMillis(time); c.setTimeZone(timeZone); int minute = c.get(Calendar.MINUTE); int hour = c.get(Calendar.HOUR_OF_DAY); int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); int month = c.get(Calendar.MONTH); int year = c.get(Calendar.YEAR); // Gets the matchers. ValueMatcher minuteMatcher = schedulingPattern.minuteMatchers.get(k); ValueMatcher hourMatcher = schedulingPattern.hourMatchers.get(k); ValueMatcher dayOfMonthMatcher = schedulingPattern.dayOfMonthMatchers.get(k); ValueMatcher dayOfWeekMatcher = schedulingPattern.dayOfWeekMatchers.get(k); ValueMatcher monthMatcher = schedulingPattern.monthMatchers.get(k); for (; ; ) { // day of week for (; ; ) { // month for (; ; ) { // day of month for (; ; ) { // hour for (; ; ) { // minutes if (minuteMatcher.match(minute)) { break; } else { minute++; if (minute > 59) { minute = 0; hour++; } } } if (hour > 23) { hour = 0; dayOfMonth++; } if (hourMatcher.match(hour)) { break; } else { hour++; minute = 0; } } if (dayOfMonth > 31) { dayOfMonth = 1; month++; } if (month > Calendar.DECEMBER) { month = Calendar.JANUARY; year++; } if (dayOfMonthMatcher instanceof DayOfMonthValueMatcher) { DayOfMonthValueMatcher aux = (DayOfMonthValueMatcher) dayOfMonthMatcher; if (aux.match(dayOfMonth, month + 1, c.isLeapYear(year))) { break; } else { dayOfMonth++; hour = 0; minute = 0; } } else if (dayOfMonthMatcher.match(dayOfMonth)) { break; } else { dayOfMonth++; hour = 0; minute = 0; } } if (monthMatcher.match(month + 1)) { break; } else { month++; dayOfMonth = 1; hour = 0; minute = 0; } } // Is this ok? c = new GregorianCalendar(); c.setTimeZone(timeZone); c.set(Calendar.MINUTE, minute); c.set(Calendar.HOUR_OF_DAY, hour); c.set(Calendar.DAY_OF_MONTH, dayOfMonth); c.set(Calendar.MONTH, month); c.set(Calendar.YEAR, year); // Day-of-month/month/year compatibility check. int oldDayOfMonth = dayOfMonth; int oldMonth = month; int oldYear = year; dayOfMonth = c.get(Calendar.DAY_OF_MONTH); month = c.get(Calendar.MONTH); year = c.get(Calendar.YEAR); if ((month != oldMonth) || (dayOfMonth != oldDayOfMonth) || (year != oldYear)) { // Take another spin! continue; } // Day of week. int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); if (dayOfWeekMatcher.match(dayOfWeek - 1)) { break; } else { dayOfMonth++; hour = 0; minute = 0; if (dayOfMonth > 31) { dayOfMonth = 1; month++; if (month > Calendar.DECEMBER) { month = Calendar.JANUARY; year++; } } } } // Seems it matches! times[k] = (c.getTimeInMillis() / (1000 * 60)) * 1000 * 60; } // Which one? long min = Long.MAX_VALUE; for (int k = 0; k < size; k++) { if (times[k] < min) { min = times[k]; } } // Updates the object current time value. time = min; // Here it is. return time; } /** * Set the time zone for predictions. * * @param timeZone the time zone to user for predictions */ public void setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/SchedulerConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import africa.absa.inception.jpa.JpaUtil; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.PlatformTransactionManager; /** * The <b>SchedulerConfiguration</b> class provides the Spring configuration for the Scheduler * module. * * @author Marcus Portmann */ @Configuration @EnableJpaRepositories( entityManagerFactoryRef = "schedulerEntityManagerFactory", basePackages = {"africa.absa.inception.scheduler"}) @EnableScheduling public class SchedulerConfiguration { /** The Spring application context. */ private final ApplicationContext applicationContext; /** * Constructs a new <b>SchedulerConfiguration</b>. * * @param applicationContext the Spring application context */ public SchedulerConfiguration(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Returns the scheduler entity manager factory bean associated with the application data source. * * @param dataSource the application data source * @param platformTransactionManager the platform transaction manager * @return the scheduler entity manager factory bean associated with the application data source */ @Bean public LocalContainerEntityManagerFactoryBean schedulerEntityManagerFactory( @Qualifier("applicationDataSource") DataSource dataSource, PlatformTransactionManager platformTransactionManager) { return JpaUtil.createEntityManager( "scheduler", dataSource, platformTransactionManager, "africa.absa.inception.scheduler"); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/SchedulerService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import africa.absa.inception.core.service.ValidationError; import africa.absa.inception.core.util.ServiceUtil; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; /** * The <b>SchedulerService</b> class provides the Scheduler Service implementation. * * @author Marcus Portmann */ @Service public class SchedulerService implements ISchedulerService, InitializingBean { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(SchedulerService.class); /** The Spring application context. */ private final ApplicationContext applicationContext; /* The name of the Scheduler Service instance. */ private final String instanceName = ServiceUtil.getServiceInstanceName("SchedulerService"); /** The Job Repository. */ private final JobRepository jobRepository; /** The JSR-303 validator. */ private final Validator validator; /* Entity Manager */ @PersistenceContext(unitName = "scheduler") private EntityManager entityManager; /* * The delay in milliseconds between successive attempts to execute a job. */ @Value("${application.scheduler.jobExecutionRetryDelay:60000}") private int jobExecutionRetryDelay; /* * The maximum number of times execution will be attempted for a job. */ @Value("${application.scheduler.maximumJobExecutionAttempts:144}") private int maximumJobExecutionAttempts; /** * Constructs a new <b>SchedulerService</b>. * * @param applicationContext the Spring application context * @param validator the JSR-303 validator * @param jobRepository the Job Repository */ public SchedulerService( ApplicationContext applicationContext, Validator validator, JobRepository jobRepository) { this.validator = validator; this.applicationContext = applicationContext; this.jobRepository = jobRepository; } @Override public void afterPropertiesSet() { logger.info("Initializing the Scheduler Service (" + instanceName + ")"); } @Override @Transactional public void createJob(Job job) throws InvalidArgumentException, DuplicateJobException, ServiceUnavailableException { validateJob(job); try { if (jobRepository.existsById(job.getId())) { throw new DuplicateJobException(job.getId()); } jobRepository.saveAndFlush(job); } catch (DuplicateJobException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to create the job (" + job.getName() + ")", e); } } @Override @Transactional public void deleteJob(String jobId) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(jobId)) { throw new InvalidArgumentException("jobId"); } try { if (!jobRepository.existsById(jobId)) { throw new JobNotFoundException(jobId); } jobRepository.deleteById(jobId); } catch (JobNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to delete the job (" + jobId + ")", e); } } @Override public void executeJob(Job job) throws InvalidArgumentException, ServiceUnavailableException { validateJob(job); Class<?> jobClass; // Load the job class. try { jobClass = Thread.currentThread().getContextClassLoader().loadClass(job.getJobClass()); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to execute the job (" + job.getName() + ") with ID (" + job.getId() + "): Failed to load the job class (" + job.getJobClass() + ")", e); } // Initialize the job IJob jobImplementation; try { // Create a new instance of the job Object jobObject = jobClass.getConstructor().newInstance(); // Check if the job is a valid job if (!(jobObject instanceof IJob)) { throw new ServiceUnavailableException( "The job class (" + job.getJobClass() + ") does not implement the africa.absa.inception.scheduler.IJob interface"); } jobImplementation = (IJob) jobObject; // Perform dependency injection for the job implementation applicationContext.getAutowireCapableBeanFactory().autowireBean(jobImplementation); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to initialize the job (" + job.getName() + ") with ID (" + job.getId() + ")", e); } // Execute the job try { // Retrieve the parameters for the job Map<String, String> parameters = new HashMap<>(); for (JobParameter jobParameter : job.getParameters()) { parameters.put(jobParameter.getName(), jobParameter.getValue()); } // Initialize the job execution context JobExecutionContext context = new JobExecutionContext(job.getNextExecution(), parameters); // Execute the job jobImplementation.execute(context); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to execute the job (" + job.getName() + ") with ID (" + job.getId() + ")", e); } } @Override public List<Job> getFilteredJobs(String filter) throws ServiceUnavailableException { try { if (StringUtils.hasText(filter)) { return jobRepository.findFiltered("%" + filter + "%"); } else { return jobRepository.findAll(); } } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the jobs matching the filter (" + filter + ")", e); } } @Override public Job getJob(String jobId) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(jobId)) { throw new InvalidArgumentException("jobId"); } try { Optional<Job> jobOptional = jobRepository.findById(jobId); if (jobOptional.isPresent()) { return jobOptional.get(); } else { throw new JobNotFoundException(jobId); } } catch (JobNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the job (" + jobId + ")", e); } } @Override public String getJobName(String jobId) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(jobId)) { throw new InvalidArgumentException("jobId"); } try { Optional<String> nameOptional = jobRepository.getNameById(jobId); if (nameOptional.isPresent()) { return nameOptional.get(); } throw new JobNotFoundException(jobId); } catch (JobNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the name of the job (" + jobId + ")", e); } } @Override public List<Job> getJobs() throws ServiceUnavailableException { try { return jobRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the jobs", e); } } @Override public int getMaximumJobExecutionAttempts() { return maximumJobExecutionAttempts; } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public Optional<Job> getNextJobScheduledForExecution() throws ServiceUnavailableException { try { LocalDateTime lastExecutedBefore = LocalDateTime.now(); lastExecutedBefore = lastExecutedBefore.minus(jobExecutionRetryDelay, ChronoUnit.MILLIS); PageRequest pageRequest = PageRequest.of(0, 1); List<Job> jobs = jobRepository.findJobsScheduledForExecutionForWrite( lastExecutedBefore, LocalDateTime.now(), pageRequest); if (jobs.size() > 0) { Job job = jobs.get(0); LocalDateTime when = LocalDateTime.now(); jobRepository.lockJobForExecution(job.getId(), instanceName, when); entityManager.detach(job); job.setStatus(JobStatus.EXECUTING); job.setLockName(instanceName); job.incrementExecutionAttempts(); job.setLastExecuted(when); return Optional.of(job); } else { return Optional.empty(); } } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the next job that has been scheduled for execution", e); } } @Override public List<Job> getUnscheduledJobs() throws ServiceUnavailableException { try { return jobRepository.findUnscheduledJobs(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the unscheduled jobs", e); } } @Override @Transactional public void rescheduleJob(String jobId, String schedulingPattern) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(jobId)) { throw new InvalidArgumentException("jobId"); } if (!StringUtils.hasText(schedulingPattern)) { throw new InvalidArgumentException("schedulingPattern"); } try { Predictor predictor = new Predictor(schedulingPattern, System.currentTimeMillis()); jobRepository.scheduleJob(jobId, predictor.nextMatchingLocalDateTime()); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to reschedule the job (" + jobId + ") for execution", e); } } @Override @Transactional public void resetJobLocks(JobStatus status, JobStatus newStatus) throws InvalidArgumentException, ServiceUnavailableException { if (status == null) { throw new InvalidArgumentException("status"); } if (newStatus == null) { throw new InvalidArgumentException("newStatus"); } try { jobRepository.resetJobLocks(status, newStatus, instanceName); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to reset the locks for the jobs with status (" + status + ") that have been locked using the lock name (" + instanceName + ")", e); } } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public boolean scheduleNextUnscheduledJobForExecution() throws ServiceUnavailableException { try { PageRequest pageRequest = PageRequest.of(0, 1); List<Job> jobs = jobRepository.findUnscheduledJobsForWrite(pageRequest); if (jobs.size() > 0) { Job job = jobs.get(0); LocalDateTime nextExecution = null; try { Predictor predictor = new Predictor(job.getSchedulingPattern(), System.currentTimeMillis()); nextExecution = predictor.nextMatchingLocalDateTime(); } catch (Throwable e) { logger.error( "The next execution date could not be determined for the unscheduled job (" + job.getId() + ") with the scheduling pattern (" + job.getSchedulingPattern() + "): The job will be marked as FAILED", e); } if (nextExecution == null) { jobRepository.setJobStatus(job.getId(), JobStatus.FAILED); } else { logger.info( "Scheduling the unscheduled job (" + job.getId() + ") for execution at (" + nextExecution + ")"); jobRepository.scheduleJob(job.getId(), nextExecution); } return true; } else { return false; } } catch (Throwable e) { throw new ServiceUnavailableException("Failed to schedule the next unscheduled job", e); } } @Override @Transactional public void setJobStatus(String jobId, JobStatus status) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(jobId)) { throw new InvalidArgumentException("jobId"); } try { if (!jobRepository.existsById(jobId)) { throw new JobNotFoundException(jobId); } jobRepository.setJobStatus(jobId, status); } catch (JobNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to set the status (" + status + ") for the job (" + jobId + ")", e); } } @Override @Transactional public void unlockJob(String jobId, JobStatus status) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(jobId)) { throw new InvalidArgumentException("jobId"); } try { if (!jobRepository.existsById(jobId)) { throw new JobNotFoundException(jobId); } jobRepository.unlockJob(jobId, status); } catch (JobNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to unlock and set the status for the job (" + jobId + ") to (" + status + ")", e); } } @Override public void updateJob(Job job) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException { validateJob(job); try { Optional<Job> jobOptional = jobRepository.findById(job.getId()); if (jobOptional.isEmpty()) { throw new JobNotFoundException(job.getId()); } Job existingJob = jobOptional.get(); existingJob.setEnabled(job.isEnabled()); existingJob.setJobClass(job.getJobClass()); existingJob.setName(job.getName()); existingJob.setParameters(job.getParameters()); existingJob.setSchedulingPattern(job.getSchedulingPattern()); existingJob.setStatus(job.getStatus()); if (!job.isEnabled()) { job.setStatus(JobStatus.UNSCHEDULED); job.setNextExecution(null); } jobRepository.saveAndFlush(job); } catch (JobNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to update the job (" + job.getId() + ")", e); } } private void validateJob(Job job) throws InvalidArgumentException { if (job == null) { throw new InvalidArgumentException("job"); } Set<ConstraintViolation<Job>> constraintViolations = validator.validate(job); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "job", ValidationError.toValidationErrors(constraintViolations)); } } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/SchedulingPattern.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.StringTokenizer; import java.util.TimeZone; /** * The <b>SchedulingPattern</b> class supports a UNIX crontab-like pattern is a string split in five * space separated parts. * * <p>Each part is intented as: * * <ol> * <li><strong>Minutes sub-pattern</strong>. During which minutes of the hour should the job been * launched? The values range is from 0 to 59. * <li><strong>Hours sub-pattern</strong>. During which hours of the day should the job been * launched? The values range is from 0 to 23. * <li><strong>Days of month sub-pattern</strong>. During which days of the month should the job * been launched? The values range is from 1 to 31. The special value L can be used to * recognize the last day of month. * <li><strong>Months sub-pattern</strong>. During which months of the year should the job been * launched? The values range is from 1 (January) to 12 (December), otherwise this sub-pattern * allows the aliases &quot;jan&quot;, &quot;feb&quot;, &quot;mar&quot;, &quot;apr&quot;, * &quot;may&quot;, &quot;jun&quot;, &quot;jul&quot;, &quot;aug&quot;, &quot;sep&quot;, * &quot;oct&quot;, &quot;nov&quot; and &quot;dec&quot;. * <li><strong>Days of week sub-pattern</strong>. During which days of the week should the job * been launched? The values range is from 0 (Sunday) to 6 (Saturday), otherwise this * sub-pattern allows the aliases &quot;sun&quot;, &quot;mon&quot;, &quot;tue&quot;, * &quot;wed&quot;, &quot;thu&quot;, &quot;fri&quot; and &quot;sat&quot;. * </ol> * * <p>The star wildcard character is also admitted, indicating &quot;every minute of the hour&quot;, * &quot;every hour of the day&quot;, &quot;every day of the month&quot;, &quot;every month of the * year&quot; and &quot;every day of the week&quot;, according to the sub-pattern in which it is * used. * * <p>Once the scheduler is started, a job will be launched when the five parts in its scheduling * pattern will be true at the same time. * * <p>Some examples: * * <p><strong>5 * * * *</strong><br> * This pattern causes a job to be launched once every hour, at the begin of the fifth minute * (00:05, 01:05, 02:05 etc.). * * <p><strong>* * * * *</strong><br> * This pattern causes a job to be launched every minute. * * <p><strong>* 12 * * Mon</strong><br> * This pattern causes a job to be launched every minute during the 12th hour of Monday. * * <p><strong>* 12 16 * Mon</strong><br> * This pattern causes a job to be launched every minute during the 12th hour of Monday, 16th, but * only if the day is the 16th of the month. * * <p>Every sub-pattern can contain two or more comma separated values. * * <p><strong>59 11 * * 1,2,3,4,5</strong><br> * This pattern causes a job to be launched at 11:59AM on Monday, Tuesday, Wednesday, Thursday and * Friday. * * <p>Values intervals are admitted and defined using the minus character. * * <p><strong>59 11 * * 1-5</strong><br> * This pattern is equivalent to the previous one. * * <p>The slash character can be used to identify step values within a range. It can be used both in * the form <em>*&#47;c</em> and <em>a-b/c</em>. The subpattern is matched every <em>c</em> values * of the range <em>0,maxvalue</em> or <em>a-b</em>. * * <p><strong>*&#47;5 * * * *</strong><br> * This pattern causes a job to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on). * * <p><strong>3-18&#47;5 * * * *</strong><br> * This pattern causes a job to be launched every 5 minutes starting from the third minute of the * hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on). * * <p><strong>*&#47;15 9-17 * * *</strong><br> * This pattern causes a job to be launched every 15 minutes between the 9th and 17th hour of the * day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45). * * <p>All the fresh described syntax rules can be used together. * * <p><strong>* 12 10-16&#47;2 * *</strong><br> * This pattern causes a job to be launched every minute during the 12th hour of the day, but only * if the day is the 10th, the 12th, the 14th or the 16th of the month. * * <p><strong>* 12 1-15,17,20-25 * *</strong><br> * This pattern causes a job to be launched every minute during the 12th hour of the day, but the * day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must * be the 17th. * * <p>Finally cron4j lets you combine more scheduling patterns into one, with the pipe character: * * <p><strong>0 5 * * *|8 10 * * *|22 17 * * *</strong><br> * This pattern causes a job to be launched every day at 05:00, 10:08 and 17:22. * * @author Carlo Pelliccia * @author Marcus Portmann */ @SuppressWarnings({"unused", "WeakerAccess"}) public class SchedulingPattern { /** The parser for the day of month values. */ private static final ValueParser DAY_OF_MONTH_VALUE_PARSER = new DayOfMonthValueParser(); /** The parser for the day of week values. */ private static final ValueParser DAY_OF_WEEK_VALUE_PARSER = new DayOfWeekValueParser(); /** The parser for the hour values. */ private static final ValueParser HOUR_VALUE_PARSER = new HourValueParser(); /** The parser for the minute values. */ private static final ValueParser MINUTE_VALUE_PARSER = new MinuteValueParser(); /** The parser for the month values. */ private static final ValueParser MONTH_VALUE_PARSER = new MonthValueParser(); /** The pattern as a string. */ private final String asString; /** The ValueMatcher list for the "day of month" field. */ protected List<ValueMatcher> dayOfMonthMatchers = new ArrayList<>(); /** The ValueMatcher list for the "day of week" field. */ protected List<ValueMatcher> dayOfWeekMatchers = new ArrayList<>(); /** The ValueMatcher list for the "hour" field. */ protected List<ValueMatcher> hourMatchers = new ArrayList<>(); /** How many matcher groups in this pattern? */ protected int matcherSize = 0; /** The ValueMatcher list for the "minute" field. */ protected List<ValueMatcher> minuteMatchers = new ArrayList<>(); /** The ValueMatcher list for the "month" field. */ protected List<ValueMatcher> monthMatchers = new ArrayList<>(); /** * Builds a SchedulingPattern by parsing it from a string. * * @param pattern the pattern as a crontab-like string * @throws InvalidSchedulingPatternException if the scheduling pattern is invalid */ public SchedulingPattern(String pattern) throws InvalidSchedulingPatternException { this.asString = pattern; StringTokenizer st1 = new StringTokenizer(pattern, "|"); if (st1.countTokens() < 1) { throw new InvalidSchedulingPatternException( String.format("Invalid pattern: \"%s\"", pattern)); } while (st1.hasMoreTokens()) { String localPattern = st1.nextToken(); StringTokenizer st2 = new StringTokenizer(localPattern, " \t"); if (st2.countTokens() != 5) { throw new InvalidSchedulingPatternException( String.format("Invalid pattern: \"%s\"", localPattern)); } try { minuteMatchers.add(buildValueMatcher(st2.nextToken(), MINUTE_VALUE_PARSER)); } catch (Exception e) { throw new InvalidSchedulingPatternException( String.format("Invalid pattern \"%s\". Error parsing minutes field", localPattern), e); } try { hourMatchers.add(buildValueMatcher(st2.nextToken(), HOUR_VALUE_PARSER)); } catch (Exception e) { throw new InvalidSchedulingPatternException( String.format("Invalid pattern \"%s\". Error parsing hours field", localPattern), e); } try { dayOfMonthMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_MONTH_VALUE_PARSER)); } catch (Exception e) { throw new InvalidSchedulingPatternException( String.format( "Invalid pattern \"%s\". Error parsing days of month field", localPattern), e); } try { monthMatchers.add(buildValueMatcher(st2.nextToken(), MONTH_VALUE_PARSER)); } catch (Exception e) { throw new InvalidSchedulingPatternException( String.format("Invalid pattern \"%s\". Error parsing months field", localPattern), e); } try { dayOfWeekMatchers.add(buildValueMatcher(st2.nextToken(), DAY_OF_WEEK_VALUE_PARSER)); } catch (Exception e) { throw new InvalidSchedulingPatternException( String.format("Invalid pattern \"%s\". Error parsing days of week field", localPattern), e); } matcherSize++; } } /** * Validates a string as a scheduling pattern. * * @param schedulingPattern the pattern to validate * @return <b>true</b> if the given string represents a valid scheduling pattern or <b> false</b> * otherwise */ @SuppressWarnings("unused") public static boolean validate(String schedulingPattern) { try { new SchedulingPattern(schedulingPattern); } catch (InvalidSchedulingPatternException e) { return false; } return true; } /** * This utility method changes an alias to an integer value. * * @param value the value * @param aliases the aliases list * @param offset the offset applied to the aliases list indices * @return the parsed value */ private static int parseAlias(String value, String[] aliases, int offset) throws Exception { for (int i = 0; i < aliases.length; i++) { if (aliases[i].equalsIgnoreCase(value)) { return offset + i; } } throw new Exception(String.format("Invalid alias \"%s\"", value)); } /** * Returns <b>true</b> if the EPOCH timestamp in milliseconds matches the pattern, according to * the given time zone. * * @param timezone the time zone * @param timestamp the EPOCH timestamp in milliseconds * @return <b>true</b> if the given timestamp matches the pattern or <b>false</b> otherwise */ public boolean match(TimeZone timezone, long timestamp) { GregorianCalendar gc = new GregorianCalendar(); gc.setTimeInMillis(timestamp); gc.setTimeZone(timezone); int minute = gc.get(Calendar.MINUTE); int hour = gc.get(Calendar.HOUR_OF_DAY); int dayOfMonth = gc.get(Calendar.DAY_OF_MONTH); int month = gc.get(Calendar.MONTH) + 1; int dayOfWeek = gc.get(Calendar.DAY_OF_WEEK) - 1; int year = gc.get(Calendar.YEAR); for (int i = 0; i < matcherSize; i++) { ValueMatcher minuteMatcher = minuteMatchers.get(i); ValueMatcher hourMatcher = hourMatchers.get(i); ValueMatcher dayOfMonthMatcher = dayOfMonthMatchers.get(i); ValueMatcher monthMatcher = monthMatchers.get(i); ValueMatcher dayOfWeekMatcher = dayOfWeekMatchers.get(i); boolean eval = minuteMatcher.match(minute) && hourMatcher.match(hour) && ((dayOfMonthMatcher instanceof DayOfMonthValueMatcher) ? ((DayOfMonthValueMatcher) dayOfMonthMatcher) .match(dayOfMonth, month, gc.isLeapYear(year)) : dayOfMonthMatcher.match(dayOfMonth)) && monthMatcher.match(month) && dayOfWeekMatcher.match(dayOfWeek); if (eval) { return true; } } return false; } /** * Returns <b>true</b> if the given EPOCH timestamp in milliseconds matches the pattern, according * to the system default time zone. * * @param timestamp the EPOCH timestamp in milliseconds * @return <b>true</b> if the given timestamp matches the pattern or <b>false</b> otherwise */ public boolean match(long timestamp) { return match(TimeZone.getDefault(), timestamp); } /** * Returns the pattern as a string. * * @return The pattern as a string. */ public String toString() { return asString; } /** * A <b>ValueMatcher</b> utility builder. * * @param str the pattern part for the <b>ValueMatcher</b> creation * @param parser the parser used to parse the values * @return the requested <b>ValueMatcher</b> */ private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception { if ((str.length() == 1) && str.equals("*")) { return new AlwaysTrueValueMatcher(); } List<Integer> values = new ArrayList<>(); StringTokenizer st = new StringTokenizer(str, ","); while (st.hasMoreTokens()) { String element = st.nextToken(); List<Integer> local; try { local = parseListElement(element, parser); } catch (Exception e) { throw new Exception( String.format( "Invalid field \"%s\", invalid element \"%s\": %s", str, element, e.getMessage())); } for (Integer value : local) { if (!values.contains(value)) { values.add(value); } } } if (values.size() == 0) { throw new Exception(String.format("Invalid field \"%s\"", str)); } if (parser == DAY_OF_MONTH_VALUE_PARSER) { return new DayOfMonthValueMatcher(values); } else { return new IntArrayValueMatcher(values); } } /** * Parses an element to retrieve the values for the pattern. * * @param str the element string * @param parser the parser used to parse the values * @return the integers representing the allowed values */ private List<Integer> parseListElement(String str, ValueParser parser) throws Exception { StringTokenizer st = new StringTokenizer(str, "/"); int size = st.countTokens(); if ((size < 1) || (size > 2)) { throw new Exception("Syntax error"); } List<Integer> values; try { values = parseRange(st.nextToken(), parser); } catch (Exception e) { throw new Exception(String.format("Invalid range: %s", e.getMessage())); } if (size == 2) { String dStr = st.nextToken(); int div; try { div = Integer.parseInt(dStr); } catch (NumberFormatException e) { throw new Exception("Invalid divisor \"" + dStr + "\""); } if (div < 1) { throw new Exception("Non positive divisor \"" + div + "\""); } List<Integer> values2 = new ArrayList<>(); for (int i = 0; i < values.size(); i += div) { values2.add(values.get(i)); } return values2; } else { return values; } } /** * Parses a range of values. * * @param str the range string. * @param parser the parser used to parse the values * @return the integers representing the allowed values */ private List<Integer> parseRange(String str, ValueParser parser) throws Exception { if (str.equals("*")) { int min = parser.getMinValue(); int max = parser.getMaxValue(); List<Integer> values = new ArrayList<>(); for (int i = min; i <= max; i++) { values.add(i); } return values; } StringTokenizer st = new StringTokenizer(str, "-"); int size = st.countTokens(); if ((size < 1) || (size > 2)) { throw new Exception("Syntax error"); } String v1Str = st.nextToken(); int v1; try { v1 = parser.parse(v1Str); } catch (Exception e) { throw new Exception(String.format("Invalid value \"%s\": %s", v1Str, e.getMessage())); } if (size == 1) { List<Integer> values = new ArrayList<>(); values.add(v1); return values; } else { String v2Str = st.nextToken(); int v2; try { v2 = parser.parse(v2Str); } catch (Exception e) { throw new Exception(String.format("Invalid value \"%s\": %s", v2Str, e.getMessage())); } List<Integer> values = new ArrayList<>(); if (v1 < v2) { for (int i = v1; i <= v2; i++) { values.add(i); } } else if (v1 > v2) { int min = parser.getMinValue(); int max = parser.getMaxValue(); for (int i = v1; i <= max; i++) { values.add(i); } for (int i = min; i <= v2; i++) { values.add(i); } } else { // v1 == v2 values.add(v1); } return values; } } /** Definition for a value parser. */ private interface ValueParser { /** * Returns the maximum value accepted by the parser. * * @return the maximum value accepted by the parser */ int getMaxValue(); /** * Returns the minimum value accepted by the parser. * * @return the minimum value accepted by the parser */ int getMinValue(); /** * Attempts to parse a value. * * @param value the value * @return the parsed value * @throws Exception If the value can't be parsed. */ int parse(String value) throws Exception; } /** The days of month value parser. */ private static class DayOfMonthValueParser extends SimpleValueParser { /** Builds the value parser. */ public DayOfMonthValueParser() { super(1, 31); } /** * Added to support last-day-of-month. * * @param value the value to be parsed * @return the integer day of the month or 32 for last day of the month */ public int parse(String value) throws Exception { if (value.equalsIgnoreCase("L")) { return 32; } else { return super.parse(value); } } } /** The value parser for the months field. */ private static class DayOfWeekValueParser extends SimpleValueParser { /** Days of week aliases. */ private static final String[] ALIASES = {"sun", "mon", "tue", "wed", "thu", "fri", "sat"}; /** Builds the months value parser. */ public DayOfWeekValueParser() { super(0, 7); } /** * Parse the value. * * @param value the value to parse * @return the parsed value */ public int parse(String value) throws Exception { try { // try as a simple value return super.parse(value) % 7; } catch (Exception e) { // try as an alias return parseAlias(value, ALIASES, 0); } } } /** The hours value parser. */ private static class HourValueParser extends SimpleValueParser { /** Builds the value parser. */ public HourValueParser() { super(0, 23); } } /** The minutes value parser. */ private static class MinuteValueParser extends SimpleValueParser { /** Builds the value parser. */ public MinuteValueParser() { super(0, 59); } } /** The value parser for the months field. */ private static class MonthValueParser extends SimpleValueParser { /** Months aliases. */ private static final String[] ALIASES = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; /** Builds the months value parser. */ public MonthValueParser() { super(1, 12); } /** * Parse the value. * * @param value the value to parse * @return the parsed value */ public int parse(String value) throws Exception { try { // try as a simple value return super.parse(value); } catch (Exception e) { // try as an alias return parseAlias(value, ALIASES, 1); } } } /** A simple value parser. */ private static class SimpleValueParser implements ValueParser { /** The maximum allowed value. */ protected int maxValue; /** The minimum allowed value. */ protected int minValue; /** * Builds the value parser. * * @param minValue the minimum allowed value * @param maxValue the maximum allowed value */ public SimpleValueParser(int minValue, int maxValue) { this.minValue = minValue; this.maxValue = maxValue; } /** * Returns the maximum value. * * @return the maximum value */ public int getMaxValue() { return maxValue; } /** * Returns the minimum value. * * @return the minimum value */ public int getMinValue() { return minValue; } /** * Parse the value * * @param value the value to parse * @return the parsed value */ public int parse(String value) throws Exception { int i; try { i = Integer.parseInt(value); } catch (NumberFormatException e) { throw new Exception("invalid integer value"); } if ((i < minValue) || (i > maxValue)) { throw new Exception("value out of range"); } return i; } } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/StringToJobStatusConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.stereotype.Component; /** * The <b>StringToJobStatusConverter</b> class implements the Spring converter that converts a * <b>String</b> type into a <b>JobStatus</b> type. * * @author Marcus Portmann */ @Component @ReadingConverter public class StringToJobStatusConverter implements Converter<String, JobStatus> { /** Constructs a new <b>StringToJobStatusConverter</b>. */ public StringToJobStatusConverter() {} @Override public JobStatus convert(String source) { return JobStatus.fromCode(source); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/TestJob.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; /** * The <b>TestJob</b> class implements the test job. * * @author Marcus Portmann */ @SuppressWarnings({"unused", "SpringJavaAutowiredMembersInspection"}) public class TestJob implements IJob { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(TestJob.class); /* Scheduler Service */ @Autowired private ISchedulerService schedulerService; /** * Execute the job. * * @param context the job execution context */ @Override public void execute(JobExecutionContext context) throws JobExecutionFailedException { try { logger.info("Executing the test job (" + schedulerService + ")"); } catch (Throwable e) { throw new JobExecutionFailedException("Failed to execute the test job", e); } } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/ValueMatcher.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; /** * The <b>ValueMatcher</b> describes the behavior that must be implemented by a ValueMatcher. * * <p>A ValueMatcher is an object that validate an integer value against a set of rules. * * @author Carlo Pelliccia * @author Marcus Portmann */ public interface ValueMatcher { /** * Validate the given integer value against a set of rules. * * @param value the value * @return <b>true</b> if the given value matches the rules of the <b>ValueMatcher</b> , * <b>false</b> otherwise */ boolean match(int value); }
0
java-sources/africa/absa/inception-scheduler-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler-api/1.2.0/africa/absa/inception/scheduler/SchedulerApi.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import africa.absa.inception.api.ApiUtil; import africa.absa.inception.api.ProblemDetails; import africa.absa.inception.api.SecureApi; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * The <b>SchedulerApi</b> class. * * @author Marcus Portmann */ @Tag(name = "Scheduler") @RestController @RequestMapping(value = "/api/scheduler") @CrossOrigin @SuppressWarnings({"unused", "WeakerAccess"}) // @el (isSecurityDisabled: africa.absa.inception.api.ApiSecurityExpressionRoot.isSecurityEnabled) public class SchedulerApi extends SecureApi { /** The Scheduler Service. */ private final ISchedulerService schedulerService; /** * Constructs a new <b>SchedulerRestController</b>. * * @param applicationContext the Spring application context * @param schedulerService the Scheduler Service */ public SchedulerApi(ApplicationContext applicationContext, ISchedulerService schedulerService) { super(applicationContext); this.schedulerService = schedulerService; } /** * Create the new job. * * @param job the job to create * @throws InvalidArgumentException if an argument is invalid * @throws DuplicateJobException if the job already exists * @throws ServiceUnavailableException if the job could not be created */ @Operation(summary = "Create the job", description = "Create the job") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The job was created successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "A job with the specified ID already exists", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping(value = "/jobs", method = RequestMethod.POST, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Scheduler.SchedulerAdministration') or hasAuthority('FUNCTION_Scheduler.JobAdministration')") public void createJob( @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The job to create", required = true) @RequestBody Job job) throws InvalidArgumentException, DuplicateJobException, ServiceUnavailableException { schedulerService.createJob(job); } /** * Delete the job. * * @param jobId the ID for the job * @throws InvalidArgumentException if an argument is invalid * @throws JobNotFoundException if the job could not be found * @throws ServiceUnavailableException if the job could not be deleted */ @Operation(summary = "Delete the job", description = "Delete the job") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The job was deleted successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The job could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/jobs/{jobId}", method = RequestMethod.DELETE, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Scheduler.SchedulerAdministration') or hasAuthority('FUNCTION_Scheduler.JobAdministration')") public void deleteJob( @Parameter(name = "jobId", description = "The ID for the job", required = true) @PathVariable String jobId) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException { schedulerService.deleteJob(jobId); } /** * Retrieve the job. * * @param jobId the ID for the job * @return the job * @throws InvalidArgumentException if an argument is invalid * @throws JobNotFoundException if the job could not be found * @throws ServiceUnavailableException if the job could not be retrieved */ @Operation(summary = "Retrieve the job", description = "Retrieve the job") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The job could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/jobs/{jobId}", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Scheduler.SchedulerAdministration') or hasAuthority('FUNCTION_Scheduler.JobAdministration')") public Job getJob( @Parameter(name = "jobId", description = "The ID for the job", required = true) @PathVariable String jobId) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException { return schedulerService.getJob(jobId); } /** * Retrieve the name of the job. * * @param jobId the ID for the job * @return the name of the job * @throws InvalidArgumentException if an argument is invalid * @throws JobNotFoundException if the job could not be found * @throws ServiceUnavailableException if the name of the job could not be retrieved */ @Operation(summary = "Retrieve the name of the job", description = "Retrieve the name of the job") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The job could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/jobs/{jobId}/name", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Scheduler.SchedulerAdministration') or hasAuthority('FUNCTION_Scheduler.JobAdministration')") public String getJobName( @Parameter(name = "jobId", description = "The ID for the job", required = true) @PathVariable String jobId) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException { return ApiUtil.quote(schedulerService.getJobName(jobId)); } /** * Retrieve the jobs. * * @return the jobs * @throws ServiceUnavailableException if the jobs could not be retrieved */ @Operation(summary = "Retrieve the jobs", description = "Retrieve the jobs") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping(value = "/jobs", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Scheduler.SchedulerAdministration') or hasAuthority('FUNCTION_Scheduler.JobAdministration')") public List<Job> getJobs() throws ServiceUnavailableException { return schedulerService.getJobs(); } /** * Update the job. * * @param jobId the ID for the job * @param job the job * @throws InvalidArgumentException if an argument is invalid * @throws JobNotFoundException if the job could not be found * @throws ServiceUnavailableException if the job could not be updated */ @Operation(summary = "Update the job", description = "Update the job") @ApiResponses( value = { @ApiResponse(responseCode = "204", description = "The job was updated successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The job could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/jobs/{jobId}", method = RequestMethod.PUT, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Scheduler.SchedulerAdministration') or hasAuthority('FUNCTION_Scheduler.JobAdministration')") public void updateJob( @Parameter(name = "jobId", description = "The ID for the job", required = true) @PathVariable String jobId, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The job to update", required = true) @RequestBody Job job) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(jobId)) { throw new InvalidArgumentException("jobId"); } if (job == null) { throw new InvalidArgumentException("job"); } if (!jobId.equals(job.getId())) { throw new InvalidArgumentException("job"); } schedulerService.updateJob(job); } }
0
java-sources/africa/absa/inception-scheduler-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler-api/1.2.0/africa/absa/inception/scheduler/SchedulerApiConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import io.swagger.v3.oas.models.info.Info; import org.springdoc.core.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * The <b>SchedulerApiConfiguration</b> class provides the Spring configuration for the Scheduler * API module. * * @author Marcus Portmann */ @Configuration public class SchedulerApiConfiguration { /** * Returns the grouped Open API for the Scheduler API. * * @return the grouped Open API for the Scheduler API */ @Bean public GroupedOpenApi schedulerOpenApi() { return GroupedOpenApi.builder() .group("scheduler") .packagesToScan("africa.absa.inception.scheduler") .addOpenApiCustomiser( openApi -> openApi.info(new Info().title("Scheduler API").version(Version.PROJECT_VERSION))) .build(); } }
0
java-sources/africa/absa/inception-scheduler-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler-api/1.2.0/africa/absa/inception/scheduler/Version.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; /** * The <b>Version</b> class. * * @author Marcus Portmann */ public final class Version { public static final String PROJECT_VERSION = "1.2.0"; }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/AuthenticationFailedException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * An <b>AuthenticationFailedException</b> is thrown to indicate that a security operation failed as * a result of an authentication failure. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/authentication-failed", title = "Authentication failed.", status = 401) public class AuthenticationFailedException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>AuthenticationFailedException</b> with the specified message. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. */ public AuthenticationFailedException(String message) { super(message); } /** * Constructs a new <b>AuthenticationFailedException</b> with the specified message and cause. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. * @param cause The cause saved for later retrieval by the <b>getCause()</b> method. (A * <b>null</b> value is permitted if the cause is nonexistent or unknown) */ public AuthenticationFailedException(String message, Throwable cause) { super(message, cause); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/AuthenticationToken.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; /** * The <b>AuthenticationToken</b> class. * * @author Marcus Portmann */ public class AuthenticationToken extends AbstractAuthenticationToken { /** The user details. */ private final UserDetails userDetails; /** * Constructs a new <b>AuthenticationToken</b>. * * @param userDetails the user details */ public AuthenticationToken(UserDetails userDetails) { super(userDetails.getAuthorities()); this.userDetails = userDetails; } @Override public Object getCredentials() { return null; } @Override public Object getPrincipal() { return userDetails; } @Override public boolean isAuthenticated() { return true; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/BackgroundPasswordResetExpiry.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * The <b>BackgroundPasswordResetExpiry</b> class implements the background password reset expiry. * * @author Marcus Portmann */ @Service public class BackgroundPasswordResetExpiry { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(BackgroundPasswordResetExpiry.class); /** The Password Reset Repository. */ private final PasswordResetRepository passwordResetRepository; /** The password reset expiry in seconds */ @Value("${inception.application.security.passwordResetExpiry:900}") private int passwordResetExpiry; /** * Constructs a new <b>BackgroundPasswordResetExpiry</b>. * * @param passwordResetRepository the Password Reset Repository */ public BackgroundPasswordResetExpiry(PasswordResetRepository passwordResetRepository) { this.passwordResetRepository = passwordResetRepository; } /** Expire the password resets. */ @Scheduled(cron = "0 * * * * *") @Transactional public void expirePasswordResets() { try { LocalDateTime requestedBefore = LocalDateTime.now(); requestedBefore = requestedBefore.minus(passwordResetExpiry, ChronoUnit.SECONDS); passwordResetRepository.expirePasswordResets(LocalDateTime.now(), requestedBefore); } catch (Throwable e) { logger.error("Failed to expire the password resets", e); } } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/Credential.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; /** * The <b>Credential</b> interface represents the abstract notion of a credential, which is a piece * of security information that can be used to confirm the identity of an entity, such as an * individual, a corporation, a login id, etc. * * @author Marcus Portmann */ @SuppressWarnings("unused") public interface Credential { /** * The equals method checks if the specified object is the same credential as this object. * * @param another the credential to compare with * @return true if the object passed in matches the credential represented by the implementation * of this interface */ @Override boolean equals(Object another); /** * The hashCode method returns an integer hash code to represent this credential. It can be used * to test for non-equality, or as an index key in a hash table. * * @return an integer hash code representing the credential */ @Override int hashCode(); /** * Returns a string representation of this credential. * * @return a string representation of this credential */ @Override String toString(); }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/DuplicateFunctionException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>DuplicateFunctionException</b> is thrown to indicate that a security operation failed as a * result of a duplicate function. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/duplicate-function", title = "A function with the specified code already exists.", status = 409) public class DuplicateFunctionException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>DuplicateFunctionException</b>. * * @param functionCode the code for the function */ public DuplicateFunctionException(String functionCode) { super("A function with the code (" + functionCode + ") already exists"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/DuplicateGroupException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>DuplicateGroupException</b> is thrown to indicate that a security operation failed as a * result of a duplicate group. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/duplicate-group", title = "A group with the specified name already exists.", status = 409) public class DuplicateGroupException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>DuplicateGroupException</b>. * * @param groupName the name of the group */ public DuplicateGroupException(String groupName) { super("A group with the name (" + groupName + ") already exists"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/DuplicateTenantException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; import java.util.UUID; /** * A <b>DuplicateTenantException</b> is thrown to indicate that a security operation failed as a * result of a duplicate tenant. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/duplicate-tenant", title = "A tenant with the specified ID or name already exists.", status = 409) public class DuplicateTenantException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>DuplicateTenantException</b>. * * @param name the name of the tenant */ public DuplicateTenantException(String name) { super("An tenant with the name (" + name + ") already exists"); } /** * Constructs a new <b>DuplicateTenantException</b>. * * @param tenantId the ID for the tenant */ public DuplicateTenantException(UUID tenantId) { super("An tenant with the ID (" + tenantId + ") already exists"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/DuplicateUserDirectoryException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; import java.util.UUID; /** * A <b>DuplicateUserDirectoryException</b> is thrown to indicate that a security operation failed * as a result of a duplicate user directory. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/duplicate-user-directory", title = "A user directory with the specified ID or name already exists.", status = 409) public class DuplicateUserDirectoryException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>DuplicateUserDirectoryException</b>. * * @param name the name of the user directory */ public DuplicateUserDirectoryException(String name) { super("A user directory with the name (" + name + ") already exists"); } /** * Constructs a new <b>DuplicateUserDirectoryException</b>. * * @param userDirectoryId the ID for the user directory */ public DuplicateUserDirectoryException(UUID userDirectoryId) { super("A user directory with the ID (" + userDirectoryId + ") already exists"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/DuplicateUserException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>DuplicateUserException</b> is thrown to indicate that a security operation failed as a * result of duplicate users. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/duplicate-user", title = "A user with the specified username already exists.", status = 409) public class DuplicateUserException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>DuplicateUserException</b>. * * @param username the username for the user */ public DuplicateUserException(String username) { super("A user with the username (" + username + ") already exists"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/ExistingGroupMembersException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>ExistingGroupMembersException</b> is thrown to indicate that a security operation failed as * a result of existing group members. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/existing-group-members", title = "The group could not be deleted as it is still associated with one or more members.", status = 409) public class ExistingGroupMembersException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>ExistingGroupMembersException</b>. * * @param groupName the name of the group */ public ExistingGroupMembersException(String groupName) { super( "The group (" + groupName + ") could not be deleted since it is still associated with 1 or more user(s)"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/ExistingPasswordException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * An <b>ExistingPasswordException</b> is thrown to indicate that a security operation failed as a * result of an existing password e.g. when attempting to change a user's password using a password * that forms part of the user's password history. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/existing-password", title = "The new password for the user has been used recently and is not valid.", status = 409) public class ExistingPasswordException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>ExistingPasswordException</b>. * * @param username the username for the user */ public ExistingPasswordException(String username) { super( "The new password for the user (" + username + ") has been used recently and is not valid"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/ExpiredPasswordException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>ExpiredPasswordException</b> is thrown to indicate that a security operation failed as a * result of an expired password. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/expired-password", title = "The password for the user has expired.", status = 409) public class ExpiredPasswordException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>ExpiredPasswordException</b>. * * @param username the username for the user */ public ExpiredPasswordException(String username) { super("The password for the user (" + username + ") has expired"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/Function.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>Function</b> class holds the information for a discrete unit of functionality for an * application that can be assigned to <b>Role</b>s. * * @author Marcus Portmann */ @Schema( description = "A discrete unit of functionality for an application that can be assigned to a role") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"code", "name", "description"}) @Entity @Table(schema = "security", name = "functions") @SuppressWarnings({"unused", "WeakerAccess"}) public class Function implements java.io.Serializable { private static final long serialVersionUID = 1000000; /** The code for the function. */ @Schema(description = "The code for the function", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "code", length = 100, nullable = false) private String code; /** The description for the function. */ @Schema(description = "The description for the function") @JsonProperty @Size(max = 100) @Column(name = "description", length = 100) private String description; /** The name of the function. */ @Schema(description = "The name of the function", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The roles the user is associated with. */ @JsonIgnore @ManyToMany(mappedBy = "functions") private Set<Role> roles = new HashSet<>(); /** Constructs a new <b>Function</b>. */ public Function() {} /** * Constructs a new <b>Function</b>. * * @param code the code for the function * @param name the name of the function * @param description the description for the function */ public Function(String code, String name, String description) { this.code = code; this.name = name; this.description = description; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } Function other = (Function) object; return Objects.equals(code, other.code); } /** * Returns the code for the function. * * @return the code for the function */ public String getCode() { return code; } /** * Returns the description for the function. * * @return the description for the function */ public String getDescription() { return description; } /** * Returns the name of the function. * * @return the name of the function */ public String getName() { return name; } /** * Returns the roles the user is associated with. * * @return the roles the user is associated with */ public Set<Role> getRoles() { return roles; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (code == null) ? 0 : code.hashCode(); } /** * Set the code for the function. * * @param code the code for the function */ public void setCode(String code) { this.code = code; } /** * Set the description for the function. * * @param description the description for the function */ public void setDescription(String description) { this.description = description; } /** * Set the name of the function. * * @param name the name of the function */ public void setName(String name) { this.name = name; } /** * Set the roles the user is associated with. * * @param roles the roles the user is associated with */ public void setRoles(Set<Role> roles) { this.roles = roles; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/FunctionNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>FunctionNotFoundException</b> is thrown to indicate that a security operation failed as a * result of a function that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/function-not-found", title = "The function could not be found.", status = 404) public class FunctionNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>FunctionNotFoundException</b>. * * @param functionCode the code for the function */ public FunctionNotFoundException(String functionCode) { super("A function with the code (" + functionCode + ") could not be found"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/FunctionRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>FunctionRepository</b> interface declares the repository for the <b>Function</b> domain * type. * * @author Marcus Portmann */ public interface FunctionRepository extends JpaRepository<Function, String> { @Modifying @Query("delete from Function f where f.code = :functionCode") void deleteById(@Param("functionCode") String functionCode); }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/Group.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.UUID; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>Group</b> class holds the information for a group. * * @author Marcus Portmann */ @Schema(description = "A group of users") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"userDirectoryId", "name", "description"}) @Entity @Table(schema = "security", name = "groups") @SuppressWarnings({"unused"}) public class Group implements Serializable { private static final long serialVersionUID = 1000000; /** The date and time the group was created. */ @JsonIgnore @Column(name = "created", nullable = false, updatable = false) private LocalDateTime created; /** The description for the group. */ @Schema(description = "The description for the group") @JsonProperty @Size(max = 100) @Column(name = "description", length = 100) private String description; /** The ID for the group. */ @JsonIgnore @Id @Column(name = "id", nullable = false) private UUID id; /** The name of the group. */ @Schema(description = "The name of the group", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The roles associated with the group. */ @JsonIgnore @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @JoinTable( schema = "security", name = "role_to_group_map", joinColumns = @JoinColumn(name = "group_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_code", referencedColumnName = "code")) private Set<Role> roles = new HashSet<>(); /** The date and time the group was last updated. */ @JsonIgnore @Column(name = "updated", insertable = false) private LocalDateTime updated; /** The ID for the user directory the group is associated with. */ @Schema( description = "The ID for the user directory the " + "group is associated with", required = true) @JsonProperty(required = true) @NotNull @Column(name = "user_directory_id", nullable = false) private UUID userDirectoryId; /** The users associated with the group. */ @JsonIgnore @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @JoinTable( schema = "security", name = "user_to_group_map", joinColumns = @JoinColumn(name = "group_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) private Set<User> users = new HashSet<>(); /** Constructs a new <b>Group</b>. */ public Group() {} /** * Constructs a new <b>Group</b>. * * @param name the name of the group */ public Group(String name) { this.name = name; } /** * Constructs a new <b>Group</b>. * * @param userDirectoryId the ID for the user directory the group is associated with * @param name the name of the group * @param description the description for the group */ public Group(UUID userDirectoryId, String name, String description) { this.userDirectoryId = userDirectoryId; this.name = name; this.description = description; } /** * Add the role to the group. * * @param role the role */ public void addRole(Role role) { roles.removeIf(existingRole -> Objects.equals(existingRole.getCode(), role.getCode())); roles.add(role); role.getGroups().add(this); } /** * Add the user to the group. * * @param user the user */ public void addUser(User user) { users.removeIf(existingUser -> Objects.equals(existingUser.getId(), user.getId())); users.add(user); user.getGroups().add(this); } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } Group other = (Group) object; return Objects.equals(id, other.id); } /** * Returns the date and time the group was created. * * @return the date and time the group was created */ public LocalDateTime getCreated() { return created; } /** * Returns the description for the group. * * @return the description for the group */ public String getDescription() { return description; } /** * Returns the ID for the group. * * @return the ID for the group */ public UUID getId() { return id; } /** * Returns the name of the group. * * @return the name of the group */ public String getName() { return name; } /** * Returns the roles associated with the group. * * @return the roles associated with the group */ public Set<Role> getRoles() { return roles; } /** * Returns the date and time the group was last updated. * * @return the date and time the group was last updated */ public LocalDateTime getUpdated() { return updated; } /** * Returns the ID for the user directory the group is associated with. * * @return the ID for the user directory the group is associated with */ public UUID getUserDirectoryId() { return userDirectoryId; } /** * Returns the users associated with the group. * * @return the users associated with the group */ public Set<User> getUsers() { return users; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } /** * Remove the role from the group. * * @param role the role */ public void removeRole(Role role) { roles.remove(role); role.getGroups().remove(this); } /** * Remove the user from the group. * * @param user the user */ public void removeUser(User user) { users.remove(user); user.getGroups().remove(this); } /** * Set the description for the group. * * @param description the description for the group */ public void setDescription(String description) { this.description = description; } /** * Set the ID for the group. * * @param id the ID for the group */ public void setId(UUID id) { this.id = id; } /** * Set the name of the group. * * @param name the name of the group */ public void setName(String name) { this.name = name; } /** * Set the roles associated with the group. * * @param roles the roles associated with the group */ public void setRoles(Set<Role> roles) { this.roles = roles; } /** * Set the ID for the user directory the group is associated with. * * @param userDirectoryId the ID for the user directory the group is associated with */ public void setUserDirectoryId(UUID userDirectoryId) { this.userDirectoryId = userDirectoryId; } /** * Set the users associated with the group. * * @param users the users associated with the group */ public void setUsers(Set<User> users) { this.users = users; } /** The Java Persistence callback method invoked before the entity is created in the database. */ @PrePersist protected void onCreate() { created = LocalDateTime.now(); } /** The Java Persistence callback method invoked before the entity is updated in the database. */ @PreUpdate protected void onUpdate() { updated = LocalDateTime.now(); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/GroupMember.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.UUID; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>GroupMember</b> class holds the information for a group member. * * @author Marcus Portmann */ @Schema(description = "A group member association") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"userDirectoryId", "groupName", "memberName", "memberType"}) @SuppressWarnings({"unused"}) public class GroupMember implements Serializable { private static final long serialVersionUID = 1000000; /** The name of the group. */ @Schema(description = "The name of the group", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) private String groupName; /** The name of the group member. */ @Schema(description = "The name of the group member", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) private String memberName; /** The group member type. */ @Schema(description = "The group member type", required = true) @JsonProperty(required = true) @NotNull private GroupMemberType memberType; /** The ID for the user directory the group is associated with. */ @Schema( description = "The ID for the user directory the " + "group is associated with", required = true) @JsonProperty(required = true) @NotNull private UUID userDirectoryId; /** Constructs a new <b>GroupMember</b>. */ public GroupMember() {} /** * Constructs a new <b>GroupMember</b>. * * @param userDirectoryId the ID for the user directory the group is associated with * @param groupName the name of the group * @param memberType the group member type * @param memberName the name of the group member */ public GroupMember( UUID userDirectoryId, String groupName, GroupMemberType memberType, String memberName) { this.userDirectoryId = userDirectoryId; this.groupName = groupName; this.memberType = memberType; this.memberName = memberName; } /** * Returns the name of the group. * * @return the name of the group */ public String getGroupName() { return groupName; } /** * Returns the name of the group member. * * @return the name of the group member */ public String getMemberName() { return memberName; } /** * Returns the group member type. * * @return the group member type */ public GroupMemberType getMemberType() { return memberType; } /** * Returns the ID for the user directory the group is associated with. * * @return the ID for the user directory the group is associated with */ public UUID getUserDirectoryId() { return userDirectoryId; } /** * Set the name of the group. * * @param groupName the name of the group */ public void setGroupName(String groupName) { this.groupName = groupName; } /** * Set the name of the group member. * * @param memberName the name of the group member */ public void setMemberName(String memberName) { this.memberName = memberName; } /** * Set the group member type. * * @param memberType the group member type */ public void setMemberType(GroupMemberType memberType) { this.memberType = memberType; } /** * Set the ID for the user directory the group is associated with. * * @param userDirectoryId the ID for the user directory the group is associated with */ public void setUserDirectoryId(UUID userDirectoryId) { this.userDirectoryId = userDirectoryId; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/GroupMemberNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>GroupMemberNotFoundException</b> is thrown to indicate that a security operation failed as a * result of a group member that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/group-member-not-found", title = "The group member could not be found.", status = 404) public class GroupMemberNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>GroupMemberNotFoundException</b>. * * @param memberType the group member type * @param memberName the group member name */ public GroupMemberNotFoundException(GroupMemberType memberType, String memberName) { super( "The group member with type (" + memberType.description() + ") and name (" + memberName + ") could not be found"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/GroupMemberType.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.v3.oas.annotations.media.Schema; /** * The <b>GroupMemberType</b> enumeration defines the possible group member types. * * @author Marcus Portmann */ @Schema(description = "The group member type") public enum GroupMemberType { /** User. */ USER("user", "User"), /** Group. */ GROUP("group", "Group"); private final String code; private final String description; GroupMemberType(String code, String description) { this.code = code; this.description = description; } /** * Returns the group member type given by the specified code value. * * @param code the code for the group member type * @return the group member type given by the specified code value */ @JsonCreator public static GroupMemberType fromCode(String code) { switch (code) { case "user": return GroupMemberType.USER; case "group": return GroupMemberType.GROUP; default: throw new RuntimeException( "Failed to determine the group member type with the invalid code (" + code + ")"); } } /** * Returns the code for the group member type. * * @return the code for the group member type */ @JsonValue public String code() { return code; } /** * Returns the description for the group member type. * * @return the description for the group member type */ public String description() { return description; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/GroupMemberTypeToStringConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.WritingConverter; import org.springframework.stereotype.Component; /** * The <b>GroupMemberTypeToStringConverter</b> class implements the Spring converter that converts a * <b>GroupMemberType</b> type into a <b>String</b> type. * * @author Marcus Portmann */ @Component @WritingConverter public class GroupMemberTypeToStringConverter implements Converter<GroupMemberType, String> { /** Constructs a new <b>GroupMemberTypeToStringConverter</b>. */ public GroupMemberTypeToStringConverter() {} @Override public String convert(GroupMemberType source) { return source.code(); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/GroupMembers.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.sorting.SortDirection; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.List; import java.util.UUID; /** * The <b>GroupMembers</b> class holds the results of a request to retrieve a list of group members. * * @author Marcus Portmann */ @Schema(description = "The results of a request to retrieve a list of group members") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "userDirectoryId", "groupName", "groupMembers", "total", "filter", "sortDirection", "pageIndex", "pageSize" }) @SuppressWarnings({"unused"}) public class GroupMembers implements Serializable { private static final long serialVersionUID = 1000000; /** The optional filter that was applied to the group members. */ @Schema(description = "The optional filter that was applied to the group members") @JsonProperty private String filter; /** The group members. */ @Schema(description = "The group members", required = true) @JsonProperty(required = true) private List<GroupMember> groupMembers; /** The name of the group the group members are associated with. */ @Schema( description = "The name of the group the group members are associated with", required = true) @JsonProperty(required = true) private String groupName; /** The optional page index. */ @Schema(description = "The optional page index") @JsonProperty private Integer pageIndex; /** The optional page size. */ @Schema(description = "The optional page size") @JsonProperty private Integer pageSize; /** The optional sort direction that was applied to the group members. */ @Schema(description = "The optional sort direction that was applied to the group members") @JsonProperty private SortDirection sortDirection; /** The total number of group members. */ @Schema(description = "The total number of group members", required = true) @JsonProperty(required = true) private long total; /** The ID for the user directory the group members are associated with. */ @Schema( description = "The ID for the user directory the group members are associated with", required = true) @JsonProperty(required = true) private UUID userDirectoryId; /** Constructs a new <b>GroupMembers</b>. */ public GroupMembers() {} /** * Constructs a new <b>GroupMembers</b>. * * @param userDirectoryId the ID for the user directory the group members are associated with * @param groupName the name of the group the group members are associated with * @param groupMembers the group members * @param total the total number of group members * @param filter the optional filter that was applied to the group members * @param sortDirection the optional sort direction that was applied to the group members * @param pageIndex the optional page index * @param pageSize the optional page size */ public GroupMembers( UUID userDirectoryId, String groupName, List<GroupMember> groupMembers, long total, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) { this.userDirectoryId = userDirectoryId; this.groupName = groupName; this.groupMembers = groupMembers; this.total = total; this.filter = filter; this.sortDirection = sortDirection; this.pageIndex = pageIndex; this.pageSize = pageSize; } /** * Returns the optional filter that was applied to the group members. * * @return the optional filter that was applied to the group members */ public String getFilter() { return filter; } /** * Returns the group members. * * @return the group members */ public List<GroupMember> getGroupMembers() { return groupMembers; } /** * Returns the name of the group the group members are associated with. * * @return the name of the group the group members are associated with */ public String getGroupName() { return groupName; } /** * Returns the optional page index. * * @return the optional page index */ public Integer getPageIndex() { return pageIndex; } /** * Returns the optional page size. * * @return the optional page size */ public Integer getPageSize() { return pageSize; } /** * Returns the optional sort direction that was applied to the group members. * * @return the optional sort direction that was applied to the group members */ public SortDirection getSortDirection() { return sortDirection; } /** * Returns the total number of group members. * * @return the total number of group members */ public Long getTotal() { return total; } /** * Returns the ID for the user directory the group members are associated with. * * @return the ID for the user directory the group members are associated with */ public UUID getUserDirectoryId() { return userDirectoryId; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/GroupNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>GroupNotFoundException</b> is thrown to indicate that a security operation failed as a * result of a group that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/group-not-found", title = "The group could not be found.", status = 404) public class GroupNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>GroupNotFoundException</b>. * * @param groupName the name of the group */ public GroupNotFoundException(String groupName) { super("The group (" + groupName + ") could not be found"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/GroupRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; /** * The <b>GroupRepository</b> interface declares the repository for the <b>Group</b> domain type. * * @author Marcus Portmann */ public interface GroupRepository extends JpaRepository<Group, UUID> { /** * Add the role to the group. * * @param groupId the ID for the group * @param roleCode the code for the role */ @Modifying @Query( value = "insert into security.role_to_group_map(role_code, group_id) " + "values (:roleCode, :groupId)", nativeQuery = true) void addRoleToGroup(@Param("groupId") UUID groupId, @Param("roleCode") String roleCode); /** * Add the user to the group. * * @param groupId the ID for the group * @param userId the ID for the user */ @Modifying @Query( value = "insert into security.user_to_group_map(user_id, group_id) " + "values (:userId, :groupId)", nativeQuery = true) void addUserToGroup(@Param("groupId") UUID groupId, @Param("userId") UUID userId); /** * Delete the group. * * @param groupId the ID for the group */ @Modifying @Query("delete from Group g where g.id = :groupId") void deleteById(@Param("groupId") UUID groupId); /** * Check whether the group exists. * * @param userDirectoryId the ID for the user directory * @param name the name of the group * @return <b>true</b> if the group exists or <b>false</b> otherwise */ @Transactional boolean existsByUserDirectoryIdAndNameIgnoreCase(UUID userDirectoryId, String name); /** * Retrieve the groups for the user directory. * * @param userDirectoryId the ID for the user directory * @return the groups for the user directory */ List<Group> findByUserDirectoryId(UUID userDirectoryId); /** * Retrieve the groups for the user directory. * * @param userDirectoryId the ID for the user directory * @param pageable the pagination information * @return the groups for the user directory */ Page<Group> findByUserDirectoryId(UUID userDirectoryId, Pageable pageable); /** * Retrieve the group. * * @param userDirectoryId the ID for the user directory * @param name the name of the group * @return an Optional containing the group or an empty Optional if the group could not be found */ Optional<Group> findByUserDirectoryIdAndNameIgnoreCase(UUID userDirectoryId, String name); /** * Retrieve the filtered groups for the user directory. * * @param userDirectoryId the ID for the user directory * @param filter the filter to apply to the groups * @param pageable the pagination information * @return the filtered groups for the user directory */ @Query( "select g from Group g where (lower(g.name) like lower(:filter)) and " + "g.userDirectoryId = :userDirectoryId") Page<Group> findFiltered( @Param("userDirectoryId") UUID userDirectoryId, @Param("filter") String filter, Pageable pageable); /** * Retrieve the filtered usernames for the group. * * @param userDirectoryId the ID for the user directory * @param groupId the ID for the group * @param filter the filter to apply to the usernames * @param pageable the pagination information * @return the filtered usernames for the group */ @Query( "select u.username from Group g join g.users as u where g.userDirectoryId = " + ":userDirectoryId and g.id = :groupId and (lower(u.username) like lower(:filter))") Page<String> getFilteredUsernamesForGroup( @Param("userDirectoryId") UUID userDirectoryId, @Param("groupId") UUID groupId, @Param("filter") String filter, Pageable pageable); /** * Retrieve the codes for the functions associated with the groups for the user directory. * * @param userDirectoryId the ID for the user directory * @param groupNames the group names * @return the function codes */ @Query( "select distinct f.code from Group g join g.roles as r join r.functions as f where g.userDirectoryId = :userDirectoryId and lower(g.name) in :groupNames") List<String> getFunctionCodesByUserDirectoryIdAndGroupNames( @Param("userDirectoryId") UUID userDirectoryId, @Param("groupNames") List<String> groupNames); /** * Retrieve the ID for the group with the specified name for the user directory. * * @param userDirectoryId the ID for the user directory * @param name the group name * @return an Optional containing the ID for the group with the specified name for the user * directory or an empty Optional if the group could not be found */ @Query( "select g.id from Group g where g.userDirectoryId = :userDirectoryId and " + "lower(g.name) like lower(:name)") Optional<UUID> getIdByUserDirectoryIdAndNameIgnoreCase( @Param("userDirectoryId") UUID userDirectoryId, @Param("name") String name); /** * Retrieve the group names for the user directory. * * @param userDirectoryId the ID for the user directory * @return the group names for the user directory */ @Query("select g.name from Group g where g.userDirectoryId = :userDirectoryId") List<String> getNamesByUserDirectoryId(@Param("userDirectoryId") UUID userDirectoryId); /** * Retrieve the number of users for the group. * * @param groupId the ID for the group * @return the number of users for the group */ @Query("select count(u.id) from Group g join g.users as u where g.id = :groupId") long getNumberOfUsersForGroup(@Param("groupId") UUID groupId); /** * Retrieve the role codes for the group. * * @param groupId the ID for the group * @return the role codes for the group */ @Query("select r.code from Group g join g.roles as r where g.id = :groupId") List<String> getRoleCodesByGroupId(@Param("groupId") UUID groupId); /** * Retrieve the codes for the roles associated with the groups for the user directory. * * @param userDirectoryId the ID for the group * @param groupNames the group names * @return the role codes */ @Query( "select distinct r.code from Group g join g.roles as r where g.userDirectoryId = :userDirectoryId and lower(g.name) in :groupNames") List<String> getRoleCodesByUserDirectoryIdAndGroupNames( @Param("userDirectoryId") UUID userDirectoryId, @Param("groupNames") List<String> groupNames); /** * Retrieve the usernames for the group. * * @param userDirectoryId the ID for the user directory * @param groupId the ID for the group * @return the usernames for the group */ @Query( "select u.username from Group g join g.users as u " + "where g.userDirectoryId = :userDirectoryId and g.id = :groupId") List<String> getUsernamesForGroup( @Param("userDirectoryId") UUID userDirectoryId, @Param("groupId") UUID groupId); /** * Retrieve the usernames for the group. * * @param userDirectoryId the ID for the user directory * @param groupId the ID for the group * @param pageable the pagination information * @return the usernames for the group */ @Query( "select u.username from Group g join g.users as u " + "where g.userDirectoryId = :userDirectoryId and g.id = :groupId") Page<String> getUsernamesForGroup( @Param("userDirectoryId") UUID userDirectoryId, @Param("groupId") UUID groupId, Pageable pageable); /** * Remove the role from the group. * * @param groupId the ID for the group * @param roleCode the code for the role * @return the number of impacted role to group mappings */ @Modifying @Query( value = "delete from security.role_to_group_map " + "where group_id=:groupId and role_code = :roleCode", nativeQuery = true) int removeRoleFromGroup(@Param("groupId") UUID groupId, @Param("roleCode") String roleCode); /** * Remove the user from the group. * * @param groupId the ID for the group * @param userId the ID for the user */ @Modifying @Query( value = "delete from security.user_to_group_map " + "where group_id=:groupId and user_id = :userId", nativeQuery = true) void removeUserFromGroup(@Param("groupId") UUID groupId, @Param("userId") UUID userId); /** * Check whether the role to group mapping exists. * * @param groupId the ID for the group * @param roleCode the code for the role * @return <b>true</b> if the role to group mapping exists or <b>false</b> otherwise */ @Query( value = "select (count(role_code) > 0) from security.role_to_group_map where " + "role_code = :roleCode and group_id = :groupId", nativeQuery = true) boolean roleToGroupMappingExists( @Param("groupId") UUID groupId, @Param("roleCode") String roleCode); }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/GroupRole.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.UUID; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>GroupRole</b> class holds the information for a group role. * * @author Marcus Portmann */ @Schema(description = "A group role association") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"userDirectoryId", "groupName", "roleCode"}) @SuppressWarnings({"unused"}) public class GroupRole implements Serializable { private static final long serialVersionUID = 1000000; /** The name of the group. */ @Schema(description = "The name of the group", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) private String groupName; /** The code for the role. */ @Schema(description = "The code for the role", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) private String roleCode; /** The ID for the user directory the group is associated with. */ @Schema( description = "The ID for the user directory the " + "group is associated with", required = true) @JsonProperty(required = true) @NotNull private UUID userDirectoryId; /** Constructs a new <b>GroupRole</b>. */ public GroupRole() {} /** * Constructs a new <b>GroupRole</b>. * * @param userDirectoryId the ID for the user directory the group is associated with * @param groupName the name of the group * @param roleCode the code for the role */ public GroupRole(UUID userDirectoryId, String groupName, String roleCode) { this.userDirectoryId = userDirectoryId; this.groupName = groupName; this.roleCode = roleCode; } /** * Returns the name of the group. * * @return the name of the group */ public String getGroupName() { return groupName; } /** * Returns the code for the role. * * @return the code for the role */ public String getRoleCode() { return roleCode; } /** * Returns the ID for the user directory the group is associated with. * * @return the ID for the user directory the group is associated with */ public UUID getUserDirectoryId() { return userDirectoryId; } /** * Set the name of the group. * * @param groupName the name of the group */ public void setGroupName(String groupName) { this.groupName = groupName; } /** * Set the code for the role. * * @param roleCode the code for the role */ public void setRoleCode(String roleCode) { this.roleCode = roleCode; } /** * Set the ID for the user directory the group is associated with. * * @param userDirectoryId the ID for the user directory the group is associated with */ public void setUserDirectoryId(UUID userDirectoryId) { this.userDirectoryId = userDirectoryId; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/GroupRoleNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>GroupRoleNotFoundException</b> is thrown to indicate that a security operation failed as a * result of a group role that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/group-role-not-found", title = "The group role could not be found.", status = 404) public class GroupRoleNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>GroupRoleNotFoundException</b>. * * @param roleCode the code for the role */ public GroupRoleNotFoundException(String roleCode) { super("The group role with code (" + roleCode + ") could not be found"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/Groups.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.sorting.SortDirection; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.List; import java.util.UUID; /** * The <b>Groups</b> class holds the results of a request to retrieve a list of groups. * * @author Marcus Portmann */ @Schema(description = "The results of a request to retrieve a list of groups") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "userDirectoryId", "groups", "total", "filter", "sortDirection", "pageIndex", "pageSize" }) @SuppressWarnings({"unused"}) public class Groups implements Serializable { private static final long serialVersionUID = 1000000; /** The optional filter that was applied to the groups. */ @Schema(description = "The optional filter that was applied to the groups") @JsonProperty private String filter; /** The groups. */ @Schema(description = "The groups", required = true) @JsonProperty(required = true) private List<Group> groups; /** The optional page index. */ @Schema(description = "The optional page index") @JsonProperty private Integer pageIndex; /** The optional page size. */ @Schema(description = "The optional page size") @JsonProperty private Integer pageSize; /** The optional sort direction that was applied to the groups. */ @Schema(description = "The optional sort direction that was applied to the groups") @JsonProperty private SortDirection sortDirection; /** The total number of groups. */ @Schema(description = "The total number of groups", required = true) @JsonProperty(required = true) private long total; /** The ID for the user directory the groups are associated with. */ @Schema( description = "The ID for the user directory the groups are associated with", required = true) @JsonProperty(required = true) private UUID userDirectoryId; /** Constructs a new <b>Groups</b>. */ public Groups() {} /** * Constructs a new <b>Groups</b>. * * @param userDirectoryId the ID for the user directory the groups are associated with * @param groups the groups * @param total the total number of groups * @param filter the optional filter that was applied to the groups * @param sortDirection the optional sort direction that was applied to the groups * @param pageIndex the optional page index * @param pageSize the optional page size */ public Groups( UUID userDirectoryId, List<Group> groups, long total, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) { this.userDirectoryId = userDirectoryId; this.groups = groups; this.total = total; this.filter = filter; this.sortDirection = sortDirection; this.pageIndex = pageIndex; this.pageSize = pageSize; } /** * Returns the optional filter that was applied to the groups. * * @return the optional filter that was applied to the groups */ public String getFilter() { return filter; } /** * Returns the groups. * * @return the groups */ public List<Group> getGroups() { return groups; } /** * Returns the optional page index. * * @return the optional page index */ public Integer getPageIndex() { return pageIndex; } /** * Returns the optional page size. * * @return the optional page size */ public Integer getPageSize() { return pageSize; } /** * Returns the optional sort direction that was applied to the groups. * * @return the optional sort direction that was applied to the groups */ public SortDirection getSortDirection() { return sortDirection; } /** * Returns the total number of groups. * * @return the total number of groups */ public Long getTotal() { return total; } /** * Returns the ID for the user directory the groups are associated with. * * @return the ID for the user directory the groups are associated with */ public UUID getUserDirectoryId() { return userDirectoryId; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/ISecurityService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import africa.absa.inception.core.sorting.SortDirection; import java.util.List; import java.util.Optional; import java.util.UUID; /** * The <b>ISecurityService</b> interface defines the functionality provided by a Security Service * implementation, which manages the security related information for an application. * * @author Marcus Portmann */ public interface ISecurityService { /** The ID for the Administrators group. */ UUID ADMINISTRATORS_GROUP_ID = UUID.fromString("00000000-0000-0000-0000-000000000000"); /** The name of the Administrators group. */ String ADMINISTRATORS_GROUP_NAME = "Administrators"; /** The code for the Administrator role. */ String ADMINISTRATOR_ROLE_CODE = "Administrator"; /** The username for the Administrator user. */ String ADMINISTRATOR_USERNAME = "administrator"; /** The ID for the default tenant. */ UUID DEFAULT_TENANT_ID = UUID.fromString("00000000-0000-0000-0000-000000000000"); /** The ID for the default internal user directory. */ UUID DEFAULT_USER_DIRECTORY_ID = UUID.fromString("00000000-0000-0000-0000-000000000000"); /** The code for the internal user directory type. */ String INTERNAL_USER_DIRECTORY_TYPE = "InternalUserDirectory"; /** The code for the LDAP user directory type. */ String LDAP_USER_DIRECTORY_TYPE = "LDAPUserDirectory"; /** The code for the Password Resetter role. */ String PASSWORD_RESETTER_ROLE_CODE = "PasswordResetter"; /** The code for the Tenant Administrator role. */ String TENANT_ADMINISTRATOR_ROLE_CODE = "TenantAdministrator"; /** * Add the group member to the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param memberType the group member type * @param memberName the group member name * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the group member could not be added to the group */ void addMemberToGroup( UUID userDirectoryId, String groupName, GroupMemberType memberType, String memberName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Add the role to the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param roleCode the code for the role * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws RoleNotFoundException if the role could not be found * @throws ServiceUnavailableException if the role could not be added to the group */ void addRoleToGroup(UUID userDirectoryId, String groupName, String roleCode) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, RoleNotFoundException, ServiceUnavailableException; /** * Add the user directory to the tenant. * * @param tenantId the ID for the tenant * @param userDirectoryId the ID for the user directory * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the user directory could not be added to the tenant */ void addUserDirectoryToTenant(UUID tenantId, UUID userDirectoryId) throws InvalidArgumentException, TenantNotFoundException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Add the user to the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param username the username for the user * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be added to the group */ void addUserToGroup(UUID userDirectoryId, String groupName, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Administratively change the password for the user. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @param newPassword the new password * @param expirePassword expire the user's password * @param lockUser lock the user * @param resetPasswordHistory reset the user's password history * @param reason the reason for changing the password * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the password could not be administratively changed */ void adminChangePassword( UUID userDirectoryId, String username, String newPassword, boolean expirePassword, boolean lockUser, boolean resetPasswordHistory, PasswordChangeReason reason) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Authenticate the user. * * @param username the username for the user * @param password the password being used to authenticate * @return the ID for the user directory * @throws InvalidArgumentException if an argument is invalid * @throws AuthenticationFailedException if the authentication failed * @throws UserLockedException if the user is locked * @throws ExpiredPasswordException if the password for the user has expired * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be authenticated */ UUID authenticate(String username, String password) throws InvalidArgumentException, AuthenticationFailedException, UserLockedException, ExpiredPasswordException, UserNotFoundException, ServiceUnavailableException; /** * Change the password for the user. * * @param username the username for the user * @param password the password for the user that is used to authorise the operation * @param newPassword the new password * @return the ID for the user directory * @throws InvalidArgumentException if an argument is invalid * @throws AuthenticationFailedException if the authentication failed * @throws UserLockedException if the user is locked * @throws ExistingPasswordException if the user has previously used the new password * @throws ServiceUnavailableException if the password could not be changed */ UUID changePassword(String username, String password, String newPassword) throws InvalidArgumentException, AuthenticationFailedException, UserLockedException, ExistingPasswordException, ServiceUnavailableException; /** * Create the new function. * * @param function the function * @throws InvalidArgumentException if an argument is invalid * @throws DuplicateFunctionException if the function already exists * @throws ServiceUnavailableException if the function could not be created */ void createFunction(Function function) throws InvalidArgumentException, DuplicateFunctionException, ServiceUnavailableException; /** * Create the new group. * * @param group the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws DuplicateGroupException if the group already exists * @throws ServiceUnavailableException if the group could not be created */ void createGroup(Group group) throws InvalidArgumentException, UserDirectoryNotFoundException, DuplicateGroupException, ServiceUnavailableException; /** * Create the new tenant. * * @param tenant the tenant * @param createUserDirectory should a new internal user directory be created for the tenant * @return an Optional containing the new internal user directory that was created for the tenant * or an empty Optional if no user directory was created * @throws InvalidArgumentException if an argument is invalid * @throws DuplicateTenantException if the tenant already exists * @throws ServiceUnavailableException if the tenant could not be created */ Optional<UserDirectory> createTenant(Tenant tenant, boolean createUserDirectory) throws InvalidArgumentException, DuplicateTenantException, ServiceUnavailableException; /** * Create the new user. * * @param user the user * @param expiredPassword create the user with its password expired * @param userLocked create the user locked * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws DuplicateUserException if the user already exists * @throws ServiceUnavailableException if the user could not be created */ void createUser(User user, boolean expiredPassword, boolean userLocked) throws InvalidArgumentException, UserDirectoryNotFoundException, DuplicateUserException, ServiceUnavailableException; /** * Create the new user directory. * * @param userDirectory the user directory * @throws InvalidArgumentException if an argument is invalid * @throws DuplicateUserDirectoryException if the user directory already exists * @throws ServiceUnavailableException if the user directory could not be created */ void createUserDirectory(UserDirectory userDirectory) throws InvalidArgumentException, DuplicateUserDirectoryException, ServiceUnavailableException; /** * Delete the function. * * @param functionCode the code for the function * @throws InvalidArgumentException if an argument is invalid * @throws FunctionNotFoundException if the function could not be found * @throws ServiceUnavailableException if the function could not be created */ void deleteFunction(String functionCode) throws InvalidArgumentException, FunctionNotFoundException, ServiceUnavailableException; /** * Delete the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ExistingGroupMembersException if the group has existing members * @throws ServiceUnavailableException if the group could not be deleted */ void deleteGroup(UUID userDirectoryId, String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ExistingGroupMembersException, ServiceUnavailableException; /** * Delete the tenant. * * @param tenantId the ID for the tenant * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the tenant could not be deleted */ void deleteTenant(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException; /** * Delete the user. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be deleted */ void deleteUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Delete the user directory. * * @param userDirectoryId the ID for the user directory * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the user directory could not be deleted */ void deleteUserDirectory(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Retrieve the users matching the user attribute criteria. * * @param userDirectoryId the ID for the user directory * @param userAttributes the user attribute criteria used to select the users * @return the users whose attributes match the user attribute criteria * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws InvalidAttributeException if an attribute is invalid * @throws ServiceUnavailableException if the users matching the user attribute criteria could not * be found */ List<User> findUsers(UUID userDirectoryId, List<UserAttribute> userAttributes) throws InvalidArgumentException, UserDirectoryNotFoundException, InvalidAttributeException, ServiceUnavailableException; /** * Retrieve the function. * * @param functionCode the code for the function * @return the function * @throws InvalidArgumentException if an argument is invalid * @throws FunctionNotFoundException if the function could not be found * @throws ServiceUnavailableException if the function could not be retrieved */ Function getFunction(String functionCode) throws InvalidArgumentException, FunctionNotFoundException, ServiceUnavailableException; /** * Retrieve the function codes for the user. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @return the function codes for the user * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the function codes could not be retrieved for the user */ List<String> getFunctionCodesForUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Retrieve all the functions. * * @return the functions * @throws ServiceUnavailableException if the functions could not be retrieved */ List<Function> getFunctions() throws ServiceUnavailableException; /** * Retrieve the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @return the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the group could not be retrieved */ Group getGroup(UUID userDirectoryId, String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException; /** * Retrieve all the group names. * * @param userDirectoryId the ID for the user directory * @return the group names * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the group names could not be retrieved */ List<String> getGroupNames(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Retrieve the names of the groups the user is a member of. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @return the names of the groups the user is a member of * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the names of the groups the user is a member of could * not be retrieved */ List<String> getGroupNamesForUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Retrieve all the groups. * * @param userDirectoryId the ID for the user directory * @return the groups * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the groups could not be retrieved */ List<Group> getGroups(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Retrieve the groups. * * @param userDirectoryId the ID for the user directory * @param filter the optional filter to apply to the groups * @param sortDirection the optional sort direction to apply to the groups * @param pageIndex the optional page index * @param pageSize the optional page size * @return the groups * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the groups could not be retrieved */ Groups getGroups( UUID userDirectoryId, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Retrieve the groups the user is a member of. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @return the groups the user is a member of * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the groups the user is a member of could not be * retrieved */ List<Group> getGroupsForUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Retrieve the group members for the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @return the group members for the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the group members could not be retrieved for the group */ List<GroupMember> getMembersForGroup(UUID userDirectoryId, String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException; /** * Retrieve the group members for the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param filter the optional filter to apply to the group members * @param sortDirection the optional sort direction to apply to the group members * @param pageIndex the optional page index * @param pageSize the optional page size * @return the group members for the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the group members could not be retrieved for the group */ GroupMembers getMembersForGroup( UUID userDirectoryId, String groupName, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException; /** * Retrieve the codes for the roles that have been assigned to the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @return the codes for the roles that have been assigned to the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the codes for the roles assigned to the group could not * be retrieved */ List<String> getRoleCodesForGroup(UUID userDirectoryId, String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException; /** * Retrieve the codes for the roles that have been assigned to the user. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @return the codes for the roles that have been assigned to the user * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the codes for the roles assigned to the user could not * be retrieved */ List<String> getRoleCodesForUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Retrieve all the roles. * * @return the roles * @throws ServiceUnavailableException if the roles could not be retrieved */ List<Role> getRoles() throws ServiceUnavailableException; /** * Retrieve the roles that have been assigned to the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @return the roles that have been assigned to the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the codes for the roles assigned to the group could not * be retrieved */ List<GroupRole> getRolesForGroup(UUID userDirectoryId, String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException; /** * Retrieve the tenant. * * @param tenantId the ID for the tenant * @return the tenant * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the tenant could not be retrieved */ Tenant getTenant(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException; /** * Retrieve the IDs for the tenants the user directory is associated with. * * @param userDirectoryId the ID for the user directory * @return the IDs for the tenants the user directory is associated with * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the tenant IDs could not be retrieved for the user * directory */ List<UUID> getTenantIdsForUserDirectory(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Retrieve the name of the tenant. * * @param tenantId the ID for the tenant * @return the name of the tenant * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the name of the tenant could not be retrieved */ String getTenantName(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException; /** * Retrieve the tenants. * * @return the tenants * @throws ServiceUnavailableException if the tenants could not be retrieved */ List<Tenant> getTenants() throws ServiceUnavailableException; /** * Retrieve the tenants. * * @param filter the optional filter to apply to the tenants * @param sortDirection the optional sort direction to apply to the tenants * @param pageIndex the optional page index * @param pageSize the optional page size * @return the tenants * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the tenants could not be retrieved */ Tenants getTenants( String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, ServiceUnavailableException; /** * Retrieve the tenants the user directory is associated with. * * @param userDirectoryId the ID for the user directory * @return the tenants the user directory is associated with * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the tenants could not be retrieved for the user * directory */ List<Tenant> getTenantsForUserDirectory(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Retrieve the user. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @return the user * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be retrieved */ User getUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Retrieve the user directories. * * @return the user directories * @throws ServiceUnavailableException if the user directories could not be retrieved */ List<UserDirectory> getUserDirectories() throws ServiceUnavailableException; /** * Retrieve the user directories. * * @param filter the optional filter to apply to the user directories * @param sortDirection the optional sort direction to apply to the user directories * @param pageIndex the optional page index * @param pageSize the optional page size * @return the user directories * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the user directories could not be retrieved */ UserDirectories getUserDirectories( String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, ServiceUnavailableException; /** * Retrieve the user directories the tenant is associated with. * * @param tenantId the ID for the tenant * @return the user directories the tenant is associated with * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the user directories could not be retrieved for the * tenant */ List<UserDirectory> getUserDirectoriesForTenant(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException; /** * Retrieve the user directory. * * @param userDirectoryId the ID for the user directory * @return the user directory * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the user directory could not be retrieved */ UserDirectory getUserDirectory(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Retrieve the capabilities the user directory supports. * * @param userDirectoryId the ID for the user directory * @return the capabilities the user directory supports * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the user directory capabilities could not be retrieved */ UserDirectoryCapabilities getUserDirectoryCapabilities(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Retrieve the ID for the user directory that the user with the specified username is associated * with. * * @param username the username for the user * @return an Optional containing the ID for the user directory that the user with the specified * username is associated with or an empty Optional if the user cannot be found * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the user directory ID could not be retrieved for the * user */ Optional<UUID> getUserDirectoryIdForUser(String username) throws InvalidArgumentException, ServiceUnavailableException; /** * Retrieve the IDs for the user directories the tenant is associated with. * * @param tenantId the ID for the tenant * @return the IDs for the user directories the tenant is associated with * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the user directory IDs could not be retrieved for the * tenant */ List<UUID> getUserDirectoryIdsForTenant(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException; /** * Retrieve the IDs for the user directories the user is associated with. Every user is associated * with a user directory, which is in turn associated with one or more tenants, which are in turn * associated with one or more user directories. The user is therefore associated indirectly with * all these user directories. * * @param username the username for the user * @return the IDs for the user directories the user is associated with * @throws InvalidArgumentException if an argument is invalid * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user directory IDs could not be retrieved for the * user */ List<UUID> getUserDirectoryIdsForUser(String username) throws InvalidArgumentException, UserNotFoundException, ServiceUnavailableException; /** * Retrieve the name of the user directory. * * @param userDirectoryId the ID for the user directory * @return the name of the user directory * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the name of the user directory could not be retrieved */ String getUserDirectoryName(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Retrieve the summaries for the user directories. * * @param filter the optional filter to apply to the user directories * @param sortDirection the optional sort direction to apply to the user directories * @param pageIndex the optional page index * @param pageSize the optional page size * @return the summaries for the user directories * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the user directory summaries could not be retrieved */ UserDirectorySummaries getUserDirectorySummaries( String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, ServiceUnavailableException; /** * Retrieve the summaries for the user directories the tenant is associated with. * * @param tenantId the ID for the tenant * @return the summaries for the user directories the tenant is associated with * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the user directory summaries could not be retrieved for * the tenant */ List<UserDirectorySummary> getUserDirectorySummariesForTenant(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException; /** * Retrieve the user directory type for the user directory. * * @param userDirectoryId the ID for the user directory * @return the user directory type for the user directory * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserDirectoryTypeNotFoundException if the user directory type could not be found * @throws ServiceUnavailableException if the user directory type could not be retrieved for the * user directory */ UserDirectoryType getUserDirectoryTypeForUserDirectory(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, UserDirectoryTypeNotFoundException, ServiceUnavailableException; /** * Retrieve the user directory types. * * @return the user directory types * @throws ServiceUnavailableException if the user directory types could not be retrieved */ List<UserDirectoryType> getUserDirectoryTypes() throws ServiceUnavailableException; /** * Retrieve the name of the user. * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @return the name of the user * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the name of the user could not be retrieved */ String getUserName(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Retrieve all the users. * * @param userDirectoryId the ID for the user directory * @return the users * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the users could not be retrieved */ List<User> getUsers(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Retrieve the users. * * @param userDirectoryId the ID for the user directory * @param filter the optional filter to apply to the users * @param sortBy the optional method used to sort the users e.g. by name * @param sortDirection the optional sort direction to apply to the users * @param pageIndex the optional page index * @param pageSize the optional page size * @return the users * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the users could not be retrieved */ Users getUsers( UUID userDirectoryId, String filter, UserSortBy sortBy, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Initiate the password reset process for the user. * * @param username the username for the user * @param resetPasswordUrl the reset password URL * @param sendEmail should the password reset e-mail be sent to the user * @throws InvalidArgumentException if an argument is invalid * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the password reset could not be initiated */ void initiatePasswordReset(String username, String resetPasswordUrl, boolean sendEmail) throws InvalidArgumentException, UserNotFoundException, ServiceUnavailableException; /** * Initiate the password reset process for the user. * * @param username the username for the user * @param resetPasswordUrl the reset password URL * @param sendEmail should the password reset e-mail be sent to the user * @param securityCode the pre-generated security code to use * @throws InvalidArgumentException if an argument is invalid * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the password reset could not be initiated */ void initiatePasswordReset( String username, String resetPasswordUrl, boolean sendEmail, String securityCode) throws InvalidArgumentException, UserNotFoundException, ServiceUnavailableException; /** * Does the user with the specified username exist? * * @param userDirectoryId the ID for the user directory * @param username the username for the user * @return <b>true</b> if a user with specified username exists or <b>false</b> otherwise * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the check for the existing user failed */ boolean isExistingUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; /** * Is the user in the group? * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param username the username for the user * @return <b>true</b> if the user is a member of the group or <b>false</b> otherwise * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the check to confirm if the user is a member of the * group failed */ boolean isUserInGroup(UUID userDirectoryId, String groupName, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, GroupNotFoundException, ServiceUnavailableException; /** * Reload the user directories. * * @throws ServiceUnavailableException if the user directories could not be realoded */ void reloadUserDirectories() throws ServiceUnavailableException; /** * Remove the group member from the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param memberType the group member type * @param memberName the group member name * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws GroupMemberNotFoundException if the group member could not be found * @throws ServiceUnavailableException if the group member could not be removed from the group */ void removeMemberFromGroup( UUID userDirectoryId, String groupName, GroupMemberType memberType, String memberName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, GroupMemberNotFoundException, ServiceUnavailableException; /** * Remove the role from the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param roleCode the code for the role * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws GroupRoleNotFoundException if the group role could not be found * @throws ServiceUnavailableException if the role could not be removed from the group */ void removeRoleFromGroup(UUID userDirectoryId, String groupName, String roleCode) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, GroupRoleNotFoundException, ServiceUnavailableException; /** * Remove the user directory from the tenant. * * @param tenantId the ID for the tenant * @param userDirectoryId the ID for the user directory * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws TenantUserDirectoryNotFoundException if the tenant user directory could not be found * @throws ServiceUnavailableException if the user directory could not be removed from the tenant */ void removeUserDirectoryFromTenant(UUID tenantId, UUID userDirectoryId) throws InvalidArgumentException, TenantNotFoundException, TenantUserDirectoryNotFoundException, ServiceUnavailableException; /** * Remove the user from the group. * * @param userDirectoryId the ID for the user directory * @param groupName the name of the group * @param username the username for the user * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be removed from the group */ void removeUserFromGroup(UUID userDirectoryId, String groupName, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Reset the password for the user. * * @param username the username for the user * @param newPassword the new password * @param securityCode the security code * @throws InvalidArgumentException if an argument is invalid * @throws InvalidSecurityCodeException if the security code is invalid * @throws UserLockedException if the user is locked * @throws ExistingPasswordException if the user has previously used the new password * @throws ServiceUnavailableException if the password for the user could not be reset */ void resetPassword(String username, String newPassword, String securityCode) throws InvalidArgumentException, InvalidSecurityCodeException, UserLockedException, ExistingPasswordException, ServiceUnavailableException; /** * Update the function. * * @param function the function * @throws InvalidArgumentException if an argument is invalid * @throws FunctionNotFoundException if the function could not be found * @throws ServiceUnavailableException if the function could not be updated */ void updateFunction(Function function) throws InvalidArgumentException, FunctionNotFoundException, ServiceUnavailableException; /** * Update the group. * * @param group the group * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the group could not be updated */ void updateGroup(Group group) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException; /** * Update the tenant. * * @param tenant the tenant * @throws InvalidArgumentException if an argument is invalid * @throws TenantNotFoundException if the tenant could not be found * @throws ServiceUnavailableException if the tenant could not be updated */ void updateTenant(Tenant tenant) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException; /** * Update the user. * * @param user the user * @param expirePassword expire the user's password as part of the update * @param lockUser lock the user as part of the update * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be updated */ void updateUser(User user, boolean expirePassword, boolean lockUser) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Update the user directory. * * @param userDirectory the user directory * @throws InvalidArgumentException if an argument is invalid * @throws UserDirectoryNotFoundException if the user directory could not be found * @throws ServiceUnavailableException if the user directory could not be updated */ void updateUserDirectory(UserDirectory userDirectory) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException; }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/IUserDirectory.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.ServiceUnavailableException; import africa.absa.inception.core.sorting.SortDirection; import java.util.List; /** * The <b>IUserDirectoryProvider</b> interface defines the functionality provided by a user * directory, which manages users and groups. * * @author Marcus Portmann */ interface IUserDirectory { /** * Add the group member to the group. * * @param groupName the name of the group * @param memberType the group member type * @param memberName the group member name * @throws GroupNotFoundException if the group could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the group member could not be added to the group */ void addMemberToGroup(String groupName, GroupMemberType memberType, String memberName) throws GroupNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Add the role to the group. * * @param groupName the name of the group * @param roleCode the code for the role * @throws GroupNotFoundException if the group could not be found * @throws RoleNotFoundException if the role could not be found * @throws ServiceUnavailableException if the role could not be added to the group */ void addRoleToGroup(String groupName, String roleCode) throws GroupNotFoundException, RoleNotFoundException, ServiceUnavailableException; /** * Add the user to the group. * * @param groupName the name of the group * @param username the username for the user * @throws GroupNotFoundException if the group could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be added to the group */ void addUserToGroup(String groupName, String username) throws GroupNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Administratively change the password for the user. * * @param username the username for the user * @param newPassword the new password * @param expirePassword expire the user's password * @param lockUser lock the user * @param resetPasswordHistory reset the user's password history * @param reason the reason for changing the password * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the password could not be administratively changed */ void adminChangePassword( String username, String newPassword, boolean expirePassword, boolean lockUser, boolean resetPasswordHistory, PasswordChangeReason reason) throws UserNotFoundException, ServiceUnavailableException; /** * Authenticate the user. * * @param username the username for the user * @param password the password being used to authenticate * @throws AuthenticationFailedException if the authentication failed * @throws UserLockedException if the user is locked * @throws ExpiredPasswordException if the password for the user has expired * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be authenticated */ void authenticate(String username, String password) throws AuthenticationFailedException, UserLockedException, ExpiredPasswordException, UserNotFoundException, ServiceUnavailableException; /** * Change the password for the user. * * @param username the username for the user * @param password the password for the user that is used to authorise the operation * @param newPassword the new password * @throws AuthenticationFailedException if the authentication failed * @throws UserLockedException if the user is locked * @throws ExistingPasswordException if the user has previously used the new password * @throws ServiceUnavailableException if the password could not be changed */ void changePassword(String username, String password, String newPassword) throws AuthenticationFailedException, UserLockedException, ExistingPasswordException, ServiceUnavailableException; /** * Create the new group. * * @param group the group * @throws DuplicateGroupException if the group already exists * @throws ServiceUnavailableException if the group could not be created */ void createGroup(Group group) throws DuplicateGroupException, ServiceUnavailableException; /** * Create the new user. * * @param user the user * @param expiredPassword create the user with its password expired * @param userLocked create the user locked * @throws DuplicateUserException if the user already exists * @throws ServiceUnavailableException if the user could not be created */ void createUser(User user, boolean expiredPassword, boolean userLocked) throws DuplicateUserException, ServiceUnavailableException; /** * Delete the group. * * @param groupName the name of the group * @throws GroupNotFoundException if the group could not be found * @throws ExistingGroupMembersException if the group has existing members * @throws ServiceUnavailableException if the group could not be deleted */ void deleteGroup(String groupName) throws GroupNotFoundException, ExistingGroupMembersException, ServiceUnavailableException; /** * Delete the user. * * @param username the username for the user * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be deleted */ void deleteUser(String username) throws UserNotFoundException, ServiceUnavailableException; /** * Retrieve the users matching the user attribute criteria. * * @param userAttributes the user attribute criteria used to select the users * @return the users whose attributes match the user attribute criteria * @throws InvalidAttributeException if an attribute is invalid * @throws ServiceUnavailableException if the users matching the user attribute criteria could not * be found */ List<User> findUsers(List<UserAttribute> userAttributes) throws InvalidAttributeException, ServiceUnavailableException; /** * Retrieve the capabilities the user directory supports. * * @return the capabilities the user directory supports * @throws ServiceUnavailableException if the user directory capabilities could not be retrieved */ UserDirectoryCapabilities getCapabilities() throws ServiceUnavailableException; /** * Retrieve the function codes for the user. * * @param username the username for the user * @return the function codes for the user * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the function codes could not be retrieved for the user */ List<String> getFunctionCodesForUser(String username) throws UserNotFoundException, ServiceUnavailableException; /** * Retrieve the group. * * @param groupName the name of the group * @return the group * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the group could not be retrieved */ Group getGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException; /** * Retrieve all the group names. * * @return the group names * @throws ServiceUnavailableException if the group names could not be retrieved */ List<String> getGroupNames() throws ServiceUnavailableException; /** * Retrieve the names of the groups the user is a member of. * * @param username the username for the user * @return the names of the groups the user is a member of * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the names of the groups the user is a member of could * not be retrieved */ List<String> getGroupNamesForUser(String username) throws UserNotFoundException, ServiceUnavailableException; /** * Retrieve all the groups. * * @return the groups * @throws ServiceUnavailableException if the groups could not be retrieved */ List<Group> getGroups() throws ServiceUnavailableException; /** * Retrieve the groups. * * @param filter the optional filter to apply to the groups * @param sortDirection the optional sort direction to apply to the groups * @param pageIndex the optional page index * @param pageSize the optional page size * @return the groups * @throws ServiceUnavailableException if the groups could not be retrieved */ Groups getGroups(String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws ServiceUnavailableException; /** * Retrieve the groups the user is a member of. * * @param username the username for the user * @return the groups the user is a member of * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the groups the user is a member of could not be * retrieved */ List<Group> getGroupsForUser(String username) throws UserNotFoundException, ServiceUnavailableException; /** * Retrieve the group members for the group. * * @param groupName the name of the group * @return the group members for the group * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the group members could not be retrieved for the group */ List<GroupMember> getMembersForGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException; /** * Retrieve the group members for the group. * * @param groupName the name of the group * @param filter the optional filter to apply to the group members * @param sortDirection the optional sort direction to apply to the group members * @param pageIndex the optional page index * @param pageSize the optional page size * @return the group members for the group * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the group members could not be retrieved for the group */ GroupMembers getMembersForGroup( String groupName, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws GroupNotFoundException, ServiceUnavailableException; /** * Retrieve the codes for the roles that have been assigned to the group. * * @param groupName the name of the group * @return the codes for the roles that have been assigned to the group * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the codes for the roles assigned to the group could not * be retrieved */ List<String> getRoleCodesForGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException; /** * Retrieve the codes for the roles that the user has been assigned. * * @param username the username for the user * @return the codes for the roles that the user has been assigned * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the codes for the roles assigned to the user could not * be retrieved */ List<String> getRoleCodesForUser(String username) throws UserNotFoundException, ServiceUnavailableException; /** * Retrieve the roles that have been assigned to the group. * * @param groupName the name of the group * @return the roles that have been assigned to the group * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the codes for the roles assigned to the group could not * be retrieved */ List<GroupRole> getRolesForGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException; /** * Retrieve the user. * * @param username the username for the user * @return the user * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be retrieved */ User getUser(String username) throws UserNotFoundException, ServiceUnavailableException; /** * Retrieve the name of the user. * * @param username the username for the user * @return the name of the user * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the name of the user could not be retrieved */ String getUserName(String username) throws UserNotFoundException, ServiceUnavailableException; /** * Retrieve all the users. * * @return the users * @throws ServiceUnavailableException if the users could not be retrieved */ List<User> getUsers() throws ServiceUnavailableException; /** * Retrieve the users. * * @param filter the optional filter to apply to the users * @param sortBy the optional method used to sort the users e.g. by name * @param sortDirection the optional sort direction to apply to the users * @param pageIndex the optional page index * @param pageSize the optional page size * @return the users * @throws ServiceUnavailableException if the users could not be retrieved */ Users getUsers( String filter, UserSortBy sortBy, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws ServiceUnavailableException; /** * Does the user with the specified username exist? * * @param username the username for the user * @return <b>true</b> if a user with specified username exists or <b>false</b> otherwise * @throws ServiceUnavailableException if the check for the existing user failed */ boolean isExistingUser(String username) throws ServiceUnavailableException; /** * Is the user in the group? * * @param groupName the name of the group * @param username the username for the user * @return <b>true</b> if the user is a member of the group or <b>false</b> otherwise * @throws UserNotFoundException if the user could not be found * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the check to confirm if the user is a member of the * group failed */ boolean isUserInGroup(String groupName, String username) throws UserNotFoundException, GroupNotFoundException, ServiceUnavailableException; /** * Remove the group member from the group. * * @param groupName the name of the group * @param memberType the group member type * @param memberName the group member name * @throws GroupNotFoundException if the group could not be found * @throws GroupMemberNotFoundException if the group member could not be found * @throws ServiceUnavailableException if the group member could not be removed from the group */ void removeMemberFromGroup(String groupName, GroupMemberType memberType, String memberName) throws GroupNotFoundException, GroupMemberNotFoundException, ServiceUnavailableException; /** * Remove the role from the group. * * @param groupName the name of the group * @param roleCode the code for the role * @throws GroupNotFoundException if the group could not be found * @throws GroupRoleNotFoundException if the group role could not be found * @throws ServiceUnavailableException if the role could not be removed from the group */ void removeRoleFromGroup(String groupName, String roleCode) throws GroupNotFoundException, GroupRoleNotFoundException, ServiceUnavailableException; /** * Remove the user from the group. * * @param groupName the name of the group * @param username the username for the user * @throws GroupNotFoundException if the group could not be found * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be removed from the group */ void removeUserFromGroup(String groupName, String username) throws GroupNotFoundException, UserNotFoundException, ServiceUnavailableException; /** * Reset the password for the user. * * @param username the username for the user * @param newPassword the new password * @throws UserNotFoundException if the user could not be found * @throws UserLockedException if the user is locked * @throws ExistingPasswordException if the user has previously used the new password * @throws ServiceUnavailableException if the password for the user could not be reset */ void resetPassword(String username, String newPassword) throws UserNotFoundException, UserLockedException, ExistingPasswordException, ServiceUnavailableException; /** * Update the group. * * @param group the group * @throws GroupNotFoundException if the group could not be found * @throws ServiceUnavailableException if the group could not be updated */ void updateGroup(Group group) throws GroupNotFoundException, ServiceUnavailableException; /** * Update the user. * * @param user the user * @param expirePassword expire the user's password as part of the update * @param lockUser lock the user as part of the update * @throws UserNotFoundException if the user could not be found * @throws ServiceUnavailableException if the user could not be updated */ void updateUser(User user, boolean expirePassword, boolean lockUser) throws UserNotFoundException, ServiceUnavailableException; }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/InternalUserDirectory.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.ServiceUnavailableException; import africa.absa.inception.core.sorting.SortDirection; import africa.absa.inception.core.util.PasswordUtil; import com.github.f4b6a3.uuid.UuidCreator; import java.security.SecureRandom; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.util.StringUtils; /** * The <b>InternalUserDirectory</b> class provides the internal user directory implementation. * * @author Marcus Portmann */ public class InternalUserDirectory extends UserDirectoryBase { /** The default maximum number of filtered groups. */ private static final int DEFAULT_MAX_FILTERED_GROUPS = 100; /** The default maximum number of filtered group members. */ private static final int DEFAULT_MAX_FILTERED_GROUP_MEMBERS = 100; /** The default maximum number of filtered users. */ private static final int DEFAULT_MAX_FILTERED_USERS = 100; /** The default number of failed password attempts before the user is locked. */ private static final int DEFAULT_MAX_PASSWORD_ATTEMPTS = 5; /** The default number of months before a user's password expires. */ private static final int DEFAULT_PASSWORD_EXPIRY_MONTHS = 3; /** The default number of months to check password history against. */ private static final int DEFAULT_PASSWORD_HISTORY_MONTHS = 12; /** The user directory capabilities common to all internal user directory instances. */ private static final UserDirectoryCapabilities INTERNAL_USER_DIRECTORY_CAPABILITIES = new UserDirectoryCapabilities(true, true, true, true, true, true, true, true); /** The maximum number of filtered group members to return. */ private final int maxFilteredGroupMembers; /** The maximum number of filtered groups to return. */ private final int maxFilteredGroups; /** The maximum number of filtered users to return. */ private final int maxFilteredUsers; /** The maximum number of password attempts. */ private final int maxPasswordAttempts; /** The password encoder. */ private final PasswordEncoder passwordEncoder; /** The password expiry period in months. */ private final int passwordExpiryMonths; /** The password history period in months. */ private final int passwordHistoryMonths; /** * Constructs a new <b>InternalUserDirectory</b>. * * @param userDirectoryId the ID for the user directory * @param parameters the parameters for the user directory * @param groupRepository the Group Repository * @param userRepository the User Repository * @param roleRepository the Role Repository * @throws ServiceUnavailableException if the internal user directory could not be initialized */ public InternalUserDirectory( UUID userDirectoryId, List<UserDirectoryParameter> parameters, GroupRepository groupRepository, UserRepository userRepository, RoleRepository roleRepository) throws ServiceUnavailableException { super(userDirectoryId, parameters, groupRepository, userRepository, roleRepository); this.passwordEncoder = new BCryptPasswordEncoder(10, new SecureRandom()); try { if (UserDirectoryParameter.contains(parameters, "MaxPasswordAttempts")) { maxPasswordAttempts = UserDirectoryParameter.getIntegerValue(parameters, "MaxPasswordAttempts"); } else { maxPasswordAttempts = DEFAULT_MAX_PASSWORD_ATTEMPTS; } if (UserDirectoryParameter.contains(parameters, "PasswordExpiryMonths")) { passwordExpiryMonths = UserDirectoryParameter.getIntegerValue(parameters, "PasswordExpiryMonths"); } else { passwordExpiryMonths = DEFAULT_PASSWORD_EXPIRY_MONTHS; } if (UserDirectoryParameter.contains(parameters, "PasswordHistoryMonths")) { passwordHistoryMonths = UserDirectoryParameter.getIntegerValue(parameters, "PasswordHistoryMonths"); } else { passwordHistoryMonths = DEFAULT_PASSWORD_HISTORY_MONTHS; } if (UserDirectoryParameter.contains(parameters, "MaxFilteredUsers")) { maxFilteredUsers = UserDirectoryParameter.getIntegerValue(parameters, "MaxFilteredUsers"); } else { maxFilteredUsers = DEFAULT_MAX_FILTERED_USERS; } if (UserDirectoryParameter.contains(parameters, "MaxFilteredGroups")) { maxFilteredGroups = UserDirectoryParameter.getIntegerValue(parameters, "MaxFilteredGroups"); } else { maxFilteredGroups = DEFAULT_MAX_FILTERED_GROUPS; } if (UserDirectoryParameter.contains(parameters, "MaxFilteredGroupMembers")) { maxFilteredGroupMembers = UserDirectoryParameter.getIntegerValue(parameters, "MaxFilteredGroupMembers"); } else { maxFilteredGroupMembers = DEFAULT_MAX_FILTERED_GROUP_MEMBERS; } } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to initialize the user directory (" + userDirectoryId + ")", e); } } @Override public void addMemberToGroup(String groupName, GroupMemberType memberType, String memberName) throws GroupNotFoundException, UserNotFoundException, ServiceUnavailableException { if (memberType != GroupMemberType.USER) { throw new ServiceUnavailableException( "Unsupported group member type (" + memberType.description() + ")"); } if (isUserInGroup(groupName, memberName)) { return; } addUserToGroup(groupName, memberName); } @Override public void addRoleToGroup(String groupName, String roleCode) throws GroupNotFoundException, RoleNotFoundException, ServiceUnavailableException { try { Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isEmpty()) { throw new GroupNotFoundException(groupName); } if (!getRoleRepository().existsById(roleCode)) { throw new RoleNotFoundException(roleCode); } if (getGroupRepository().roleToGroupMappingExists(groupIdOptional.get(), roleCode)) { return; } getGroupRepository().addRoleToGroup(groupIdOptional.get(), roleCode); } catch (GroupNotFoundException | RoleNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to add the role (" + roleCode + ") to the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void addUserToGroup(String groupName, String username) throws GroupNotFoundException, UserNotFoundException, ServiceUnavailableException { try { Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isEmpty()) { throw new GroupNotFoundException(groupName); } Optional<UUID> userIdOptional = getUserRepository() .getIdByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userIdOptional.isEmpty()) { throw new UserNotFoundException(username); } getGroupRepository().addUserToGroup(groupIdOptional.get(), userIdOptional.get()); } catch (GroupNotFoundException | UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to add the user (" + username + ") to the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void adminChangePassword( String username, String newPassword, boolean expirePassword, boolean lockUser, boolean resetPasswordHistory, PasswordChangeReason reason) throws UserNotFoundException, ServiceUnavailableException { try { Optional<UUID> userIdOptional = getUserRepository() .getIdByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userIdOptional.isEmpty()) { throw new UserNotFoundException(username); } String encodedNewPassword = passwordEncoder.encode(newPassword); int passwordAttempts = 0; if (lockUser) { passwordAttempts = maxPasswordAttempts; } LocalDateTime passwordExpiry; if (expirePassword) { passwordExpiry = LocalDateTime.now(); } else { passwordExpiry = LocalDateTime.now(); passwordExpiry = passwordExpiry.plus(passwordExpiryMonths, ChronoUnit.MONTHS); } getUserRepository() .changePassword( userIdOptional.get(), encodedNewPassword, passwordAttempts, Optional.of(passwordExpiry)); if (resetPasswordHistory) { getUserRepository().resetPasswordHistory(userIdOptional.get()); } getUserRepository().savePasswordInPasswordHistory(userIdOptional.get(), encodedNewPassword); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to change the password for the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void authenticate(String username, String password) throws AuthenticationFailedException, UserLockedException, ExpiredPasswordException, UserNotFoundException, ServiceUnavailableException { try { Optional<User> userOptional = getUserRepository() .findByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userOptional.isEmpty()) { throw new UserNotFoundException(username); } User user = userOptional.get(); if ((user.getPasswordAttempts() != null) && (user.getPasswordAttempts() >= maxPasswordAttempts)) { throw new UserLockedException(username); } if (!passwordEncoder.matches(password, user.getPassword())) { if ((user.getPasswordAttempts() != null) && (user.getPasswordAttempts() != -1)) { getUserRepository().incrementPasswordAttempts(user.getId()); } throw new AuthenticationFailedException( "Authentication failed for the user (" + username + ")"); } if (user.hasPasswordExpired()) { throw new ExpiredPasswordException(username); } } catch (AuthenticationFailedException | UserNotFoundException | UserLockedException | ExpiredPasswordException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to authenticate the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void changePassword(String username, String password, String newPassword) throws AuthenticationFailedException, UserLockedException, ExistingPasswordException, ServiceUnavailableException { try { Optional<User> userOptional = getUserRepository() .findByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userOptional.isEmpty()) { throw new AuthenticationFailedException( "Authentication failed while attempting to change the password for the user (" + username + ")"); } User user = userOptional.get(); if ((user.getPasswordAttempts() != null) && (user.getPasswordAttempts() > maxPasswordAttempts)) { throw new UserLockedException(username); } String encodedNewPassword = passwordEncoder.encode(newPassword); if (!passwordEncoder.matches(password, user.getPassword())) { throw new AuthenticationFailedException( "Authentication failed while attempting to change the password for the user (" + username + ")"); } if (isPasswordInHistory(user.getId(), newPassword)) { throw new ExistingPasswordException(username); } LocalDateTime passwordExpiry = LocalDateTime.now(); passwordExpiry = passwordExpiry.plus(passwordExpiryMonths, ChronoUnit.MONTHS); getUserRepository() .changePassword(user.getId(), encodedNewPassword, 0, Optional.of(passwordExpiry)); getUserRepository().savePasswordInPasswordHistory(user.getId(), encodedNewPassword); } catch (AuthenticationFailedException | ExistingPasswordException | UserLockedException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to change the password for the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void createGroup(Group group) throws DuplicateGroupException, ServiceUnavailableException { try { if (getGroupRepository() .existsByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), group.getName())) { throw new DuplicateGroupException(group.getName()); } group.setId(UuidCreator.getShortPrefixComb()); getGroupRepository().saveAndFlush(group); } catch (DuplicateGroupException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the group (" + group.getName() + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void createUser(User user, boolean expiredPassword, boolean userLocked) throws DuplicateUserException, ServiceUnavailableException { try { if (getUserRepository() .existsByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), user.getUsername())) { throw new DuplicateUserException(user.getUsername()); } user.setId(UuidCreator.getShortPrefixComb()); String encodedNewPassword; if (!isNullOrEmpty(user.getPassword())) { encodedNewPassword = passwordEncoder.encode(user.getPassword()); } else { encodedNewPassword = passwordEncoder.encode(PasswordUtil.generateRandomPassword()); } user.setPassword(encodedNewPassword); if (userLocked) { user.setPasswordAttempts(maxPasswordAttempts); } else { user.setPasswordAttempts(0); } if (expiredPassword) { user.setPasswordExpiry(LocalDateTime.now()); } else { LocalDateTime passwordExpiry = LocalDateTime.now(); passwordExpiry = passwordExpiry.plus(passwordExpiryMonths, ChronoUnit.MONTHS); user.setPasswordExpiry(passwordExpiry); } getUserRepository().saveAndFlush(user); getUserRepository().savePasswordInPasswordHistory(user.getId(), encodedNewPassword); } catch (DuplicateUserException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the user (" + user.getUsername() + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void deleteGroup(String groupName) throws GroupNotFoundException, ExistingGroupMembersException, ServiceUnavailableException { try { Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isEmpty()) { throw new GroupNotFoundException(groupName); } if (getGroupRepository().getNumberOfUsersForGroup(groupIdOptional.get()) > 0) { throw new ExistingGroupMembersException(groupName); } getGroupRepository().deleteById(groupIdOptional.get()); } catch (GroupNotFoundException | ExistingGroupMembersException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to delete the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void deleteUser(String username) throws UserNotFoundException, ServiceUnavailableException { try { Optional<UUID> userIdOptional = getUserRepository() .getIdByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userIdOptional.isEmpty()) { throw new UserNotFoundException(username); } getUserRepository().deleteById(userIdOptional.get()); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to delete the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public List<User> findUsers(List<UserAttribute> userAttributes) throws InvalidAttributeException, ServiceUnavailableException { try { User userCriteria = new User(); userCriteria.setUserDirectoryId(getUserDirectoryId()); for (UserAttribute userAttribute : userAttributes) { if (userAttribute.getName().equalsIgnoreCase("status")) { userCriteria.setStatus(UserStatus.fromCode(userAttribute.getValue())); } else if (userAttribute.getName().equalsIgnoreCase("email")) { userCriteria.setEmail(userAttribute.getValue()); } else if (userAttribute.getName().equalsIgnoreCase("name")) { userCriteria.setName(userAttribute.getValue()); } else if (userAttribute.getName().equalsIgnoreCase("preferredName")) { userCriteria.setPreferredName(userAttribute.getValue()); } else if (userAttribute.getName().equalsIgnoreCase("phoneNumber")) { userCriteria.setPhoneNumber(userAttribute.getValue()); } else if (userAttribute.getName().equalsIgnoreCase("mobileNumber")) { userCriteria.setMobileNumber(userAttribute.getValue()); } else if (userAttribute.getName().equalsIgnoreCase("username")) { userCriteria.setUsername(userAttribute.getValue()); } else { throw new InvalidAttributeException(userAttribute.getName()); } } ExampleMatcher matcher = ExampleMatcher.matching() .withIgnoreNullValues() .withIgnoreCase() .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING); return getUserRepository().findAll(Example.of(userCriteria, matcher)); } catch (InvalidAttributeException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to find the users for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public UserDirectoryCapabilities getCapabilities() { return INTERNAL_USER_DIRECTORY_CAPABILITIES; } @Override public List<String> getFunctionCodesForUser(String username) throws UserNotFoundException, ServiceUnavailableException { try { Optional<UUID> userIdOptional = getUserRepository() .getIdByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userIdOptional.isEmpty()) { throw new UserNotFoundException(username); } return getUserRepository().getFunctionCodesByUserId(userIdOptional.get()); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the function codes for the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public Group getGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException { try { Optional<Group> groupOptional = getGroupRepository() .findByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupOptional.isPresent()) { return groupOptional.get(); } else { throw new GroupNotFoundException(groupName); } } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public List<String> getGroupNames() throws ServiceUnavailableException { try { return getGroupRepository().getNamesByUserDirectoryId(getUserDirectoryId()); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the group names for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public List<String> getGroupNamesForUser(String username) throws UserNotFoundException, ServiceUnavailableException { try { Optional<UUID> userIdOptional = getUserRepository() .getIdByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userIdOptional.isEmpty()) { throw new UserNotFoundException(username); } return getUserRepository().getGroupNamesByUserId(userIdOptional.get()); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the names of the groups the user (" + username + ") is a member of for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public List<Group> getGroups() throws ServiceUnavailableException { try { return getGroupRepository().findByUserDirectoryId(getUserDirectoryId()); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the groups for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public Groups getGroups( String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws ServiceUnavailableException { try { if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = maxFilteredGroups; } PageRequest pageRequest = PageRequest.of( pageIndex, Math.min(pageSize, maxFilteredGroups), (sortDirection == SortDirection.ASCENDING) ? Sort.Direction.ASC : Sort.Direction.DESC, "name"); Page<Group> groupPage; if (StringUtils.hasText(filter)) { groupPage = getGroupRepository() .findFiltered(getUserDirectoryId(), "%" + filter + "%", pageRequest); } else { groupPage = getGroupRepository().findByUserDirectoryId(getUserDirectoryId(), pageRequest); } return new Groups( getUserDirectoryId(), groupPage.toList(), groupPage.getTotalElements(), filter, sortDirection, pageIndex, pageSize); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the filtered groups for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public List<Group> getGroupsForUser(String username) throws UserNotFoundException, ServiceUnavailableException { try { Optional<UUID> userIdOptional = getUserRepository() .getIdByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userIdOptional.isEmpty()) { throw new UserNotFoundException(username); } return getUserRepository().getGroupsByUserId(userIdOptional.get()); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the groups the user is a member of (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public List<GroupMember> getMembersForGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException { try { Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isEmpty()) { throw new GroupNotFoundException(groupName); } List<String> usernames = getGroupRepository().getUsernamesForGroup(getUserDirectoryId(), groupIdOptional.get()); List<GroupMember> groupMembers = new ArrayList<>(); for (String username : usernames) { groupMembers.add( new GroupMember(getUserDirectoryId(), groupName, GroupMemberType.USER, username)); } return groupMembers; } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the group members for the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public GroupMembers getMembersForGroup( String groupName, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws GroupNotFoundException, ServiceUnavailableException { try { Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isEmpty()) { throw new GroupNotFoundException(groupName); } if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = maxFilteredGroups; } PageRequest pageRequest = PageRequest.of(pageIndex, Math.min(pageSize, maxFilteredGroupMembers)); Page<String> usernamesForGroupPage; if (StringUtils.hasText(filter)) { usernamesForGroupPage = getGroupRepository() .getFilteredUsernamesForGroup( getUserDirectoryId(), groupIdOptional.get(), "%" + filter + "%", pageRequest); } else { usernamesForGroupPage = getGroupRepository() .getUsernamesForGroup(getUserDirectoryId(), groupIdOptional.get(), pageRequest); } List<GroupMember> groupMembers = new ArrayList<>(); for (String username : usernamesForGroupPage) { groupMembers.add( new GroupMember(getUserDirectoryId(), groupName, GroupMemberType.USER, username)); } if ((sortDirection == null) || (sortDirection == SortDirection.ASCENDING)) { groupMembers.sort(Comparator.comparing(GroupMember::getMemberName)); } else { groupMembers.sort(Comparator.comparing(GroupMember::getMemberName).reversed()); } return new GroupMembers( getUserDirectoryId(), groupName, groupMembers, usernamesForGroupPage.getTotalElements(), filter, sortDirection, pageIndex, pageSize); } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the group members for the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public List<String> getRoleCodesForGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException { try { Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isEmpty()) { throw new GroupNotFoundException(groupName); } return getGroupRepository().getRoleCodesByGroupId(groupIdOptional.get()); } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the role codes for the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public List<String> getRoleCodesForUser(String username) throws UserNotFoundException, ServiceUnavailableException { try { Optional<UUID> userIdOptional = getUserRepository() .getIdByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userIdOptional.isEmpty()) { throw new UserNotFoundException(username); } return getUserRepository().getRoleCodesByUserId(userIdOptional.get()); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the role codes for the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public List<GroupRole> getRolesForGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException { try { Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isEmpty()) { throw new GroupNotFoundException(groupName); } List<GroupRole> groupRoles = new ArrayList<>(); for (String roleCode : getGroupRepository().getRoleCodesByGroupId(groupIdOptional.get())) { groupRoles.add(new GroupRole(getUserDirectoryId(), groupName, roleCode)); } return groupRoles; } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the roles for the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public User getUser(String username) throws UserNotFoundException, ServiceUnavailableException { try { Optional<User> userOptional = getUserRepository() .findByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userOptional.isPresent()) { return userOptional.get(); } else { throw new UserNotFoundException(username); } } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public String getUserName(String username) throws UserNotFoundException, ServiceUnavailableException { try { Optional<String> userNameOptional = getUserRepository() .getNameByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userNameOptional.isPresent()) { return userNameOptional.get(); } else { throw new UserNotFoundException(username); } } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the name of the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public List<User> getUsers() throws ServiceUnavailableException { try { return getUserRepository().findByUserDirectoryId(getUserDirectoryId()); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the users for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public Users getUsers( String filter, UserSortBy sortBy, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws ServiceUnavailableException { try { PageRequest pageRequest = null; if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = maxFilteredUsers; } if (sortBy == UserSortBy.USERNAME) { pageRequest = PageRequest.of( pageIndex, Math.min(pageSize, maxFilteredUsers), (sortDirection == SortDirection.ASCENDING) ? Sort.Direction.ASC : Sort.Direction.DESC, "username"); } else if (sortBy == UserSortBy.NAME) { pageRequest = PageRequest.of( pageIndex, Math.min(pageSize, maxFilteredUsers), (sortDirection == SortDirection.ASCENDING) ? Sort.Direction.ASC : Sort.Direction.DESC, "name"); } else if (sortBy == UserSortBy.PREFERRED_NAME) { pageRequest = PageRequest.of( pageIndex, Math.min(pageSize, maxFilteredUsers), (sortDirection == SortDirection.ASCENDING) ? Sort.Direction.ASC : Sort.Direction.DESC, "preferredName"); } Page<User> userPage; if (StringUtils.hasText(filter)) { userPage = getUserRepository().findFiltered(getUserDirectoryId(), "%" + filter + "%", pageRequest); } else { userPage = getUserRepository().findByUserDirectoryId(getUserDirectoryId(), pageRequest); } return new Users( getUserDirectoryId(), userPage.toList(), userPage.getTotalElements(), filter, sortBy, sortDirection, pageIndex, pageSize); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the filtered users for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public boolean isExistingUser(String username) throws ServiceUnavailableException { try { return getUserRepository() .existsByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to check whether the user (" + username + ") is an existing user for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public boolean isUserInGroup(String groupName, String username) throws UserNotFoundException, GroupNotFoundException, ServiceUnavailableException { try { Optional<UUID> userIdOptional = getUserRepository() .getIdByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userIdOptional.isEmpty()) { throw new UserNotFoundException(username); } Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isEmpty()) { throw new GroupNotFoundException(groupName); } return getUserRepository().isUserInGroup(userIdOptional.get(), groupIdOptional.get()); } catch (UserNotFoundException | GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to check if the user (" + username + ") is in the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void removeMemberFromGroup(String groupName, GroupMemberType memberType, String memberName) throws GroupNotFoundException, GroupMemberNotFoundException, ServiceUnavailableException { if (memberType != GroupMemberType.USER) { throw new ServiceUnavailableException( "Unsupported group member type (" + memberType.description() + ")"); } try { removeUserFromGroup(groupName, memberName); } catch (UserNotFoundException e) { throw new GroupMemberNotFoundException(memberType, memberName); } } @Override public void removeRoleFromGroup(String groupName, String roleCode) throws GroupNotFoundException, GroupRoleNotFoundException, ServiceUnavailableException { try { Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isEmpty()) { throw new GroupNotFoundException(groupName); } if (getGroupRepository().removeRoleFromGroup(groupIdOptional.get(), roleCode) == 0) { throw new GroupRoleNotFoundException(roleCode); } } catch (GroupNotFoundException | GroupRoleNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to remove the role (" + roleCode + ") from the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void removeUserFromGroup(String groupName, String username) throws GroupNotFoundException, UserNotFoundException, ServiceUnavailableException { try { Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isEmpty()) { throw new GroupNotFoundException(groupName); } Optional<UUID> userIdOptional = getUserRepository() .getIdByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userIdOptional.isEmpty()) { throw new UserNotFoundException(username); } getGroupRepository().removeUserFromGroup(groupIdOptional.get(), userIdOptional.get()); } catch (GroupNotFoundException | UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to remove the user (" + username + ") from the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void resetPassword(String username, String newPassword) throws UserNotFoundException, UserLockedException, ExistingPasswordException, ServiceUnavailableException { try { Optional<User> userOptional = getUserRepository() .findByUserDirectoryIdAndUsernameIgnoreCase(getUserDirectoryId(), username); if (userOptional.isEmpty()) { throw new UserNotFoundException(username); } User user = userOptional.get(); if ((user.getPasswordAttempts() != null) && (user.getPasswordAttempts() > maxPasswordAttempts)) { throw new UserLockedException(username); } String encodedNewPassword = passwordEncoder.encode(newPassword); if (isPasswordInHistory(user.getId(), newPassword)) { throw new ExistingPasswordException(username); } LocalDateTime passwordExpiry = LocalDateTime.now(); passwordExpiry = passwordExpiry.plus(passwordExpiryMonths, ChronoUnit.MONTHS); getUserRepository().resetPassword(user.getId(), encodedNewPassword, passwordExpiry); getUserRepository().savePasswordInPasswordHistory(user.getId(), encodedNewPassword); } catch (UserNotFoundException | UserLockedException | ExistingPasswordException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to reset the password for the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void updateGroup(Group group) throws GroupNotFoundException, ServiceUnavailableException { try { Optional<Group> groupOptional = getGroupRepository() .findByUserDirectoryIdAndNameIgnoreCase(group.getUserDirectoryId(), group.getName()); if (groupOptional.isEmpty()) { throw new GroupNotFoundException(group.getName()); } Group existingGroup = groupOptional.get(); existingGroup.setDescription(group.getDescription()); getGroupRepository().saveAndFlush(existingGroup); } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to update the group (" + group.getName() + ") for the user directory (" + getUserDirectoryId() + ")", e); } } @Override public void updateUser(User user, boolean expirePassword, boolean lockUser) throws UserNotFoundException, ServiceUnavailableException { try { Optional<User> userOptional = getUserRepository() .findByUserDirectoryIdAndUsernameIgnoreCase( user.getUserDirectoryId(), user.getUsername()); if (userOptional.isEmpty()) { throw new UserNotFoundException(user.getUsername()); } User existingUser = userOptional.get(); if (user.getName() != null) { existingUser.setName(user.getName()); } if (user.getPreferredName() != null) { existingUser.setPreferredName(user.getPreferredName()); } if (user.getEmail() != null) { existingUser.setEmail(user.getEmail()); } if (user.getPhoneNumber() != null) { existingUser.setPhoneNumber(user.getPhoneNumber()); } if (user.getMobileNumber() != null) { existingUser.setMobileNumber(user.getMobileNumber()); } if (StringUtils.hasText(user.getPassword())) { existingUser.setPassword(passwordEncoder.encode(user.getPassword())); } if (lockUser) { existingUser.setPasswordAttempts(maxPasswordAttempts); } else if (user.getPasswordAttempts() != null) { existingUser.setPasswordAttempts(user.getPasswordAttempts()); } if (expirePassword) { existingUser.setPasswordExpiry(LocalDateTime.now()); } else if (user.getPasswordExpiry() != null) { existingUser.setPasswordExpiry(user.getPasswordExpiry()); } getUserRepository().saveAndFlush(existingUser); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to update the user (" + user.getUsername() + ") for the user directory (" + getUserDirectoryId() + ")", e); } } /** * Is the password a historical password that cannot be reused for a period of time i.e. was the * password used previously in the last X months. * * @param userId the ID for the user * @param password the password * @return <b>true</b> if the password was previously used and cannot be reused for a period of * time or <b>false</b> otherwise */ private boolean isPasswordInHistory(UUID userId, String password) { LocalDateTime after = LocalDateTime.now(); after = after.minus(passwordHistoryMonths, ChronoUnit.MONTHS); for (String historicalPassword : getUserRepository().getPasswordHistory(userId, after)) { if (passwordEncoder.matches(password, historicalPassword)) { return true; } } return false; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/InvalidAttributeException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>InvalidAttributeException</b> is thrown to indicate that a security operation failed as a * result of an invalid attribute. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/invalid-attribute", title = "The attribute is invalid.", status = 404) public class InvalidAttributeException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>InvalidAttributeException</b>. * * @param name the name of the attribute */ public InvalidAttributeException(String name) { super("The attribute (" + name + ") is invalid"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/InvalidConfigurationException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>InvalidConfigurationException</b> is thrown to indicate that a security operation failed as * a result of invalid configuration. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/invalid-configuration", title = "The configuration is invalid.", status = 404) public class InvalidConfigurationException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>InvalidConfigurationException</b> with the specified message. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. */ public InvalidConfigurationException(String message) { super(message); } /** * Constructs a new <b>InvalidConfigurationException</b> with the specified message and cause. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. * @param cause The cause saved for later retrieval by the <b>getCause()</b> method. (A * <b>null</b> value is permitted if the cause is nonexistent or unknown) */ public InvalidConfigurationException(String message, Throwable cause) { super(message, cause); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/InvalidSecurityCodeException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * An <b>InvalidSecurityCodeException</b> is thrown to indicate that a security operation failed as * a result of an invalid security code. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/invalid-security-code", title = "Invalid security code.", status = 401) public class InvalidSecurityCodeException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>InvalidSecurityCodeException</b>. * * @param username the username for the user */ public InvalidSecurityCodeException(String username) { super("Invalid security code for the user (" + username + ")"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/LDAPUserDirectory.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.ServiceUnavailableException; import africa.absa.inception.core.sorting.SortDirection; import africa.absa.inception.core.util.JNDIUtil; import com.github.f4b6a3.uuid.UuidCreator; import java.util.ArrayList; import java.util.Comparator; import java.util.Hashtable; import java.util.List; import java.util.Optional; import java.util.UUID; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.ModificationItem; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.util.StringUtils; /** * The <b>LDAPUserDirectory</b> class provides the LDAP user directory implementation. * * @author Marcus Portmann */ @SuppressWarnings({"unused", "Duplicates", "SpringJavaAutowiredMembersInspection"}) public class LDAPUserDirectory extends UserDirectoryBase { /** The default maximum number of filtered groups. */ private static final int DEFAULT_MAX_FILTERED_GROUPS = 100; /** The default maximum number of filtered group members. */ private static final int DEFAULT_MAX_FILTERED_GROUP_MEMBERS = 100; /** The default maximum number of filtered users. */ private static final int DEFAULT_MAX_FILTERED_USERS = 100; /** The empty attribute list. */ private static final String[] EMPTY_ATTRIBUTE_LIST = new String[0]; /* Logger */ private static final Logger logger = LoggerFactory.getLogger(LDAPUserDirectory.class); private final LdapName baseDN; private final String bindDN; private final String bindPassword; /** The user directory capabilities supported by this user directory instance. */ private final UserDirectoryCapabilities capabilities; private final LdapName groupBaseDN; private final String groupMemberAttribute; private final String[] groupMemberAttributeArray; private final String groupNameAttribute; private final String groupObjectClass; private final String host; /** The maximum number of filtered group members to return. */ private final int maxFilteredGroupMembers; /** The maximum number of filtered groups to return. */ private final int maxFilteredGroups; /** The maximum number of filtered users to return. */ private final int maxFilteredUsers; private final int port; private final boolean useSSL; private final LdapName userBaseDN; private final String userEmailAttribute; private final String userMobileNumberAttribute; private final String userNameAttribute; private final String userObjectClass; private final String userPhoneNumberAttribute; private final String userPreferredNameAttribute; private final String userUsernameAttribute; /** The data source used to provide connections to the application database. */ @Autowired @Qualifier("applicationDataSource") private DataSource dataSource; private String groupDescriptionAttribute; /** * Constructs a new <b>LDAPUserDirectory</b>. * * @param userDirectoryId the ID for the user directory * @param parameters the parameters for the user directory * @param groupRepository the Group Repository * @param userRepository the User Repository * @param roleRepository the Role Repository * @throws ServiceUnavailableException if the LDAP user directory could not be initialized */ public LDAPUserDirectory( UUID userDirectoryId, List<UserDirectoryParameter> parameters, GroupRepository groupRepository, UserRepository userRepository, RoleRepository roleRepository) throws ServiceUnavailableException { super(userDirectoryId, parameters, groupRepository, userRepository, roleRepository); try { if (UserDirectoryParameter.contains(parameters, "Host")) { host = UserDirectoryParameter.getStringValue(parameters, "Host"); } else { throw new ServiceUnavailableException( "No Host parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "Port")) { port = UserDirectoryParameter.getIntegerValue(parameters, "Port"); } else { throw new ServiceUnavailableException( "No Port parameter found for the user directory (" + userDirectoryId + ")"); } useSSL = UserDirectoryParameter.contains(parameters, "UseSSL") && Boolean.parseBoolean(UserDirectoryParameter.getStringValue(parameters, "UseSSL")); if (UserDirectoryParameter.contains(parameters, "BindDN")) { bindDN = UserDirectoryParameter.getStringValue(parameters, "BindDN"); } else { throw new ServiceUnavailableException( "No BindDN parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "BindPassword")) { bindPassword = UserDirectoryParameter.getStringValue(parameters, "BindPassword"); } else { throw new ServiceUnavailableException( "No BindPassword parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "BaseDN")) { baseDN = new LdapName(UserDirectoryParameter.getStringValue(parameters, "BaseDN")); } else { throw new ServiceUnavailableException( "No BindDN parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "UserBaseDN")) { userBaseDN = new LdapName(UserDirectoryParameter.getStringValue(parameters, "UserBaseDN")); } else { throw new ServiceUnavailableException( "No UserBaseDN parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "GroupBaseDN")) { groupBaseDN = new LdapName(UserDirectoryParameter.getStringValue(parameters, "GroupBaseDN")); } else { throw new ServiceUnavailableException( "No GroupBaseDN parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "UserObjectClass")) { userObjectClass = UserDirectoryParameter.getStringValue(parameters, "UserObjectClass"); } else { throw new ServiceUnavailableException( "No UserObjectClass parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "UserUsernameAttribute")) { userUsernameAttribute = UserDirectoryParameter.getStringValue(parameters, "UserUsernameAttribute"); } else { throw new ServiceUnavailableException( "No UserUsernameAttribute parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "UserNameAttribute")) { userNameAttribute = UserDirectoryParameter.getStringValue(parameters, "UserNameAttribute"); } else { throw new ServiceUnavailableException( "No UserNameAttribute parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "UserPreferredNameAttribute")) { userPreferredNameAttribute = UserDirectoryParameter.getStringValue(parameters, "UserPreferredNameAttribute"); } else { throw new ServiceUnavailableException( "No UserPreferredNameAttribute parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "UserPhoneNumberAttribute")) { userPhoneNumberAttribute = UserDirectoryParameter.getStringValue(parameters, "UserPhoneNumberAttribute"); } else { throw new ServiceUnavailableException( "No UserPhoneNumberAttribute parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "UserMobileNumberAttribute")) { userMobileNumberAttribute = UserDirectoryParameter.getStringValue(parameters, "UserMobileNumberAttribute"); } else { throw new ServiceUnavailableException( "No UserMobileNumberAttribute parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "UserEmailAttribute")) { userEmailAttribute = UserDirectoryParameter.getStringValue(parameters, "UserEmailAttribute"); } else { throw new ServiceUnavailableException( "No UserEmailAttribute parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "GroupObjectClass")) { groupObjectClass = UserDirectoryParameter.getStringValue(parameters, "GroupObjectClass"); } else { throw new ServiceUnavailableException( "No GroupObjectClass parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "GroupNameAttribute")) { groupNameAttribute = UserDirectoryParameter.getStringValue(parameters, "GroupNameAttribute"); } else { throw new ServiceUnavailableException( "No GroupNameAttribute parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "GroupMemberAttribute")) { groupMemberAttribute = UserDirectoryParameter.getStringValue(parameters, "GroupMemberAttribute"); groupMemberAttributeArray = new String[] {groupMemberAttribute}; } else { throw new ServiceUnavailableException( "No GroupMemberAttribute parameter found for the user directory (" + userDirectoryId + ")"); } if (UserDirectoryParameter.contains(parameters, "GroupDescriptionAttribute")) { groupDescriptionAttribute = UserDirectoryParameter.getStringValue(parameters, "GroupDescriptionAttribute"); } if (UserDirectoryParameter.contains(parameters, "MaxFilteredUsers")) { maxFilteredUsers = UserDirectoryParameter.getIntegerValue(parameters, "MaxFilteredUsers"); } else { maxFilteredUsers = DEFAULT_MAX_FILTERED_USERS; } if (UserDirectoryParameter.contains(parameters, "MaxFilteredGroups")) { maxFilteredGroups = UserDirectoryParameter.getIntegerValue(parameters, "MaxFilteredGroups"); } else { maxFilteredGroups = DEFAULT_MAX_FILTERED_GROUPS; } if (UserDirectoryParameter.contains(parameters, "MaxFilteredGroupMembers")) { maxFilteredGroupMembers = UserDirectoryParameter.getIntegerValue(parameters, "MaxFilteredGroupMembers"); } else { maxFilteredGroupMembers = DEFAULT_MAX_FILTERED_GROUP_MEMBERS; } boolean supportsAdminChangePassword = true; if (UserDirectoryParameter.contains(parameters, "SupportsAdminChangePassword")) { supportsAdminChangePassword = UserDirectoryParameter.getBooleanValue(parameters, "SupportsAdminChangePassword"); } boolean supportsChangePassword = true; if (UserDirectoryParameter.contains(parameters, "SupportsChangePassword")) { supportsChangePassword = UserDirectoryParameter.getBooleanValue(parameters, "SupportsChangePassword"); } boolean supportsGroupAdministration = true; if (UserDirectoryParameter.contains(parameters, "SupportsGroupAdministration")) { supportsGroupAdministration = UserDirectoryParameter.getBooleanValue(parameters, "SupportsGroupAdministration"); } boolean supportsGroupMemberAdministration = true; if (UserDirectoryParameter.contains(parameters, "SupportsGroupMemberAdministration")) { supportsGroupMemberAdministration = UserDirectoryParameter.getBooleanValue(parameters, "SupportsGroupMemberAdministration"); } boolean supportsUserAdministration = true; if (UserDirectoryParameter.contains(parameters, "SupportsUserAdministration")) { supportsUserAdministration = UserDirectoryParameter.getBooleanValue(parameters, "SupportsUserAdministration"); } capabilities = new UserDirectoryCapabilities( supportsAdminChangePassword, supportsChangePassword, supportsGroupAdministration, supportsGroupMemberAdministration, false, false, supportsUserAdministration, false); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to initialize the user directory (" + userDirectoryId + ")", e); } } @Override public void addMemberToGroup(String groupName, GroupMemberType memberType, String memberName) throws GroupNotFoundException, UserNotFoundException, ServiceUnavailableException { if (!capabilities.getSupportsGroupMemberAdministration()) { throw new ServiceUnavailableException( "The group member administration capability is not supported for the user directory (" + getUserDirectoryId() + ""); } if (memberType != GroupMemberType.USER) { throw new ServiceUnavailableException( "Unsupported group member type (" + memberType.description() + ")"); } if (isUserInGroup(groupName, memberName)) { return; } addUserToGroup(groupName, memberName); } @Override public void addRoleToGroup(String groupName, String roleCode) throws GroupNotFoundException, RoleNotFoundException, ServiceUnavailableException { DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName groupDN = getGroupDN(dirContext, groupName); if (groupDN == null) { throw new GroupNotFoundException(groupName); } if (!getRoleRepository().existsById(roleCode)) { throw new RoleNotFoundException(roleCode); } UUID groupId; Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isPresent()) { groupId = groupIdOptional.get(); } else { groupId = UuidCreator.getShortPrefixComb(); Group group = getGroup(groupName); group.setId(groupId); getGroupRepository().saveAndFlush(group); } if (getGroupRepository().roleToGroupMappingExists(groupId, roleCode)) { return; } getGroupRepository().addRoleToGroup(groupId, roleCode); } catch (GroupNotFoundException | RoleNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to add the role (" + roleCode + ") to the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void addUserToGroup(String groupName, String username) throws UserNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (!capabilities.getSupportsGroupMemberAdministration()) { throw new ServiceUnavailableException( "The group member administration capability is not supported for the user directory (" + getUserDirectoryId() + ""); } DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new UserNotFoundException(username); } LdapName groupDN = getGroupDN(dirContext, groupName); if (groupDN == null) { throw new GroupNotFoundException(groupName); } Attributes attributes = dirContext.getAttributes(groupDN, groupMemberAttributeArray); BasicAttribute attribute = new BasicAttribute(groupMemberAttribute); if (attributes.get(groupMemberAttribute) != null) { @SuppressWarnings("unchecked") NamingEnumeration<String> groupMembers = (NamingEnumeration<String>) attributes.get(groupMemberAttribute).getAll(); while (groupMembers.hasMore()) { LdapName groupMemberDN = new LdapName(groupMembers.next()); if (groupMemberDN.equals(userDN)) { return; } else { attribute.add(groupMemberDN.toString()); } } } attribute.add(userDN.toString()); dirContext.modifyAttributes( groupDN, new ModificationItem[] {new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute)}); } catch (UserNotFoundException | GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to add the user (" + username + ") to the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void adminChangePassword( String username, String newPassword, boolean expirePassword, boolean lockUser, boolean resetPasswordHistory, PasswordChangeReason reason) throws UserNotFoundException, ServiceUnavailableException { if (!capabilities.getSupportsAdminChangePassword()) { throw new ServiceUnavailableException( "The admin change password capability is not supported for the user directory (" + getUserDirectoryId() + ""); } DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new UserNotFoundException(username); } List<ModificationItem> modificationItems = new ArrayList<>(); BasicAttribute passwordAttribute = new BasicAttribute("userPassword"); passwordAttribute.add(newPassword); modificationItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, passwordAttribute)); dirContext.modifyAttributes(userDN, modificationItems.toArray(new ModificationItem[0])); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to change the password for the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void authenticate(String username, String password) throws AuthenticationFailedException, UserLockedException, ExpiredPasswordException, UserNotFoundException, ServiceUnavailableException { DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new UserNotFoundException(username); } DirContext userDirContext = null; try { userDirContext = getDirContext(userDN.toString(), password); } catch (Throwable e) { if (e.getCause() instanceof javax.naming.AuthenticationException) { throw new AuthenticationFailedException( "Failed to authenticate the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")"); } else { logger.error( "Failed to authenticate the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); throw new AuthenticationFailedException( "Failed to authenticate the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } finally { JNDIUtil.close(userDirContext); } } catch (AuthenticationFailedException | UserNotFoundException e) { throw e; } // TODO: FIX THIS IMPLEMENTATION BY CORRECTLY INTERPRETING USER LOCKED ERROR -- MARCUS // catch (AuthenticationFailedException | UserNotFoundException | UserLockedException // | ExpiredPasswordException e) // { // throw e; // } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to authenticate the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void changePassword(String username, String password, String newPassword) throws AuthenticationFailedException, UserLockedException, ExistingPasswordException, ServiceUnavailableException { if (!capabilities.getSupportsChangePassword()) { throw new ServiceUnavailableException( "The change password capability is not supported for the user directory (" + getUserDirectoryId() + ""); } DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new AuthenticationFailedException( "Authentication failed while attempting to change the password for the user (" + username + ")"); } DirContext userDirContext = null; try { userDirContext = getDirContext(userDN.toString(), password); } catch (Throwable e) { if (e.getCause() instanceof javax.naming.AuthenticationException) { throw new AuthenticationFailedException( "Authentication failed while attempting to change the password for the user (" + username + ")"); } else { logger.error( "Failed to authenticate the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); throw new AuthenticationFailedException( "Failed to authenticate the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } } finally { JNDIUtil.close(userDirContext); } List<ModificationItem> modificationItems = new ArrayList<>(); BasicAttribute passwordAttribute = new BasicAttribute("userPassword"); passwordAttribute.add(newPassword); modificationItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, passwordAttribute)); dirContext.modifyAttributes(userDN, modificationItems.toArray(new ModificationItem[0])); } catch (AuthenticationFailedException e) { throw e; } // TODO: FIX THIS IMPLEMENTATION BY CORRECTLY INTERPRETING USER LOCKED ERROR -- MARCUS // catch (AuthenticationFailedException | UserNotFoundException | UserLockedException // | ExpiredPasswordException e) // { // throw e; // } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to change the password for the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void createGroup(Group group) throws DuplicateGroupException, ServiceUnavailableException { if (!capabilities.getSupportsGroupAdministration()) { throw new ServiceUnavailableException( "The group administration capability is not supported for the user directory (" + getUserDirectoryId() + ""); } DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName groupDN = getGroupDN(dirContext, group.getName()); if (groupDN != null) { throw new DuplicateGroupException(group.getName()); } else { groupDN = new LdapName(groupNameAttribute + "=" + group.getName() + "," + groupBaseDN.toString()); } Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute("objectclass", "top")); attributes.put(new BasicAttribute("objectclass", groupObjectClass)); /* * This is a "hack" to get around the problem where the groupOfNames object class does not * support empty groups. We add the group as a member of itself. This "fake" group member * will be filtered when returning the group members. */ if (groupObjectClass.equalsIgnoreCase("groupOfNames")) { attributes.put(new BasicAttribute(groupMemberAttribute, groupDN.toString())); } attributes.put(new BasicAttribute(groupNameAttribute, group.getName())); if (StringUtils.hasText(groupDescriptionAttribute)) { attributes.put( new BasicAttribute( groupDescriptionAttribute, StringUtils.hasText(group.getDescription()) ? group.getDescription() : "")); } dirContext.bind(groupDN, dirContext, attributes); /* * Create the corresponding group in the database that will be used to map to one or more * roles. */ group.setId(UuidCreator.getShortPrefixComb()); getGroupRepository().saveAndFlush(group); } catch (DuplicateGroupException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the group (" + group.getName() + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void createUser(User user, boolean expiredPassword, boolean userLocked) throws DuplicateUserException, ServiceUnavailableException { if (!capabilities.getSupportsUserAdministration()) { throw new ServiceUnavailableException( "The user administration capability is not supported for the user directory (" + getUserDirectoryId() + ""); } DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, user.getUsername()); if (userDN != null) { throw new DuplicateUserException(user.getUsername()); } Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute("objectclass", "top")); attributes.put(new BasicAttribute("objectclass", userObjectClass)); attributes.put(new BasicAttribute(userUsernameAttribute, user.getUsername())); if ((StringUtils.hasText(userNameAttribute)) && (StringUtils.hasText(user.getName()))) { attributes.put(new BasicAttribute(userNameAttribute, user.getName())); } if ((StringUtils.hasText(userPreferredNameAttribute)) && (StringUtils.hasText(user.getPreferredName()))) { attributes.put(new BasicAttribute(userPreferredNameAttribute, user.getPreferredName())); } if ((StringUtils.hasText(userEmailAttribute)) && (StringUtils.hasText(user.getEmail()))) { attributes.put(new BasicAttribute(userEmailAttribute, user.getEmail())); } if ((StringUtils.hasText(userPhoneNumberAttribute)) && (StringUtils.hasText(user.getPhoneNumber()))) { attributes.put(new BasicAttribute(userPhoneNumberAttribute, user.getPhoneNumber())); } if ((StringUtils.hasText(userMobileNumberAttribute)) && (StringUtils.hasText(user.getMobileNumber()))) { attributes.put(new BasicAttribute(userMobileNumberAttribute, user.getMobileNumber())); } attributes.put( new BasicAttribute( "userPassword", StringUtils.hasText(user.getPassword()) ? user.getPassword() : "")); userDN = new LdapName( userUsernameAttribute + "=" + user.getUsername() + "," + userBaseDN.toString()); dirContext.bind(userDN, dirContext, attributes); } catch (DuplicateUserException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the user (" + user.getUsername() + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void deleteGroup(String groupName) throws GroupNotFoundException, ExistingGroupMembersException, ServiceUnavailableException { if (!capabilities.getSupportsGroupAdministration()) { throw new ServiceUnavailableException( "The group administration capability is not supported for the user directory (" + getUserDirectoryId() + ""); } DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName groupDN = getGroupDN(dirContext, groupName); if (groupDN == null) { throw new GroupNotFoundException(groupName); } Attributes attributes = dirContext.getAttributes(groupDN, groupMemberAttributeArray); if (attributes.get(groupMemberAttribute) != null) { var attribute = attributes.get(groupMemberAttribute); if (attribute.size() == 1) { LdapName lastGroupMember = new LdapName(String.valueOf(attribute.get(0))); if (!lastGroupMember.equals(groupDN)) { throw new ExistingGroupMembersException(groupName); } } else if (attribute.size() > 1) { throw new ExistingGroupMembersException(groupName); } } dirContext.destroySubcontext(groupDN); // Delete the corresponding group in the database Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); groupIdOptional.ifPresent(uuid -> getGroupRepository().deleteById(uuid)); } catch (GroupNotFoundException | ExistingGroupMembersException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to delete the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void deleteUser(String username) throws UserNotFoundException, ServiceUnavailableException { if (!capabilities.getSupportsUserAdministration()) { throw new ServiceUnavailableException( "The user administration capability is not supported for the user directory (" + getUserDirectoryId() + ""); } DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new UserNotFoundException(username); } // Remove the user from any groups String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", groupObjectClass, groupMemberAttribute, userDN.toString()); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); while (searchResults.hasMore()) { SearchResult searchResult = searchResults.next(); Attributes attributes = searchResult.getAttributes(); BasicAttribute attribute = new BasicAttribute(groupMemberAttribute); if (attributes.get(groupMemberAttribute) != null) { @SuppressWarnings("unchecked") NamingEnumeration<String> groupMembers = (NamingEnumeration<String>) attributes.get(groupMemberAttribute).getAll(); while (groupMembers.hasMore()) { LdapName groupMemberDN = new LdapName(groupMembers.next()); if (!groupMemberDN.equals(userDN)) { attribute.add(groupMemberDN.toString()); } } } if (attribute.size() > 0) { dirContext.modifyAttributes( new LdapName(searchResult.getNameInNamespace()), new ModificationItem[] { new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute) }); } else { dirContext.modifyAttributes( new LdapName(searchResult.getNameInNamespace()), new ModificationItem[] { new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attribute) }); } } dirContext.destroySubcontext(userDN); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to delete the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public List<User> findUsers(List<UserAttribute> userAttributes) throws InvalidAttributeException, ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); String searchFilter = "(objectClass=" + userObjectClass + ")"; if (userAttributes.size() > 0) { StringBuilder buffer = new StringBuilder(); buffer.append("(&(objectClass="); buffer.append(userObjectClass); buffer.append(")"); for (UserAttribute userAttribute : userAttributes) { buffer.append("("); buffer.append(userAttribute.getName()); buffer.append("=*"); buffer.append(userAttribute.getValue()); buffer.append("*)"); } buffer.append(")"); searchFilter = buffer.toString(); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchControls.setCountLimit(maxFilteredUsers); List<User> users = new ArrayList<>(); searchResults = dirContext.search(userBaseDN, searchFilter, searchControls); while (searchResults.hasMore() && (users.size() <= maxFilteredUsers)) { users.add(buildUserFromSearchResult(searchResults.next())); } return users; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to find the users for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public UserDirectoryCapabilities getCapabilities() { return capabilities; } @Override public List<String> getFunctionCodesForUser(String username) throws UserNotFoundException, ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new UserNotFoundException(username); } String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", groupObjectClass, groupMemberAttribute, userDN.toString()); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); List<String> groupNames = new ArrayList<>(); while (searchResults.hasMore()) { SearchResult searchResult = searchResults.next(); if (searchResult.getAttributes().get(groupNameAttribute) != null) { groupNames.add( String.valueOf(searchResult.getAttributes().get(groupNameAttribute).get()) .toLowerCase()); } } if (groupNames.isEmpty()) { return new ArrayList<>(); } return getGroupRepository() .getFunctionCodesByUserDirectoryIdAndGroupNames(getUserDirectoryId(), groupNames); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the function codes for the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public Group getGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", groupObjectClass, groupNameAttribute, groupName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); if (searchResults.hasMore()) { return buildGroupFromSearchResult(searchResults.next()); } else { throw new GroupNotFoundException(groupName); } } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public List<String> getGroupNames() throws ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); String searchFilter = String.format("(objectClass=%s)", groupObjectClass); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchControls.setCountLimit(maxFilteredGroups); searchControls.setReturningAttributes(new String[] {groupNameAttribute}); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); List<String> groupNames = new ArrayList<>(); while (searchResults.hasMore() && (groupNames.size() <= maxFilteredGroups)) { SearchResult searchResult = searchResults.next(); Attributes attributes = searchResult.getAttributes(); groupNames.add(String.valueOf(attributes.get(groupNameAttribute).get())); } return groupNames; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the group names for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public List<String> getGroupNamesForUser(String username) throws UserNotFoundException, ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new UserNotFoundException(username); } String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", groupObjectClass, groupMemberAttribute, userDN.toString()); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); List<String> groupNames = new ArrayList<>(); while (searchResults.hasMore()) { SearchResult searchResult = searchResults.next(); if (searchResult.getAttributes().get(groupNameAttribute) != null) { groupNames.add( String.valueOf(searchResult.getAttributes().get(groupNameAttribute).get())); } } return groupNames; } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the names of the groups the user (" + username + ") is a member of for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public List<Group> getGroups() throws ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); String searchFilter = String.format("(objectClass=%s)", groupObjectClass); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchControls.setCountLimit(maxFilteredGroups); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); List<Group> groups = new ArrayList<>(); while (searchResults.hasMore() && (groups.size() <= maxFilteredGroups)) { groups.add(buildGroupFromSearchResult(searchResults.next())); } return groups; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the groups for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public Groups getGroups( String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); String searchFilter; if (StringUtils.hasText(filter)) { searchFilter = String.format( "(&(objectClass=%s)(%s=*%s*))", groupObjectClass, groupNameAttribute, filter); } else { searchFilter = String.format("(objectClass=%s)", groupObjectClass); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchControls.setCountLimit(maxFilteredGroups); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); List<Group> groups = new ArrayList<>(); while (searchResults.hasMore() && (groups.size() <= maxFilteredGroups)) { groups.add(buildGroupFromSearchResult(searchResults.next())); } if (sortDirection == SortDirection.ASCENDING) { groups.sort(Comparator.comparing(Group::getName)); } else { groups.sort((Group group1, Group group2) -> group2.getName().compareTo(group1.getName())); } long totalGroups = groups.size(); if ((pageIndex != null) && (pageSize != null)) { int toIndex = (pageIndex * pageSize) + pageSize; groups = groups.subList(pageIndex * pageSize, Math.min(toIndex, groups.size())); } return new Groups( getUserDirectoryId(), groups, totalGroups, filter, sortDirection, pageIndex, pageSize); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the filtered groups for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public List<Group> getGroupsForUser(String username) throws UserNotFoundException, ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new UserNotFoundException(username); } String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", groupObjectClass, groupMemberAttribute, userDN.toString()); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); List<Group> groups = new ArrayList<>(); while (searchResults.hasMore()) { groups.add(buildGroupFromSearchResult(searchResults.next())); } return groups; } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the groups the user is a member of (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public List<GroupMember> getMembersForGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", groupObjectClass, groupNameAttribute, groupName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); if (searchResults.hasMore()) { SearchResult searchResult = searchResults.next(); List<GroupMember> groupMembers = new ArrayList<>(); var attribute = searchResult.getAttributes().get(groupMemberAttribute); if (attribute != null) { for (int i = 0; ((i < attribute.size()) && (i < maxFilteredGroupMembers)); i++) { LdapName groupMemberDn = new LdapName(String.valueOf(attribute.get(i))); for (Rdn rdn : groupMemberDn.getRdns()) { if (rdn.getType().equalsIgnoreCase(userUsernameAttribute)) { groupMembers.add( new GroupMember( getUserDirectoryId(), groupName, GroupMemberType.USER, String.valueOf(rdn.getValue()))); break; } } } } return groupMembers; } else { throw new GroupNotFoundException(groupName); } } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the members for the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public GroupMembers getMembersForGroup( String groupName, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws GroupNotFoundException, ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); if (StringUtils.hasText(filter)) { filter = filter.toLowerCase(); } String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", groupObjectClass, groupNameAttribute, groupName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); if (searchResults.hasMore()) { SearchResult searchResult = searchResults.next(); List<GroupMember> groupMembers = new ArrayList<>(); var attribute = searchResult.getAttributes().get(groupMemberAttribute); if (attribute != null) { for (int i = 0; i < attribute.size(); i++) { LdapName groupMemberDn = new LdapName(String.valueOf(attribute.get(i))); for (Rdn rdn : groupMemberDn.getRdns()) { if (rdn.getType().equalsIgnoreCase(userUsernameAttribute)) { if (!StringUtils.hasText(filter)) { groupMembers.add( new GroupMember( getUserDirectoryId(), groupName, GroupMemberType.USER, String.valueOf(rdn.getValue()))); } else { /* * NOTE: We perform the filtering here as directory servers like OpenLDAP do not * support substring case-insensitive matches for the member attribute on * the groupOfNames objectclass. */ String username = String.valueOf(rdn.getValue()); if (username.contains(filter)) { groupMembers.add( new GroupMember( getUserDirectoryId(), groupName, GroupMemberType.USER, String.valueOf(rdn.getValue()))); } } break; } } } } if (sortDirection == SortDirection.ASCENDING) { groupMembers.sort(Comparator.comparing(GroupMember::getMemberName)); } else { groupMembers.sort( (GroupMember groupMember1, GroupMember groupMember2) -> groupMember2.getMemberName().compareTo(groupMember1.getMemberName())); } long totalGroupMembers = groupMembers.size(); if ((pageIndex != null) && (pageSize != null)) { pageSize = Math.min(pageSize, maxFilteredGroupMembers); int toIndex = (pageIndex * pageSize) + pageSize; groupMembers = groupMembers.subList(pageIndex * pageSize, Math.min(toIndex, groupMembers.size())); } return new GroupMembers( getUserDirectoryId(), groupName, groupMembers, totalGroupMembers, filter, sortDirection, pageIndex, pageSize); } else { throw new GroupNotFoundException(groupName); } } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the filtered members for the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public List<String> getRoleCodesForGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException { DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName groupDN = getGroupDN(dirContext, groupName); if (groupDN == null) { throw new GroupNotFoundException(groupName); } Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isPresent()) { return getGroupRepository().getRoleCodesByGroupId(groupIdOptional.get()); } else { return new ArrayList<>(); } } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the role codes for the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public List<String> getRoleCodesForUser(String username) throws UserNotFoundException, ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new UserNotFoundException(username); } String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", groupObjectClass, groupMemberAttribute, userDN.toString()); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); List<String> groupNames = new ArrayList<>(); while (searchResults.hasMore()) { SearchResult searchResult = searchResults.next(); if (searchResult.getAttributes().get(groupNameAttribute) != null) { groupNames.add( String.valueOf(searchResult.getAttributes().get(groupNameAttribute).get()) .toLowerCase()); } } if (groupNames.isEmpty()) { return new ArrayList<>(); } return getGroupRepository() .getRoleCodesByUserDirectoryIdAndGroupNames(getUserDirectoryId(), groupNames); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the role codes for the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public List<GroupRole> getRolesForGroup(String groupName) throws GroupNotFoundException, ServiceUnavailableException { DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName groupDN = getGroupDN(dirContext, groupName); if (groupDN == null) { throw new GroupNotFoundException(groupName); } Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); List<GroupRole> groupRoles = new ArrayList<>(); if (groupIdOptional.isPresent()) { for (String roleCode : getGroupRepository().getRoleCodesByGroupId(groupIdOptional.get())) { groupRoles.add(new GroupRole(getUserDirectoryId(), groupName, roleCode)); } } return groupRoles; } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the roles for the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public User getUser(String username) throws UserNotFoundException, ServiceUnavailableException { DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); User user = getUser(dirContext, username); if (user == null) { throw new UserNotFoundException(username); } return user; } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public String getUserName(String username) throws UserNotFoundException, ServiceUnavailableException { DirContext dirContext = null; try { // TODO: MAKE THIS IMPLEMENTATION MORE EFFICIENT AND DO NOT RETRIEVE THE WHOLE USER -- MARCUS dirContext = getDirContext(bindDN, bindPassword); User user = getUser(dirContext, username); if (user == null) { throw new UserNotFoundException(username); } StringBuilder buffer = new StringBuilder(user.getName()); if (StringUtils.hasText(user.getPreferredName())) { if (buffer.length() > 0) { buffer.append(" "); } buffer.append(user.getPreferredName()); } return buffer.toString(); } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the name of the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public List<User> getUsers() throws ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); String searchFilter = String.format("(objectClass=%s)", userObjectClass); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchControls.setCountLimit(maxFilteredUsers); List<User> users = new ArrayList<>(); searchResults = dirContext.search(userBaseDN, searchFilter, searchControls); while (searchResults.hasMore() && (users.size() <= maxFilteredUsers)) { users.add(buildUserFromSearchResult(searchResults.next())); } return users; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the users for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } public Users getUsers( String filter, UserSortBy sortBy, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); String searchFilter; if (StringUtils.hasText(filter)) { searchFilter = String.format( "(&(objectClass=%s)(|(%s=*%s*)(%s=*%s*)(%s=*%s*)))", userObjectClass, userUsernameAttribute, filter, userNameAttribute, filter, userPreferredNameAttribute, filter); } else { searchFilter = String.format("(objectClass=%s)", userObjectClass); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchControls.setCountLimit(maxFilteredUsers); // TODO: Implement sorting of users for LDAP queries -- MARCUS List<User> users = new ArrayList<>(); searchResults = dirContext.search(userBaseDN, searchFilter, searchControls); while (searchResults.hasMore() && (users.size() <= maxFilteredUsers)) { users.add(buildUserFromSearchResult(searchResults.next())); } if (sortDirection == SortDirection.ASCENDING) { if (sortBy == UserSortBy.USERNAME) { users.sort(Comparator.comparing(User::getUsername)); } else if (sortBy == UserSortBy.NAME) { users.sort(Comparator.comparing(User::getName)); } else if (sortBy == UserSortBy.PREFERRED_NAME) { users.sort(Comparator.comparing(User::getPreferredName)); } } else { if (sortBy == UserSortBy.USERNAME) { users.sort( (User user1, User user2) -> user2.getUsername().compareTo(user1.getUsername())); } else if (sortBy == UserSortBy.NAME) { users.sort((User user1, User user2) -> user2.getName().compareTo(user1.getName())); } else if (sortBy == UserSortBy.PREFERRED_NAME) { users.sort( (User user1, User user2) -> user2.getPreferredName().compareTo(user1.getPreferredName())); } } long totalUsers = users.size(); if ((pageIndex != null) && (pageSize != null)) { int toIndex = (pageIndex * pageSize) + pageSize; users = users.subList(pageIndex * pageSize, Math.min(toIndex, users.size())); } return new Users( getUserDirectoryId(), users, totalUsers, filter, sortBy, sortDirection, pageIndex, pageSize); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the filtered users for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public boolean isExistingUser(String username) throws ServiceUnavailableException { DirContext dirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { dirContext = getDirContext(bindDN, bindPassword); String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", userObjectClass, userUsernameAttribute, username); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchResults = dirContext.search(baseDN, searchFilter, searchControls); return searchResults.hasMore(); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to check whether the user (" + username + ") is an existing user for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(searchResults); JNDIUtil.close(dirContext); } } @Override public boolean isUserInGroup(String groupName, String username) throws UserNotFoundException, GroupNotFoundException, ServiceUnavailableException { DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new UserNotFoundException(username); } LdapName groupDN = getGroupDN(dirContext, groupName); if (groupDN == null) { throw new GroupNotFoundException(groupName); } Attributes attributes = dirContext.getAttributes(groupDN, groupMemberAttributeArray); if (attributes.get(groupMemberAttribute) != null) { NamingEnumeration<?> attributeValues = attributes.get(groupMemberAttribute).getAll(); while (attributeValues.hasMore()) { LdapName memberDN = new LdapName((String) attributeValues.next()); if (memberDN.equals(userDN)) { return true; } } } return false; } catch (UserNotFoundException | GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to check if the user (" + username + ") is in the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void removeMemberFromGroup(String groupName, GroupMemberType memberType, String memberName) throws GroupNotFoundException, GroupMemberNotFoundException, ServiceUnavailableException { if (!capabilities.getSupportsGroupMemberAdministration()) { throw new ServiceUnavailableException( "The group member administration capability is not supported for the user directory (" + getUserDirectoryId() + ""); } if (memberType != GroupMemberType.USER) { throw new ServiceUnavailableException( "Unsupported group member type (" + memberType.description() + ")"); } try { removeUserFromGroup(groupName, memberName); } catch (UserNotFoundException e) { throw new GroupMemberNotFoundException(memberType, memberName); } } @Override public void removeRoleFromGroup(String groupName, String roleCode) throws GroupNotFoundException, GroupRoleNotFoundException, ServiceUnavailableException { DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName groupDN = getGroupDN(dirContext, groupName); if (groupDN == null) { throw new GroupNotFoundException(groupName); } Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), groupName); if (groupIdOptional.isPresent()) { if (getGroupRepository().removeRoleFromGroup(groupIdOptional.get(), roleCode) == 0) { throw new GroupRoleNotFoundException(roleCode); } } else { throw new GroupRoleNotFoundException(roleCode); } } catch (GroupNotFoundException | GroupRoleNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to remove the role (" + roleCode + ") from the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void removeUserFromGroup(String groupName, String username) throws UserNotFoundException, GroupNotFoundException, ServiceUnavailableException { DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new UserNotFoundException(username); } LdapName groupDN = getGroupDN(dirContext, groupName); if (groupDN == null) { throw new GroupNotFoundException(groupName); } Attributes attributes = dirContext.getAttributes(groupDN, groupMemberAttributeArray); BasicAttribute attribute = new BasicAttribute(groupMemberAttribute); if (attributes.get(groupMemberAttribute) != null) { @SuppressWarnings("unchecked") NamingEnumeration<String> groupMembers = (NamingEnumeration<String>) attributes.get(groupMemberAttribute).getAll(); while (groupMembers.hasMore()) { LdapName groupMemberDN = new LdapName(groupMembers.next()); if (!groupMemberDN.equals(userDN)) { attribute.add(groupMemberDN.toString()); } } } if (attribute.size() > 0) { dirContext.modifyAttributes( groupDN, new ModificationItem[] {new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute)}); } else { dirContext.modifyAttributes( groupDN, new ModificationItem[] {new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attribute)}); } } catch (UserNotFoundException | GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to remove the user (" + username + ") from the group (" + groupName + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void resetPassword(String username, String newPassword) throws UserNotFoundException, UserLockedException, ExistingPasswordException, ServiceUnavailableException { if (!capabilities.getSupportsChangePassword()) { throw new ServiceUnavailableException( "The change password capability is not supported for the user directory (" + getUserDirectoryId() + ""); } DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, username); if (userDN == null) { throw new UserNotFoundException(username); } List<ModificationItem> modificationItems = new ArrayList<>(); BasicAttribute passwordAttribute = new BasicAttribute("userPassword"); passwordAttribute.add(newPassword); modificationItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, passwordAttribute)); dirContext.modifyAttributes(userDN, modificationItems.toArray(new ModificationItem[0])); } catch (UserNotFoundException e) { throw e; } // TODO: FIX THIS IMPLEMENTATION BY CORRECTLY INTERPRETING USER LOCKED ERROR -- MARCUS // catch (UserNotFoundException | UserLockedException // | ExpiredPasswordException e) // { // throw e; // } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to reset the password for the user (" + username + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void updateGroup(Group group) throws GroupNotFoundException, ServiceUnavailableException { if (!capabilities.getSupportsGroupAdministration()) { throw new ServiceUnavailableException( "The group administration capability is not supported for the user directory (" + getUserDirectoryId() + ""); } DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName groupDN = getGroupDN(dirContext, group.getName()); if (groupDN == null) { throw new GroupNotFoundException(group.getName()); } List<ModificationItem> modificationItems = new ArrayList<>(); if (StringUtils.hasText(groupDescriptionAttribute)) { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute( groupDescriptionAttribute, StringUtils.hasText(group.getDescription()) ? group.getDescription() : ""))); } if (modificationItems.size() > 0) { dirContext.modifyAttributes(groupDN, modificationItems.toArray(new ModificationItem[0])); } // Update the corresponding group in the database Optional<UUID> groupIdOptional = getGroupRepository() .getIdByUserDirectoryIdAndNameIgnoreCase(getUserDirectoryId(), group.getName()); if (groupIdOptional.isEmpty()) { group.setId(UuidCreator.getShortPrefixComb()); } else { group.setId(groupIdOptional.get()); } getGroupRepository().saveAndFlush(group); } catch (GroupNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to update the group (" + group.getName() + ") for the user directory (" + getUserDirectoryId() + ")", e); } finally { JNDIUtil.close(dirContext); } } @Override public void updateUser(User user, boolean expirePassword, boolean lockUser) throws UserNotFoundException, ServiceUnavailableException { if (!capabilities.getSupportsUserAdministration()) { throw new ServiceUnavailableException( "The user administration capability is not supported for the user directory (" + getUserDirectoryId() + ""); } DirContext dirContext = null; try { dirContext = getDirContext(bindDN, bindPassword); LdapName userDN = getUserDN(dirContext, user.getUsername()); if (userDN == null) { throw new UserNotFoundException(user.getUsername()); } List<ModificationItem> modificationItems = new ArrayList<>(); if (StringUtils.hasText(userNameAttribute)) { if (StringUtils.hasText(user.getName())) { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(userNameAttribute, user.getName()))); } else { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(userNameAttribute))); } } if (StringUtils.hasText(userPreferredNameAttribute)) { if (StringUtils.hasText(user.getPreferredName())) { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(userPreferredNameAttribute, user.getPreferredName()))); } else { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(userPreferredNameAttribute))); } } if (StringUtils.hasText(userEmailAttribute)) { if (StringUtils.hasText(user.getEmail())) { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(userEmailAttribute, user.getEmail()))); } else { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(userEmailAttribute))); } } if (StringUtils.hasText(userPhoneNumberAttribute)) { if (StringUtils.hasText(user.getPhoneNumber())) { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(userPhoneNumberAttribute, user.getPhoneNumber()))); } else { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(userPhoneNumberAttribute))); } } if (StringUtils.hasText(userMobileNumberAttribute)) { if (StringUtils.hasText(user.getMobileNumber())) { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(userMobileNumberAttribute, user.getMobileNumber()))); } else { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(userMobileNumberAttribute))); } } if (StringUtils.hasText(user.getPassword())) { modificationItems.add( new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", user.getPassword()))); } if (modificationItems.size() > 0) { dirContext.modifyAttributes(userDN, modificationItems.toArray(new ModificationItem[0])); } } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to update the user (" + user.getUsername() + ") for the user directory (" + getUserDirectoryId() + "): " + e.getMessage(), e); } finally { JNDIUtil.close(dirContext); } } private Group buildGroupFromSearchResult(SearchResult searchResult) throws NamingException { Attributes attributes = searchResult.getAttributes(); Group group = new Group(String.valueOf(attributes.get(groupNameAttribute).get())); group.setId(null); group.setUserDirectoryId(getUserDirectoryId()); if ((StringUtils.hasText(groupDescriptionAttribute)) && (attributes.get(groupDescriptionAttribute) != null)) { group.setDescription(String.valueOf(attributes.get(groupDescriptionAttribute).get())); } else { group.setDescription(""); } return group; } private User buildUserFromSearchResult(SearchResult searchResult) throws NamingException { Attributes attributes = searchResult.getAttributes(); User user = new User(); // user.setId(new LdapName(searchResult.getNameInNamespace().toLowerCase()).toString()); user.setUsername(String.valueOf(attributes.get(userUsernameAttribute).get())); user.setUserDirectoryId(getUserDirectoryId()); // TODO: Correctly process LDAP attributes for user to set status -- MARCUS user.setStatus(UserStatus.ACTIVE); user.setPassword(""); if ((StringUtils.hasText(userNameAttribute)) && (attributes.get(userNameAttribute) != null)) { user.setName(String.valueOf(attributes.get(userNameAttribute).get())); } else { user.setName(""); } if ((StringUtils.hasText(userPreferredNameAttribute)) && (attributes.get(userPreferredNameAttribute) != null)) { user.setPreferredName(String.valueOf(attributes.get(userPreferredNameAttribute).get())); } else { user.setPreferredName(""); } if ((StringUtils.hasText(userPhoneNumberAttribute)) && (attributes.get(userPhoneNumberAttribute) != null)) { user.setPhoneNumber(String.valueOf(attributes.get(userPhoneNumberAttribute).get())); } else { user.setPhoneNumber(""); } if ((StringUtils.hasText(userMobileNumberAttribute)) && (attributes.get(userMobileNumberAttribute) != null)) { user.setMobileNumber(String.valueOf(attributes.get(userMobileNumberAttribute).get())); } else { user.setMobileNumber(""); } if ((StringUtils.hasText(userEmailAttribute)) && (attributes.get(userEmailAttribute) != null)) { user.setEmail(String.valueOf(attributes.get(userEmailAttribute).get())); } else { user.setEmail(""); } return user; } private DirContext getDirContext(String userDN, String password) throws ServiceUnavailableException { try { String url = useSSL ? "ldaps://" : "ldap://"; url += host; url += ":"; url += port; String connectionType = "simple"; Hashtable<String, String> environment = new Hashtable<>(); environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); environment.put(Context.PROVIDER_URL, url); environment.put(Context.SECURITY_AUTHENTICATION, connectionType); environment.put(Context.SECURITY_PRINCIPAL, userDN); environment.put(Context.SECURITY_CREDENTIALS, password); return new InitialDirContext(environment); } catch (Throwable e) { throw new ServiceUnavailableException( String.format( "Failed to retrieve the JNDI directory context for the user directory (%s)", getUserDirectoryId()), e); } } private LdapName getGroupDN(DirContext dirContext, String groupName) throws ServiceUnavailableException { NamingEnumeration<SearchResult> searchResults = null; try { List<LdapName> groupDNs = new ArrayList<>(); String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", groupObjectClass, groupNameAttribute, groupName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchControls.setReturningAttributes(EMPTY_ATTRIBUTE_LIST); searchResults = dirContext.search(groupBaseDN, searchFilter, searchControls); while (searchResults.hasMore()) { groupDNs.add(new LdapName(searchResults.next().getNameInNamespace().toLowerCase())); } if (groupDNs.size() == 0) { return null; } else if (groupDNs.size() == 1) { return groupDNs.get(0); } else { StringBuilder buffer = new StringBuilder(); for (LdapName groupDN : groupDNs) { if (buffer.length() > 0) { buffer.append(" "); } buffer.append("(").append(groupDN).append(")"); } throw new ServiceUnavailableException( String.format( "Found multiple groups (%d) with the name of the group (%s) with DNs %s", groupDNs.size(), groupName, buffer.toString())); } } catch (Throwable e) { throw new ServiceUnavailableException( String.format( "Failed to retrieve the DN for the group (%s) from the LDAP directory (%s:%d)", groupName, host, port), e); } finally { JNDIUtil.close(searchResults); } } private User getUser(DirContext dirContext, String username) throws ServiceUnavailableException { NamingEnumeration<SearchResult> searchResults = null; try { List<User> users = new ArrayList<>(); String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", userObjectClass, userUsernameAttribute, username); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); // First search for a non-shared user searchResults = dirContext.search(baseDN, searchFilter, searchControls); while (searchResults.hasMore()) { users.add(buildUserFromSearchResult(searchResults.next())); } if (users.size() == 0) { return null; } else if (users.size() == 1) { return users.get(0); } else { StringBuilder buffer = new StringBuilder(); for (User user : users) { if (buffer.length() > 0) { buffer.append(" "); } buffer.append("(").append(user.getId()).append(")"); } throw new ServiceUnavailableException( String.format( "Found multiple users (%d) with the username (%s) with DNs %s", users.size(), username, buffer.toString())); } } catch (Throwable e) { throw new ServiceUnavailableException( String.format( "Failed to retrieve the details for the user (%s) from the LDAP directory (%s:%d)", username, host, port), e); } finally { JNDIUtil.close(searchResults); } } private LdapName getUserDN(DirContext dirContext, String username) throws ServiceUnavailableException { NamingEnumeration<SearchResult> searchResults = null; try { List<LdapName> userDNs = new ArrayList<>(); String searchFilter = String.format( "(&(objectClass=%s)(%s=%s))", userObjectClass, userUsernameAttribute, username); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningObjFlag(false); searchControls.setReturningAttributes(EMPTY_ATTRIBUTE_LIST); searchResults = dirContext.search(baseDN, searchFilter, searchControls); while (searchResults.hasMore()) { userDNs.add(new LdapName(searchResults.next().getNameInNamespace().toLowerCase())); } if (userDNs.size() == 0) { return null; } else if (userDNs.size() == 1) { return userDNs.get(0); } else { StringBuilder buffer = new StringBuilder(); for (LdapName userDN : userDNs) { if (buffer.length() > 0) { buffer.append(" "); } buffer.append("(").append(userDN).append(")"); } throw new ServiceUnavailableException( String.format( "Found multiple users (%d) with the username (%s) with DNs %s", userDNs.size(), username, buffer.toString())); } } catch (Throwable e) { throw new ServiceUnavailableException( String.format( "Failed to retrieve the DN for the user (%s) from the LDAP directory (%s:%d)", username, host, port), e); } finally { JNDIUtil.close(searchResults); } } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/PasswordChange.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>PasswordChange</b> class holds the information for a password change. * * @author Marcus Portmann */ @Schema(description = "A password change") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "expirePassword", "lockUser", "newPassword", "password", "reason", "resetPasswordHistory", "securityCode" }) @SuppressWarnings({"unused"}) public class PasswordChange implements Serializable { private static final long serialVersionUID = 1000000; /** Expire the user's password when performing an administrative password change. */ @Schema( description = "Expire the user's password when performing an administrative password change") @JsonProperty private Boolean expirePassword; /** Lock the user when performing an administrative password change. */ @Schema(description = "Lock the user when performing an administrative password change") @JsonProperty private Boolean lockUser; /** The new password. */ @Schema(description = "The new password", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) private String newPassword; /** * The password for the user that is used to authorise the operation when performing a user * password change. */ @Schema( description = "The password for the user that is used to authorise the operation when performing a user password change") @JsonProperty @Size(min = 1, max = 100) private String password; /** The reason for changing the password. */ @Schema(description = "The reason for changing the password", required = true) @JsonProperty(required = true) @NotNull private PasswordChangeReason reason; /** Reset the user's password history when performing an administrative password change. */ @Schema( description = "Reset the user's password history when performing an administrative password change") @JsonProperty private Boolean resetPasswordHistory; /** The security code when performing a forgotten password change. */ @Schema(description = "The security code when performing a forgotten password change.") @JsonProperty private String securityCode; /** Constructs a new <b>PasswordChange</b>. */ public PasswordChange() {} /** * Constructs a new <b>PasswordChange</b> for a USER password change. * * @param newPassword the new password * @param password the password for the user that is used to authorise the operation when * performing a user password change */ public PasswordChange(String newPassword, String password) { this.newPassword = newPassword; this.password = password; this.reason = PasswordChangeReason.USER; } /** * Constructs a new <b>PasswordChange</b> for an ADMINISTRATIVE password change. * * @param newPassword the new password * @param expirePassword expire the user's password when performing the administrative password * change * @param lockUser lock the user when performing the administrative password change * @param resetPasswordHistory reset the user's password history when performing the * administrative password change */ public PasswordChange( String newPassword, Boolean expirePassword, Boolean lockUser, Boolean resetPasswordHistory) { this.newPassword = newPassword; this.expirePassword = expirePassword; this.lockUser = lockUser; this.resetPasswordHistory = resetPasswordHistory; this.reason = PasswordChangeReason.ADMINISTRATIVE; } /** * Returns whether the user's password should be expired when performing an administrative * password change. * * @return <b>true</b> if the user's password should be expired when performing an administrative * password changeor <b>false</b> otherwise */ public Boolean getExpirePassword() { return expirePassword; } /** * Returns whether the user should be locked when performing an administrative password change. * * @return <b>true</b> if the user should be locked when performing an administrative password * change or <b>false</b> otherwise */ public Boolean getLockUser() { return lockUser; } /** * Returns the new password. * * @return the new password */ public String getNewPassword() { return newPassword; } /** * Returns the password for the user that is used to authorise the operation when performing a * user password change. * * @return the password for the user that is used to authorise the operation when performing a * user password change */ public String getPassword() { return password; } /** * Returns the reason for changing the password. * * @return the reason for changing the password */ public PasswordChangeReason getReason() { return reason; } /** * Returns whether the user's password history should be reset when performing an administrative * password change. * * @return <b>true</b> if the user's password history should be reset when performing an * administrative password changeor <b>false</b> otherwise */ public Boolean getResetPasswordHistory() { return resetPasswordHistory; } /** * Returns the security code when performing a forgotten password change. * * @return the security code when performing a forgotten password change */ public String getSecurityCode() { return securityCode; } /** * Set whether the user's password should be expired when performing an administrative password * change. * * @param expirePassword expire the user's password when performing an administrative password * change */ public void setExpirePassword(Boolean expirePassword) { this.expirePassword = expirePassword; } /** * Set whether the user should be locked when performing an administrative password change. * * @param lockUser lock the user when performing an administrative password change */ public void setLockUser(Boolean lockUser) { this.lockUser = lockUser; } /** * Set the new password when performing a user password change. * * @param newPassword the new password when performing a new password change */ public void setNewPassword(String newPassword) { this.newPassword = newPassword; } /** * Set the password for the user that is used to authorise the operation when performing a user * password change. * * @param password the password for the user that is used to authorise the operation when * performing a user password change */ public void setPassword(String password) { this.password = password; } /** * Set the reason for changing the password. * * @param reason the reason for changing the password */ public void setReason(PasswordChangeReason reason) { this.reason = reason; } /** * Set whether the user's password history should be reset when performing an administrative * password change. * * @param resetPasswordHistory reset the user's password history when performing an administrative * password change */ public void setResetPasswordHistory(Boolean resetPasswordHistory) { this.resetPasswordHistory = resetPasswordHistory; } /** * Set the security code when performing a forgotten password change. * * @param securityCode the security code when performing a forgotten password change */ public void setSecurityCode(String securityCode) { this.securityCode = securityCode; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/PasswordChangeReason.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.v3.oas.annotations.media.Schema; /** * The <b>PasswordChangeReason</b> enumeration defines the possible reasons for why a user's * password was changed. * * @author Marcus Portmann */ @Schema(description = "The password change reason") public enum PasswordChangeReason { /** User. */ USER("user", "User"), /** Administrative. */ ADMINISTRATIVE("administrative", "Administrative"), /** Reset. */ RESET("reset", "Reset"); private final String code; private final String description; PasswordChangeReason(String code, String description) { this.code = code; this.description = description; } /** * Returns the password change reason given by the specified code value. * * @param code the code for the password change reason * @return the password change reason given by the specified code value */ @JsonCreator public static PasswordChangeReason fromCode(String code) { switch (code) { case "user": return PasswordChangeReason.USER; case "administrative": return PasswordChangeReason.ADMINISTRATIVE; case "reset": return PasswordChangeReason.RESET; default: throw new RuntimeException( "Failed to determine the password change reason with the invalid code (" + code + ")"); } } /** * Returns the code for the password change reason. * * @return the code for the password change reason */ @JsonValue public String code() { return code; } /** * Returns the description for the password change reason. * * @return the description for the password change reason */ public String description() { return description; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/PasswordChangeReasonToStringConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.WritingConverter; import org.springframework.stereotype.Component; /** * The <b>PasswordChangeReasonToStringConverter</b> class implements the Spring converter that * converts a <b>PasswordChangeReason</b> type into a <b>String</b> type. * * @author Marcus Portmann */ @Component @WritingConverter public class PasswordChangeReasonToStringConverter implements Converter<PasswordChangeReason, String> { /** Constructs a new <b>PasswordChangeReasonToStringConverter</b>. */ public PasswordChangeReasonToStringConverter() {} @Override public String convert(PasswordChangeReason source) { return source.code(); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/PasswordReset.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>PasswordReset</b> class holds the information for a password rest. * * @author Marcus Portmann */ @Schema(description = "A password reset") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"username", "requested", "completed", "expired", "status", "securityCodeHash"}) @SuppressWarnings({"unused"}) @Entity @Table(schema = "security", name = "password_resets") @IdClass(PasswordResetId.class) public class PasswordReset implements Serializable { private static final long serialVersionUID = 1000000; /** The date and time the password reset was completed. */ @Schema(description = "The date and time the password reset was completed") @JsonProperty @Column(name = "completed") private LocalDateTime completed; /** The date and time the password reset expired. */ @Schema(description = "The date and time the password reset expired") @JsonProperty @Column(name = "expired") private LocalDateTime expired; /** The date and time the password reset was requested. */ @Schema(description = "The date and time the password reset was requested") @JsonProperty @Id @Column(name = "requested", nullable = false) private LocalDateTime requested; /** The security code hash. */ @Schema(description = "The security code hash", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "security_code_hash", length = 100, nullable = false) private String securityCodeHash; /** The status of the password reset. */ @Schema(description = "The status of the password reset", required = true) @JsonProperty(required = true) @NotNull @Column(name = "status", nullable = false) private PasswordResetStatus status; /** The username for the user associated with the password reset. */ @Schema( description = "The username for the user associated with the password reset", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "username", length = 100, nullable = false) private String username; /** Constructs a new <b>PasswordReset</b>. */ public PasswordReset() {} /** * Constructs a new <b>PasswordReset</b>. * * @param username the username for the user associated with the password reset * @param securityCodeHash the security code hash */ public PasswordReset(String username, String securityCodeHash) { this.username = username; this.securityCodeHash = securityCodeHash; this.requested = LocalDateTime.now(); this.status = PasswordResetStatus.REQUESTED; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } PasswordReset other = (PasswordReset) object; return Objects.equals(username, other.username) && Objects.equals(requested, other.requested); } /** * Returns the date and time the password reset was completed. * * @return the date and time the password reset was completed */ public LocalDateTime getCompleted() { return completed; } /** * Returns the date and time the password reset expired. * * @return the date and time the password reset expired */ public LocalDateTime getExpired() { return expired; } /** * Returns the date and time the password reset was requested. * * @return the date and time the password reset was requested */ public LocalDateTime getRequested() { return requested; } /** * Returns the security code hash. * * @return the security code hash */ public String getSecurityCodeHash() { return securityCodeHash; } /** * Returns the status of the password reset. * * @return the status of the password reset */ public PasswordResetStatus getStatus() { return status; } /** * Returns the username for the user associated with the password reset. * * @return the username for the user associated with the password reset */ public String getUsername() { return username; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((username == null) ? 0 : username.hashCode()) + ((requested == null) ? 0 : requested.hashCode()); } /** * Set the date and time the password reset was completed. * * @param completed the date and time the password reset was completed */ public void setCompleted(LocalDateTime completed) { this.completed = completed; } /** * Set the date and time the password reset expired. * * @param expired the date and time the password reset expired */ public void setExpired(LocalDateTime expired) { this.expired = expired; } /** * Set the date and time the password reset was requested. * * @param requested the date and time the password reset was requested */ public void setRequested(LocalDateTime requested) { this.requested = requested; } /** * Set the security code hash. * * @param securityCodeHash the security code hash */ public void setSecurityCodeHash(String securityCodeHash) { this.securityCodeHash = securityCodeHash; } /** * Set the status of the password reset. * * @param status the status of the password reset */ public void setStatus(PasswordResetStatus status) { this.status = status; } /** * Set the username for the user associated with the password reset. * * @param username the username for the user associated with the password reset */ public void setUsername(String username) { this.username = username; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/PasswordResetId.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; /** * The <b>PasswordResetId</b> class implements the ID class for the <b>PasswordReset</b> class. * * @author Marcus Portmann */ @SuppressWarnings({"UnusedDeclaration"}) public class PasswordResetId implements Serializable { private static final long serialVersionUID = 1000000; /** The date and time the password reset was requested. */ private LocalDateTime requested; /** The username for the user associated with the password reset. */ private String username; /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } PasswordResetId other = (PasswordResetId) object; return Objects.equals(username, other.username) && Objects.equals(requested, other.requested); } /** * Returns the date and time the password reset was requested. * * @return the date and time the password reset was requested */ public LocalDateTime getRequested() { return requested; } /** * Returns the username for the user associated with the password reset. * * @return the username for the user associated with the password reset */ public String getUsername() { return username; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((username == null) ? 0 : username.hashCode()) + ((requested == null) ? 0 : requested.hashCode()); } /** * Set the date and time the password reset was requested. * * @param requested the date and time the password reset was requested */ public void setRequested(LocalDateTime requested) { this.requested = requested; } /** * Set the username for the user associated with the password reset. * * @param username the username for the user associated with the password reset */ public void setUsername(String username) { this.username = username; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/PasswordResetRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.time.LocalDateTime; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>PasswordResetRepository</b> interface declares the repository for the <b> * PasswordReset</b> domain type. * * @author Marcus Portmann */ public interface PasswordResetRepository extends JpaRepository<PasswordReset, PasswordResetId> { /** * Expire the password resets. * * @param currentTimestamp the current date and time * @param requestedBefore the date and time to expire password resets after */ @Modifying @Query( "update PasswordReset pr set pr.expired = :currentTimestamp, pr.status = 3 " + "where pr.status = 1 and pr.requested < :requestedBefore") void expirePasswordResets( @Param("currentTimestamp") LocalDateTime currentTimestamp, @Param("requestedBefore") LocalDateTime requestedBefore); /** * Retrieve the password reset with the specified status for the user. * * @param username the username for the user * @param status the password reset status * @return the password resets with the specified status for the user */ List<PasswordReset> findAllByUsernameAndStatus(String username, PasswordResetStatus status); }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/PasswordResetStatus.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.v3.oas.annotations.media.Schema; /** * The <b>PasswordResetStatus</b> enumeration defines the possible statuses for a password reset. * * @author Marcus Portmann */ @Schema(description = "The password reset status") public enum PasswordResetStatus { /** Requested. */ REQUESTED("requested", "Requested"), /** Completed. */ COMPLETED("completed", "Completed"), /** Expired. */ EXPIRED("expired", "Expired"); private final String code; private final String description; PasswordResetStatus(String code, String description) { this.code = code; this.description = description; } /** * Returns the password reset status given by the specified code value. * * @param code the code for the password reset status * @return the password reset status given by the specified code value */ @JsonCreator public static PasswordResetStatus fromCode(String code) { switch (code) { case "requested": return PasswordResetStatus.REQUESTED; case "completed": return PasswordResetStatus.COMPLETED; case "expired": return PasswordResetStatus.EXPIRED; default: throw new RuntimeException( "Failed to determine the password reset status with the invalid code (" + code + ")"); } } /** * Returns the numeric code for the password reset status. * * @param passwordResetStatus the password reset status * @return the numeric code for the password reset status */ public static int toNumericCode(PasswordResetStatus passwordResetStatus) { switch (passwordResetStatus) { case REQUESTED: return 1; case COMPLETED: return 2; case EXPIRED: return 3; default: throw new RuntimeException( "Failed to determine the numeric code for the password reset status (" + passwordResetStatus.code() + ")"); } } /** * Returns the password reset status for the specified numeric code. * * @param numericCode the numeric code for the password reset status * @return the password reset status given by the specified numeric code value */ public static PasswordResetStatus fromNumericCode(int numericCode) { switch (numericCode) { case 1: return PasswordResetStatus.REQUESTED; case 2: return PasswordResetStatus.COMPLETED; case 3: return PasswordResetStatus.EXPIRED; default: throw new RuntimeException( "Failed to determine the password reset status for the numeric code (" + numericCode + ")"); } } /** * Returns the code value for the password reset status. * * @return the code value for the password reset status */ @JsonValue public String code() { return code; } /** * Returns the description for the password reset status. * * @return the description for the password reset status */ public String description() { return description; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/PasswordResetStatusConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import javax.persistence.AttributeConverter; import javax.persistence.Converter; /** * The <b>PasswordResetStatusConverter</b> class implements the custom JPA converter for the * <b>PasswordResetStatus</b> enumeration. * * @author Marcus Portmann */ @Converter(autoApply = true) public class PasswordResetStatusConverter implements AttributeConverter<PasswordResetStatus, Integer> { /** * Converts the value stored in the entity attribute into the data representation to be stored in * the database. * * @param attribute the entity attribute value to be converted * @return the converted data to be stored in the database column */ @Override public Integer convertToDatabaseColumn(PasswordResetStatus attribute) { if (attribute == null) return null; return PasswordResetStatus.toNumericCode(attribute); } /** * Converts the data stored in the database column into the value to be stored in the entity * attribute. Note that it is the responsibility of the converter writer to specify the correct * dbData type for the corresponding column for use by the JDBC driver: i.e., persistence * providers are not expected to do such type conversion. * * @param dbData the data from the database column to be converted * @return the converted value to be stored in the entity attribute */ @Override public PasswordResetStatus convertToEntityAttribute(Integer dbData) { if (dbData == null) return null; return PasswordResetStatus.fromNumericCode(dbData); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/PasswordResetStatusToStringConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.WritingConverter; import org.springframework.stereotype.Component; /** * The <b>PasswordResetStatusToStringConverter</b> class implements the Spring converter that * converts a <b>PasswordResetStatus</b> type into a <b>String</b> type. * * @author Marcus Portmann */ @Component @WritingConverter public class PasswordResetStatusToStringConverter implements Converter<PasswordResetStatus, String> { /** Constructs a new <b>PasswordResetStatusToStringConverter</b>. */ public PasswordResetStatusToStringConverter() {} @Override public String convert(PasswordResetStatus source) { return source.code(); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/Role.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>Role</b> class holds the information for a role. * * @author Marcus Portmann */ @Schema( description = "A representation of a particular job function that is used to assign the permissions needed to perform particular system functions to a user") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"code", "name", "description"}) @Entity @Table(schema = "security", name = "roles") @SuppressWarnings({"unused"}) public class Role implements java.io.Serializable { private static final long serialVersionUID = 1000000; /** The code for the role. */ @Schema(description = "The code for the role", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "code", length = 100, nullable = false) private String code; /** The description for the role. */ @Schema(description = "The description for the role") @JsonProperty @Size(max = 100) @Column(name = "description", length = 100) private String description; /** The functions associated with the role. */ @JsonIgnore @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @JoinTable( schema = "security", name = "function_to_role_map", joinColumns = @JoinColumn(name = "role_code", referencedColumnName = "code"), inverseJoinColumns = @JoinColumn(name = "function_code", referencedColumnName = "code")) private Set<Function> functions = new HashSet<>(); /** The groups the role is associated with. */ @JsonIgnore @ManyToMany(mappedBy = "roles") private Set<Group> groups = new HashSet<>(); /** The name of the role. */ @Schema(description = "The name of the role", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** Constructs a new <b>Role</b>. */ public Role() {} /** * Add the function to the role. * * @param function the function */ public void addFunction(Function function) { functions.removeIf( existingFunction -> Objects.equals(existingFunction.getCode(), function.getCode())); functions.add(function); function.getRoles().add(this); } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } Role other = (Role) object; return Objects.equals(code, other.code); } /** * Returns the code for the role. * * @return the code for the role */ public String getCode() { return code; } /** * Returns the description for the role. * * @return the description for the role */ public String getDescription() { return description; } /** * Returns the functions associated with the role. * * @return the functions associated with the role */ public Set<Function> getFunctions() { return functions; } /** * Returns the groups the role is associated with. * * @return the groups the role is associated with */ public Set<Group> getGroups() { return groups; } /** * Returns the name of the role. * * @return the name of the role */ public String getName() { return name; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (code == null) ? 0 : code.hashCode(); } /** * Remove the function to the role. * * @param function the function */ public void removeFunction(Function function) { functions.remove(function); function.getRoles().remove(this); } /** * Set the code for the role. * * @param code the code for the role */ public void setCode(String code) { this.code = code; } /** * Set the description for the role. * * @param description the description for the role */ public void setDescription(String description) { this.description = description; } /** * Set the functions associated with the role. * * @param functions the functions associated with the role */ public void setFunctions(Set<Function> functions) { this.functions = functions; } /** * Set the groups the role is associated with. * * @param groups the groups the role is associated with */ public void setGroups(Set<Group> groups) { this.groups = groups; } /** * Set the name of the role. * * @param name the name of the role */ public void setName(String name) { this.name = name; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/RoleNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>RoleNotFoundException</b> is thrown to indicate that a security operation failed as a result * of a role that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/role-not-found", title = "The role could not be found.", status = 404) public class RoleNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>RoleNotFoundException</b>. * * @param roleCode the code for the role */ public RoleNotFoundException(String roleCode) { super("The role (" + roleCode + ") could not be found"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/RoleRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>RoleRepository</b> interface declares the repository for the <b>Role</b> domain type. * * @author Marcus Portmann */ public interface RoleRepository extends JpaRepository<Role, String> { @Modifying @Query("delete from Role r where r.code = :roleCode") void deleteById(@Param("roleCode") String roleCode); }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/SecurityConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.jpa.JpaUtil; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; /** * The <b>SecurityConfiguration</b> class provides the Spring configuration for the Security module. * * @author Marcus Portmann */ @Configuration @EnableJpaRepositories( entityManagerFactoryRef = "securityEntityManagerFactory", basePackages = {"africa.absa.inception.security"}) public class SecurityConfiguration { /** The Spring application context. */ private final ApplicationContext applicationContext; /** * Constructs a new <b>SecurityConfiguration</b>. * * @param applicationContext the Spring application context */ public SecurityConfiguration(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Returns the security entity manager factory bean associated with the application data source. * * @param dataSource the application data source * @param platformTransactionManager the platform transaction manager * @return the security entity manager factory bean associated with the application data source */ @Bean public LocalContainerEntityManagerFactoryBean securityEntityManagerFactory( @Qualifier("applicationDataSource") DataSource dataSource, PlatformTransactionManager platformTransactionManager) { return JpaUtil.createEntityManager( "security", dataSource, platformTransactionManager, "africa.absa.inception.security"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/SecurityService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import africa.absa.inception.core.service.ValidationError; import africa.absa.inception.core.sorting.SortDirection; import africa.absa.inception.core.util.PasswordUtil; import africa.absa.inception.core.util.RandomStringGenerator; import africa.absa.inception.core.util.ResourceUtil; import africa.absa.inception.mail.IMailService; import africa.absa.inception.mail.MailTemplate; import africa.absa.inception.mail.MailTemplateContentType; import java.lang.reflect.Constructor; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; /** * The <b>SecurityService</b> class provides the Security Service implementation. * * @author Marcus Portmann */ @Service @SuppressWarnings({"unused", "WeakerAccess", "DuplicatedCode"}) public class SecurityService implements ISecurityService, InitializingBean { /** The maximum number of filtered tenants. */ private static final int MAX_FILTERED_ORGANISATIONS = 100; /** The maximum number of filtered tenants. */ private static final int MAX_FILTERED_TENANTS = 100; /** The maximum number of filtered user directories. */ private static final int MAX_FILTERED_USER_DIRECTORIES = 100; /** The code for the password reset mail template. */ private static final String PASSWORD_RESET_MAIL_TEMPLATE_ID = "Inception.Security.PasswordResetMail"; /* Logger */ private static final Logger logger = LoggerFactory.getLogger(SecurityService.class); /** The Spring application context. */ private final ApplicationContext applicationContext; /** The Function Repository. */ private final FunctionRepository functionRepository; /** The Group repository. */ private final GroupRepository groupRepository; /** The Mail Service. */ private final IMailService mailService; /** The Password Reset Repository. */ private final PasswordResetRepository passwordResetRepository; /** The Role Repository. */ private final RoleRepository roleRepository; /** * The random alphanumeric string generator that will be used to generate security codes for * password resets. */ private final RandomStringGenerator securityCodeGenerator = new RandomStringGenerator( 20, new SecureRandom(), "1234567890ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx"); /** The Tenant Repository. */ private final TenantRepository tenantRepository; /** The User Directory Repository. */ private final UserDirectoryRepository userDirectoryRepository; /** The User Directory Summary Repository. */ private final UserDirectorySummaryRepository userDirectorySummaryRepository; /** The User Directory Type Repository. */ private final UserDirectoryTypeRepository userDirectoryTypeRepository; /** The User Repository. */ private final UserRepository userRepository; /** The JSR-303 validator. */ private final Validator validator; /** The user directories. */ private Map<UUID, IUserDirectory> userDirectories = new ConcurrentHashMap<>(); /** * Constructs a new <b>SecurityService</b>. * * @param applicationContext the Spring application context * @param validator the JSR-303 validator * @param mailService the Mail Service * @param functionRepository the Function Repository * @param groupRepository the Group Repository * @param tenantRepository the Tenant Repository * @param passwordResetRepository the Password Reset Repository * @param roleRepository the Role Repository * @param userDirectoryRepository the User Directory Repository * @param userDirectorySummaryRepository the User Directory Summary Repository * @param userDirectoryTypeRepository the User Directory Type Repository * @param userRepository the User Repository */ public SecurityService( ApplicationContext applicationContext, Validator validator, IMailService mailService, FunctionRepository functionRepository, GroupRepository groupRepository, TenantRepository tenantRepository, PasswordResetRepository passwordResetRepository, RoleRepository roleRepository, UserDirectoryRepository userDirectoryRepository, UserDirectorySummaryRepository userDirectorySummaryRepository, UserDirectoryTypeRepository userDirectoryTypeRepository, UserRepository userRepository) { this.applicationContext = applicationContext; this.validator = validator; this.mailService = mailService; this.functionRepository = functionRepository; this.groupRepository = groupRepository; this.tenantRepository = tenantRepository; this.passwordResetRepository = passwordResetRepository; this.roleRepository = roleRepository; this.userDirectoryRepository = userDirectoryRepository; this.userDirectorySummaryRepository = userDirectorySummaryRepository; this.userDirectoryTypeRepository = userDirectoryTypeRepository; this.userRepository = userRepository; } @Override @Transactional public void addMemberToGroup( UUID userDirectoryId, String groupName, GroupMemberType memberType, String memberName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, UserNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } if (memberType == null) { throw new InvalidArgumentException("memberType"); } if (!StringUtils.hasText(memberName)) { throw new InvalidArgumentException("memberName"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } userDirectory.addMemberToGroup(groupName, memberType, memberName); } @Override @Transactional public void addRoleToGroup(UUID userDirectoryId, String groupName, String roleCode) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, RoleNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } if (!StringUtils.hasText(roleCode)) { throw new InvalidArgumentException("roleCode"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } userDirectory.addRoleToGroup(groupName, roleCode); } @Override @Transactional public void addUserDirectoryToTenant(UUID tenantId, UUID userDirectoryId) throws InvalidArgumentException, TenantNotFoundException, UserDirectoryNotFoundException, ServiceUnavailableException { if (tenantId == null) { throw new InvalidArgumentException("tenantId"); } if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } try { if (!tenantRepository.existsById(tenantId)) { throw new TenantNotFoundException(tenantId); } if (!userDirectoryRepository.existsById(userDirectoryId)) { throw new UserDirectoryNotFoundException(userDirectoryId); } if (tenantRepository.userDirectoryToTenantMappingExists(tenantId, userDirectoryId)) { return; } tenantRepository.addUserDirectoryToTenant(tenantId, userDirectoryId); } catch (TenantNotFoundException | UserDirectoryNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to add the user directory (" + userDirectoryId + ") to the tenant (" + tenantId + ")", e); } } @Override @Transactional public void addUserToGroup(UUID userDirectoryId, String groupName, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, UserNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } userDirectory.addUserToGroup(groupName, username); } @Override @Transactional public void adminChangePassword( UUID userDirectoryId, String username, String newPassword, boolean expirePassword, boolean lockUser, boolean resetPasswordHistory, PasswordChangeReason reason) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } if (!StringUtils.hasText(newPassword)) { throw new InvalidArgumentException("newPassword"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } userDirectory.adminChangePassword( username, newPassword, expirePassword, lockUser, resetPasswordHistory, reason); } @Override public void afterPropertiesSet() { try { // Load the default password reset mail template if (!mailService.mailTemplateExists(PASSWORD_RESET_MAIL_TEMPLATE_ID)) { byte[] passwordResetMailTemplate = ResourceUtil.getClasspathResource("africa/absa/inception/security/PasswordReset.ftl"); MailTemplate mailTemplate = new MailTemplate( PASSWORD_RESET_MAIL_TEMPLATE_ID, "Password Reset", MailTemplateContentType.HTML, passwordResetMailTemplate); mailService.createMailTemplate(mailTemplate); } // Load the user directories reloadUserDirectories(); } catch (Throwable e) { throw new RuntimeException("Failed to initialize the Security Service", e); } } @Override @Transactional public UUID authenticate(String username, String password) throws InvalidArgumentException, AuthenticationFailedException, UserLockedException, ExpiredPasswordException, UserNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } if (!StringUtils.hasText(password)) { throw new InvalidArgumentException("password"); } try { // First check if this is an internal user and if so determine the user directory ID Optional<UUID> internalUserDirectoryIdOptional = getInternalUserDirectoryIdForUser(username); if (internalUserDirectoryIdOptional.isPresent()) { UUID internalUserDirectoryId = internalUserDirectoryIdOptional.get(); IUserDirectory internalUserDirectory = userDirectories.get(internalUserDirectoryId); if (internalUserDirectory == null) { throw new ServiceUnavailableException( "The user directory ID (" + internalUserDirectoryId + ") for the internal user (" + username + ") is invalid"); } else { internalUserDirectory.authenticate(username, password); return internalUserDirectoryId; } } else { /* * Check all of the "external" user directories to see if one of them can authenticate this * user. */ for (UUID userDirectoryId : userDirectories.keySet()) { IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory != null) { if (!(userDirectory instanceof InternalUserDirectory)) { if (userDirectory.isExistingUser(username)) { userDirectory.authenticate(username, password); return userDirectoryId; } } } } throw new UserNotFoundException(username); } } catch (AuthenticationFailedException | UserNotFoundException | UserLockedException | ExpiredPasswordException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to authenticate the user (" + username + ")", e); } } @Override @Transactional public UUID changePassword(String username, String password, String newPassword) throws InvalidArgumentException, AuthenticationFailedException, UserLockedException, ExistingPasswordException, ServiceUnavailableException { if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } if (!StringUtils.hasText(password)) { throw new InvalidArgumentException("password"); } if (!StringUtils.hasText(newPassword)) { throw new InvalidArgumentException("newPassword"); } try { // First check if this is an internal user and if so determine the user directory ID Optional<UUID> internalUserDirectoryIdOptional = getInternalUserDirectoryIdForUser(username); if (internalUserDirectoryIdOptional.isPresent()) { UUID internalUserDirectoryId = internalUserDirectoryIdOptional.get(); IUserDirectory internalUserDirectory = userDirectories.get(internalUserDirectoryId); if (internalUserDirectory == null) { throw new ServiceUnavailableException( "The user directory ID (" + internalUserDirectoryId + ") for the internal user (" + username + ") is invalid"); } else { internalUserDirectory.changePassword(username, password, newPassword); return internalUserDirectoryId; } } else { /* * Check all of the "external" user directories to see if one of them can change the * password for this user. */ for (UUID userDirectoryId : userDirectories.keySet()) { IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory != null) { if (!(userDirectory instanceof InternalUserDirectory)) { if (userDirectory.isExistingUser(username)) { userDirectory.changePassword(username, password, newPassword); return userDirectoryId; } } } } throw new AuthenticationFailedException( "Authentication failed while attempting to change the password for the user (" + username + ")"); } } catch (AuthenticationFailedException | UserLockedException | ExistingPasswordException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to change the password for the user (" + username + ")", e); } } @Override @Transactional public void createFunction(Function function) throws InvalidArgumentException, DuplicateFunctionException, ServiceUnavailableException { validateFunction(function); try { if (functionRepository.existsById(function.getCode())) { throw new DuplicateFunctionException(function.getCode()); } functionRepository.saveAndFlush(function); } catch (DuplicateFunctionException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the function (" + function.getCode() + ")", e); } } @Override @Transactional public void createGroup(Group group) throws InvalidArgumentException, UserDirectoryNotFoundException, DuplicateGroupException, ServiceUnavailableException { validateGroup(group); IUserDirectory userDirectory = userDirectories.get(group.getUserDirectoryId()); if (userDirectory == null) { throw new UserDirectoryNotFoundException(group.getUserDirectoryId()); } userDirectory.createGroup(group); } @Override @Transactional public Optional<UserDirectory> createTenant(Tenant tenant, boolean createUserDirectory) throws InvalidArgumentException, DuplicateTenantException, ServiceUnavailableException { validateTenant(tenant); UserDirectory userDirectory = null; try { if ((tenant.getId() != null) && tenantRepository.existsById(tenant.getId())) { throw new DuplicateTenantException(tenant.getId()); } if (tenantRepository.existsByNameIgnoreCase(tenant.getName())) { throw new DuplicateTenantException(tenant.getName()); } if (createUserDirectory) { userDirectory = newInternalUserDirectoryForTenant(tenant); tenant.linkUserDirectory(userDirectory); } tenantRepository.saveAndFlush(tenant); try { reloadUserDirectories(); } catch (Throwable e) { logger.error("Failed to reload the user directories", e); } return Optional.ofNullable(userDirectory); } catch (DuplicateTenantException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the tenant (" + tenant.getId() + ")", e); } } @Override @Transactional public void createUser(User user, boolean expiredPassword, boolean userLocked) throws InvalidArgumentException, UserDirectoryNotFoundException, DuplicateUserException, ServiceUnavailableException { validateUser(user); IUserDirectory userDirectory = userDirectories.get(user.getUserDirectoryId()); if (userDirectory == null) { throw new UserDirectoryNotFoundException(user.getUserDirectoryId()); } if (getUserDirectoryIdForUser(user.getUsername()).isPresent()) { throw new DuplicateUserException(user.getUsername()); } userDirectory.createUser(user, expiredPassword, userLocked); } @Override @Transactional public void createUserDirectory(UserDirectory userDirectory) throws InvalidArgumentException, DuplicateUserDirectoryException, ServiceUnavailableException { validateUserDirectory(userDirectory); try { if ((userDirectory.getId() != null) && userDirectoryRepository.existsById(userDirectory.getId())) { throw new DuplicateUserDirectoryException(userDirectory.getId()); } if (userDirectoryRepository.existsByNameIgnoreCase(userDirectory.getName())) { throw new DuplicateUserDirectoryException(userDirectory.getName()); } userDirectoryRepository.saveAndFlush(userDirectory); try { reloadUserDirectories(); } catch (Throwable e) { logger.error("Failed to reload the user directories", e); } } catch (DuplicateUserDirectoryException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the user directory (" + userDirectory.getName() + ")", e); } } @Override @Transactional public void deleteFunction(String functionCode) throws InvalidArgumentException, FunctionNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(functionCode)) { throw new InvalidArgumentException("functionCode"); } try { if (!functionRepository.existsById(functionCode)) { throw new FunctionNotFoundException(functionCode); } functionRepository.deleteById(functionCode); } catch (FunctionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to delete the function (" + functionCode + ")", e); } } @Override @Transactional public void deleteGroup(UUID userDirectoryId, String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ExistingGroupMembersException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } userDirectory.deleteGroup(groupName); } @Override @Transactional public void deleteTenant(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { if (tenantId == null) { throw new InvalidArgumentException("tenantId"); } try { if (!tenantRepository.existsById(tenantId)) { throw new TenantNotFoundException(tenantId); } tenantRepository.deleteById(tenantId); } catch (TenantNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to delete the tenant (" + tenantId + ")", e); } } @Override @Transactional public void deleteUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } userDirectory.deleteUser(username); } @Override @Transactional public void deleteUserDirectory(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } try { if (!userDirectoryRepository.existsById(userDirectoryId)) { throw new UserDirectoryNotFoundException(userDirectoryId); } userDirectoryRepository.deleteById(userDirectoryId); try { reloadUserDirectories(); } catch (Throwable e) { logger.error("Failed to reload the user directories", e); } } catch (UserDirectoryNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to delete the user directory (" + userDirectoryId + ")", e); } } @Override public List<User> findUsers(UUID userDirectoryId, List<UserAttribute> userAttributes) throws InvalidArgumentException, UserDirectoryNotFoundException, InvalidAttributeException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (userAttributes == null) { throw new InvalidArgumentException("attributes"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.findUsers(userAttributes); } @Override public Function getFunction(String functionCode) throws InvalidArgumentException, FunctionNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(functionCode)) { throw new InvalidArgumentException("functionCode"); } try { Optional<Function> functionOptional = functionRepository.findById(functionCode); if (functionOptional.isPresent()) { return functionOptional.get(); } else { throw new FunctionNotFoundException(functionCode); } } catch (FunctionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the function (" + functionCode + ")", e); } } @Override public List<String> getFunctionCodesForUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getFunctionCodesForUser(username); } @Override public List<Function> getFunctions() throws ServiceUnavailableException { try { return functionRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the functions", e); } } @Override public Group getGroup(UUID userDirectoryId, String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getGroup(groupName); } @Override public List<String> getGroupNames(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getGroupNames(); } @Override public List<String> getGroupNamesForUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getGroupNamesForUser(username); } @Override public List<Group> getGroups(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getGroups(); } @Override public Groups getGroups( UUID userDirectoryId, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if ((pageIndex != null) && (pageIndex < 0)) { throw new InvalidArgumentException("pageIndex"); } if ((pageSize != null) && (pageSize <= 0)) { throw new InvalidArgumentException("pageSize"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getGroups(filter, sortDirection, pageIndex, pageSize); } @Override public List<Group> getGroupsForUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getGroupsForUser(username); } @Override public List<GroupMember> getMembersForGroup(UUID userDirectoryId, String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getMembersForGroup(groupName); } @Override @Transactional public GroupMembers getMembersForGroup( UUID userDirectoryId, String groupName, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } if ((pageIndex != null) && (pageIndex < 0)) { throw new InvalidArgumentException("pageIndex"); } if ((pageSize != null) && (pageSize <= 0)) { throw new InvalidArgumentException("pageSize"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getMembersForGroup(groupName, filter, sortDirection, pageIndex, pageSize); } @Override public List<String> getRoleCodesForGroup(UUID userDirectoryId, String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getRoleCodesForGroup(groupName); } @Override public List<String> getRoleCodesForUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getRoleCodesForUser(username); } @Override public List<Role> getRoles() throws ServiceUnavailableException { try { return roleRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the roles", e); } } @Override public List<GroupRole> getRolesForGroup(UUID userDirectoryId, String groupName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getRolesForGroup(groupName); } @Override public Tenant getTenant(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { if (tenantId == null) { throw new InvalidArgumentException("tenantId"); } try { Optional<Tenant> tenantOptional = tenantRepository.findById(tenantId); if (tenantOptional.isPresent()) { return tenantOptional.get(); } else { throw new TenantNotFoundException(tenantId); } } catch (TenantNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the tenant (" + tenantId + ")", e); } } @Override public List<UUID> getTenantIdsForUserDirectory(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } try { if (!userDirectoryRepository.existsById(userDirectoryId)) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectoryRepository.getTenantIdsById(userDirectoryId); } catch (UserDirectoryNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the IDs for the tenants for the user directory (" + userDirectoryId + ")", e); } } @Override public String getTenantName(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { if (tenantId == null) { throw new InvalidArgumentException("tenantId"); } try { Optional<String> nameOptional = tenantRepository.getNameById(tenantId); if (nameOptional.isPresent()) { return nameOptional.get(); } else { throw new TenantNotFoundException(tenantId); } } catch (TenantNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the name of the tenant (" + tenantId + ")", e); } } @Override public List<Tenant> getTenants() throws ServiceUnavailableException { try { return tenantRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the tenants", e); } } @Override public Tenants getTenants( String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, ServiceUnavailableException { if ((pageIndex != null) && (pageIndex < 0)) { throw new InvalidArgumentException("pageIndex"); } if ((pageSize != null) && (pageSize <= 0)) { throw new InvalidArgumentException("pageSize"); } if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = MAX_FILTERED_TENANTS; } try { Page<Tenant> tenantPage; PageRequest pageRequest = PageRequest.of( pageIndex, Math.min(pageSize, MAX_FILTERED_TENANTS), (sortDirection == SortDirection.ASCENDING) ? Sort.Direction.ASC : Sort.Direction.DESC, "name"); if (StringUtils.hasText(filter)) { tenantPage = tenantRepository.findFiltered("%" + filter + "%", pageRequest); } else { tenantPage = tenantRepository.findAll(pageRequest); } return new Tenants( tenantPage.toList(), tenantPage.getTotalElements(), filter, sortDirection, pageIndex, pageSize); } catch (Throwable e) { String message = "Failed to retrieve the tenants"; if (StringUtils.hasText(filter)) { message += String.format(" matching the filter \"%s\"", filter); } if ((pageIndex != null) && (pageSize != null)) { message += " for the page " + pageIndex + " using the page size " + pageSize; } message += ": "; message += e.getMessage(); throw new ServiceUnavailableException(message, e); } } @Override public List<Tenant> getTenantsForUserDirectory(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } try { if (!userDirectoryRepository.existsById(userDirectoryId)) { throw new UserDirectoryNotFoundException(userDirectoryId); } return tenantRepository.findAllByUserDirectoryId(userDirectoryId); } catch (UserDirectoryNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the tenants associated with the user directory (" + userDirectoryId + ")", e); } } @Override public User getUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getUser(username); } @Override public List<UserDirectory> getUserDirectories() throws ServiceUnavailableException { try { return userDirectoryRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the user directories", e); } } @Override public UserDirectories getUserDirectories( String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, ServiceUnavailableException { if ((pageIndex != null) && (pageIndex < 0)) { throw new InvalidArgumentException("pageIndex"); } if ((pageSize != null) && (pageSize <= 0)) { throw new InvalidArgumentException("pageSize"); } if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = MAX_FILTERED_USER_DIRECTORIES; } try { Page<UserDirectory> userDirectoryPage; PageRequest pageRequest = PageRequest.of( pageIndex, Math.min(pageSize, MAX_FILTERED_USER_DIRECTORIES), (sortDirection == SortDirection.ASCENDING) ? Sort.Direction.ASC : Sort.Direction.DESC, "name"); if (StringUtils.hasText(filter)) { userDirectoryPage = userDirectoryRepository.findFiltered("%" + filter + "%", pageRequest); } else { userDirectoryPage = userDirectoryRepository.findAll(pageRequest); } return new UserDirectories( userDirectoryPage.toList(), userDirectoryPage.getTotalElements(), filter, sortDirection, pageIndex, pageSize); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the filtered user directories", e); } } @Override public List<UserDirectory> getUserDirectoriesForTenant(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { if (tenantId == null) { throw new InvalidArgumentException("tenantId"); } try { if (!tenantRepository.existsById(tenantId)) { throw new TenantNotFoundException(tenantId); } return userDirectoryRepository.findAllByTenantId(tenantId); } catch (TenantNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the user directories associated with the tenant (" + tenantId + ")", e); } } @Override public UserDirectory getUserDirectory(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } try { Optional<UserDirectory> userDirectoryOptional = userDirectoryRepository.findById(userDirectoryId); if (userDirectoryOptional.isPresent()) { return userDirectoryOptional.get(); } else { throw new UserDirectoryNotFoundException(userDirectoryId); } } catch (UserDirectoryNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the user directory (" + userDirectoryId + ")", e); } } @Override public UserDirectoryCapabilities getUserDirectoryCapabilities(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getCapabilities(); } @Override public Optional<UUID> getUserDirectoryIdForUser(String username) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } try { // First check if this is an internal user and if so determine the user directory ID Optional<UUID> internalUserDirectoryIdOptional = getInternalUserDirectoryIdForUser(username); if (internalUserDirectoryIdOptional.isPresent()) { return internalUserDirectoryIdOptional; } else { /* * Check all of the "external" user directories to see if the user is associated with one * of them. */ for (UUID userDirectoryId : userDirectories.keySet()) { IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory != null) { if (!(userDirectory instanceof InternalUserDirectory)) { if (userDirectory.isExistingUser(username)) { return Optional.of(userDirectoryId); } } } } return Optional.empty(); } } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the user directory ID for the user (" + username + ")", e); } } @Override public List<UUID> getUserDirectoryIdsForTenant(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { if (tenantId == null) { throw new InvalidArgumentException("tenantId"); } try { if (!tenantRepository.existsById(tenantId)) { throw new TenantNotFoundException(tenantId); } return tenantRepository.getUserDirectoryIdsById(tenantId); } catch (TenantNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the IDs for the user directories associated with the tenant (" + tenantId + ")", e); } } @Override public List<UUID> getUserDirectoryIdsForUser(String username) throws InvalidArgumentException, UserNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } try { List<UUID> userDirectoryIdsForUser = new ArrayList<>(); Optional<UUID> userDirectoryIdOptional = getUserDirectoryIdForUser(username); if (userDirectoryIdOptional.isEmpty()) { throw new UserNotFoundException(username); } /* * Retrieve the list of IDs for the tenants the user is associated with as a result * of their user directory being associated with these tenants. */ List<UUID> tenantIds = getTenantIdsForUserDirectory(userDirectoryIdOptional.get()); /* * Retrieve the list of IDs for the user directories the user is associated with as a result * of being associated with one or more tenants. */ for (var tenantId : tenantIds) { // Retrieve the list of user directories associated with the tenant var userDirectoryIdsForTenant = getUserDirectoryIdsForTenant(tenantId); userDirectoryIdsForUser.addAll(userDirectoryIdsForTenant); } return userDirectoryIdsForUser; } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the IDs for the user directories the user (" + username + ") is associated with", e); } } @Override public String getUserDirectoryName(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } try { Optional<String> nameOptional = userDirectoryRepository.getNameById(userDirectoryId); if (nameOptional.isPresent()) { return nameOptional.get(); } else { throw new UserDirectoryNotFoundException(userDirectoryId); } } catch (UserDirectoryNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the name of the user directory (" + userDirectoryId + ")", e); } } @Override public UserDirectorySummaries getUserDirectorySummaries( String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, ServiceUnavailableException { if ((pageIndex != null) && (pageIndex < 0)) { throw new InvalidArgumentException("pageIndex"); } if ((pageSize != null) && (pageSize <= 0)) { throw new InvalidArgumentException("pageSize"); } if (pageIndex == null) { pageIndex = 0; } if (pageSize == null) { pageSize = MAX_FILTERED_USER_DIRECTORIES; } try { Page<UserDirectorySummary> userDirectorySummaryPage; PageRequest pageRequest = PageRequest.of( pageIndex, Math.min(pageSize, MAX_FILTERED_USER_DIRECTORIES), (sortDirection == SortDirection.ASCENDING) ? Sort.Direction.ASC : Sort.Direction.DESC, "name"); if (StringUtils.hasText(filter)) { userDirectorySummaryPage = userDirectorySummaryRepository.findFiltered("%" + filter + "%", pageRequest); } else { userDirectorySummaryPage = userDirectorySummaryRepository.findAll(pageRequest); } return new UserDirectorySummaries( userDirectorySummaryPage.toList(), userDirectorySummaryPage.getTotalElements(), filter, sortDirection, pageIndex, pageSize); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the filtered summaries for the user directories", e); } } @Override public List<UserDirectorySummary> getUserDirectorySummariesForTenant(UUID tenantId) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { if (tenantId == null) { throw new InvalidArgumentException("tenantId"); } try { if (!tenantRepository.existsById(tenantId)) { throw new TenantNotFoundException(tenantId); } return userDirectorySummaryRepository.findAllByTenantId(tenantId); } catch (TenantNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the summaries for the user " + "directories associated with the tenant (" + tenantId + ")", e); } } @Override public UserDirectoryType getUserDirectoryTypeForUserDirectory(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, UserDirectoryTypeNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } try { Optional<String> typeOptional = userDirectoryRepository.getTypeForUserDirectoryById(userDirectoryId); if (typeOptional.isEmpty()) { throw new UserDirectoryNotFoundException(userDirectoryId); } Optional<UserDirectoryType> userDirectoryTypeOptional = userDirectoryTypeRepository.findById(typeOptional.get()); if (userDirectoryTypeOptional.isPresent()) { return userDirectoryTypeOptional.get(); } else { throw new UserDirectoryTypeNotFoundException(typeOptional.get()); } } catch (UserDirectoryNotFoundException | UserDirectoryTypeNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the user directory type for the user directory (" + userDirectoryId + ")", e); } } @Override public List<UserDirectoryType> getUserDirectoryTypes() throws ServiceUnavailableException { try { return userDirectoryTypeRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the user directory types", e); } } @Override public String getUserName(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getUserName(username); } @Override public List<User> getUsers(UUID userDirectoryId) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getUsers(); } @Override public Users getUsers( UUID userDirectoryId, String filter, UserSortBy sortBy, SortDirection sortDirection, Integer pageIndex, Integer pageSize) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (sortBy == null) { sortBy = UserSortBy.NAME; } if (sortDirection == null) { sortDirection = SortDirection.ASCENDING; } if ((pageIndex != null) && (pageIndex < 0)) { throw new InvalidArgumentException("pageIndex"); } if ((pageSize != null) && (pageSize <= 0)) { throw new InvalidArgumentException("pageSize"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.getUsers(filter, sortBy, sortDirection, pageIndex, pageSize); } @Override @Transactional public void initiatePasswordReset(String username, String resetPasswordUrl, boolean sendEmail) throws InvalidArgumentException, UserNotFoundException, ServiceUnavailableException { initiatePasswordReset(username, resetPasswordUrl, sendEmail, null); } @Override @Transactional public void initiatePasswordReset( String username, String resetPasswordUrl, boolean sendEmail, String securityCode) throws InvalidArgumentException, UserNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } if (!StringUtils.hasText(resetPasswordUrl)) { throw new InvalidArgumentException("resetPasswordUrl"); } try { Optional<UUID> userDirectoryIdOptional = getUserDirectoryIdForUser(username); if (userDirectoryIdOptional.isEmpty()) { throw new UserNotFoundException(username); } IUserDirectory userDirectory = userDirectories.get(userDirectoryIdOptional.get()); User user = userDirectory.getUser(username); if (StringUtils.hasText(user.getEmail())) { if (!StringUtils.hasText(securityCode)) { securityCode = securityCodeGenerator.nextString(); } String securityCodeHash = PasswordUtil.createPasswordHash(securityCode); PasswordReset passwordReset = new PasswordReset(username, securityCodeHash); if (sendEmail) { sendPasswordResetEmail(user, resetPasswordUrl, securityCode); } passwordResetRepository.saveAndFlush(passwordReset); } else { logger.warn( "Failed to send the password reset communication to the user (" + username + ") who does not have a valid e-mail address"); } } catch (UserNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to initiate the password reset process for the user (" + username + ")", e); } } @Override public boolean isExistingUser(UUID userDirectoryId, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.isExistingUser(username); } @Override public boolean isUserInGroup(UUID userDirectoryId, String groupName, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, GroupNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } return userDirectory.isUserInGroup(groupName, username); } @Override public void reloadUserDirectories() throws ServiceUnavailableException { try { Map<UUID, IUserDirectory> reloadedUserDirectories = new ConcurrentHashMap<>(); List<UserDirectoryType> userDirectoryTypes = getUserDirectoryTypes(); for (UserDirectory userDirectory : getUserDirectories()) { UserDirectoryType userDirectoryType; userDirectoryType = userDirectoryTypes.stream() .filter( possibleUserDirectoryType -> possibleUserDirectoryType.getCode().equals(userDirectory.getType())) .findFirst() .orElse(null); if (userDirectoryType == null) { logger.error( "Failed to load the user directory (" + userDirectory.getId() + "): The user directory type (" + userDirectory.getType() + ") was not loaded"); continue; } try { Class<?> clazz = Thread.currentThread() .getContextClassLoader() .loadClass(userDirectoryType.getUserDirectoryClassName()); if (!IUserDirectory.class.isAssignableFrom(clazz)) { throw new ServiceUnavailableException( "The user directory class (" + userDirectoryType.getUserDirectoryClassName() + ") does not implement the IUserDirectory interface"); } Class<? extends IUserDirectory> userDirectoryClass = clazz.asSubclass(IUserDirectory.class); Constructor<? extends IUserDirectory> userDirectoryClassConstructor; try { userDirectoryClassConstructor = userDirectoryClass.getConstructor( UUID.class, List.class, GroupRepository.class, UserRepository.class, RoleRepository.class); } catch (NoSuchMethodException e) { throw new ServiceUnavailableException( "The user directory class (" + userDirectoryType.getUserDirectoryClassName() + ") does not provide a valid constructor (long, Map<String,String>)"); } IUserDirectory userDirectoryInstance = userDirectoryClassConstructor.newInstance( userDirectory.getId(), userDirectory.getParameters(), groupRepository, userRepository, roleRepository); applicationContext.getAutowireCapableBeanFactory().autowireBean(userDirectoryInstance); reloadedUserDirectories.put(userDirectory.getId(), userDirectoryInstance); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to initialize the user directory (" + userDirectory.getId() + ")(" + userDirectory.getName() + ")", e); } } this.userDirectories = reloadedUserDirectories; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to reload the user directories", e); } } @Override @Transactional public void removeMemberFromGroup( UUID userDirectoryId, String groupName, GroupMemberType memberType, String memberName) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, GroupMemberNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } if (memberType == null) { throw new InvalidArgumentException("memberType"); } if (!StringUtils.hasText(memberName)) { throw new InvalidArgumentException("memberName"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } userDirectory.removeMemberFromGroup(groupName, memberType, memberName); } @Override @Transactional public void removeRoleFromGroup(UUID userDirectoryId, String groupName, String roleCode) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, GroupRoleNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } if (!StringUtils.hasText(roleCode)) { throw new InvalidArgumentException("roleCode"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } userDirectory.removeRoleFromGroup(groupName, roleCode); } @Override @Transactional public void removeUserDirectoryFromTenant(UUID tenantId, UUID userDirectoryId) throws InvalidArgumentException, TenantNotFoundException, TenantUserDirectoryNotFoundException, ServiceUnavailableException { if (tenantId == null) { throw new InvalidArgumentException("tenantId"); } if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } try { if (!tenantRepository.existsById(tenantId)) { throw new TenantNotFoundException(tenantId); } if (!tenantRepository.userDirectoryToTenantMappingExists(tenantId, userDirectoryId)) { throw new TenantUserDirectoryNotFoundException(tenantId, userDirectoryId); } tenantRepository.removeUserDirectoryFromTenant(tenantId, userDirectoryId); } catch (TenantNotFoundException | TenantUserDirectoryNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to add the user directory (" + userDirectoryId + ") to the tenant (" + tenantId + ")", e); } } @Override @Transactional public void removeUserFromGroup(UUID userDirectoryId, String groupName, String username) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, UserNotFoundException, ServiceUnavailableException { if (userDirectoryId == null) { throw new InvalidArgumentException("userDirectoryId"); } if (!StringUtils.hasText(groupName)) { throw new InvalidArgumentException("groupName"); } if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } IUserDirectory userDirectory = userDirectories.get(userDirectoryId); if (userDirectory == null) { throw new UserDirectoryNotFoundException(userDirectoryId); } userDirectory.removeUserFromGroup(groupName, username); } @Override @Transactional public void resetPassword(String username, String newPassword, String securityCode) throws InvalidArgumentException, InvalidSecurityCodeException, UserLockedException, ExistingPasswordException, ServiceUnavailableException { if (!StringUtils.hasText(username)) { throw new InvalidArgumentException("username"); } if (!StringUtils.hasText(newPassword)) { throw new InvalidArgumentException("newPassword"); } if (!StringUtils.hasText(securityCode)) { throw new InvalidArgumentException("securityCode"); } try { Optional<UUID> userDirectoryIdOptional = getUserDirectoryIdForUser(username); if (userDirectoryIdOptional.isEmpty()) { throw new InvalidSecurityCodeException(username); } List<PasswordReset> passwordResets = passwordResetRepository.findAllByUsernameAndStatus( username, PasswordResetStatus.REQUESTED); String securityCodeHash = PasswordUtil.createPasswordHash(securityCode); for (PasswordReset passwordReset : passwordResets) { if (passwordReset.getSecurityCodeHash().equals(securityCodeHash)) { IUserDirectory userDirectory = userDirectories.get(userDirectoryIdOptional.get()); userDirectory.resetPassword(username, newPassword); return; } } throw new InvalidSecurityCodeException(username); } catch (UserLockedException | InvalidSecurityCodeException | ExistingPasswordException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to reset the password for the user (" + username + ")", e); } } @Override @Transactional public void updateFunction(Function function) throws InvalidArgumentException, FunctionNotFoundException, ServiceUnavailableException { validateFunction(function); try { if (!functionRepository.existsById(function.getCode())) { throw new FunctionNotFoundException(function.getCode()); } functionRepository.saveAndFlush(function); } catch (FunctionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to update the function (" + function.getCode() + ")", e); } } @Override @Transactional public void updateGroup(Group group) throws InvalidArgumentException, UserDirectoryNotFoundException, GroupNotFoundException, ServiceUnavailableException { validateGroup(group); IUserDirectory userDirectory = userDirectories.get(group.getUserDirectoryId()); if (userDirectory == null) { throw new UserDirectoryNotFoundException(group.getUserDirectoryId()); } userDirectory.updateGroup(group); } @Override @Transactional public void updateTenant(Tenant tenant) throws InvalidArgumentException, TenantNotFoundException, ServiceUnavailableException { validateTenant(tenant); try { Optional<Tenant> tenantOptional = tenantRepository.findById(tenant.getId()); if (tenantOptional.isPresent()) { Tenant existingTenant = tenantOptional.get(); existingTenant.setName(tenant.getName()); existingTenant.setStatus(tenant.getStatus()); tenantRepository.saveAndFlush(existingTenant); } else { throw new TenantNotFoundException(tenant.getId()); } } catch (TenantNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to update the tenant (" + tenant.getId() + ")", e); } } @Override @Transactional public void updateUser(User user, boolean expirePassword, boolean lockUser) throws InvalidArgumentException, UserDirectoryNotFoundException, UserNotFoundException, ServiceUnavailableException { validateUser(user); IUserDirectory userDirectory = userDirectories.get(user.getUserDirectoryId()); if (userDirectory == null) { throw new UserDirectoryNotFoundException(user.getUserDirectoryId()); } userDirectory.updateUser(user, expirePassword, lockUser); } @Override @Transactional public void updateUserDirectory(UserDirectory userDirectory) throws InvalidArgumentException, UserDirectoryNotFoundException, ServiceUnavailableException { validateUserDirectory(userDirectory); try { if (!userDirectoryRepository.existsById(userDirectory.getId())) { throw new UserDirectoryNotFoundException(userDirectory.getId()); } userDirectoryRepository.saveAndFlush(userDirectory); reloadUserDirectories(); } catch (UserDirectoryNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to update the user directory (" + userDirectory.getName() + ")", e); } } /** * Returns the ID for the internal user directory the internal user with the specified username is * associated with. * * @param username the username for the internal user * @return an Optional containing the ID for the internal user directory the internal user with * the specified username is associated with or an empty Optional if an internal user with the * specified username could not be found */ private Optional<UUID> getInternalUserDirectoryIdForUser(String username) throws ServiceUnavailableException { try { return userRepository.getUserDirectoryIdByUsernameIgnoreCase(username); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the ID for the internal user directory for the internal user (" + username + ")", e); } } /** * Checks whether the specified value is <b>null</b> or blank. * * @param value the value to check * @return true if the value is <b>null</b> or blank */ private boolean isNullOrEmpty(Object value) { if (value == null) { return true; } if (value instanceof String) { return ((String) value).length() == 0; } return false; } private UserDirectory newInternalUserDirectoryForTenant(Tenant tenant) throws ServiceUnavailableException { UserDirectory userDirectory = new UserDirectory(); if (tenant.getId() != null) { userDirectory.setId(tenant.getId()); } userDirectory.setType("InternalUserDirectory"); userDirectory.setName(tenant.getName() + " Internal User Directory"); String buffer = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE userDirectory " + "SYSTEM \"UserDirectoryConfiguration.dtd\"><userDirectory>" + "<parameter><name>MaxPasswordAttempts</name><value>5</value></parameter>" + "<parameter><name>PasswordExpiryMonths</name><value>12</value></parameter>" + "<parameter><name>PasswordHistoryMonths</name><value>24</value></parameter>" + "<parameter><name>MaxFilteredUsers</name><value>100</value></parameter>" + "</userDirectory>"; try { userDirectory.setConfiguration(buffer); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to set the configuration for the user directory", e); } return userDirectory; } private void sendPasswordResetEmail(User user, String resetPasswordUrl, String securityCode) throws ServiceUnavailableException { try { if (StringUtils.hasText(user.getEmail())) { Map<String, String> parameters = new HashMap<>(); parameters.put("preferredName", user.getPreferredName().toUpperCase()); parameters.put("securityCode", securityCode); parameters.put( "resetPasswordUrl", resetPasswordUrl + "?username=" + URLEncoder.encode(user.getUsername(), StandardCharsets.UTF_8) + "&securityCode=" + URLEncoder.encode(securityCode, StandardCharsets.UTF_8)); mailService.sendMail( Collections.singletonList(user.getEmail()), "Password Reset", "no-reply@inception.digital", "Inception", PASSWORD_RESET_MAIL_TEMPLATE_ID, parameters); } } catch (Throwable e) { throw new ServiceUnavailableException("Failed to send the password reset e-mail", e); } } private void validateFunction(Function function) throws InvalidArgumentException { if (function == null) { throw new InvalidArgumentException("function"); } Set<ConstraintViolation<Function>> constraintViolations = validator.validate(function); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "function", ValidationError.toValidationErrors(constraintViolations)); } } private void validateGroup(Group group) throws InvalidArgumentException { if (group == null) { throw new InvalidArgumentException("group"); } Set<ConstraintViolation<Group>> constraintViolations = validator.validate(group); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "group", ValidationError.toValidationErrors(constraintViolations)); } } private void validateTenant(Tenant tenant) throws InvalidArgumentException { if (tenant == null) { throw new InvalidArgumentException("tenant"); } Set<ConstraintViolation<Tenant>> constraintViolations = validator.validate(tenant); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "tenant", ValidationError.toValidationErrors(constraintViolations)); } } private void validateUser(User user) throws InvalidArgumentException { if (user == null) { throw new InvalidArgumentException("user"); } Set<ConstraintViolation<User>> constraintViolations = validator.validate(user); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "user", ValidationError.toValidationErrors(constraintViolations)); } } private void validateUserDirectory(UserDirectory userDirectory) throws InvalidArgumentException { if (userDirectory == null) { throw new InvalidArgumentException("userDirectory"); } Set<ConstraintViolation<UserDirectory>> constraintViolations = validator.validate(userDirectory); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "userDirectory", ValidationError.toValidationErrors(constraintViolations)); } } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/SecurityServiceAuthenticationManager.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.util.UUID; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.LockedException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; /** * The <b>SecurityServiceAuthenticationManager</b> class provides an authentication manager * implementation based on the Security Service. * * @author Marcus Portmann */ @SuppressWarnings("unused") public class SecurityServiceAuthenticationManager implements AuthenticationManager { /** The Security Service. */ private final ISecurityService securityService; /** The User Details Service. */ private final UserDetailsService userDetailsService; /** * Constructs a new <b>SecurityServiceAuthenticationManager</b>. * * @param securityService the Security Service * @param userDetailsService the User Details Service */ public SecurityServiceAuthenticationManager( ISecurityService securityService, UserDetailsService userDetailsService) { this.securityService = securityService; this.userDetailsService = userDetailsService; } /** * Attempts to authenticate the passed {@link Authentication} object, returning a fully populated * <b>Authentication</b> object (including granted authorities) if successful. * * <p>An <b>AuthenticationManager</b> must honour the following contract concerning exceptions: * * <ul> * <li>A {@link DisabledException} must be thrown if an account is disabled and the <b> * AuthenticationManager</b> can test for this state. * <li>A {@link LockedException} must be thrown if an account is locked and the <b> * AuthenticationManager</b> can test for account locking. * <li>A {@link BadCredentialsException} must be thrown if incorrect credentials are presented. * Whilst the above exceptions are optional, an <b>AuthenticationManager</b> must * <B>always</B> test credentials. * </ul> * * <p>Exceptions should be tested for and if applicable thrown in the order expressed above (i.e. * if an account is disabled or locked, the authentication request is immediately rejected and the * credentials testing process is not performed). This prevents credentials being tested against * disabled or locked accounts. * * @param authentication the authentication request object * @return a fully authenticated object including credentials */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { try { // Authenticate the user UUID authenticationUserDirectoryId = securityService.authenticate( authentication.getPrincipal().toString(), authentication.getCredentials().toString()); // Retrieve the details for the user UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getPrincipal().toString()); return new AuthenticationToken(userDetails); } catch (AuthenticationFailedException | UserNotFoundException e) { throw new BadCredentialsException( "Failed to authenticate the user (" + authentication.getPrincipal() + "): Bad credentials"); } catch (UserLockedException e) { throw new LockedException( "Failed to authenticate the user (" + authentication.getPrincipal() + "): User locked"); } catch (ExpiredPasswordException e) { throw new CredentialsExpiredException( "Failed to authenticate the user (" + authentication.getPrincipal() + "): Credentials expired"); } catch (Throwable e) { throw new AuthenticationServiceException( "Failed to authenticate the user (" + authentication.getPrincipal() + ")", e); } } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/StringToGroupMemberTypeConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.stereotype.Component; /** * The <b>StringToGroupMemberTypeConverter</b> class implements the Spring converter that converts a * <b>String</b> type into a <b>GroupMemberType</b> type. * * @author Marcus Portmann */ @SuppressWarnings("unused") @Component @ReadingConverter public class StringToGroupMemberTypeConverter implements Converter<String, GroupMemberType> { /** Constructs a new <b>StringToGroupMemberTypeConverter</b>. */ public StringToGroupMemberTypeConverter() {} @Override public GroupMemberType convert(String source) { return GroupMemberType.fromCode(source); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/StringToPasswordChangeReasonConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.stereotype.Component; /** * The <b>StringToPasswordChangeReasonConverter</b> class implements the Spring converter that * converts a <b>String</b> type into a <b>PasswordChangeReason</b> type. * * @author Marcus Portmann */ @Component @ReadingConverter public class StringToPasswordChangeReasonConverter implements Converter<String, PasswordChangeReason> { /** Constructs a new <b>StringToPasswordChangeReasonConverter</b>. */ public StringToPasswordChangeReasonConverter() {} @Override public PasswordChangeReason convert(String source) { return PasswordChangeReason.fromCode(source); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/StringToPasswordResetStatusConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.stereotype.Component; /** * The <b>StringToPasswordResetStatusConverter</b> class implements the Spring converter that * converts a <b>String</b> type into a <b>PasswordResetStatus</b> type. * * @author Marcus Portmann */ @Component @ReadingConverter public class StringToPasswordResetStatusConverter implements Converter<String, PasswordResetStatus> { /** Constructs a new <b>StringToPasswordResetStatusConverter</b>. */ public StringToPasswordResetStatusConverter() {} @Override public PasswordResetStatus convert(String source) { return PasswordResetStatus.fromCode(source); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/StringToTenantStatusConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.stereotype.Component; /** * The <b>StringToTenantStatusConverter</b> class implements the Spring converter that converts a * <b>String</b> type into a <b>TenantStatus</b> type. * * @author Marcus Portmann */ @Component @ReadingConverter public class StringToTenantStatusConverter implements Converter<String, TenantStatus> { /** Constructs a new <b>StringToTenantStatusConverter</b>. */ public StringToTenantStatusConverter() {} @Override public TenantStatus convert(String source) { return TenantStatus.fromCode(source); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/StringToUserSortByConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; /** * The <b>StringToUserSortByConverter</b> class implements the Spring converter that converts a * <b>String</b> type into a <b>UserSortBy</b> type. * * @author Marcus Portmann */ @Component public class StringToUserSortByConverter implements Converter<String, UserSortBy> { /** Constructs a new <b>StringToUserSortByConverter</b>. */ public StringToUserSortByConverter() {} @Override public UserSortBy convert(String source) { return UserSortBy.fromCode(source); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/StringToUserStatusConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.stereotype.Component; /** * The <b>StringToUserStatusConverter</b> class implements the Spring converter that converts a * <b>String</b> type into a <b>UserStatus</b> type. * * @author Marcus Portmann */ @Component @ReadingConverter public class StringToUserStatusConverter implements Converter<String, UserStatus> { /** Constructs a new <b>StringToUserStatusConverter</b>. */ public StringToUserStatusConverter() {} @Override public UserStatus convert(String source) { return UserStatus.fromCode(source); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/Tenant.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.UUID; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>Tenant</b> class holds the information for a tenant. * * @author Marcus Portmann */ @Schema( description = "A group of users who share common access with specific privileges to a particular subset of the information managed by a multi-tenant application") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "name", "status"}) @Entity @Table(schema = "security", name = "tenants") @SuppressWarnings({"unused", "WeakerAccess"}) public class Tenant implements Serializable { private static final long serialVersionUID = 1000000; /** The date and time the tenant was created. */ @JsonIgnore @Column(name = "created", nullable = false, updatable = false) private LocalDateTime created; /** The ID for the tenant. */ @Schema(description = "The ID for the tenant", required = true) @JsonProperty(required = true) @NotNull @Id @Column(name = "id", nullable = false) private UUID id; /** The name of the tenant. */ @Schema(description = "The name of the tenant", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The status for the tenant. */ @Schema(description = "The status for the tenant", required = true) @JsonProperty(required = true) @NotNull @Column(name = "status", nullable = false) private TenantStatus status; /** The date and time the tenant was last updated. */ @JsonIgnore @Column(name = "updated", insertable = false) private LocalDateTime updated; /** The user directories associated with the tenant. */ @JsonIgnore @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @JoinTable( schema = "security", name = "user_directory_to_tenant_map", joinColumns = @JoinColumn(name = "tenant_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_directory_id", referencedColumnName = "id")) private Set<UserDirectory> userDirectories = new HashSet<>(); /** Constructs a new <b>Tenant</b>. */ public Tenant() {} /** * Constructs a new <b>Tenant</b>. * * @param name the name of the tenant * @param status the status for the tenant */ public Tenant(String name, TenantStatus status) { this.name = name; this.status = status; } /** * Constructs a new <b>Tenant</b>. * * @param id the ID for the tenant * @param name the name of the tenant * @param status the status for the tenant */ public Tenant(UUID id, String name, TenantStatus status) { this.id = id; this.name = name; this.status = status; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } Tenant other = (Tenant) object; return Objects.equals(id, other.id); } /** * Returns the date and time the tenant was created. * * @return the date and time the tenant was created */ public LocalDateTime getCreated() { return created; } /** * Returns the ID for the tenant. * * @return the ID for the tenant */ public UUID getId() { return id; } /** * Returns the name of the tenant. * * @return the name of the tenant */ public String getName() { return name; } /** * Returns the status for the tenant. * * @return the status for the tenant */ public TenantStatus getStatus() { return status; } /** * Returns the date and time the tenant was last updated. * * @return the date and time the tenant was last updated */ public LocalDateTime getUpdated() { return updated; } /** * Returns the user directories associated with the tenant. * * @return the user directories associated with the tenant */ public Set<UserDirectory> getUserDirectories() { return userDirectories; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } /** * Link the user directory to the tenant. * * @param userDirectory the user directory */ public void linkUserDirectory(UserDirectory userDirectory) { userDirectories.add(userDirectory); userDirectory.getTenants().add(this); } /** * Set the ID for the tenant. * * @param id the ID for the tenant */ public void setId(UUID id) { this.id = id; } /** * Set the name of the tenant. * * @param name the name of the tenant */ public void setName(String name) { this.name = name; } /** * Set the status for the tenant. * * @param status the status for the tenant */ public void setStatus(TenantStatus status) { this.status = status; } /** * Set the user directories associated with the tenant. * * @param userDirectories the user directories associated with the tenant */ public void setUserDirectories(Set<UserDirectory> userDirectories) { this.userDirectories = userDirectories; } /** * Unlink the user directory from the tenant. * * @param userDirectory the user directory */ public void unlinkUserDirectory(UserDirectory userDirectory) { userDirectories.remove(userDirectory); userDirectory.getTenants().remove(this); } /** The Java Persistence callback method invoked before the entity is created in the database. */ @PrePersist protected void onCreate() { created = LocalDateTime.now(); } /** The Java Persistence callback method invoked before the entity is updated in the database. */ @PreUpdate protected void onUpdate() { updated = LocalDateTime.now(); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/TenantNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; import java.util.UUID; /** * An <b>TenantNotFoundException</b> is thrown to indicate that a security operation failed as a * result of a tenant that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/tenant-not-found", title = "The tenant could not be found.", status = 404) public class TenantNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>TenantNotFoundException</b>. * * @param tenantId the ID for the tenant */ public TenantNotFoundException(UUID tenantId) { super("The tenant (" + tenantId + ") could not be found"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/TenantRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>TenantRepository</b> interface declares the repository for the <b> Tenant</b> domain type. * * @author Marcus Portmann */ public interface TenantRepository extends JpaRepository<Tenant, UUID> { /** * Add the user directory to the tenant. * * @param tenantId the ID for the tenant * @param userDirectoryId the ID for the user directory */ @Modifying @Query( value = "insert into security.user_directory_to_tenant_map(tenant_id, user_directory_id) " + "values (:tenantId, :userDirectoryId)", nativeQuery = true) void addUserDirectoryToTenant( @Param("tenantId") UUID tenantId, @Param("userDirectoryId") UUID userDirectoryId); /** * Delete the tenant. * * @param tenantId the ID for the tenant */ @Modifying @Query("delete from Tenant u where u.id = :tenantId") void deleteById(@Param("tenantId") UUID tenantId); /** * Check whether the tenant with the specified name exists. * * @param name the name of the tenant * @return <b>true</b> if a tenant with the specified name exists or <b>false</b> otherwise */ boolean existsByNameIgnoreCase(String name); /** * Retrieve the tenants. * * @param pageable the pagination information * @return the tenants */ Page<Tenant> findAll(Pageable pageable); /** * Retrieve the tenants for the user directory. * * @param userDirectoryId the ID for the user directory * @return the tenants for the user directory */ @Query("select o from Tenant o join o.userDirectories as ud where ud.id = :userDirectoryId") List<Tenant> findAllByUserDirectoryId(@Param("userDirectoryId") UUID userDirectoryId); /** * Retrieve the filtered tenants. * * @param filter the filter to apply to the tenants * @param pageable the pagination information * @return the filtered tenants */ @Query("select t from Tenant t where (lower(t.name) like lower(:filter))") Page<Tenant> findFiltered(String filter, Pageable pageable); /** * Retrieve the name of the tenant. * * @param tenantId the ID for the tenant * @return an Optional containing the name of the tenant or an empty Optional if the tenant could * not be found */ @Query("select o.name from Tenant o where o.id = :tenantId") Optional<String> getNameById(@Param("tenantId") UUID tenantId); /** * Retrieve the IDs for the user directories for the tenant. * * @param tenantId the ID for the tenant * @return the IDs for the user directories for the tenant */ @Query("select ud.id from UserDirectory ud join ud.tenants as o where o.id = :tenantId") List<UUID> getUserDirectoryIdsById(@Param("tenantId") UUID tenantId); /** * Remove the user directory from the tenant * * @param tenantId the ID for the tenant * @param userDirectoryId the ID for the user directory */ @Modifying @Query( value = "delete from security.user_directory_to_tenant_map " + "where tenant_id=:tenantId and user_directory_id = :userDirectoryId", nativeQuery = true) void removeUserDirectoryFromTenant( @Param("tenantId") UUID tenantId, @Param("userDirectoryId") UUID userDirectoryId); /** * Check whether the user directory to tenant mapping exists. * * @param tenantId the ID for the tenant * @param userDirectoryId the ID for the user directory * @return <b>true</b> if the user directory to tenant mapping exists or <b>false</b> otherwise */ @Query( value = "select (count(user_directory_id) > 0) from security.user_directory_to_tenant_map where " + "tenant_id = :tenantId and user_directory_id = :userDirectoryId", nativeQuery = true) boolean userDirectoryToTenantMappingExists( @Param("tenantId") UUID tenantId, @Param("userDirectoryId") UUID userDirectoryId); }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/TenantStatus.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.v3.oas.annotations.media.Schema; /** * The <b>TenantStatus</b> enumeration defines the possible statuses for a tenant. * * @author Marcus Portmann */ @Schema(description = "The tenant status") public enum TenantStatus { /** Inactive. */ INACTIVE("inactive", "Inactive"), /** Active. */ ACTIVE("active", "Active"); private final String code; private final String description; TenantStatus(String code, String description) { this.code = code; this.description = description; } /** * Returns the tenant status given by the specified code value. * * @param code the code for the tenant status * @return the tenant status given by the specified code value */ @JsonCreator public static TenantStatus fromCode(String code) { switch (code) { case "inactive": return TenantStatus.INACTIVE; case "active": return TenantStatus.ACTIVE; default: throw new RuntimeException( "Failed to determine the tenant status with the invalid code (" + code + ")"); } } /** * Returns the numeric code for the tenant status. * * @param tenantStatus the tenant status * @return the numeric code for the tenant status */ public static int toNumericCode(TenantStatus tenantStatus) { switch (tenantStatus) { case ACTIVE: return 1; case INACTIVE: return 2; default: throw new RuntimeException( "Failed to determine the numeric code for the tenant status (" + tenantStatus.code() + ")"); } } /** * Returns the tenant status for the specified numeric code. * * @param numericCode the numeric code for the tenant status * @return the tenant status given by the specified numeric code value */ public static TenantStatus fromNumericCode(int numericCode) { switch (numericCode) { case 1: return TenantStatus.ACTIVE; case 2: return TenantStatus.INACTIVE; default: throw new RuntimeException( "Failed to determine the tenant status for the numeric code (" + numericCode + ")"); } } /** * Returns the code value for the tenant status. * * @return the code value for the tenant status */ @JsonValue public String code() { return code; } /** * Returns the description for the tenant status. * * @return the description for the tenant status */ public String description() { return description; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/TenantStatusConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import javax.persistence.AttributeConverter; import javax.persistence.Converter; /** * The <b>TenantStatusConverter</b> class implements the custom JPA converter for the <b> * TenantStatus</b> enumeration. * * @author Marcus Portmann */ @Converter(autoApply = true) public class TenantStatusConverter implements AttributeConverter<TenantStatus, Integer> { /** * Converts the value stored in the entity attribute into the data representation to be stored in * the database. * * @param attribute the entity attribute value to be converted * @return the converted data to be stored in the database column */ @Override public Integer convertToDatabaseColumn(TenantStatus attribute) { if (attribute == null) return null; return TenantStatus.toNumericCode(attribute); } /** * Converts the data stored in the database column into the value to be stored in the entity * attribute. Note that it is the responsibility of the converter writer to specify the correct * dbData type for the corresponding column for use by the JDBC driver: i.e., persistence * providers are not expected to do such type conversion. * * @param dbData the data from the database column to be converted * @return the converted value to be stored in the entity attribute */ @Override public TenantStatus convertToEntityAttribute(Integer dbData) { if (dbData == null) return null; return TenantStatus.fromNumericCode(dbData); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/TenantStatusToStringConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.WritingConverter; import org.springframework.stereotype.Component; /** * The <b>TenantStatusToStringConverter</b> class implements the Spring converter that converts a * <b>TenantStatus</b> type into a <b>String</b> type. * * @author Marcus Portmann */ @Component @WritingConverter public class TenantStatusToStringConverter implements Converter<TenantStatus, String> { /** Constructs a new <b>TenantStatusToStringConverter</b>. */ public TenantStatusToStringConverter() {} @Override public String convert(TenantStatus source) { return source.code(); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/TenantUserDirectory.java
package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Id; import javax.validation.constraints.NotNull; /** * The <b>TenantUserDirectory</b> class holds the information for a tenant user directory. * * @author Marcus Portmann */ @Schema(description = "A tenant user directory association") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"tenantId", "userDirectoryId"}) @SuppressWarnings({"unused"}) public class TenantUserDirectory implements Serializable { /** The ID for the tenant. */ @Schema(description = "The ID for the tenant", required = true) @JsonProperty(required = true) @NotNull @Id @Column(name = "tenantId", nullable = false) private UUID tenantId; /** The ID for the user directory. */ @Schema(description = "The ID for the user directory", required = true) @JsonProperty(required = true) @NotNull @Id @Column(name = "userDirectoryId", nullable = false) private UUID userDirectoryId; /** Constructs a new <b>TenantUserDirectory</b>. */ public TenantUserDirectory() {} /** * Constructs a new <b>TenantUserDirectory</b>. * * @param tenantId the ID for the tenant * @param userDirectoryId the ID for the user directory */ public TenantUserDirectory(UUID tenantId, UUID userDirectoryId) { this.tenantId = tenantId; this.userDirectoryId = userDirectoryId; } /** * Returns the ID for the tenant. * * @return the ID for the tenant */ public UUID getTenantId() { return tenantId; } /** * Returns the ID for the user directory. * * @return the ID for the user directory */ public UUID getUserDirectoryId() { return userDirectoryId; } /** * Set the ID for the tenant. * * @param tenantId the ID for the tenant */ public void setTenantId(UUID tenantId) { this.tenantId = tenantId; } /** * Set the ID for the user directory. * * @param userDirectoryId the ID for the user directory */ public void setUserDirectoryId(UUID userDirectoryId) { this.userDirectoryId = userDirectoryId; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/TenantUserDirectoryNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; import java.util.UUID; /** * A <b>TenantUserDirectoryNotFoundException</b> is thrown to indicate that a security operation * failed as a result of a tenant user directory that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/tenant-user-directory-not-found", title = "The tenant user directory could not be found.", status = 404) public class TenantUserDirectoryNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>TenantUserDirectoryNotFoundException</b>. * * @param tenantId the ID for the tenant * @param userDirectoryId the ID for the user directory */ public TenantUserDirectoryNotFoundException(UUID tenantId, UUID userDirectoryId) { super( "The tenant user directory for the tenant (" + tenantId + ") and user directory (" + userDirectoryId + ") could not be found"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/Tenants.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.sorting.SortDirection; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.List; /** * The <b>Tenants</b> class holds the results of a request to retrieve a list of tenants. * * @author Marcus Portmann */ @Schema(description = "The results of a request to retrieve a list of tenants") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"tenants", "total", "filter", "sortDirection", "pageIndex", "pageSize"}) @SuppressWarnings({"unused"}) public class Tenants implements Serializable { private static final long serialVersionUID = 1000000; /** The optional filter that was applied to the tenants. */ @Schema(description = "The optional filter that was applied to the tenants") @JsonProperty private String filter; /** The optional page index. */ @Schema(description = "The optional page index") @JsonProperty private Integer pageIndex; /** The optional page size. */ @Schema(description = "The optional page size") @JsonProperty private Integer pageSize; /** The optional sort direction that was applied to the tenants. */ @Schema(description = "The optional sort direction that was applied to the tenants") @JsonProperty private SortDirection sortDirection; /** The tenants. */ @Schema(description = "The tenants", required = true) @JsonProperty(required = true) private List<Tenant> tenants; /** The total number of tenants. */ @Schema(description = "The total number of tenants", required = true) @JsonProperty(required = true) private long total; /** Constructs a new <b>Tenants</b>. */ public Tenants() {} /** * Constructs a new <b>Tenants</b>. * * @param tenants the tenants * @param total the total number of tenants * @param filter the optional filter that was applied to the tenants * @param sortDirection the optional sort direction that was applied to the tenants * @param pageIndex the optional page index * @param pageSize the optional page size */ public Tenants( List<Tenant> tenants, long total, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) { this.tenants = tenants; this.total = total; this.filter = filter; this.sortDirection = sortDirection; this.pageIndex = pageIndex; this.pageSize = pageSize; } /** * Returns the optional filter that was applied to the tenants. * * @return the optional filter that was applied to the tenants */ public String getFilter() { return filter; } /** * Returns the optional page index. * * @return the optional page index */ public Integer getPageIndex() { return pageIndex; } /** * Returns the optional page size. * * @return the optional page size */ public Integer getPageSize() { return pageSize; } /** * Returns the optional sort direction that was applied to the tenants. * * @return the optional sort direction that was applied to the tenants */ public SortDirection getSortDirection() { return sortDirection; } /** * Returns the tenants. * * @return the tenants */ public List<Tenant> getTenants() { return tenants; } /** * Returns the total number of tenants. * * @return the total number of tenants */ public Long getTotal() { return total; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/User.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; /** * The <b>User</b> class holds the information for a user. * * @author Marcus Portmann */ @Schema(description = "A user") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "userDirectoryId", "username", "name", "preferredName", "mobileNumber", "phoneNumber", "email", "status", "password", "passwordAttempts", "passwordExpiry" }) @Entity @Table(schema = "security", name = "users") @SuppressWarnings({"unused", "WeakerAccess"}) public class User implements Serializable { private static final long serialVersionUID = 1000000; /** The date and time the user was created. */ @JsonIgnore @Column(name = "created", nullable = false, updatable = false) private LocalDateTime created; /** The e-mail address for the user. */ @Schema(description = "The e-mail address for the user") @JsonProperty @Size(max = 100) @Pattern( message = "invalid e-mail address", regexp = "^$|(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\" + ".[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d" + "-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\" + ".)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}" + "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-zA-Z0-9-]*[a-zA-Z0-9]:" + "(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e" + "-\\x7f])+)\\])") @Column(name = "email", length = 100) private String email; /** The groups the user is associated with. */ @JsonIgnore @ManyToMany(mappedBy = "users") private Set<Group> groups = new HashSet<>(); /** The ID for the user. */ @JsonIgnore @Id @Column(name = "id", nullable = false) private UUID id; /** The international format mobile number for the user. */ @Schema(description = "The international format mobile number for the user") @JsonProperty @Size(max = 100) @Pattern( message = "invalid international format mobile number", regexp = "^$|(\\+|00)(297|93|244|1264|358|355|376|971|54|374|1684|1268|61" + "|43|994|257|32|229|226|880|359|973|1242|387|590|375|501|1441|591|55|1246|673|975|267|236|1" + "|61|41|56|86|225|237|243|242|682|57|269|238|506|53|5999|61|1345|357|420|49|253|1767|45|1809" + "|1829|1849|213|593|20|291|212|34|372|251|358|679|500|33|298|691|241|44|995|44|233|350|224" + "|590|220|245|240|30|1473|299|502|594|1671|592|852|504|385|509|36|62|44|91|246|353|98|964|354" + "|972|39|1876|44|962|81|76|77|254|996|855|686|1869|82|383|965|856|961|231|218|1758|423|94|266" + "|370|352|371|853|590|212|377|373|261|960|52|692|389|223|356|95|382|976|1670|258|222|1664|596" + "|230|265|60|262|264|687|227|672|234|505|683|31|47|977|674|64|968|92|507|64|51|63|680|675|48" + "|1787|1939|850|351|595|970|689|974|262|40|7|250|966|249|221|65|500|4779|677|232|503|378|252" + "|508|381|211|239|597|421|386|46|268|1721|248|963|1649|235|228|66|992|690|993|670|676|1868" + "|216|90|688|886|255|256|380|598|1|998|3906698|379|1784|58|1284|1340|84|678|681|685|967|27" + "|260|263)(9[976]\\d|8[987530]\\d|6[987]\\d|5[90]\\d|42\\d|3[875]\\d|2[98654321]\\d|9[8543210" + "]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\\d{4,20}$") @Column(name = "mobile_number", length = 100) private String mobileNumber; /** The name of the user. */ @Schema(description = "The name of the user", required = true) @JsonProperty(required = true) @NotNull @Size(max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** * The password or password hash for the user. * * <p>The password is not required as part of the JSON or XML representation of the user, other * than when creating the user, so the field is nullable but the database column is not. */ @Schema(description = "The password or password hash for the user") @JsonProperty @Size(max = 100) @Column(name = "password", length = 100, nullable = false) private String password; /** * The number of failed authentication attempts as a result of an incorrect password for the user. */ @Schema( description = "The number of failed authentication attempts as a result of an incorrect password for " + "the user", example = "0") @JsonProperty @Column(name = "password_attempts", nullable = false) private Integer passwordAttempts; /** The date and time the password for the user expires. */ @Schema(description = "The date and time the password for the user expires") @JsonProperty @Column(name = "password_expiry", nullable = false) private LocalDateTime passwordExpiry; /** The phone number for the user. */ @Schema(description = "The phone number for the user") @JsonProperty @Size(max = 100) @Column(name = "phone_number", length = 100) private String phoneNumber; /** The preferred name for the user. */ @Schema(description = "The preferred name for the user") @JsonProperty @Size(max = 100) @Column(name = "preferred_name", length = 100) private String preferredName; /** The status for the user. */ @Schema(description = "The status for the user", required = true) @JsonProperty(required = true) @NotNull @Column(name = "status", nullable = false) private UserStatus status; /** The date and time the user was last updated. */ @JsonIgnore @Column(name = "updated", insertable = false) private LocalDateTime updated; /** The ID for the user directory the user is associated with. */ @Schema( description = "The ID for the user directory the " + "user is associated with", required = true) @JsonProperty(required = true) @NotNull @Column(name = "user_directory_id", nullable = false) private UUID userDirectoryId; /** The username for the user. */ @Schema(description = "The username for the user", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "username", length = 100, nullable = false) private String username; /** Constructs a new <b>User</b>. */ public User() {} /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } User other = (User) object; return Objects.equals(id, other.id); } /** * Returns the date and time the user was created. * * @return the date and time the user was created */ public LocalDateTime getCreated() { return created; } /** * Returns the e-mail address for the user. * * @return the e-mail address for the user */ public String getEmail() { return email; } /** * Returns the groups the user is associated with. * * @return the groups the user is associated with */ public Set<Group> getGroups() { return groups; } /** * Returns the ID for the user. * * @return the ID for the user */ public UUID getId() { return id; } /** * Returns the international format mobile number for the user. * * @return the international format mobile number for the user */ public String getMobileNumber() { return mobileNumber; } /** * Returns the name of the user. * * @return the name of the user */ public String getName() { return name; } /** * Returns the password or password hash for the user. * * @return the password or password hash for the user */ public String getPassword() { return password; } /** * Returns the number of failed authentication attempts as a result of an incorrect password for * the user. * * @return the number of failed authentication attempts as a result of an incorrect password for * the user */ public Integer getPasswordAttempts() { return passwordAttempts; } /** * Returns the date and time the password for the user expires. * * @return the date and time the password for the user expires */ public LocalDateTime getPasswordExpiry() { return passwordExpiry; } /** * Returns the phone number for the user. * * @return the phone number for the user */ public String getPhoneNumber() { return phoneNumber; } /** * Returns the preferred name for the user. * * @return the preferred name for the user */ public String getPreferredName() { return preferredName; } /** * Returns the status for the user. * * @return the status for the user */ public UserStatus getStatus() { return status; } /** * Returns the date and time the user was last updated. * * @return the date and time the user was last updated */ public LocalDateTime getUpdated() { return updated; } /** * Returns the ID for the user directory the user is associated with. * * @return the ID for the user directory the user is associated with */ public UUID getUserDirectoryId() { return userDirectoryId; } /** * Returns the username for the user. * * @return the username for the user */ public String getUsername() { if (username != null) { username = username.toLowerCase(); } return username; } /** * Has the password for the user expired? * * @return <b>true</b> if the password for the user has expired or <b>false</b> otherwise */ public boolean hasPasswordExpired() { if (passwordExpiry != null) { return LocalDateTime.now().isAfter(passwordExpiry); } return false; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } /** * Is the user active? * * @return <b>true</b> if the user is active or <b>false</b> otherwise */ @JsonIgnore public boolean isActive() { return (status == UserStatus.ACTIVE); } /** * Is the user expired? * * @return <b>true</b> if the user is expired or <b>false</b> otherwise */ @JsonIgnore public boolean isExpired() { return (status == UserStatus.EXPIRED); } /** * Is the user locked? * * @return <b>true</b> if the user is locked or <b>false</b> otherwise */ @JsonIgnore public boolean isLocked() { return (status == UserStatus.LOCKED); } /** * Set the e-mail address for the user. * * @param email the e-mail address for the user */ public void setEmail(String email) { this.email = email; } /** * Set the groups the user is associated with. * * @param groups the groups the user is associated with */ public void setGroups(Set<Group> groups) { this.groups = groups; } /** * Set the ID for the user. * * @param id the ID for the user */ public void setId(UUID id) { this.id = id; } /** * Set the international format mobile number for the user. * * @param mobileNumber the international format mobile number for the user */ public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } /** * Set the name of the user. * * @param name the name of the user */ public void setName(String name) { this.name = name; } /** * Set the password or password hash for the user. * * @param password the password or password hash for the user */ public void setPassword(String password) { this.password = password; } /** * Set the password attempts for the user. * * @param passwordAttempts the password attempts for the user */ public void setPasswordAttempts(int passwordAttempts) { this.passwordAttempts = passwordAttempts; } /** * Set the date and time the password for the user expires. * * @param passwordExpiry the date and time the password for the user expires */ public void setPasswordExpiry(LocalDateTime passwordExpiry) { this.passwordExpiry = passwordExpiry; } /** * Set the phone number for the user. * * @param phoneNumber the phone number for the user */ public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } /** * Set the preferred name for the user. * * @param preferredName the preferred name for the user */ public void setPreferredName(String preferredName) { this.preferredName = preferredName; } /** * Set the status for the user. * * @param status the status for the user */ public void setStatus(UserStatus status) { this.status = status; } /** * Set the ID for the user directory the user is associated with. * * @param userDirectoryId the ID for the user directory the user is associated with */ public void setUserDirectoryId(UUID userDirectoryId) { this.userDirectoryId = userDirectoryId; } /** * Set the username for the user. * * @param username the username for the user */ public void setUsername(String username) { this.username = username; } /** The Java Persistence callback method invoked before the entity is created in the database. */ @PrePersist protected void onCreate() { created = LocalDateTime.now(); } /** The Java Persistence callback method invoked before the entity is updated in the database. */ @PreUpdate protected void onUpdate() { updated = LocalDateTime.now(); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserAttribute.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.util.Base64Util; import africa.absa.inception.core.util.BinaryBuffer; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.math.BigDecimal; import java.util.List; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>UserAttribute</b> class stores a user attribute as a name-value pair. * * @author Marcus Portmann */ @Schema(description = "A user attribute in the form of a name-value pair") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"name", "value"}) @SuppressWarnings({"unused", "WeakerAccess"}) public class UserAttribute implements Serializable { private static final long serialVersionUID = 1000000; /** The name of the user attribute. */ @Schema(description = "The name of the user attribute", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) private String name; /** The value for the user attribute. */ @Schema(description = "The value for the user attribute", required = true) @JsonProperty(required = true) @NotNull @Size(max = 4000) private String value; /** Constructs a new <b>UserAttribute</b>. */ public UserAttribute() {} /** * Constructs a new <b>UserAttribute</b>. * * @param name the name of the user attribute * @param value the <b>BigDecimal</b> value for the user attribute */ public UserAttribute(String name, BigDecimal value) { this.name = name; this.value = String.valueOf(value); } /** * Constructs a new <b>UserAttribute</b>. * * @param name the name of the user attribute * @param value the binary value for the user attribute */ public UserAttribute(String name, BinaryBuffer value) { this.name = name; this.value = Base64Util.encodeBytes(value.getData()); } /** * Constructs a new <b>UserAttribute</b>. * * @param name the name of the user attribute * @param value the binary value for the user attribute */ public UserAttribute(String name, byte[] value) { this.name = name; this.value = Base64Util.encodeBytes(value); } /** * Constructs a new <b>UserAttribute</b>. * * @param name the name of the user attribute * @param value the <b>double</b> value for the user attribute */ public UserAttribute(String name, double value) { this.name = name; this.value = String.valueOf(value); } /** * Constructs a new <b>UserAttribute</b>. * * @param name the name of the user attribute * @param value the <b>long</b> value for the user attribute */ public UserAttribute(String name, long value) { this.name = name; this.value = String.valueOf(value); } /** * Constructs a new <b>UserAttribute</b>. * * @param name the name of the user attribute * @param value the <b>String</b> value for the user attribute */ public UserAttribute(String name, String value) { this.name = name; this.value = value; } /** * Returns whether the list of user attributes contains a user attribute whose name matches the * specified name. * * @param list the user attributes to search * @param name the name of the attribute * @return <b>true</b> if the list of user attributes contains a user attribute whose name matches * the specified name or <b>false</b> otherwise */ public static boolean contains(List<UserAttribute> list, String name) { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { return true; } } return false; } /** * Returns the binary value for the user attribute with the specified name in the specified list. * * @param list the user attributes to search * @param name the name of the attribute * @return the binary value for the user attribute with the specified name in the specified list * @throws UserAttributeException if the binary value could not be retrieved for the user * attribute */ public static byte[] getBinaryValue(List<UserAttribute> list, String name) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { try { return Base64Util.decode(userAttribute.value); } catch (Throwable e) { throw new UserAttributeException( String.format( "Failed to retrieve the binary value for the user attribute (%s)", userAttribute.name)); } } } throw new UserAttributeException( String.format( "Failed to retrieve the binary value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Returns the <b>BigDecimal</b> value for the user attribute with the specified name in the * specified list. * * @param list the user attributes to search * @param name the name of the attribute * @return the <b>BigDecimal</b> value for the user attribute with the specified name in the * specified list * @throws UserAttributeException if the decimal value could not be retrieved for the user * attribute */ public static BigDecimal getDecimalValue(List<UserAttribute> list, String name) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { try { return new BigDecimal(userAttribute.value); } catch (Throwable e) { throw new UserAttributeException( String.format( "Failed to retrieve the decimal value for the user attribute (%s)", userAttribute.name)); } } } throw new UserAttributeException( String.format( "Failed to retrieve the decimal value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Returns the <b>double</b> value for the user attribute with the specified name in the specified * list. * * @param list the user attributes to search * @param name the name of the attribute * @return the <b>double</b> value for the user attribute with the specified name in the specified * list * @throws UserAttributeException if the double value could not be retrieved for the user * attribute */ public static double getDoubleValue(List<UserAttribute> list, String name) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { try { return Double.parseDouble(userAttribute.value); } catch (Throwable e) { throw new UserAttributeException( String.format( "Failed to retrieve the double value for the user attribute (%s)", userAttribute.name)); } } } throw new UserAttributeException( String.format( "Failed to retrieve the double value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Returns the <b>int</b> value for the user attribute with the specified name in the specified * list. * * @param list the user attributes to search * @param name the name of the attribute * @return the <b>int</b> value for the user attribute with the specified name in the specified * list * @throws UserAttributeException if the integer value could not be retrieved for the user * attribute */ public static int getIntegerValue(List<UserAttribute> list, String name) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { try { return Integer.parseInt(userAttribute.value); } catch (Throwable e) { throw new UserAttributeException( String.format( "Failed to retrieve the integer value for the user attribute (%s)", userAttribute.name)); } } } throw new UserAttributeException( String.format( "Failed to retrieve the integer value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Returns the <b>long</b> value for the user attribute with the specified name in the specified * list. * * @param list the user attributes to search * @param name the name of the attribute * @return the <b>long</b> value for the user attribute with the specified name in the specified * list * @throws UserAttributeException if the long value could not be retrieved for the user attribute */ public static long getLongValue(List<UserAttribute> list, String name) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { try { return Long.parseLong(userAttribute.value); } catch (Throwable e) { throw new UserAttributeException( String.format( "Failed to retrieve the long value for the user attribute (%s)", userAttribute.name)); } } } throw new UserAttributeException( String.format( "Failed to retrieve the long value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Returns the <b>String</b> value for the user attribute with the specified name in the specified * list. * * @param list the user attributes to search * @param name the name of the attribute * @return the <b>String</b> value for the user attribute with the specified name in the specified * list * @throws UserAttributeException if the string value could not be retrieved for the user * attribute */ public static String getStringValue(List<UserAttribute> list, String name) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { return userAttribute.value; } } throw new UserAttributeException( String.format( "Failed to retrieve the string value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Set the binary value for the user attribute with the specified name in the specified list. * * @param list the user attributes to search * @param name the name of the attribute * @param value the binary value for the user attribute * @throws UserAttributeException if the binary value could not be set for the user attribute */ public static void setBinaryValue(List<UserAttribute> list, String name, BinaryBuffer value) throws UserAttributeException { setBinaryValue(list, name, value.getData()); } /** * Set the binary value for the user attribute with the specified name in the specified list. * * @param list the user attributes to search * @param name the name of the attribute * @param value the binary value for the user attribute * @throws UserAttributeException if the binary value could not be set for the user attribute */ public static void setBinaryValue(List<UserAttribute> list, String name, byte[] value) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { userAttribute.setBinaryValue(value); return; } } throw new UserAttributeException( String.format( "Failed to set the binary value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Set the <b>BigDecimal</b> value for the user attribute with the specified name in the specified * list. * * @param list the user attributes to search * @param name the name of the attribute * @param value the <b>BigDecimal</b> value for the user attribute * @throws UserAttributeException if the decimal value could not be set for the user attribute */ public static void setDecimalValue(List<UserAttribute> list, String name, BigDecimal value) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { userAttribute.setDecimalValue(value); return; } } throw new UserAttributeException( String.format( "Failed to set the decimal value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Set the <b>double</b> value for the user attribute with the specified name in the specified * list. * * @param list the user attributes to search * @param name the name of the attribute * @param value the <b>double</b> value for the user attribute * @throws UserAttributeException if the double value could not be set for the user attribute */ public static void setDoubleValue(List<UserAttribute> list, String name, double value) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { userAttribute.setDoubleValue(value); return; } } throw new UserAttributeException( String.format( "Failed to set the double value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Set the <b>int</b> value for the user attribute with the specified name in the specified list. * * @param list the user attributes to search * @param name the name of the attribute * @param value the <b>int</b> value for the user attribute * @throws UserAttributeException if the integer value could not be set for the user attribute */ public static void setIntegerValue(List<UserAttribute> list, String name, int value) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { userAttribute.setIntegerValue(value); return; } } throw new UserAttributeException( String.format( "Failed to set the integer value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Set the <b>long</b> value for the user attribute with the specified name in the specified list. * * @param list the user attributes to search * @param name the name of the attribute * @param value the <b>long</b> value for the user attribute * @throws UserAttributeException if the long value could not be set for the user attribute */ public static void setLongValue(List<UserAttribute> list, String name, long value) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { userAttribute.setLongValue(value); return; } } throw new UserAttributeException( String.format( "Failed to set the long value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Set the <b>String</b> value for the user attribute with the specified name in the specified * list. * * @param list the user attributes to search * @param name the name of the attribute * @param value the <b>String</b> value for the user attribute * @throws UserAttributeException if the string value could not be set for the user attribute */ public static void setStringValue(List<UserAttribute> list, String name, String value) throws UserAttributeException { for (UserAttribute userAttribute : list) { if (userAttribute.name.equalsIgnoreCase(name)) { userAttribute.setStringValue(value); return; } } throw new UserAttributeException( String.format( "Failed to set the string value for the user attribute (%s): " + "The attribute could not be found", name)); } /** * Returns the binary value for the user attribute. * * @return the binary value for the user attribute * @throws UserAttributeException if the binary value could not be retrieved for the user * attribute */ public byte[] getBinaryValue() throws UserAttributeException { try { return Base64Util.decode(value); } catch (Throwable e) { throw new UserAttributeException( String.format("Failed to retrieve the binary value for the user attribute (%s)", name)); } } /** * Returns the <b>BigDecimal</b> value for the user attribute. * * @return the <b>BigDecimal</b> value for the user attribute * @throws UserAttributeException if the decimal value could not be retrieved for the user * attribute */ public BigDecimal getDecimalValue() throws UserAttributeException { try { return new BigDecimal(value); } catch (Throwable e) { throw new UserAttributeException( String.format("Failed to retrieve the decimal value for the user attribute (%s)", name)); } } /** * Returns the <b>double</b> value for the user attribute. * * @return the <b>double</b> value for the user attribute * @throws UserAttributeException if the double value could not be retrieved for the user * attribute */ public double getDoubleValue() throws UserAttributeException { try { return Double.parseDouble(value); } catch (Throwable e) { throw new UserAttributeException( String.format("Failed to retrieve the double value for the user attribute (%s)", name)); } } /** * Returns the <b>int</b> value for the user attribute. * * @return the <b>int</b> value for the user attribute * @throws UserAttributeException if the integer value could not be retrieved for the user * attribute */ public int getIntegerValue() throws UserAttributeException { try { return Integer.parseInt(value); } catch (Throwable e) { throw new UserAttributeException( String.format("Failed to retrieve the integer value for the user attribute (%s)", name)); } } /** * Returns the <b>long</b> value for the user attribute. * * @return the <b>long</b> value for the user attribute * @throws UserAttributeException if the long value could not be retrieved for the user attribute */ public long getLongValue() throws UserAttributeException { try { return Long.parseLong(value); } catch (Throwable e) { throw new UserAttributeException( String.format("Failed to retrieve the long value for the user attribute (%s)", name)); } } /** * Returns the name of the user attribute. * * @return the name of the user attribute */ public String getName() { return name; } /** * Returns the <b>String</b> value for the user attribute. * * @return the <b>String</b> value for the user attribute */ public String getStringValue() { return value; } /** * Returns the <b>String</b> value for the user attribute. * * @return the <b>String</b> value for the user attribute */ public String getValue() { return value; } /** * Set the binary value for the user attribute. * * @param value the binary value for the user attribute */ public void setBinaryValue(BinaryBuffer value) { this.value = Base64Util.encodeBytes(value.getData()); } /** * Set the binary value for the user attribute. * * @param value the binary value for the user attribute */ public void setBinaryValue(byte[] value) { this.value = Base64Util.encodeBytes(value); } /** * Set the <b>BigDecimal</b> value for the user attribute. * * @param value the <b>BigDecimal</b> value for the user attribute */ public void setDecimalValue(BigDecimal value) { this.value = String.valueOf(value); } /** * Set the <b>double</b> value for the user attribute. * * @param value the <b>double</b> value for the user attribute */ public void setDoubleValue(double value) { this.value = String.valueOf(value); } /** * Set the <b>int</b> value for the user attribute. * * @param value the <b>int</b> value for the user attribute */ public void setIntegerValue(int value) { this.value = String.valueOf(value); } /** * Set the <b>long</b> value for the user attribute. * * @param value the <b>long</b> value for the user attribute */ public void setLongValue(long value) { this.value = String.valueOf(value); } /** * Set the name of the user attribute. * * @param name the name of the user attribute */ public void setName(String name) { this.name = name; } /** * Set the <b>String</b> value for the user attribute. * * @param value the <b>String</b> value for the user attribute */ public void setStringValue(String value) { this.value = value; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserAttributeException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * An <b>UserAttributeException</b> is thrown to indicate an invalid operation was performed on a * <b>UserAttribute</b> instance. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/user-attribute", title = "An error has occurred and the request could not be processed at this time.") public class UserAttributeException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>UserAttributeException</b> with the specified message. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. */ public UserAttributeException(String message) { super(message); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDetails.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; /** * The <b>UserDetails</b> class stores the details for a user. * * @author Marcus Portmann */ public class UserDetails implements org.springframework.security.core.userdetails.UserDetails { /** The authorities granted to the user. */ private final List<GrantedAuthority> authorities; /** The user. */ private final User user; /** * Constructs a new <b>UserDetails</b>. * * @param user the user * @param roleCodes the codes for the roles that the user has been assigned * @param functionCodes the function codes for the user * @param tenantIds the IDs for the tenants the user is associated with * @param userDirectoryIds the list of IDs for the user user directories the user is associated * with as a result of being associated with one or more tenants */ UserDetails( User user, List<String> roleCodes, List<String> functionCodes, List<UUID> tenantIds, List<UUID> userDirectoryIds) { this.user = user; // Build the list of granted authorities this.authorities = new ArrayList<>(); functionCodes.stream() .map(functionCode -> new SimpleGrantedAuthority("FUNCTION_" + functionCode)) .forEach(authorities::add); roleCodes.stream() .map(roleCode -> new SimpleGrantedAuthority("ROLE_" + roleCode)) .forEach(authorities::add); } /** * Returns the authorities granted to the user. * * @return the authorities */ @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } /** * Returns the password hash for the user. * * @return the password hash for the user */ @Override public String getPassword() { return user.getPassword(); } /** * Returns the user. * * @return the user */ public User getUser() { return user; } /** * Returns the username used to authenticate the user. * * @return the username */ @Override public String getUsername() { return user.getUsername(); } /** * Returns whether the user's account has expired. * * @return <b>true</b> if the user's account has NOT expired or <b>false</b> otherwise */ @Override public boolean isAccountNonExpired() { return (!user.isExpired()); } /** * Returns whether the user's account is locked. * * @return <b>true</b> if the user's account is NOT locked or <b>false</b> otherwise */ @Override public boolean isAccountNonLocked() { return (!user.isLocked()); } /** * Returns whether the user's credentials have expired. * * @return <b>true</b> if the user's credentials have NOT expired or <b>false</b> otherwise */ @Override public boolean isCredentialsNonExpired() { return (!user.hasPasswordExpired()); } /** * Returns whether the user's account is enabled. * * @return <b>true</b> if the user's account is enabled or <b>false</b> otherwise */ @Override public boolean isEnabled() { return user.isActive(); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDetailsService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; /** * The <b>UserDetailsService</b> class provides the User Details Service implementation that * provides the details for users. * * @author Marcus Portmann */ public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService { /* Security Service */ @Autowired private ISecurityService securityService; /** * Locates the user based on the username. In the actual implementation, the search may possibly * be case sensitive, or case insensitive depending on how the implementation instance is * configured. In this case, the <b>UserDetails</b> object that comes back may have a username * that is of a different case than what was actually requested. * * @param username the username for the user whose data is required. * @return a fully populated user record (never <b>null</b>) */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { try { Optional<UUID> userDirectoryIdOptional = securityService.getUserDirectoryIdForUser(username); if (userDirectoryIdOptional.isEmpty()) { throw new UsernameNotFoundException( "Failed to retrieve the details for the user (" + username + "): The user is not associated with any of the configured user directories"); } else { UUID userDirectoryId = userDirectoryIdOptional.get(); // Retrieve the details for the user User user = securityService.getUser(userDirectoryId, username); // Retrieve the function codes for the user List<String> functionCodes = securityService.getFunctionCodesForUser(userDirectoryId, username); // Retrieve the list of IDs for the tenants the user is associated with List<UUID> tenantIds = securityService.getTenantIdsForUserDirectory(userDirectoryId); /* * Retrieve the list of IDs for the user directories the user is associated with as a result * of being associated with one or more tenants. */ List<UUID> userDirectoryIdsForTenants = new ArrayList<>(); for (var tenantId : tenantIds) { // Retrieve the list of user directories associated with the tenant var userDirectoryIdsForTenant = securityService.getUserDirectoryIdsForTenant(tenantId); userDirectoryIdsForTenants.addAll(userDirectoryIdsForTenant); } // Retrieve the list of roles for the user List<String> roleCodes = securityService.getRoleCodesForUser(userDirectoryId, username); return new africa.absa.inception.security.UserDetails( user, roleCodes, functionCodes, tenantIds, userDirectoryIdsForTenants); } } catch (UserNotFoundException e) { throw new UsernameNotFoundException( "Failed to retrieve the details for the user (" + username + "): The user could not be found"); } catch (UsernameNotFoundException e) { throw e; } catch (Throwable e) { throw new RuntimeException( "Failed to retrieve the details for the user (" + username + ")", e); } } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectories.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.sorting.SortDirection; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.List; /** * The <b>UserDirectories</b> class holds the results of a request to retrieve a list of user * directories. * * @author Marcus Portmann */ @Schema(description = "The results of a request to retrieve a list of user directories") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"userDirectories", "total", "filter", "sortDirection", "pageIndex", "pageSize"}) @SuppressWarnings({"unused"}) public class UserDirectories implements Serializable { private static final long serialVersionUID = 1000000; /** The optional filter that was applied to the user directories. */ @Schema(description = "The optional filter that was applied to the user directories") @JsonProperty private String filter; /** The optional page index. */ @Schema(description = "The optional page index") @JsonProperty private Integer pageIndex; /** The optional page size. */ @Schema(description = "The optional page size") @JsonProperty private Integer pageSize; /** The optional sort direction that was applied to the user directories. */ @Schema(description = "The optional sort direction that was applied to the user directories") @JsonProperty private SortDirection sortDirection; /** The total number of user directories. */ @Schema(description = "The total number of user directories", required = true) @JsonProperty(required = true) private long total; /** The user directories. */ @Schema(description = "The user directories", required = true) @JsonProperty(required = true) private List<UserDirectory> userDirectories; /** Constructs a new <b>UserDirectories</b>. */ public UserDirectories() {} /** * Constructs a new <b>UserDirectories</b>. * * @param userDirectories the user directories * @param total the total number of user directories * @param filter the optional filter that was applied to the user directories * @param sortDirection the optional sort direction that was applied to the user directories * @param pageIndex the optional page index * @param pageSize the optional page size */ public UserDirectories( List<UserDirectory> userDirectories, long total, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) { this.userDirectories = userDirectories; this.total = total; this.filter = filter; this.sortDirection = sortDirection; this.pageIndex = pageIndex; this.pageSize = pageSize; } /** * Returns the optional filter that was applied to the user directories. * * @return the optional filter that was applied to the user directories */ public String getFilter() { return filter; } /** * Returns the optional page index. * * @return the optional page index */ public Integer getPageIndex() { return pageIndex; } /** * Returns the optional page size. * * @return the optional page size */ public Integer getPageSize() { return pageSize; } /** * Returns the optional sort direction that was applied to the user directories. * * @return the optional sort direction that was applied to the user directories */ public SortDirection getSortDirection() { return sortDirection; } /** * Returns the total number of user directories. * * @return the total number of user directories */ public Long getTotal() { return total; } /** * Returns the user directories. * * @return the user directories */ public List<UserDirectory> getUserDirectories() { return userDirectories; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectory.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.xml.DtdJarResolver; import africa.absa.inception.core.xml.XmlParserErrorHandler; import africa.absa.inception.core.xml.XmlUtil; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.ByteArrayInputStream; import java.io.Serializable; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.springframework.util.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; /** * The <b>UserDirectory</b> class holds the information for a user directory. * * @author Marcus Portmann */ @Schema(description = "A user directory") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "type", "name", "parameters"}) @Entity @Table(schema = "security", name = "user_directories") @SuppressWarnings({"unused"}) public class UserDirectory implements Serializable { private static final long serialVersionUID = 1000000; /** The date and time the user directory was created. */ @JsonIgnore @Column(name = "created", nullable = false, updatable = false) private LocalDateTime created; /** The ID for the user directory. */ @Schema(description = "The ID for the user directory", required = true) @JsonProperty(required = true) @NotNull @Id @Column(name = "id", nullable = false) private UUID id; /** The name of the user directory. */ @Schema(description = "The name of the user directory", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The parameters for the user directory. */ @Schema(description = "The parameters for the user directory", required = true) @JsonProperty(required = true) @Valid @Transient private List<UserDirectoryParameter> parameters = new ArrayList<>(); /** The tenants the user directory is associated with. */ @JsonIgnore @ManyToMany(mappedBy = "userDirectories") private Set<Tenant> tenants = new HashSet<>(); /** The code for the user directory type. */ @Schema(description = "The code for the user directory type", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "type", length = 100, nullable = false) private String type; /** The date and time the user directory was last updated. */ @JsonIgnore @Column(name = "updated", insertable = false) private LocalDateTime updated; /** Constructs a new <b>UserDirectory</b>. */ public UserDirectory() {} /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } UserDirectory other = (UserDirectory) object; return Objects.equals(id, other.id); } /** * Returns the XML configuration data for the user directory. * * @return the XML configuration data for the user directory */ @JsonIgnore @Access(AccessType.PROPERTY) @Column(name = "configuration", length = 4000, nullable = false) public String getConfiguration() { StringBuilder buffer = new StringBuilder(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append( "<!DOCTYPE userDirectory SYSTEM \"UserDirectoryConfiguration.dtd\"><userDirectory>"); for (UserDirectoryParameter parameter : parameters) { buffer.append("<parameter>"); buffer.append("<name>").append(parameter.getName()).append("</name>"); buffer .append("<value>") .append(StringUtils.hasText(parameter.getValue()) ? parameter.getValue() : "") .append("</value>"); buffer.append("</parameter>"); } buffer.append("</userDirectory>"); return buffer.toString(); } /** * Returns the date and time the user directory was created. * * @return the date and time the user directory was created */ public LocalDateTime getCreated() { return created; } /** * Returns the ID for the user directory. * * @return the ID for the user directory */ public UUID getId() { return id; } /** * Returns the name of the user directory. * * @return the name of the user directory */ public String getName() { return name; } /** * Returns the parameters for the user directory. * * @return the parameters for the user directory */ public List<UserDirectoryParameter> getParameters() { return parameters; } /** * Returns the tenants the user directory is associated with. * * @return the tenants the user directory is associated with */ public Set<Tenant> getTenants() { return tenants; } /** * Returns the code for the user directory type. * * @return the code for the user directory type */ public String getType() { return type; } /** * Returns the date and time the user directory was last updated. * * @return the date and time the user directory was last updated */ public LocalDateTime getUpdated() { return updated; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } /** * Set the XML configuration data for the user directory. * * @param configuration the XML configuration data for the user directory * @throws InvalidConfigurationException if the XML configuration data could not be set for the * user directory */ public void setConfiguration(String configuration) throws InvalidConfigurationException { try { // Parse the XML configuration data DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setValidating(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); builder.setEntityResolver( new DtdJarResolver( "UserDirectoryConfiguration.dtd", "META-INF/UserDirectoryConfiguration.dtd")); builder.setErrorHandler(new XmlParserErrorHandler()); InputSource inputSource = new InputSource(new ByteArrayInputStream(configuration.getBytes())); Document document = builder.parse(inputSource); Element rootElement = document.getDocumentElement(); // Read the user directory parameters configuration parameters = new ArrayList<>(); NodeList parameterElements = rootElement.getElementsByTagName("parameter"); for (int i = 0; i < parameterElements.getLength(); i++) { Element parameterElement = (Element) parameterElements.item(i); Optional<String> nameOptional = XmlUtil.getChildElementText(parameterElement, "name"); Optional<String> valueOptional = XmlUtil.getChildElementText(parameterElement, "value"); if (nameOptional.isPresent() && valueOptional.isPresent()) { parameters.add(new UserDirectoryParameter(nameOptional.get(), valueOptional.get())); } } } catch (Throwable e) { throw new InvalidConfigurationException( "Failed to parse the XML configuration data for the user directory", e); } } /** * Set the ID for the user directory. * * @param id the ID for the user directory */ public void setId(UUID id) { this.id = id; } /** * Set the name of the user directory. * * @param name the name of the user directory */ public void setName(String name) { this.name = name; } /** * Set the parameters for the user directory. * * @param parameters the parameters for the user directory */ public void setParameters(List<UserDirectoryParameter> parameters) { this.parameters = parameters; } /** * Set the tenants the user directory is associated with. * * @param tenants the tenants the user directory is associated with */ public void setTenants(Set<Tenant> tenants) { this.tenants = tenants; } /** * Set the code for the user directory type. * * @param type the code for the user directory type */ public void setType(String type) { this.type = type; } /** The Java Persistence callback method invoked before the entity is created in the database. */ @PrePersist protected void onCreate() { created = LocalDateTime.now(); } /** The Java Persistence callback method invoked before the entity is updated in the database. */ @PreUpdate protected void onUpdate() { updated = LocalDateTime.now(); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectoryBase.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.util.List; import java.util.UUID; /** * The <b>UserDirectoryBase</b> class provides the base class from which all user directory classes * should be derived. * * @author Marcus Portmann */ @SuppressWarnings({"unused", "WeakerAccess"}) public abstract class UserDirectoryBase implements IUserDirectory { /** The Group Repository. */ private final GroupRepository groupRepository; /** The parameters for the user directory. */ private final List<UserDirectoryParameter> parameters; /** The Role Repository. */ private final RoleRepository roleRepository; /** The ID for the user directory. */ private final UUID userDirectoryId; /** The User Repository. */ private final UserRepository userRepository; /** * Constructs a new <b>UserDirectoryBase</b>. * * @param userDirectoryId the ID for the user directory * @param parameters the parameters for the user directory * @param groupRepository the Group Repository * @param userRepository the User Repository * @param roleRepository the Role Repository */ public UserDirectoryBase( UUID userDirectoryId, List<UserDirectoryParameter> parameters, GroupRepository groupRepository, UserRepository userRepository, RoleRepository roleRepository) { this.userDirectoryId = userDirectoryId; this.parameters = parameters; this.groupRepository = groupRepository; this.userRepository = userRepository; this.roleRepository = roleRepository; } /** * Returns the Group Repository. * * @return the Group Repository */ public GroupRepository getGroupRepository() { return groupRepository; } /** * Returns the parameters for the user directory. * * @return the parameters for the user directory */ public List<UserDirectoryParameter> getParameters() { return parameters; } /** * Returns the Role Repository. * * @return the Role Repository */ public RoleRepository getRoleRepository() { return roleRepository; } /** * Returns the ID for the user directory. * * @return the ID for the user directory */ public UUID getUserDirectoryId() { return userDirectoryId; } /** * Returns the User Repository. * * @return the User Repository */ public UserRepository getUserRepository() { return userRepository; } /** * Checks whether the specified value is <b>null</b> or blank. * * @param value the value to check * @return true if the value is <b>null</b> or blank */ protected boolean isNullOrEmpty(Object value) { if (value == null) { return true; } if (value instanceof String) { return ((String) value).length() == 0; } return false; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectoryCapabilities.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import javax.validation.constraints.NotNull; /** * The <b>UserDirectoryCapabilities</b> class holds the information that describes the capabilities * supported by a user directory. * * @author Marcus Portmann */ @Schema(description = "The capabilities supported by a user directory") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "supportsAdminChangePassword", "supportsChangePassword", "supportsGroupAdministration", "supportsGroupMemberAdministration", "supportsPasswordExpiry", "supportsPasswordHistory", "supportsUserAdministration", "supportsUserLocks" }) @SuppressWarnings({"unused"}) public class UserDirectoryCapabilities { /** The user directory supports the admin change password capability. */ @Schema( description = "The the user directory supports the admin change password capability", required = true) @JsonProperty(required = true) @NotNull private boolean supportsAdminChangePassword; /** The user directory supports the change password capability. */ @Schema( description = "The user directory supports the change password capability", required = true) @JsonProperty(required = true) @NotNull private boolean supportsChangePassword; /** The user directory supports the group administration capability. */ @Schema( description = "The user directory supports the group administration capability", required = true) @JsonProperty(required = true) @NotNull private boolean supportsGroupAdministration; /** The user directory supports the group member administration capability. */ @Schema( description = "The user directory supports the group member administration capability", required = true) @JsonProperty(required = true) @NotNull private boolean supportsGroupMemberAdministration; /** The user directory supports the password expiry capability. */ @Schema( description = "The user directory supports the password expiry capability", required = true) @JsonProperty(required = true) @NotNull private boolean supportsPasswordExpiry; /** The user directory supports the password history capability. */ @Schema( description = "The user directory supports the password history capability", required = true) @JsonProperty(required = true) @NotNull private boolean supportsPasswordHistory; /** The user directory supports the user administration capability. */ @Schema( description = "The user directory supports the user administration capability", required = true) @JsonProperty(required = true) @NotNull private boolean supportsUserAdministration; /** The user directory supports the user locks capability. */ @Schema(description = "The user directory supports the user locks capability", required = true) @JsonProperty(required = true) @NotNull private boolean supportsUserLocks; /** Constructs a new <b>UserDirectoryCapabilities</b>. */ public UserDirectoryCapabilities() {} /** * Constructs a new <b>UserDirectoryCapabilities</b>. * * @param supportsAdminChangePassword the user directory supports the admin change password * capability * @param supportsChangePassword the user directory supports the change password capability * @param supportsGroupAdministration the user directory supports the group administration * capability * @param supportsGroupMemberAdministration the user directory supports the group member * administration capability * @param supportsPasswordExpiry the user directory supports the password expiry capability * @param supportsPasswordHistory the user directory supports the password history capability * @param supportsUserAdministration the user directory supports the user administration * capability * @param supportsUserLocks the user directory supports the user locks capability */ public UserDirectoryCapabilities( boolean supportsAdminChangePassword, boolean supportsChangePassword, boolean supportsGroupAdministration, boolean supportsGroupMemberAdministration, boolean supportsPasswordExpiry, boolean supportsPasswordHistory, boolean supportsUserAdministration, boolean supportsUserLocks) { this.supportsAdminChangePassword = supportsAdminChangePassword; this.supportsChangePassword = supportsChangePassword; this.supportsGroupAdministration = supportsGroupAdministration; this.supportsGroupMemberAdministration = supportsGroupMemberAdministration; this.supportsPasswordExpiry = supportsPasswordExpiry; this.supportsPasswordHistory = supportsPasswordHistory; this.supportsUserAdministration = supportsUserAdministration; this.supportsUserLocks = supportsUserLocks; } /** * Returns whether the user directory supports the admin change password capability. * * @return <b>true</b> if the user directory supports the admin change password capability or * <b>false</b> otherwise */ public boolean getSupportsAdminChangePassword() { return supportsAdminChangePassword; } /** * Returns whether the user directory supports the change password capability. * * @return <b>true</b> if the user directory supports the change password capability or * <b>false</b> otherwise */ public boolean getSupportsChangePassword() { return supportsChangePassword; } /** * Returns whether the user directory supports the group administration capability. * * @return <b>true</b> if the user directory supports the group administration capability or * <b>false</b> otherwise */ public boolean getSupportsGroupAdministration() { return supportsGroupAdministration; } /** * Returns whether the user directory supports the group member administration capability. * * @return <b>true</b> if the user directory supports the group member administration capability * or <b>false</b> otherwise */ public boolean getSupportsGroupMemberAdministration() { return supportsGroupMemberAdministration; } /** * Returns whether the user directory supports the password expiry capability. * * @return <b>true</b> if the user directory supports the password expiry capability or * <b>false</b> otherwise */ public boolean getSupportsPasswordExpiry() { return supportsPasswordExpiry; } /** * Returns whether the user directory supports the password history capability. * * @return <b>true</b> if the user directory supports the password history capability or * <b>false</b> otherwise */ public boolean getSupportsPasswordHistory() { return supportsPasswordHistory; } /** * Returns whether the user directory supports the user administration capability. * * @return <b>true</b> if the user directory supports the user administration capability or * <b>false</b> otherwise */ public boolean getSupportsUserAdministration() { return supportsUserAdministration; } /** * Returns whether the user directory supports the user locks capability. * * @return <b>true</b> if the user directory supports the user locks capability or <b> false</b> */ public boolean getSupportsUserLocks() { return supportsUserLocks; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectoryNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; import java.util.UUID; /** * An <b>UserDirectoryNotFoundException</b> is thrown to indicate that a security operation failed * as a result of a user directory that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/user-directory-not-found", title = "The user directory could not be found.", status = 404) public class UserDirectoryNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>UserDirectoryNotFoundException</b>. * * @param userDirectoryId the ID for the user directory */ public UserDirectoryNotFoundException(UUID userDirectoryId) { super("The user directory with ID (" + userDirectoryId + ") could not be found"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectoryParameter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.util.Base64Util; import africa.absa.inception.core.util.BinaryBuffer; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.math.BigDecimal; import java.util.List; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>UserDirectoryParameter</b> class stores a parameter for a user directory as a name-value * pair. * * @author Marcus Portmann */ @Schema(description = "A name-value pair parameter for a user directory") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"name", "value"}) @SuppressWarnings({"unused", "WeakerAccess"}) public class UserDirectoryParameter implements Serializable { private static final long serialVersionUID = 1000000; /** The name of the user directory parameter. */ @Schema(description = "The name of the user directory parameter", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) private String name; /** The value for the user directory parameter. */ @Schema(description = "The value for the user directory parameter", required = true) @JsonProperty(required = true) @NotNull @Size(max = 4000) private String value; /** Constructs a new <b>UserDirectoryParameter</b>. */ public UserDirectoryParameter() {} /** * Constructs a new <b>UserDirectoryParameter</b>. * * @param name the name of the user directory parameter * @param value the <b>BigDecimal</b> value for the user directory parameter */ public UserDirectoryParameter(String name, BigDecimal value) { this.name = name; this.value = String.valueOf(value); } /** * Constructs a new <b>UserDirectoryParameter</b>. * * @param name the name of the user directory parameter * @param value the binary value for the user directory parameter */ public UserDirectoryParameter(String name, BinaryBuffer value) { this.name = name; this.value = Base64Util.encodeBytes(value.getData()); } /** * Constructs a new <b>UserDirectoryParameter</b>. * * @param name the name of the user directory parameter * @param value the binary value for the user directory parameter */ public UserDirectoryParameter(String name, byte[] value) { this.name = name; this.value = Base64Util.encodeBytes(value); } /** * Constructs a new <b>UserDirectoryParameter</b>. * * @param name the name of the user directory parameter * @param value the <b>double</b> value for the user directory parameter */ public UserDirectoryParameter(String name, double value) { this.name = name; this.value = String.valueOf(value); } /** * Constructs a new <b>UserDirectoryParameter</b>. * * @param name the name of the user directory parameter * @param value the <b>long</b> value for the user directory parameter */ public UserDirectoryParameter(String name, long value) { this.name = name; this.value = String.valueOf(value); } /** * Constructs a new <b>UserDirectoryParameter</b>. * * @param name the name of the user directory parameter * @param value the <b>String</b> value for the user directory parameter */ public UserDirectoryParameter(String name, String value) { this.name = name; this.value = value; } /** * Returns whether the list of user directory parameters contains a user directory parameter whose * name matches the specified name. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @return <b>true</b> if the list of user directory parameters contains a user directory * parameter whose name matches the specified name or <b>false</b> otherwise */ public static boolean contains(List<UserDirectoryParameter> parameters, String name) { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { return true; } } return false; } /** * Returns the binary value for the user directory parameter with the specified name in the * specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @return the binary value for the user directory parameter with the specified name in the * specified list * @throws UserDirectoryParameterException if the binary value could not be retrieved for the user * directory parameter */ public static byte[] getBinaryValue(List<UserDirectoryParameter> parameters, String name) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { try { return Base64Util.decode(parameter.value); } catch (Throwable e) { throw new UserDirectoryParameterException( String.format( "Failed to retrieve the binary value for the user directory parameter (%s)", parameter.name)); } } } throw new UserDirectoryParameterException( String.format( "Failed to retrieve the binary value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Returns the <b>boolean</b> value for the user directory parameter with the specified name in * the specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @return the <b>boolean</b> value for the user directory parameter with the specified name in * the specified list * @throws UserDirectoryParameterException if the boolean value could not be retrieved for the * user directory parameter */ public static boolean getBooleanValue(List<UserDirectoryParameter> parameters, String name) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { try { return Boolean.parseBoolean(parameter.value); } catch (Throwable e) { throw new UserDirectoryParameterException( String.format( "Failed to retrieve the boolean value for the user directory parameter (%s)", parameter.name)); } } } throw new UserDirectoryParameterException( String.format( "Failed to retrieve the boolean value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Returns the <b>BigDecimal</b> value for the user directory parameter with the specified name in * the specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @return the <b>BigDecimal</b> value for the user directory parameter with the specified name in * the specified list * @throws UserDirectoryParameterException if the decimal value could not be retrieved for the * user directory parameter */ public static BigDecimal getDecimalValue(List<UserDirectoryParameter> parameters, String name) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { try { return new BigDecimal(parameter.value); } catch (Throwable e) { throw new UserDirectoryParameterException( String.format( "Failed to retrieve the decimal value for the user directory parameter (%s)", parameter.name)); } } } throw new UserDirectoryParameterException( String.format( "Failed to retrieve the decimal value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Returns the <b>double</b> value for the user directory parameter with the specified name in the * specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @return the <b>double</b> value for the user directory parameter with the specified name in the * specified list * @throws UserDirectoryParameterException if the double value could not be retrieved for the user * directory parameter */ public static double getDoubleValue(List<UserDirectoryParameter> parameters, String name) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { try { return Double.parseDouble(parameter.value); } catch (Throwable e) { throw new UserDirectoryParameterException( String.format( "Failed to retrieve the double value for the user directory parameter (%s)", parameter.name)); } } } throw new UserDirectoryParameterException( String.format( "Failed to retrieve the double value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Returns the <b>int</b> value for the user directory parameter with the specified name in the * specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @return the <b>int</b> value for the user directory parameter with the specified name in the * specified list * @throws UserDirectoryParameterException if the integer value could not be retrieved for the * user directory parameter */ public static int getIntegerValue(List<UserDirectoryParameter> parameters, String name) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { try { return Integer.parseInt(parameter.value); } catch (Throwable e) { throw new UserDirectoryParameterException( String.format( "Failed to retrieve the integer value for the user directory parameter (%s)", parameter.name)); } } } throw new UserDirectoryParameterException( String.format( "Failed to retrieve the integer value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Returns the <b>long</b> value for the user directory parameter with the specified name in the * specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @return the <b>long</b> value for the user directory parameter with the specified name in the * specified list * @throws UserDirectoryParameterException if the long value could not be retrieved for the user * directory parameter */ public static long getLongValue(List<UserDirectoryParameter> parameters, String name) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { try { return Long.parseLong(parameter.value); } catch (Throwable e) { throw new UserDirectoryParameterException( String.format( "Failed to retrieve the long value for the user directory parameter (%s)", parameter.name)); } } } throw new UserDirectoryParameterException( String.format( "Failed to retrieve the long value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Returns the <b>String</b> value for the user directory parameter with the specified name in the * specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @return the <b>String</b> value for the user directory parameter with the specified name in the * specified list * @throws UserDirectoryParameterException if the string value could not be retrieved for the user * directory parameter */ public static String getStringValue(List<UserDirectoryParameter> parameters, String name) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { return parameter.value; } } throw new UserDirectoryParameterException( String.format( "Failed to retrieve the string value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Set the binary value for the user directory parameter with the specified name in the specified * list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @param value the binary value for the user directory parameter * @throws UserDirectoryParameterException if the binary value could not be set for the user * directory parameter */ public static void setBinaryValue( List<UserDirectoryParameter> parameters, String name, BinaryBuffer value) throws UserDirectoryParameterException { setBinaryValue(parameters, name, value.getData()); } /** * Set the binary value for the user directory parameter with the specified name in the specified * list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @param value the binary value for the user directory parameter * @throws UserDirectoryParameterException if the binary value could not be set for the user * directory parameter */ public static void setBinaryValue( List<UserDirectoryParameter> parameters, String name, byte[] value) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { parameter.setBinaryValue(value); return; } } throw new UserDirectoryParameterException( String.format( "Failed to set the binary value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Set the <b>BigDecimal</b> value for the user directory parameter with the specified name in the * specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @param value the <b>BigDecimal</b> value for the user directory parameter * @throws UserDirectoryParameterException if the decimal value could not be set for the user * directory parameter */ public static void setDecimalValue( List<UserDirectoryParameter> parameters, String name, BigDecimal value) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { parameter.setDecimalValue(value); return; } } throw new UserDirectoryParameterException( String.format( "Failed to set the decimal value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Set the <b>double</b> value for the user directory parameter with the specified name in the * specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @param value the <b>double</b> value for the user directory parameter * @throws UserDirectoryParameterException if the double value could not be set for the user * directory parameter */ public static void setDoubleValue( List<UserDirectoryParameter> parameters, String name, double value) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { parameter.setDoubleValue(value); return; } } throw new UserDirectoryParameterException( String.format( "Failed to set the double value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Set the <b>int</b> value for the user directory parameter with the specified name in the * specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @param value the <b>int</b> value for the user directory parameter * @throws UserDirectoryParameterException if the integer value could not be set for the user * directory parameter */ public static void setIntegerValue( List<UserDirectoryParameter> parameters, String name, int value) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { parameter.setIntegerValue(value); return; } } throw new UserDirectoryParameterException( String.format( "Failed to set the long value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Set the <b>long</b> value for the user directory parameter with the specified name in the * specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @param value the <b>long</b> value for the user directory parameter * @throws UserDirectoryParameterException if the long value could not be set for the user * directory parameter */ public static void setLongValue(List<UserDirectoryParameter> parameters, String name, long value) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { parameter.setLongValue(value); return; } } throw new UserDirectoryParameterException( String.format( "Failed to set the long value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Set the <b>String</b> value for the user directory parameter with the specified name in the * specified list. * * @param parameters the user directory parameters to search * @param name the name of the user directory parameter to search for * @param value the <b>String</b> value for the user directory parameter * @throws UserDirectoryParameterException if the string value could not be set for the user * directory parameter */ public static void setStringValue( List<UserDirectoryParameter> parameters, String name, String value) throws UserDirectoryParameterException { for (UserDirectoryParameter parameter : parameters) { if (parameter.name.equalsIgnoreCase(name)) { parameter.setStringValue(value); return; } } throw new UserDirectoryParameterException( String.format( "Failed to set the string value for the user directory parameter (%s): " + "The user directory parameter could not be found", name)); } /** * Returns the binary value for the user directory parameter. * * @return the binary value for the user directory parameter * @throws UserDirectoryParameterException if the binary value could not be retrieved for the user * directory parameter */ @JsonIgnore public byte[] getBinaryValue() throws UserDirectoryParameterException { try { return Base64Util.decode(value); } catch (Throwable e) { throw new UserDirectoryParameterException( String.format( "Failed to retrieve the binary value for the user directory parameter (%s)", name)); } } /** * Returns the <b>BigDecimal</b> value for the user directory parameter. * * @return the <b>BigDecimal</b> value for the user directory parameter * @throws UserDirectoryParameterException if the decimal value could not be retrieved for the * user directory parameter */ @JsonIgnore public BigDecimal getDecimalValue() throws UserDirectoryParameterException { try { return new BigDecimal(value); } catch (Throwable e) { throw new UserDirectoryParameterException( String.format( "Failed to retrieve the decimal value for the user directory parameter (%s)", name)); } } /** * Returns the <b>double</b> value for the user directory parameter. * * @return the <b>double</b> value for the user directory parameter * @throws UserDirectoryParameterException if the double value could not be retrieved for the user * directory parameter */ @JsonIgnore public double getDoubleValue() throws UserDirectoryParameterException { try { return Double.parseDouble(value); } catch (Throwable e) { throw new UserDirectoryParameterException( String.format( "Failed to retrieve the double value for the user directory parameter (%s)", name)); } } /** * Returns the <b>int</b> value for the user directory parameter. * * @return the <b>int</b> value for the user directory parameter * @throws UserDirectoryParameterException if the integer value could not be retrieved for the * user directory parameter */ @JsonIgnore public int getIntegerValue() throws UserDirectoryParameterException { try { return Integer.parseInt(value); } catch (Throwable e) { throw new UserDirectoryParameterException( String.format( "Failed to retrieve the integer value for the user directory parameter (%s)", name)); } } /** * Returns the <b>long</b> value for the user directory parameter. * * @return the <b>long</b> value for the user directory parameter * @throws UserDirectoryParameterException if the long value could not be retrieved for the user * directory parameter */ @JsonIgnore public long getLongValue() throws UserDirectoryParameterException { try { return Long.parseLong(value); } catch (Throwable e) { throw new UserDirectoryParameterException( String.format( "Failed to retrieve the long value for the user directory parameter (%s)", name)); } } /** * Returns the name of the user directory parameter. * * @return the name of the user directory parameter */ public String getName() { return name; } /** * Returns the <b>String</b> value for the user directory parameter. * * @return the <b>String</b> value for the user directory parameter */ @JsonIgnore public String getStringValue() { return value; } /** * Returns the <b>String</b> value for the user directory parameter. * * @return the <b>String</b> value for the user directory parameter */ public String getValue() { return value; } /** * Set the binary value for the user directory parameter. * * @param value the binary value for the user directory parameter */ @JsonIgnore public void setBinaryValue(BinaryBuffer value) { this.value = Base64Util.encodeBytes(value.getData()); } /** * Set the binary value for the user directory parameter. * * @param value the binary value for the user directory parameter */ @JsonIgnore public void setBinaryValue(byte[] value) { this.value = Base64Util.encodeBytes(value); } /** * Set the <b>boolean</b> value for the user directory parameter. * * @param value the <b>boolean</b> value for the user directory parameter */ @JsonIgnore public void setBooleanValue(boolean value) { this.value = String.valueOf(value); } /** * Set the <b>BigDecimal</b> value for the user directory parameter. * * @param value the <b>BigDecimal</b> value for the user directory parameter */ @JsonIgnore public void setDecimalValue(BigDecimal value) { this.value = String.valueOf(value); } /** * Set the <b>double</b> value for the user directory parameter. * * @param value the <b>double</b> value for the user directory parameter */ @JsonIgnore public void setDoubleValue(double value) { this.value = String.valueOf(value); } /** * Set the <b>int</b> value for the user directory parameter. * * @param value the <b>int</b> value for the user directory parameter */ @JsonIgnore public void setIntegerValue(int value) { this.value = String.valueOf(value); } /** * Set the <b>long</b> value for the user directory parameter. * * @param value the <b>long</b> value for the user directory parameter */ @JsonIgnore public void setLongValue(long value) { this.value = String.valueOf(value); } /** * Set the name of the user directory parameter. * * @param name the name of the user directory parameter */ public void setName(String name) { this.name = name; } /** * Set the <b>String</b> value for the user directory parameter. * * @param value the <b>String</b> value for the user directory parameter */ @JsonIgnore public void setStringValue(String value) { this.value = value; } /** * Set the <b>String</b> value for the user directory parameter. * * @param value the <b>String</b> value for the user directory parameter */ public void setValue(String value) { this.value = value; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectoryParameterException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * An <b>UserDirectoryParameterException</b> is thrown to indicate an invalid operation was * performed on a <b>UserDirectoryParameter</b> instance. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/user-directory-parameter", title = "An error has occurred and the request could not be processed at this time.") public class UserDirectoryParameterException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>UserDirectoryParameterException</b> with the specified message. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. */ public UserDirectoryParameterException(String message) { super(message); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectoryRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>UserDirectoryRepository</b> interface declares the repository for the <b> * UserDirectory</b> domain type. * * @author Marcus Portmann */ public interface UserDirectoryRepository extends JpaRepository<UserDirectory, UUID> { /** * Delete the user directory. * * @param userDirectoryId the ID for the user directory */ @Modifying @Query("delete from UserDirectory ud where ud.id = :userDirectoryId") void deleteById(@Param("userDirectoryId") UUID userDirectoryId); /** * Check whether the user directory with the specified name exists. * * @param name the name of the user directory * @return <b>true</b> if a user directory with the specified name exists or <b>false</b> * otherwise */ boolean existsByNameIgnoreCase(String name); /** * Retrieve the user directories. * * @param pageable the pagination information * @return the user directories */ Page<UserDirectory> findAll(Pageable pageable); /** * Retrieve the user directories for the tenant. * * @param tenantId the ID for the tenant * @return the user directories for the tenant */ @Query("select ud from UserDirectory ud join ud.tenants as o where o.id = :tenantId") List<UserDirectory> findAllByTenantId(@Param("tenantId") UUID tenantId); /** * Retrieve the filtered user directories. * * @param filter the filter to apply to the user directories * @param pageable the pagination information * @return the filtered user directories */ @Query("select ud from UserDirectory ud where (lower(ud.name) like lower(:filter))") Page<UserDirectory> findFiltered(String filter, Pageable pageable); /** * Retrieve the name of the user directory. * * @param userDirectoryId the ID for the user directory * @return an Optional containing the name of the user directory or an empty Optional if the user * directory could not be found */ @Query("select ud.name from UserDirectory ud where ud.id = :userDirectoryId") Optional<String> getNameById(@Param("userDirectoryId") UUID userDirectoryId); /** * Retrieve the IDs for the tenants for the user directory. * * @param userDirectoryId the ID for the user directory * @return the IDs for the tenants for the user directory */ @Query("select o.id from Tenant o join o.userDirectories as ud where ud.id = :userDirectoryId") List<UUID> getTenantIdsById(@Param("userDirectoryId") UUID userDirectoryId); /** * Retrieve the type for the user directory. * * @param userDirectoryId the ID for the user directory * @return an Optional containing the type for the user directory or an empty Optional if the user * directory could not be found */ @Query("select ud.type from UserDirectory ud where ud.id = :userDirectoryId") Optional<String> getTypeForUserDirectoryById(@Param("userDirectoryId") UUID userDirectoryId); }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectorySummaries.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.sorting.SortDirection; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.List; /** * The <b>UserDirectorySummaries</b> class holds the results of a request to retrieve a list of user * directory summaries. * * @author Marcus Portmann */ @Schema(description = "The results of a request to retrieve a list of user directory summaries") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "userDirectorySummaries", "total", "filter", "sortDirection", "pageIndex", "pageSize" }) @SuppressWarnings({"unused"}) public class UserDirectorySummaries implements Serializable { private static final long serialVersionUID = 1000000; /** The optional filter that was applied to the user directory summaries. */ @Schema(description = "The optional filter that was applied to the user directory summaries") @JsonProperty private String filter; /** The optional page index. */ @Schema(description = "The optional page index") @JsonProperty private Integer pageIndex; /** The optional page size. */ @Schema(description = "The optional page size") @JsonProperty private Integer pageSize; /** The optional sort direction that was applied to the user directory summaries. */ @Schema( description = "The optional sort direction that was applied to the user directory summaries") @JsonProperty private SortDirection sortDirection; /** The total number of user directory summaries. */ @Schema(description = "The total number of user directory summaries", required = true) @JsonProperty(required = true) private long total; /** The user directory summaries. */ @Schema(description = "The user directory summaries", required = true) @JsonProperty(required = true) private List<UserDirectorySummary> userDirectorySummaries; /** Constructs a new <b>UserDirectorySummaries</b>. */ public UserDirectorySummaries() {} /** * Constructs a new <b>UserDirectorySummaries</b>. * * @param userDirectorySummaries the user directory summaries * @param total the total number of user directory summaries * @param filter the optional filter that was applied to the user directory summaries * @param sortDirection the optional sort direction that was applied to the user directory * summaries * @param pageIndex the optional page index * @param pageSize the optional page size */ public UserDirectorySummaries( List<UserDirectorySummary> userDirectorySummaries, long total, String filter, SortDirection sortDirection, Integer pageIndex, Integer pageSize) { this.userDirectorySummaries = userDirectorySummaries; this.total = total; this.filter = filter; this.sortDirection = sortDirection; this.pageIndex = pageIndex; this.pageSize = pageSize; } /** * Returns the optional filter that was applied to the user directory summaries. * * @return the optional filter that was applied to the user directory summaries */ public String getFilter() { return filter; } /** * Returns the optional page index. * * @return the optional page index */ public Integer getPageIndex() { return pageIndex; } /** * Returns the optional page size. * * @return the optional page size */ public Integer getPageSize() { return pageSize; } /** * Returns the optional sort direction that was applied to the user directory summaries. * * @return the optional sort direction that was applied to the user directory summaries */ public SortDirection getSortDirection() { return sortDirection; } /** * Returns the total number of user directory summaries. * * @return the total number of user directory summaries */ public Long getTotal() { return total; } /** * Returns the user directory summaries. * * @return the user directory summaries */ public List<UserDirectorySummary> getUserDirectorySummaries() { return userDirectorySummaries; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectorySummary.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.UUID; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>UserDirectorySummary</b> class holds the summary information for a user directory. * * @author Marcus Portmann */ @Schema(description = "A user directory summary") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "type", "name"}) @Entity @Table(schema = "security", name = "user_directories") @SuppressWarnings({"unused"}) public class UserDirectorySummary implements java.io.Serializable { private static final long serialVersionUID = 1000000; /** The user directories associated with the tenant. */ @JsonIgnore @ManyToMany(cascade = {CascadeType.REFRESH}) @JoinTable( schema = "security", name = "user_directory_to_tenant_map", joinColumns = @JoinColumn(name = "user_directory_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "tenant_id", referencedColumnName = "id")) private final Set<Tenant> tenants = new HashSet<>(); /** The ID for the user directory. */ @Schema(description = "The ID for the user directory", required = true) @JsonProperty(required = true) @NotNull @Id @Column(name = "id", nullable = false) private UUID id; /** The name of the user directory. */ @Schema(description = "The name of the user directory", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The code for the user directory type. */ @Schema(description = "The code for the user directory type", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "type", length = 100, nullable = false) private String type; /** Constructs a new <b>UserDirectorySummary</b>. */ public UserDirectorySummary() {} /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } UserDirectorySummary other = (UserDirectorySummary) object; return Objects.equals(id, other.id); } /** * Returns the ID for the user directory. * * @return the ID for the user directory */ public UUID getId() { return id; } /** * Returns the name of the user directory. * * @return the name of the user directory */ public String getName() { return name; } /** * Returns the code for the user directory type. * * @return the code for the user directory type */ public String getType() { return type; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectorySummaryRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.util.List; import java.util.UUID; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>UserDirectorySummaryRepository</b> interface declares the repository for the <b> * UserDirectorySummary</b> domain type. * * @author Marcus Portmann */ public interface UserDirectorySummaryRepository extends JpaRepository<UserDirectorySummary, UUID> { /** * Retrieve the user directory summaries. * * @param pageable the pagination information * @return the user directory summaries */ Page<UserDirectorySummary> findAll(Pageable pageable); /** * Retrieve the user directory summaries for the tenant. * * @param tenantId the ID for the tenant * @return the user directory summaries for the tenant */ @Query("select uds from UserDirectorySummary uds join uds.tenants as o where o.id = :tenantId") List<UserDirectorySummary> findAllByTenantId(@Param("tenantId") UUID tenantId); /** * Retrieve the filtered user directory summaries. * * @param filter the filter to apply to the user directory summaries * @param pageable the pagination information * @return the filtered user directory summaries */ @Query("select uds from UserDirectorySummary uds where (lower(uds.name) like lower(:filter))") Page<UserDirectorySummary> findFiltered(String filter, Pageable pageable); }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectoryType.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>UserDirectoryType</b> class holds the information for a user directory type. * * @author Marcus Portmann */ @Schema(description = "A user directory type") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"code", "name", "userDirectoryClassName"}) @Entity @Table(schema = "security", name = "user_directory_types") @SuppressWarnings({"unused"}) public class UserDirectoryType implements java.io.Serializable { private static final long serialVersionUID = 1000000; /** The code for the user directory type. */ @Schema(description = "The code for the user directory type", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "code", length = 100, nullable = false) private String code; /** The name of the user directory type. */ @Schema(description = "The name of the user directory type", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The Java class that implements the user directory type. */ @JsonIgnore @Transient private transient Class userDirectoryClass; /** The fully qualified name of the Java class that implements the user directory type. */ @Schema( description = "The fully qualified name of the Java class that implements the user directory type", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 1000) @Column(name = "user_directory_class", length = 1000, nullable = false) private String userDirectoryClassName; /** Constructs a new <b>UserDirectoryType</b>. */ public UserDirectoryType() {} /** * Constructs a new <b>UserDirectoryType</b>. * * @param code the code for the user directory type * @param name the name of the user directory type * @param userDirectoryClassName the fully qualified name of the Java class that implements the * user directory type */ UserDirectoryType(String code, String name, String userDirectoryClassName) { this.code = code; this.name = name; this.userDirectoryClassName = userDirectoryClassName; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } UserDirectoryType other = (UserDirectoryType) object; return Objects.equals(code, other.code); } /** * Returns the code for the user directory type. * * @return the code for the user directory type */ public String getCode() { return code; } /** * Returns the name of the user directory type. * * @return the name of the user directory type */ public String getName() { return name; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (code == null) ? 0 : code.hashCode(); } /** * Returns the fully qualified name of the Java class that implements the user directory type. * * @return the fully qualified name of the Java class that implements the user directory type */ String getUserDirectoryClassName() { return userDirectoryClassName; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectoryTypeNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>UserDirectoryTypeNotFoundException</b> is thrown to indicate that a security operation * failed as a result of a user directory type that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/user-directory-type-not-found", title = "The user directory type could not be found.", status = 404) public class UserDirectoryTypeNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>UserDirectoryTypeNotFoundException</b>. * * @param userDirectoryTypeCode the code for the user directory type */ public UserDirectoryTypeNotFoundException(String userDirectoryTypeCode) { super("A user directory type with the code (" + userDirectoryTypeCode + ") could not be found"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserDirectoryTypeRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>UserDirectoryTypeRepository</b> interface declares the repository for the <b> * UserDirectoryType</b> domain type. * * @author Marcus Portmann */ public interface UserDirectoryTypeRepository extends JpaRepository<UserDirectoryType, String> { @Modifying @Query("delete from UserDirectoryType udt where udt.code = :userDirectoryTypeCode") void deleteById(@Param("userDirectoryTypeCode") String userDirectoryTypeCode); }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserLockedException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>UserLockedException</b> is thrown to indicate that a security operation failed as a result * of a user being locked. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/user-locked", title = "The user has exceeded the maximum number of failed password attempts and has been locked.", status = 403) @SuppressWarnings({"unused", "WeakerAccess"}) public class UserLockedException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>UserLockedException</b>. * * @param username the username for the user */ public UserLockedException(String username) { super( "The user (" + username + ") has exceeded the maximum number of failed password attempts and has been locked"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * An <b>UserNotFoundException</b> is thrown to indicate that a security operation failed as a * result of a user that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/security/user-not-found", title = "The user could not be found.", status = 404) public class UserNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>UserNotFoundException</b>. * * @param username the username for the user */ public UserNotFoundException(String username) { super("The user (" + username + ") could not be found"); } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.QueryByExampleExecutor; /** * The <b>UserRepository</b> interface declares the repository for the <b>User</b> domain type. * * @author Marcus Portmann */ public interface UserRepository extends JpaRepository<User, UUID>, QueryByExampleExecutor<User> { /** * Change the password for the user. * * @param userId the ID for the user * @param password the password * @param passwordAttempts the password attempts * @param passwordExpiry the password expiry */ @Modifying @Query( "update User u set u.password = :password, u.passwordAttempts = :passwordAttempts, " + "u.passwordExpiry = :passwordExpiry where u.id = :userId") void changePassword( @Param("userId") UUID userId, @Param("password") String password, @Param("passwordAttempts") int passwordAttempts, @Param("passwordExpiry") Optional<LocalDateTime> passwordExpiry); // long countByUserDirectoryId(UUID userDirectoryId); /** * Delete the user. * * @param userId the ID for the user */ @Modifying @Query("delete from User u where u.id = :userId") void deleteById(@Param("userId") UUID userId); /** * Check whether the user exists. * * @param userDirectoryId the ID for the user directory * @param username the username * @return <b>true</b> if the user exists or <b>false</b> otherwise */ boolean existsByUserDirectoryIdAndUsernameIgnoreCase(UUID userDirectoryId, String username); /** * Retrieve the users for the user directory. * * @param userDirectoryId the ID for the user directory * @return the users for the user directory */ List<User> findByUserDirectoryId(UUID userDirectoryId); /** * Retrieve the users for the user directory. * * @param userDirectoryId the ID for the user directory * @param pageable the pagination information * @return the users for the user directory */ Page<User> findByUserDirectoryId(UUID userDirectoryId, Pageable pageable); /** * Retrieve the user with the specified username for the user directory. * * @param userDirectoryId the ID for the user directory * @param username the username * @return an Optional containing the user or an empty Optional if the user could not be found */ Optional<User> findByUserDirectoryIdAndUsernameIgnoreCase(UUID userDirectoryId, String username); /** * Retrieve the filtered users for the user directory. * * @param userDirectoryId the ID for the user directory * @param filter the filter to apply to the users * @param pageable the pagination information * @return the filtered users for the user directory */ @Query( "select u from User u where ((lower(u.username) like lower(:filter)) or " + "(lower(u.name) like lower(:filter))) and u.userDirectoryId = :userDirectoryId") Page<User> findFiltered( @Param("userDirectoryId") UUID userDirectoryId, @Param("filter") String filter, Pageable pageable); /** * Retrieve the function codes for the user. * * @param userId the ID for the user * @return the function codes for the user */ @Query( "select f.code from User u join u.groups as g join g.roles as r join r.functions as f " + "where u.id = :userId") List<String> getFunctionCodesByUserId(@Param("userId") UUID userId); /** * Retrieve the group names for the user * * @param userId the ID for the user * @return the group names for the user */ @Query("select g.name from User u join u.groups as g where u.id = :userId") List<String> getGroupNamesByUserId(@Param("userId") UUID userId); /** * Retrieve the groups for the user. * * @param userId the ID for the user * @return the groups for the user */ @Query("select g from User u join u.groups as g where u.id = :userId") List<Group> getGroupsByUserId(@Param("userId") UUID userId); /** * Retrieve the ID for the user with the specified username for the user directory. * * @param userDirectoryId the ID for the user directory * @param username the username * @return an Optional containing the ID for the user with the specified username for the user * directory or an empty Optional if the user could not be found */ @Query( "select u.id from User u where u.userDirectoryId = :userDirectoryId and lower(u.username) " + "like lower(:username)") Optional<UUID> getIdByUserDirectoryIdAndUsernameIgnoreCase( @Param("userDirectoryId") UUID userDirectoryId, @Param("username") String username); /** * Retrieve the name for the user with the specified username for the user directory. * * @param userDirectoryId the ID for the user directory * @param username the username * @return an Optional containing the name for the user with the specified username for the user * directory or an empty Optional if the user could not be found */ @Query( "select u.name from User u where ((lower(u.username) = lower(:username)) " + "and u.userDirectoryId = :userDirectoryId)") Optional<String> getNameByUserDirectoryIdAndUsernameIgnoreCase( UUID userDirectoryId, String username); /** * Retrieve the password history for the user. * * @param userId the ID for the user * @param after the date and time after which password history entries will be retrieved * @return the password history for the user */ @Query( value = "select password from security.users_password_history " + "where user_id = :userId and changed > :after", nativeQuery = true) List<String> getPasswordHistory( @Param("userId") UUID userId, @Param("after") LocalDateTime after); /** * Retrieve the role codes for the user. * * @param userId the ID for the user * @return the role codes for the user */ @Query("select r.code from User u join u.groups as g join g.roles as r where u.id = :userId") List<String> getRoleCodesByUserId(@Param("userId") UUID userId); /** * Retrieve the ID for the user directory for the user with the specified username. * * @param username the username * @return an Optional containing the ID for the user directory for the user with the specified * username or an empty Optional if the user could not be found */ @Query("select u.userDirectoryId from User u where lower(u.username) = lower(:username)") Optional<UUID> getUserDirectoryIdByUsernameIgnoreCase(@Param("username") String username); /** * Increment the password attempts for the user. * * @param userId the ID for the user */ @Modifying @Query("update User u set u.passwordAttempts = u.passwordAttempts + 1 where u.id = :userId") void incrementPasswordAttempts(@Param("userId") UUID userId); /** * Check whether the user is a member of the group. * * @param userId the ID for the user * @param groupId the ID for the group * @return <b>true</b> if the user is a member of the group or <b>false</b> otherwise */ @Query( "select case when (count(u.id) > 0) then true else false end from User u join u.groups " + "as g where u.id = :userId and g.id = :groupId") boolean isUserInGroup(@Param("userId") UUID userId, @Param("groupId") UUID groupId); /** * Reset the password for the user. * * @param userId the ID for the user * @param password the password * @param passwordExpiry the password expiry */ @Modifying @Query( "update User u set u.password = :password, u.passwordAttempts = 0, " + "u.passwordExpiry = :passwordExpiry where u.id = :userId") void resetPassword( @Param("userId") UUID userId, @Param("password") String password, @Param("passwordExpiry") LocalDateTime passwordExpiry); /** * Reset the password history for the user. * * @param userId the ID for the user */ @Modifying @Query( value = "delete from security.users_password_history where user_id = :userId", nativeQuery = true) void resetPasswordHistory(@Param("userId") UUID userId); /** * Save the password in the password history for the user. * * @param userId the ID for the user * @param password the password */ @Modifying @Query( value = "insert into security.users_password_history(user_id, changed, password) " + "values (:userId, current_timestamp, :password)", nativeQuery = true) void savePasswordInPasswordHistory( @Param("userId") UUID userId, @Param("password") String password); }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserSortBy.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.v3.oas.annotations.media.Schema; /** * The <b>UserSortBy</b> enumeration defines the possible methods used to sort a list of users. * * @author Marcus Portmann */ @Schema(description = "The method used to sort the list of users") public enum UserSortBy { /** Sort by name. */ NAME("name", "Sort By Name"), /** Sort by preferred name. */ PREFERRED_NAME("preferred_name", "Sort By Preferred Name"), /** Sort by username. */ USERNAME("username", "Sort By Username"); private final String code; private final String description; UserSortBy(String code, String description) { this.code = code; this.description = description; } /** * Returns the method used to sort a list of users given by the specified code value. * * @param code the code for the method used to sort a list of users * @return the method used to sort a list of users given by the specified code value */ @JsonCreator public static UserSortBy fromCode(String code) { switch (code) { case "name": return UserSortBy.NAME; case "preferred_name": return UserSortBy.PREFERRED_NAME; case "username": return UserSortBy.USERNAME; default: throw new RuntimeException( "Failed to determine the user sort by with the invalid code (" + code + ")"); } } /** * Returns the code for the method used to sort a list of users. * * @return the code for the method used to sort a list of users */ @JsonValue public String code() { return code; } /** * Returns the description for the method used to sort a list of users. * * @return the description for the method used to sort a list of users */ public String description() { return description; } /** * Return the string representation of the method used to sort a list of users enumeration value. * * @return the string representation of the method used to sort a list of users enumeration value */ public String toString() { return description; } }
0
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-security/1.2.0/africa/absa/inception/security/UserSortByToStringConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.security; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; /** * The <b>UserSortByToStringConverter</b> class implements the Spring converter that converts a * <b>UserSortBy</b> type into a <b>String</b> type. * * @author Marcus Portmann */ @Component public class UserSortByToStringConverter implements Converter<UserSortBy, String> { /** Constructs a new <b>UserSortByToStringConverter</b>. */ public UserSortByToStringConverter() {} @Override public String convert(UserSortBy source) { return source.code(); } }