upgrade spring, add javadoc, formatting

This commit is contained in:
_Bastler 2022-04-13 16:38:23 +02:00
parent 8ebed47574
commit eb829bfa26
168 changed files with 1554 additions and 2020 deletions

View File

@ -31,7 +31,9 @@ public class Application extends SpringBootServletInitializer {
}
/*
* @see org.springframework.boot.web.servlet.support.SpringBootServletInitializer#onStartup(javax.servlet.ServletContext)
* @see
* org.springframework.boot.web.servlet.support.SpringBootServletInitializer#
* onStartup(javax.servlet.ServletContext)
*/
@Override
public void onStartup(ServletContext servletContext) throws ServletException {

View File

@ -115,18 +115,16 @@ public class BorrowItemManager implements UserDataProvider {
* @param search the search
* @return the page
*/
public Page<BorrowItem> get(int page, int size, String sortBy, boolean descending,
String search) {
public Page<BorrowItem> get(int page, int size, String sortBy, boolean descending, String search) {
if (StringUtils.hasText(search)) {
return borrowItemRepository.findAll(
qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search)),
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending()
: Sort.by(sortBy).ascending()));
return borrowItemRepository
.findAll(qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search)), PageRequest
.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
}
return borrowItemRepository.findAll(PageRequest.of(page, size,
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
return borrowItemRepository.findAll(
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
}
/**
@ -140,20 +138,19 @@ public class BorrowItemManager implements UserDataProvider {
* @param search the search
* @return the for user
*/
public Page<BorrowItem> getForUser(Long userId, int page, int size, String sortBy,
boolean descending, String search) {
public Page<BorrowItem> getForUser(Long userId, int page, int size, String sortBy, boolean descending,
String search) {
BooleanBuilder query = new BooleanBuilder();
query.and(qBorrowItem.owner.eq(userId));
if (StringUtils.hasText(search)) {
query.and(
qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search)));
query.and(qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search)));
}
return borrowItemRepository.findAll(query.getValue(), PageRequest.of(page, size,
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
return borrowItemRepository.findAll(query.getValue(),
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
}
/**
@ -165,10 +162,10 @@ public class BorrowItemManager implements UserDataProvider {
public BorrowItem save(BorrowItem borrowItem) {
if (borrowItem.getId() != null && !borrowItem.getId().equals(0L)) {
borrowItemManualSlotRepository.deleteAll(borrowItemManualSlotRepository
.findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId())));
borrowItemPeriodSlotRepository.deleteAll(borrowItemPeriodSlotRepository
.findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId())));
borrowItemManualSlotRepository.deleteAll(
borrowItemManualSlotRepository.findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId())));
borrowItemPeriodSlotRepository.deleteAll(
borrowItemPeriodSlotRepository.findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId())));
}
List<? extends BorrowItemSlot> slots = borrowItem.getSlots();
@ -216,12 +213,11 @@ public class BorrowItemManager implements UserDataProvider {
* @param borrowItem the borrow item
*/
public void delete(BorrowItem borrowItem) {
borrowItemManualSlotRepository.deleteAll(borrowItemManualSlotRepository
.findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId())));
borrowItemPeriodSlotRepository.deleteAll(borrowItemPeriodSlotRepository
.findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId())));
borrowRequestRepository.deleteAll(
borrowRequestRepository.findAll(qBorrowRequest.item.eq(borrowItem.getId())));
borrowItemManualSlotRepository
.deleteAll(borrowItemManualSlotRepository.findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId())));
borrowItemPeriodSlotRepository
.deleteAll(borrowItemPeriodSlotRepository.findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId())));
borrowRequestRepository.deleteAll(borrowRequestRepository.findAll(qBorrowRequest.item.eq(borrowItem.getId())));
borrowItemRepository.delete(borrowItem);
}
@ -233,8 +229,7 @@ public class BorrowItemManager implements UserDataProvider {
*/
public void delete(Long id) {
BorrowItem borrowItem = get(id);
Assert.notNull(borrowItem, "Invalid borrow item id: "
+ id);
Assert.notNull(borrowItem, "Invalid borrow item id: " + id);
delete(borrowItem);
}
@ -244,12 +239,8 @@ public class BorrowItemManager implements UserDataProvider {
* @param borrowItem the borrow item
*/
public void notifyOwner(BorrowItem borrowItem) {
Assert.isTrue(
borrowItem.getEmailNotification() != null
&& borrowItem.getEmailNotification().booleanValue(),
"Email notification not enabled for '"
+ borrowItem.getId()
+ "'!");
Assert.isTrue(borrowItem.getEmailNotification() != null && borrowItem.getEmailNotification().booleanValue(),
"Email notification not enabled for '" + borrowItem.getId() + "'!");
String email = borrowItem.getEmail();
if (!StringUtils.hasText(email)) {
@ -276,8 +267,7 @@ public class BorrowItemManager implements UserDataProvider {
public List<UserData> getUserData(Long userId) {
List<UserData> result = Lists.newArrayList();
Iterator<BorrowItem> items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId))
.iterator();
Iterator<BorrowItem> items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId)).iterator();
while (items.hasNext()) {
result.add(items.next());
}
@ -290,8 +280,7 @@ public class BorrowItemManager implements UserDataProvider {
*/
@Override
public void purgeUserData(Long userId) {
Iterator<BorrowItem> items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId))
.iterator();
Iterator<BorrowItem> items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId)).iterator();
while (items.hasNext()) {
delete(items.next());
}

View File

@ -75,10 +75,9 @@ public class BorrowRequestManager implements UserDataProvider {
* @param descending the descending
* @return the for user
*/
public Page<BorrowRequest> getForUser(Long userId, int page, int size, String sortBy,
boolean descending) {
return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId), PageRequest.of(page,
size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
public Page<BorrowRequest> getForUser(Long userId, int page, int size, String sortBy, boolean descending) {
return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId),
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
}
/**
@ -92,12 +91,10 @@ public class BorrowRequestManager implements UserDataProvider {
* @param descending the descending
* @return the for user and status
*/
public Page<BorrowRequest> getForUserAndStatus(Long userId, BorrowRequestStatus status,
int page, int size, String sortBy, boolean descending) {
return borrowRequestRepository.findAll(
qBorrowRequest.user.eq(userId).and(qBorrowRequest.status.eq(status)),
PageRequest.of(page, size,
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
public Page<BorrowRequest> getForUserAndStatus(Long userId, BorrowRequestStatus status, int page, int size,
String sortBy, boolean descending) {
return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId).and(qBorrowRequest.status.eq(status)),
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
}
/**
@ -110,10 +107,9 @@ public class BorrowRequestManager implements UserDataProvider {
* @param descending the descending
* @return the for owner
*/
public Page<BorrowRequest> getForOwner(Long userId, int page, int size, String sortBy,
boolean descending) {
return borrowRequestRepository.findAllByOwner(userId, PageRequest.of(page, size,
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
public Page<BorrowRequest> getForOwner(Long userId, int page, int size, String sortBy, boolean descending) {
return borrowRequestRepository.findAllByOwner(userId,
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
}
/**
@ -127,10 +123,10 @@ public class BorrowRequestManager implements UserDataProvider {
* @param descending the descending
* @return the for owner and status
*/
public Page<BorrowRequest> getForOwnerAndStatus(Long userId, BorrowRequestStatus status,
int page, int size, String sortBy, boolean descending) {
return borrowRequestRepository.findAllByOwnerAndStatus(userId, status, PageRequest.of(page,
size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
public Page<BorrowRequest> getForOwnerAndStatus(Long userId, BorrowRequestStatus status, int page, int size,
String sortBy, boolean descending) {
return borrowRequestRepository.findAllByOwnerAndStatus(userId, status,
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
}
/**
@ -207,8 +203,7 @@ public class BorrowRequestManager implements UserDataProvider {
JwtKey jwtKey = jwtKeyManager.getLatest(JWT_BORROW_KEY_NAME, true);
JWSHeader.Builder headerBuilder = new JWSHeader.Builder(
jwtKeyManager.getJwsAlgorithm(jwtKey));
JWSHeader.Builder headerBuilder = new JWSHeader.Builder(jwtKeyManager.getJwsAlgorithm(jwtKey));
headerBuilder.keyID(jwtKey.getKeyID());
headerBuilder.type(JOSEObjectType.JWT);
@ -233,9 +228,7 @@ public class BorrowRequestManager implements UserDataProvider {
JwtKey jwtKey = jwtKeyManager.getByKeyID(jwt.getHeader().getKeyID());
if (jwtKey == null) {
throw new KeySourceException("No key found for given KeyID! ("
+ jwt.getHeader().getKeyID()
+ ")");
throw new KeySourceException("No key found for given KeyID! (" + jwt.getHeader().getKeyID() + ")");
}
if (jwt.getJWTClaimsSet() == null) {
@ -259,14 +252,13 @@ public class BorrowRequestManager implements UserDataProvider {
@Override
public List<UserData> getUserData(Long userId) {
List<UserData> result = Lists.newArrayList();
Iterator<BorrowRequest> userRequests = borrowRequestRepository
.findAll(qBorrowRequest.user.eq(userId)).iterator();
Iterator<BorrowRequest> userRequests = borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId))
.iterator();
while (userRequests.hasNext()) {
result.add(userRequests.next());
}
Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId)
.iterator();
Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId).iterator();
while (ownerRequests.hasNext()) {
result.add(ownerRequests.next());
}
@ -279,14 +271,13 @@ public class BorrowRequestManager implements UserDataProvider {
*/
@Override
public void purgeUserData(Long userId) {
Iterator<BorrowRequest> userRequests = borrowRequestRepository
.findAll(qBorrowRequest.user.eq(userId)).iterator();
Iterator<BorrowRequest> userRequests = borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId))
.iterator();
while (userRequests.hasNext()) {
delete(userRequests.next());
}
Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId)
.iterator();
Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId).iterator();
while (ownerRequests.hasNext()) {
delete(ownerRequests.next());
}

View File

@ -57,8 +57,7 @@ public class BorrowItemController extends BaseController {
@PreAuthorize("isAuthenticated()")
@GetMapping
public Page<BorrowItem> getBorrowItems(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter,
@RequestParam("sort") Optional<String> sortParameter,
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("sort") Optional<String> sortParameter,
@RequestParam("desc") Optional<Boolean> descParameter,
@RequestParam("search") Optional<String> searchParameter,
@RequestParam("owner") Optional<Boolean> ownerParameter) {
@ -71,17 +70,15 @@ public class BorrowItemController extends BaseController {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
}
borrowItems = borrowItemManager.getForUser(getCurrentUserId(), pageParameter.orElse(0),
sizeParameter.orElse(10), sortParameter.orElse("id"),
descParameter.orElse(false), searchParameter.orElse(null));
sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false),
searchParameter.orElse(null));
} else {
if (!permissionManager.hasPermission(getCurrentUserId(),
BorrowPermissions.BORROW_REQUESTS)
if (!permissionManager.hasPermission(getCurrentUserId(), BorrowPermissions.BORROW_REQUESTS)
|| !permissionManager.isFullUser(getCurrentUserId())) {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
}
borrowItems = borrowItemManager.get(pageParameter.orElse(0), sizeParameter.orElse(10),
sortParameter.orElse("id"), descParameter.orElse(false),
searchParameter.orElse(null));
sortParameter.orElse("id"), descParameter.orElse(false), searchParameter.orElse(null));
}
for (BorrowItem borrowItem : borrowItems.getContent()) {

View File

@ -75,10 +75,8 @@ public class BorrowRequestController extends BaseController {
*/
@PreAuthorize("isAuthenticated()")
@GetMapping
public Page<BorrowRequest> getBorrowRequests(
@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter,
@RequestParam("sort") Optional<String> sortParameter,
public Page<BorrowRequest> getBorrowRequests(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("sort") Optional<String> sortParameter,
@RequestParam("desc") Optional<Boolean> descParameter,
@RequestParam("owner") Optional<Boolean> ownerParameter) {
@ -89,18 +87,15 @@ public class BorrowRequestController extends BaseController {
|| !permissionManager.isFullUser(getCurrentUserId())) {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
}
borrowRequests = borrowRequestManager.getForOwner(getCurrentUserId(),
pageParameter.orElse(0), sizeParameter.orElse(10), sortParameter.orElse("id"),
descParameter.orElse(false));
borrowRequests = borrowRequestManager.getForOwner(getCurrentUserId(), pageParameter.orElse(0),
sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false));
} else {
if (!permissionManager.hasPermission(getCurrentUserId(),
BorrowPermissions.BORROW_REQUESTS)
if (!permissionManager.hasPermission(getCurrentUserId(), BorrowPermissions.BORROW_REQUESTS)
|| !permissionManager.isFullUser(getCurrentUserId())) {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
}
borrowRequests = borrowRequestManager.getForUser(getCurrentUserId(),
pageParameter.orElse(0), sizeParameter.orElse(10), sortParameter.orElse("id"),
descParameter.orElse(false));
borrowRequests = borrowRequestManager.getForUser(getCurrentUserId(), pageParameter.orElse(0),
sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false));
}
for (BorrowRequest borrowRequest : borrowRequests.getContent()) {
@ -153,8 +148,7 @@ public class BorrowRequestController extends BaseController {
}
if (borrowRequest.getId() == null || borrowRequest.getId().equals(0L)) {
if (borrowItem.getEmailNotification() != null
&& borrowItem.getEmailNotification().booleanValue()) {
if (borrowItem.getEmailNotification() != null && borrowItem.getEmailNotification().booleanValue()) {
borrowItemManager.notifyOwner(borrowItem);
}
}
@ -230,12 +224,9 @@ public class BorrowRequestController extends BaseController {
String issuer = jwtBorrowIssuer;
if (!StringUtils.hasText(issuer)) {
issuer = request.getScheme()
+ "://"
+ request.getServerName();
issuer = request.getScheme() + "://" + request.getServerName();
if (request.getServerPort() != 443 && request.getServerPort() != 80) {
issuer += ":"
+ request.getServerPort();
issuer += ":" + request.getServerPort();
}
}
try {
@ -255,16 +246,14 @@ public class BorrowRequestController extends BaseController {
* @return the object
*/
@PostMapping("verify")
public Object verfiy(@RequestBody String serialized, HttpServletRequest request,
HttpServletResponse response) {
public Object verfiy(@RequestBody String serialized, HttpServletRequest request, HttpServletResponse response) {
try {
SignedJWT signedJwt = SignedJWT.parse(serialized);
Errors errors = new RequestBodyErrors(signedJwt);
borrowJwtValidator.validate(signedJwt, errors);
if (errors.hasErrors()) {
if (errors.getGlobalErrors().isEmpty()) {
throw new EntityResponseStatusException(errors.getAllErrors(),
HttpStatus.PRECONDITION_FAILED);
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.PRECONDITION_FAILED);
} else {
throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE);
}

View File

@ -48,13 +48,11 @@ public class BorrowItemValidator implements Validator {
errors.rejectValue("availability", "REQUIRED");
}
if (StringUtils.hasText(borrowItem.getUrl())
&& !urlValidator.isValid(borrowItem.getUrl())) {
if (StringUtils.hasText(borrowItem.getUrl()) && !urlValidator.isValid(borrowItem.getUrl())) {
errors.rejectValue("url", "INVALID_URL");
}
if (StringUtils.hasText(borrowItem.getEmail())
&& !emailValidator.isValid(borrowItem.getEmail())) {
if (StringUtils.hasText(borrowItem.getEmail()) && !emailValidator.isValid(borrowItem.getEmail())) {
errors.rejectValue("email", "INVALID_EMAIL");
}
@ -64,18 +62,15 @@ public class BorrowItemValidator implements Validator {
errors.rejectValue("maxDuration", "INVALID");
}
if (borrowItem.getAvailability() != null && borrowItem.getSlots() != null
&& !borrowItem.getSlots().isEmpty()) {
if (borrowItem.getAvailability() != null && borrowItem.getSlots() != null && !borrowItem.getSlots().isEmpty()) {
for (BorrowItemSlot borrowItemSlot : borrowItem.getSlots()) {
switch (borrowItem.getAvailability()) {
case MANUAL:
if (borrowItemSlot instanceof BorrowItemManualSlot) {
BorrowItemManualSlot borrowItemManualSlot = (BorrowItemManualSlot) borrowItemSlot;
if (borrowItemManualSlot.getStart() == null
|| borrowItemManualSlot.getEnd() == null) {
if (borrowItemManualSlot.getStart() == null || borrowItemManualSlot.getEnd() == null) {
errors.rejectValue("slots", "MISSING_DATES");
} else if (borrowItemManualSlot.getStart()
.isAfter(borrowItemManualSlot.getEnd())) {
} else if (borrowItemManualSlot.getStart().isAfter(borrowItemManualSlot.getEnd())) {
errors.rejectValue("slots", "INVALID_DATES");
}
}
@ -83,18 +78,14 @@ public class BorrowItemValidator implements Validator {
case PERIOD:
if (borrowItemSlot instanceof BorrowItemPeriodSlot) {
BorrowItemPeriodSlot borrowItemPeriodSlot = (BorrowItemPeriodSlot) borrowItemSlot;
if (borrowItemPeriodSlot.getStartDay() == null
|| borrowItemPeriodSlot.getStartTime() == null
if (borrowItemPeriodSlot.getStartDay() == null || borrowItemPeriodSlot.getStartTime() == null
|| borrowItemPeriodSlot.getEndDay() == null
|| borrowItemPeriodSlot.getEndTime() == null) {
errors.rejectValue("slots", "MISSING_DATES");
} else if (borrowItemPeriodSlot.getStartDay()
.compareTo(borrowItemPeriodSlot.getEndDay()) > 0) {
} else if (borrowItemPeriodSlot.getStartDay().compareTo(borrowItemPeriodSlot.getEndDay()) > 0) {
errors.rejectValue("slots", "INVALID_DAY");
} else if (borrowItemPeriodSlot.getStartDay()
.compareTo(borrowItemPeriodSlot.getEndDay()) == 0
&& borrowItemPeriodSlot.getStartTime()
.isAfter(borrowItemPeriodSlot.getEndTime())) {
} else if (borrowItemPeriodSlot.getStartDay().compareTo(borrowItemPeriodSlot.getEndDay()) == 0
&& borrowItemPeriodSlot.getStartTime().isAfter(borrowItemPeriodSlot.getEndTime())) {
errors.rejectValue("slots", "INVALID_TIME");
}
}

View File

@ -111,8 +111,7 @@ public class BorrowJwtValidator implements Validator {
}
try {
if (!BorrowRequestStatus.valueOf(claims.getStringClaim("status"))
.equals(BorrowRequestStatus.ACCEPTED)) {
if (!BorrowRequestStatus.valueOf(claims.getStringClaim("status")).equals(BorrowRequestStatus.ACCEPTED)) {
errors.rejectValue("status", "INVALID");
}
} catch (ParseException e) {

View File

@ -66,6 +66,13 @@ public class BorrowRequestValidator implements Validator {
validateTime(borrowRequest, borrowItem, errors);
}
/**
* Validate time.
*
* @param borrowRequest the borrow request
* @param borrowItem the borrow item
* @param errors the errors
*/
public void validateTime(BorrowRequest borrowRequest, BorrowItem borrowItem, Errors errors) {
if (borrowRequest.getStarts() == null) {
errors.rejectValue("starts", "REQUIRED");
@ -77,16 +84,14 @@ public class BorrowRequestValidator implements Validator {
return;
}
borrowRequest
.setStarts(InstantHelper.truncate(borrowRequest.getStarts(), ChronoUnit.SECONDS));
borrowRequest.setStarts(InstantHelper.truncate(borrowRequest.getStarts(), ChronoUnit.SECONDS));
borrowRequest.setEnds(InstantHelper.truncate(borrowRequest.getEnds(), ChronoUnit.SECONDS));
// expiry + start
if (borrowRequest.getStarts().isAfter(borrowRequest.getEnds())
|| borrowRequestRepository.exists(qBorrowRequest.item.eq(borrowRequest.getItem())
// exlude self
.and(qBorrowRequest.id
.ne(borrowRequest.getId() == null ? -1L : borrowRequest.getId()))
.and(qBorrowRequest.id.ne(borrowRequest.getId() == null ? -1L : borrowRequest.getId()))
// accepted
.and(qBorrowRequest.status.eq(BorrowRequestStatus.ACCEPTED))
// expires after start
@ -96,8 +101,8 @@ public class BorrowRequestValidator implements Validator {
errors.rejectValue("starts", "ALREADY_USED");
errors.rejectValue("ends", "ALREADY_USED");
} else {
if (borrowItem.getMinDuration() != null && borrowItem.getMinDuration().compareTo(
Duration.between(borrowRequest.getEnds(), borrowRequest.getStarts())) > 0) {
if (borrowItem.getMinDuration() != null && borrowItem.getMinDuration()
.compareTo(Duration.between(borrowRequest.getEnds(), borrowRequest.getStarts())) > 0) {
errors.rejectValue("starts", "TOO_SHORT");
errors.rejectValue("ends", "TOO_SHORT");
} else if (borrowItem.getMaxDuration() != null
@ -119,12 +124,10 @@ public class BorrowRequestValidator implements Validator {
for (BorrowItemSlot borrowItemSlot : borrowItem.getSlots()) {
if (borrowItemSlot instanceof BorrowItemManualSlot) {
BorrowItemManualSlot borrowItemManualSlot = (BorrowItemManualSlot) borrowItemSlot;
if (borrowRequest.getStarts()
.compareTo(borrowItemManualSlot.getStart()) >= 0) {
if (borrowRequest.getStarts().compareTo(borrowItemManualSlot.getStart()) >= 0) {
validStart = true;
}
if (borrowRequest.getEnds()
.compareTo(borrowItemManualSlot.getEnd()) <= 0) {
if (borrowRequest.getEnds().compareTo(borrowItemManualSlot.getEnd()) <= 0) {
validEnd = true;
}
if (validStart && validEnd) {
@ -140,8 +143,7 @@ public class BorrowRequestValidator implements Validator {
BorrowItemPeriodSlot borrowItemPeriodSlot = (BorrowItemPeriodSlot) borrowItemSlot;
if (borrowRequest.getStarts().atZone(ZoneOffset.UTC).getDayOfWeek()
.compareTo(borrowItemPeriodSlot.getStartDay()) >= 0
&& LocalTime
.ofInstant(borrowRequest.getStarts(), ZoneOffset.UTC)
&& LocalTime.ofInstant(borrowRequest.getStarts(), ZoneOffset.UTC)
.compareTo(borrowItemPeriodSlot.getStartTime()) >= 0) {
validStart = true;
}

View File

@ -13,6 +13,6 @@ import de.bstly.we.borrow.model.BorrowItemManualSlot;
* The Interface BorrowItemManualSlotRepository.
*/
@Repository
public interface BorrowItemManualSlotRepository extends JpaRepository<BorrowItemManualSlot, Long>,
QuerydslPredicateExecutor<BorrowItemManualSlot> {
public interface BorrowItemManualSlotRepository
extends JpaRepository<BorrowItemManualSlot, Long>, QuerydslPredicateExecutor<BorrowItemManualSlot> {
}

View File

@ -13,6 +13,6 @@ import de.bstly.we.borrow.model.BorrowItemPeriodSlot;
* The Interface BorrowItemPeriodSlotRepository.
*/
@Repository
public interface BorrowItemPeriodSlotRepository extends JpaRepository<BorrowItemPeriodSlot, Long>,
QuerydslPredicateExecutor<BorrowItemPeriodSlot> {
public interface BorrowItemPeriodSlotRepository
extends JpaRepository<BorrowItemPeriodSlot, Long>, QuerydslPredicateExecutor<BorrowItemPeriodSlot> {
}

View File

@ -13,6 +13,5 @@ import de.bstly.we.borrow.model.BorrowItem;
* The Interface BorrowItemRepository.
*/
@Repository
public interface BorrowItemRepository
extends JpaRepository<BorrowItem, Long>, QuerydslPredicateExecutor<BorrowItem> {
public interface BorrowItemRepository extends JpaRepository<BorrowItem, Long>, QuerydslPredicateExecutor<BorrowItem> {
}

View File

@ -49,7 +49,7 @@ public interface BorrowRequestRepository
* @return the page
*/
@Query("SELECT request FROM BorrowRequest request INNER JOIN BorrowItem as item ON request.item = item.id WHERE item.owner = :owner AND request.status = :status")
Page<BorrowRequest> findAllByOwnerAndStatus(@Param("owner") Long owner,
@Param("status") BorrowRequestStatus status, Pageable pageable);
Page<BorrowRequest> findAllByOwnerAndStatus(@Param("owner") Long owner, @Param("status") BorrowRequestStatus status,
Pageable pageable);
}

View File

@ -56,6 +56,12 @@
<version>1.7</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
@ -64,7 +70,7 @@
<dependency>
<groupId>org.passay</groupId>
<artifactId>passay</artifactId>
<version>1.6.0</version>
<version>1.6.1</version>
</dependency>
<dependency>
@ -76,7 +82,7 @@
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.66</version>
<version>1.70</version>
</dependency>
<dependency>
@ -87,7 +93,7 @@
<dependency>
<groupId>javax.measure</groupId>
<artifactId>unit-api</artifactId>
<version>2.1.2</version>
<version>2.1.3</version>
</dependency>
<dependency>

View File

@ -47,8 +47,8 @@ public class PermissionManager implements UserDataProvider {
*/
public List<Permission> get(Long target, String name) {
if (target != null && StringUtils.hasText(name)) {
return Lists.newArrayList(permissionRepository
.findAll(qPermission.target.eq(target).and(qPermission.name.eq(name))));
return Lists.newArrayList(
permissionRepository.findAll(qPermission.target.eq(target).and(qPermission.name.eq(name))));
}
return Lists.newArrayList();
}
@ -62,10 +62,9 @@ public class PermissionManager implements UserDataProvider {
*/
public List<Permission> getNotExpires(Long target, String name) {
if (target != null && StringUtils.hasText(name)) {
return Lists.newArrayList(permissionRepository
.findAll(qPermission.target.eq(target).and(qPermission.name.eq(name))
.and(qPermission.expires.after(Instant.now()).and(qPermission.starts
.isNull().or(qPermission.starts.before(Instant.now()))))));
return Lists.newArrayList(permissionRepository.findAll(qPermission.target.eq(target)
.and(qPermission.name.eq(name)).and(qPermission.expires.after(Instant.now())
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))));
}
return Lists.newArrayList();
}
@ -91,9 +90,9 @@ public class PermissionManager implements UserDataProvider {
*/
public List<Permission> getNotExpiresByTarget(Long target) {
if (target != null) {
return Lists.newArrayList(permissionRepository.findAll(qPermission.target.eq(target)
.and(qPermission.expires.after(Instant.now()).and(qPermission.starts.isNull()
.or(qPermission.starts.before(Instant.now()))))));
return Lists.newArrayList(permissionRepository
.findAll(qPermission.target.eq(target).and(qPermission.expires.after(Instant.now())
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))));
}
return Lists.newArrayList();
}
@ -106,9 +105,9 @@ public class PermissionManager implements UserDataProvider {
*/
public List<Permission> getNotExpiresByName(String name) {
if (name != null) {
return Lists.newArrayList(permissionRepository.findAll(qPermission.name.eq(name)
.and(qPermission.expires.after(Instant.now()).and(qPermission.starts.isNull()
.or(qPermission.starts.before(Instant.now()))))));
return Lists.newArrayList(
permissionRepository.findAll(qPermission.name.eq(name).and(qPermission.expires.after(Instant.now())
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))));
}
return Lists.newArrayList();
}
@ -121,8 +120,8 @@ public class PermissionManager implements UserDataProvider {
*/
public List<Permission> getNotExpiresByTargetIgnoreStart(Long target) {
if (target != null) {
return Lists.newArrayList(permissionRepository.findAll(
qPermission.target.eq(target).and(qPermission.expires.after(Instant.now()))));
return Lists.newArrayList(permissionRepository
.findAll(qPermission.target.eq(target).and(qPermission.expires.after(Instant.now()))));
}
return Lists.newArrayList();
}
@ -134,9 +133,9 @@ public class PermissionManager implements UserDataProvider {
* @return true, if is full user
*/
public boolean isFullUser(Long target) {
return permissionRepository.exists(qPermission.target.eq(target)
.and(qPermission.addon.isFalse()).and(qPermission.expires.after(Instant.now()).and(
qPermission.starts.isNull().or(qPermission.starts.before(Instant.now())))));
return permissionRepository.exists(qPermission.target.eq(target).and(qPermission.addon.isFalse())
.and(qPermission.expires.after(Instant.now())
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now())))));
}
/**
@ -152,9 +151,8 @@ public class PermissionManager implements UserDataProvider {
}
return target != null && permissionRepository.exists(qPermission.name.eq(name)
.and(qPermission.target.eq(target))
.and(qPermission.expires.after(Instant.now()).and(
qPermission.starts.isNull().or(qPermission.starts.before(Instant.now())))));
.and(qPermission.target.eq(target)).and(qPermission.expires.after(Instant.now())
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now())))));
}
/**
@ -167,8 +165,7 @@ public class PermissionManager implements UserDataProvider {
* @param expires the expires
* @return the permission
*/
public Permission create(Long target, String name, boolean addon, Instant starts,
Instant expires) {
public Permission create(Long target, String name, boolean addon, Instant starts, Instant expires) {
Permission newPermission = new Permission();
newPermission.setTarget(target);
newPermission.setName(name);
@ -186,11 +183,8 @@ public class PermissionManager implements UserDataProvider {
* @return the permission
*/
public Permission update(Permission permission) {
Assert.isTrue(permissionRepository.existsById(permission.getId()), "Permission '"
+ permission.getName()
+ "' for target + '"
+ permission.getTarget()
+ "' not exists!");
Assert.isTrue(permissionRepository.existsById(permission.getId()),
"Permission '" + permission.getName() + "' for target + '" + permission.getTarget() + "' not exists!");
Permission updatePermission = permissionRepository.getById(permission.getId());
updatePermission.setStarts(permission.getStarts());
updatePermission.setExpires(permission.getExpires());
@ -210,11 +204,11 @@ public class PermissionManager implements UserDataProvider {
for (Permission permission : permissionRepository
.findAll(qPermission.name.eq(name).and(qPermission.expires.after(Instant.now())))) {
if (!permissionRepository.exists(
qPermission.name.eq(clone).and(qPermission.target.eq(permission.getTarget()))
if (!permissionRepository
.exists(qPermission.name.eq(clone).and(qPermission.target.eq(permission.getTarget()))
.and(qPermission.expires.goe(permission.getExpires())))) {
permissions.add(create(permission.getTarget(), clone, permission.isAddon(),
permission.getStarts(), permission.getExpires()));
permissions.add(create(permission.getTarget(), clone, permission.isAddon(), permission.getStarts(),
permission.getExpires()));
}
}
@ -260,8 +254,7 @@ public class PermissionManager implements UserDataProvider {
* @param starts the starts
* @param expires the expires
*/
public void applyItem(Long target, Integer item, JsonArray answers, Instant starts,
Instant expires) {
public void applyItem(Long target, Integer item, JsonArray answers, Instant starts, Instant expires) {
for (Permission permission : getForItem(target, item, answers, starts, expires)) {
permissionRepository.save(permission);
}
@ -277,8 +270,7 @@ public class PermissionManager implements UserDataProvider {
* @param expires the expires
* @return the for item
*/
public List<Permission> getForItem(Long target, Integer item, JsonArray answers, Instant starts,
Instant expires) {
public List<Permission> getForItem(Long target, Integer item, JsonArray answers, Instant starts, Instant expires) {
List<Permission> permissions = Lists.newArrayList();
for (PermissionMapping permissionMapping : permissionMappingManager.getAllByItem(item)) {
for (String name : permissionMapping.getNames()) {
@ -294,51 +286,42 @@ public class PermissionManager implements UserDataProvider {
}
if (permissionMapping.isLifetimeRound()) {
permissionStarts = InstantHelper.truncate(permissionStarts,
permissionMapping.getLifetimeUnit());
permissionStarts = InstantHelper.truncate(permissionStarts, permissionMapping.getLifetimeUnit());
}
if (permissionsExpires == null) {
permissionsExpires = InstantHelper.plus(
permissionStarts == null ? Instant.now() : permissionStarts,
permissionsExpires = InstantHelper.plus(permissionStarts == null ? Instant.now() : permissionStarts,
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit());
}
boolean additional = permissionMapping.isAddon();
for (JsonElement anwser : answers) {
if (anwser.isJsonObject()
&& anwser.getAsJsonObject().has("question_identifier")) {
if (anwser.isJsonObject() && anwser.getAsJsonObject().has("question_identifier")) {
if (StringUtils.hasText(permissionMapping.getStartsQuestion())
&& permissionMapping.getStartsQuestion()
.equals(anwser.getAsJsonObject().get("question_identifier")
.getAsString())
.equals(anwser.getAsJsonObject().get("question_identifier").getAsString())
&& anwser.getAsJsonObject().has("answer")) {
String dateTimeString = anwser.getAsJsonObject().get("answer")
.getAsString();
String dateTimeString = anwser.getAsJsonObject().get("answer").getAsString();
if (StringUtils.hasText(dateTimeString)) {
dateTimeString = dateTimeString.replace(" ", "T");
permissionStarts = OffsetDateTime.parse(dateTimeString).toInstant();
permissionsExpires = InstantHelper.plus(permissionStarts,
permissionMapping.getLifetime(),
permissionMapping.getLifetimeUnit());
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit());
additional = false;
}
}
if (StringUtils.hasText(permissionMapping.getExpiresQuestion())
&& permissionMapping.getExpiresQuestion()
.equals(anwser.getAsJsonObject().get("question_identifier")
.getAsString())
.equals(anwser.getAsJsonObject().get("question_identifier").getAsString())
&& anwser.getAsJsonObject().has("answer")) {
String dateTimeString = anwser.getAsJsonObject().get("answer")
.getAsString();
String dateTimeString = anwser.getAsJsonObject().get("answer").getAsString();
if (StringUtils.hasText(dateTimeString)) {
dateTimeString = dateTimeString.replace(" ", "T");
permissionsExpires = InstantHelper.plus(
OffsetDateTime.parse(dateTimeString).toInstant(),
permissionMapping.getLifetime(),
permissionMapping.getLifetimeUnit());
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit());
additional = false;
}
}
@ -372,18 +355,17 @@ public class PermissionManager implements UserDataProvider {
permission.setStarts(permissionStarts);
permission.setExpires(permissionsExpires);
} else {
if (permission.getStarts() != null
&& permission.getStarts().isBefore(Instant.now())) {
if (permission.getStarts() != null && permission.getStarts().isBefore(Instant.now())) {
permission.setStarts(null);
}
permission.setExpires(InstantHelper.plus(permission.getExpires(),
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit()));
permission.setExpires(InstantHelper.plus(permission.getExpires(), permissionMapping.getLifetime(),
permissionMapping.getLifetimeUnit()));
}
if (permissionMapping.isLifetimeRound()) {
permission.setExpires(InstantHelper.truncate(permission.getExpires(),
permissionMapping.getLifetimeUnit()));
permission.setExpires(
InstantHelper.truncate(permission.getExpires(), permissionMapping.getLifetimeUnit()));
}
permissions.add(permission);

View File

@ -38,8 +38,7 @@ public class PermissionMappingManager {
* @return the all by item
*/
public List<PermissionMapping> getAllByItem(Integer item) {
return Lists.newArrayList(
permissionMappingRepository.findAll(qPermissionMapping.item.eq(item)));
return Lists.newArrayList(permissionMappingRepository.findAll(qPermissionMapping.item.eq(item)));
}
/**
@ -49,8 +48,7 @@ public class PermissionMappingManager {
* @return the all by name
*/
public List<PermissionMapping> getAllByName(String name) {
return Lists.newArrayList(
permissionMappingRepository.findAll(qPermissionMapping.names.contains(name)));
return Lists.newArrayList(permissionMappingRepository.findAll(qPermissionMapping.names.contains(name)));
}
/**
@ -71,8 +69,8 @@ public class PermissionMappingManager {
* @return true, if successful
*/
public boolean exists(Integer item, String name) {
return permissionMappingRepository.exists(
qPermissionMapping.item.eq(item).and(qPermissionMapping.names.contains(name)));
return permissionMappingRepository
.exists(qPermissionMapping.item.eq(item).and(qPermissionMapping.names.contains(name)));
}
/**
@ -91,15 +89,12 @@ public class PermissionMappingManager {
* @param expiresQuestion the expires question
* @return the permission mapping
*/
public PermissionMapping create(Integer item, Set<String> names, Long lifetime,
ChronoUnit lifetimeUnit, boolean lifetimeRound, boolean addon, String product,
Instant starts, Instant expires, String startsQuestion, String expiresQuestion) {
public PermissionMapping create(Integer item, Set<String> names, Long lifetime, ChronoUnit lifetimeUnit,
boolean lifetimeRound, boolean addon, String product, Instant starts, Instant expires,
String startsQuestion, String expiresQuestion) {
for (String name : names) {
Assert.isTrue(!exists(item, name), "PermissionMapping for item '"
+ item
+ "' with permission '"
+ name
+ "' already exists!");
Assert.isTrue(!exists(item, name),
"PermissionMapping for item '" + item + "' with permission '" + name + "' already exists!");
}
PermissionMapping permissionMapping = new PermissionMapping();
permissionMapping.setItem(item);
@ -132,9 +127,7 @@ public class PermissionMappingManager {
* @param id the id
*/
public void delete(Long id) {
Assert.isTrue(permissionMappingRepository.existsById(id), "Permission Mapping '"
+ id
+ "' does not exists!");
Assert.isTrue(permissionMappingRepository.existsById(id), "Permission Mapping '" + id + "' does not exists!");
PermissionMapping permissionMapping = permissionMappingRepository.findById(id).get();
permissionMappingRepository.delete(permissionMapping);
}

View File

@ -91,9 +91,9 @@ public class PretixManager implements SmartInitializingSingleton {
private int quotaAddons;
protected WebClient webClient;
/*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
* @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/
@Override
public void afterSingletonsInstantiated() {
@ -119,21 +119,21 @@ public class PretixManager implements SmartInitializingSingleton {
environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_CHECKINLIST, ""));
}
if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS)) {
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS, environment
.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS, "0"));
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS,
environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS, "0"));
}
if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS)) {
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS, environment
.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS, "0"));
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS,
environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS, "0"));
}
if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM)) {
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, environment
.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, "0"));
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM,
environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, "0"));
}
if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM)) {
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, environment
.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, "0"));
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM,
environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, "0"));
}
buildWebClient();
@ -148,11 +148,9 @@ public class PretixManager implements SmartInitializingSingleton {
organizer = systemPropertyManager.get(SYSTEM_PROPERTY_PRETIX_ORGANIZER);
event = systemPropertyManager.get(SYSTEM_PROPERTY_PRETIX_EVENT);
checkinlist = systemPropertyManager.get(SYSTEM_PROPERTY_PRETIX_CHECKINLIST);
quotaRegistration = systemPropertyManager
.getInteger(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS);
quotaRegistration = systemPropertyManager.getInteger(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS);
quotaAddons = systemPropertyManager.getInteger(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS);
webClient = WebClient.builder().baseUrl(host)
.defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
webClient = WebClient.builder().baseUrl(host).defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.defaultHeader(HttpHeaders.AUTHORIZATION, "Token " + token).build();
}
@ -199,10 +197,8 @@ public class PretixManager implements SmartInitializingSingleton {
public JsonObject getCheckInItemBySecret(String secret) {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
queryParams.add("secret", secret);
JsonObject orderPositions = request(
String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/",
organizer, event, checkinlist),
HttpMethod.GET, queryParams).getAsJsonObject();
JsonObject orderPositions = request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/",
organizer, event, checkinlist), HttpMethod.GET, queryParams).getAsJsonObject();
JsonArray results = orderPositions.getAsJsonArray("results");
if (results.size() == 1) {
@ -219,8 +215,7 @@ public class PretixManager implements SmartInitializingSingleton {
* @return the order
*/
public JsonObject getOrder(String code) {
return request(
String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer, event, code),
return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer, event, code),
HttpMethod.GET).getAsJsonObject();
}
@ -235,15 +230,14 @@ public class PretixManager implements SmartInitializingSingleton {
queryParams.add("secret", secret);
JsonObject orderPositions = request(
String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event),
HttpMethod.GET, queryParams).getAsJsonObject();
String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event), HttpMethod.GET,
queryParams).getAsJsonObject();
JsonArray results = orderPositions.getAsJsonArray("results");
if (results.size() == 1) {
JsonObject orderPosition = results.get(0).getAsJsonObject();
return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer,
event, orderPosition.get("order").getAsString()), HttpMethod.GET)
.getAsJsonObject();
return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer, event,
orderPosition.get("order").getAsString()), HttpMethod.GET).getAsJsonObject();
}
return null;
@ -256,8 +250,8 @@ public class PretixManager implements SmartInitializingSingleton {
* @return the json object
*/
public JsonObject createOrder(JsonObject order) {
return request(String.format("/api/v1/organizers/%s/events/%s/orders/", organizer, event),
HttpMethod.POST, order).getAsJsonObject();
return request(String.format("/api/v1/organizers/%s/events/%s/orders/", organizer, event), HttpMethod.POST,
order).getAsJsonObject();
}
/**
@ -268,8 +262,8 @@ public class PretixManager implements SmartInitializingSingleton {
* @return the json object
*/
public JsonObject extendOrder(String code, JsonObject expire) {
return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/extend/", organizer,
event, code), HttpMethod.POST, expire).getAsJsonObject();
return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/extend/", organizer, event, code),
HttpMethod.POST, expire).getAsJsonObject();
}
/**
@ -278,8 +272,8 @@ public class PretixManager implements SmartInitializingSingleton {
* @param code the code
*/
public void sendEmail(String code) {
request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/resend_link/", organizer,
event, code), HttpMethod.POST);
request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/resend_link/", organizer, event, code),
HttpMethod.POST);
}
/**
@ -293,8 +287,8 @@ public class PretixManager implements SmartInitializingSingleton {
queryParams.add("secret", secret);
JsonObject orderPositions = request(
String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event),
HttpMethod.GET, queryParams).getAsJsonObject();
String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event), HttpMethod.GET,
queryParams).getAsJsonObject();
JsonArray results = orderPositions.getAsJsonArray("results");
if (results.size() == 1) {
@ -313,8 +307,7 @@ public class PretixManager implements SmartInitializingSingleton {
*/
public Instant getLastPaymentDateForOrder(String order) {
JsonArray paymentResults = request(
String.format("/api/v1/organizers/%s/events/%s/orders/%s/payments/", organizer,
event, order),
String.format("/api/v1/organizers/%s/events/%s/orders/%s/payments/", organizer, event, order),
HttpMethod.GET).getAsJsonObject().getAsJsonArray("results");
Instant lastDate = null;
@ -343,10 +336,8 @@ public class PretixManager implements SmartInitializingSingleton {
public JsonObject getCheckInItemByItem(Integer item) {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
queryParams.add("item", String.valueOf(item));
JsonObject orderPositions = request(
String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/",
organizer, event, checkinlist),
HttpMethod.GET, queryParams).getAsJsonObject();
JsonObject orderPositions = request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/",
organizer, event, checkinlist), HttpMethod.GET, queryParams).getAsJsonObject();
JsonArray results = orderPositions.getAsJsonArray("results");
if (results.size() == 1) {
@ -377,10 +368,8 @@ public class PretixManager implements SmartInitializingSingleton {
* @return the check in positions
*/
public JsonObject getCheckInPositions(String idOrSecret) {
return request(
String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/",
organizer, event, checkinlist, idOrSecret),
HttpMethod.GET).getAsJsonObject();
return request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/", organizer, event,
checkinlist, idOrSecret), HttpMethod.GET).getAsJsonObject();
}
/**
@ -390,8 +379,7 @@ public class PretixManager implements SmartInitializingSingleton {
* @return the json object
*/
public JsonObject redeem(String idOrSecret) {
return request(String.format(
"/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/redeem/", organizer,
return request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/redeem/", organizer,
event, checkinlist, idOrSecret), HttpMethod.POST).getAsJsonObject();
}
@ -424,8 +412,8 @@ public class PretixManager implements SmartInitializingSingleton {
voucher.addProperty("max_usages", 1);
voucher.addProperty("quota", quotaId);
voucher.addProperty("block_quota", true);
return request(String.format("/api/v1/organizers/%s/events/%s/vouchers/", organizer, event),
HttpMethod.POST, voucher).getAsJsonObject();
return request(String.format("/api/v1/organizers/%s/events/%s/vouchers/", organizer, event), HttpMethod.POST,
voucher).getAsJsonObject();
}
/**
@ -435,8 +423,7 @@ public class PretixManager implements SmartInitializingSingleton {
* @return the item
*/
public JsonObject getItem(Integer item) {
return request(
String.format("/api/v1/organizers/%s/events/%s/items/%s/", organizer, event, item),
return request(String.format("/api/v1/organizers/%s/events/%s/items/%s/", organizer, event, item),
HttpMethod.GET).getAsJsonObject();
}
@ -447,9 +434,8 @@ public class PretixManager implements SmartInitializingSingleton {
* @return the variations
*/
public JsonArray getVariations(Integer item) {
return request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/",
organizer, event, item), HttpMethod.GET).getAsJsonObject()
.getAsJsonArray("results");
return request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/", organizer, event, item),
HttpMethod.GET).getAsJsonObject().getAsJsonArray("results");
}
/**
@ -460,8 +446,8 @@ public class PretixManager implements SmartInitializingSingleton {
* @param variation the variation
*/
public void updateVariation(Integer item, Integer variationId, JsonObject variation) {
request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer,
event, item, variationId), HttpMethod.PATCH, variation);
request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer, event, item,
variationId), HttpMethod.PATCH, variation);
}
/**
@ -471,8 +457,8 @@ public class PretixManager implements SmartInitializingSingleton {
* @param variation the variation
*/
public void deleteVariation(Integer item, Integer variation) {
request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer,
event, item, variation), HttpMethod.DELETE);
request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer, event, item,
variation), HttpMethod.DELETE);
}
/**
@ -506,8 +492,7 @@ public class PretixManager implements SmartInitializingSingleton {
* @param queryParameters the query parameters
* @return the json element
*/
public JsonElement request(String path, HttpMethod method,
MultiValueMap<String, String> queryParameters) {
public JsonElement request(String path, HttpMethod method, MultiValueMap<String, String> queryParameters) {
return request(path, method, null, queryParameters);
}

View File

@ -38,8 +38,7 @@ public class QuotaManager implements UserDataProvider {
*/
public Quota get(Long target, String name) {
if (target != null && name != null) {
return quotaRepository.findOne(qQuota.name.eq(name).and(qQuota.target.eq(target)))
.orElse(null);
return quotaRepository.findOne(qQuota.name.eq(name).and(qQuota.target.eq(target))).orElse(null);
}
return null;
}
@ -75,8 +74,7 @@ public class QuotaManager implements UserDataProvider {
*/
public List<Quota> getNotExpiresByTarget(Long target) {
if (target != null) {
return Lists.newArrayList(
quotaRepository.findAll(qQuota.target.eq(target).and(qQuota.value.gt(0))));
return Lists.newArrayList(quotaRepository.findAll(qQuota.target.eq(target).and(qQuota.value.gt(0))));
}
return Lists.newArrayList();
}
@ -89,8 +87,8 @@ public class QuotaManager implements UserDataProvider {
* @return true, if successful
*/
public boolean hasQuota(Long target, String name) {
return target != null && quotaRepository
.exists(qQuota.name.eq(name).and(qQuota.target.eq(target)).and(qQuota.value.gt(0)));
return target != null
&& quotaRepository.exists(qQuota.name.eq(name).and(qQuota.target.eq(target)).and(qQuota.value.gt(0)));
}
/**
@ -121,17 +119,10 @@ public class QuotaManager implements UserDataProvider {
* @return the quota
*/
public Quota update(Quota quota) {
Assert.isTrue(
quotaRepository.exists(
qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))),
"Quota '"
+ quota.getName()
+ "' for target + '"
+ quota.getTarget()
+ "' not exists!");
Assert.isTrue(quotaRepository.exists(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))),
"Quota '" + quota.getName() + "' for target + '" + quota.getTarget() + "' not exists!");
Quota updateQuota = quotaRepository
.findOne(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName())))
.get();
.findOne(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))).get();
updateQuota.setValue(quota.getValue());
updateQuota.setUnit(quota.getUnit());
updateQuota.setDisposable(quota.isDisposable());
@ -150,10 +141,9 @@ public class QuotaManager implements UserDataProvider {
List<Quota> quotas = Lists.newArrayList();
for (Quota quota : quotaRepository.findAll(qQuota.name.eq(name))) {
if (!quotaRepository
.exists(qQuota.name.eq(clone).and(qQuota.target.eq(quota.getTarget())))) {
quotas.add(create(quota.getTarget(), clone, value >= 0 ? value : quota.getValue(),
quota.getUnit(), quota.isDisposable()));
if (!quotaRepository.exists(qQuota.name.eq(clone).and(qQuota.target.eq(quota.getTarget())))) {
quotas.add(create(quota.getTarget(), clone, value >= 0 ? value : quota.getValue(), quota.getUnit(),
quota.isDisposable()));
}
}
@ -168,13 +158,8 @@ public class QuotaManager implements UserDataProvider {
*/
public void delete(Long target, String name) {
Assert.isTrue(quotaRepository.exists(qQuota.target.eq(target).and(qQuota.name.eq(name))),
"Quota '"
+ name
+ "' for target + '"
+ target
+ "' not exists!");
Quota delete = quotaRepository.findOne(qQuota.target.eq(target).and(qQuota.name.eq(name)))
.get();
"Quota '" + name + "' for target + '" + target + "' not exists!");
Quota delete = quotaRepository.findOne(qQuota.target.eq(target).and(qQuota.name.eq(name))).get();
quotaRepository.delete(delete);
}
@ -208,8 +193,7 @@ public class QuotaManager implements UserDataProvider {
boolean added = false;
for (Quota quota : quotas) {
if (quota.getName().equals(quotaMapping.getName())) {
quota.setValue(
quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
: quotaMapping.getValue());
added = true;
}
@ -219,8 +203,7 @@ public class QuotaManager implements UserDataProvider {
if (target != null && hasQuota(target, quotaMapping.getName())) {
Quota quota = get(target, quotaMapping.getName());
quota.setValue(
quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
: quotaMapping.getValue());
quotas.add(quota);
@ -248,12 +231,12 @@ public class QuotaManager implements UserDataProvider {
for (QuotaMapping quotaMapping : quotaMappingManager.getAllByItem(item)) {
Quota quota = get(target, quotaMapping.getName());
if (quota == null) {
quota = create(target, quotaMapping.getName(), quotaMapping.getValue(),
quotaMapping.getUnit(), quotaMapping.isDisposable());
quota = create(target, quotaMapping.getName(), quotaMapping.getValue(), quotaMapping.getUnit(),
quotaMapping.isDisposable());
} else {
quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
: quotaMapping.getValue());
quota.setValue(
quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() : quotaMapping.getValue());
quota = update(quota);
}

View File

@ -36,8 +36,7 @@ public class QuotaMappingManager {
* @return the all by item
*/
public List<QuotaMapping> getAllByItem(Integer item) {
return Lists
.newArrayList(quotaMappingRepository.findAll(qQuotaMapping.items.contains(item)));
return Lists.newArrayList(quotaMappingRepository.findAll(qQuotaMapping.items.contains(item)));
}
/**
@ -58,8 +57,7 @@ public class QuotaMappingManager {
* @return true, if successful
*/
public boolean exists(Integer item, String name) {
return quotaMappingRepository
.exists(qQuotaMapping.items.contains(item).and(qQuotaMapping.name.eq(name)));
return quotaMappingRepository.exists(qQuotaMapping.items.contains(item).and(qQuotaMapping.name.eq(name)));
}
/**
@ -74,11 +72,11 @@ public class QuotaMappingManager {
* @param disposable the disposable
* @return the quota mapping
*/
public QuotaMapping create(Set<Integer> items, String name, long value, String unit,
boolean append, Set<String> products, boolean disposable) {
public QuotaMapping create(Set<Integer> items, String name, long value, String unit, boolean append,
Set<String> products, boolean disposable) {
for (Integer item : items) {
Assert.isTrue(!exists(item, name), "QuotaMapping for item '" + item + "' with quota '"
+ name + "' already exists!");
Assert.isTrue(!exists(item, name),
"QuotaMapping for item '" + item + "' with quota '" + name + "' already exists!");
}
QuotaMapping quotaMapping = new QuotaMapping();
quotaMapping.setItems(items);
@ -98,13 +96,10 @@ public class QuotaMappingManager {
* @return the quota mapping
*/
public QuotaMapping update(QuotaMapping quotaMapping) {
Assert.isTrue(
quotaMapping.getId() != null
&& quotaMappingRepository.existsById(quotaMapping.getId()),
Assert.isTrue(quotaMapping.getId() != null && quotaMappingRepository.existsById(quotaMapping.getId()),
"QuotaMapping '" + quotaMapping.getId() + "' does not exists!");
QuotaMapping updateQuotaMapping = quotaMappingRepository.findById(quotaMapping.getId())
.get();
QuotaMapping updateQuotaMapping = quotaMappingRepository.findById(quotaMapping.getId()).get();
updateQuotaMapping.setProducts(quotaMapping.getProducts());
updateQuotaMapping.setItems(quotaMapping.getItems());
updateQuotaMapping.setValue(quotaMapping.getValue());
@ -120,8 +115,7 @@ public class QuotaMappingManager {
* @param id the id
*/
public void delete(Long id) {
Assert.isTrue(quotaMappingRepository.existsById(id),
"QuotaMapping '" + id + "' does not exists!");
Assert.isTrue(quotaMappingRepository.existsById(id), "QuotaMapping '" + id + "' does not exists!");
quotaMappingRepository.deleteById(id);
}

View File

@ -52,9 +52,9 @@ public class Setup implements SmartInitializingSingleton {
private Logger logger = LoggerFactory.getLogger(Setup.class);
/*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
* @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/
@Override
public void afterSingletonsInstantiated() {
@ -75,14 +75,12 @@ public class Setup implements SmartInitializingSingleton {
Resource resource = resourceLoader.getResource("classpath:usernames.txt");
if (resource.exists()) {
BufferedReader br = new BufferedReader(
new InputStreamReader(resource.getInputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
List<String> usernames = Lists.newArrayList();
String line;
while ((line = br.readLine()) != null) {
if (StringUtils.hasText(line) && !usernames.contains(line)
&& !line.startsWith("#")) {
if (StringUtils.hasText(line) && !usernames.contains(line) && !line.startsWith("#")) {
usernames.add(line);
}
}

View File

@ -47,8 +47,7 @@ public class SystemPropertyManager {
* @return the string
*/
public String get(String key, String defaultValue) {
return systemPropertyRepository.findById(key).orElse(new SystemProperty(key, defaultValue))
.getValue();
return systemPropertyRepository.findById(key).orElse(new SystemProperty(key, defaultValue)).getValue();
}
/**

View File

@ -61,9 +61,7 @@ public class UserDataManager implements SmartInitializingSingleton {
private Gson gson = new Gson();
/*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
*/
/*
*
* @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/
@ -90,8 +88,7 @@ public class UserDataManager implements SmartInitializingSingleton {
* @param dry the dry
*/
public void purge(boolean dry) {
long days = systemPropertyManager.getLong(SYSTEM_PROPERTY_USERDATA_DAYS,
SYSTEM_PROPERTY_USERDATA_DAYS_DEFAULT);
long days = systemPropertyManager.getLong(SYSTEM_PROPERTY_USERDATA_DAYS, SYSTEM_PROPERTY_USERDATA_DAYS_DEFAULT);
Pageable pageable = PageRequest.of(0, 100, Sort.by("id"));
Page<User> page;
@ -99,14 +96,12 @@ public class UserDataManager implements SmartInitializingSingleton {
page = userRepository.findAll(pageable);
for (User user : page.getContent()) {
if (!UserStatus.SLEEP.equals(user.getStatus())) {
if (permissionManager.getNotExpiresByTargetIgnoreStart(user.getId())
.isEmpty()) {
if (permissionManager.getNotExpiresByTargetIgnoreStart(user.getId()).isEmpty()) {
if (UserStatus.PURGE.equals(user.getStatus())) {
purge(user, dry);
} else if (UserStatus.NORMAL.equals(user.getStatus())) {
Instant last = Instant.MIN;
for (Permission permission : permissionManager
.getAllByTarget(user.getId())) {
for (Permission permission : permissionManager.getAllByTarget(user.getId())) {
if (permission.getExpires().isAfter(last)) {
last = permission.getExpires();
}
@ -132,51 +127,31 @@ public class UserDataManager implements SmartInitializingSingleton {
public void purge(User user, boolean dry) {
Long userId = user.getId();
if (dry) {
logger.debug("Would purge all data of user '"
+ user.getUsername()
+ "' [id="
+ user.getId()
+ "]!");
logger.debug("Would purge all data of user '" + user.getUsername() + "' [id=" + user.getId() + "]!");
} else {
logger.warn("Purge all data of user '"
+ user.getUsername()
+ "' [id="
+ user.getId()
+ "]!");
logger.warn("Purge all data of user '" + user.getUsername() + "' [id=" + user.getId() + "]!");
}
for (UserDataProvider provider : providers) {
if (dry) {
List<UserData> result = provider.getUserData(userId);
if (!result.isEmpty()) {
logger.debug("\tWould have purged '"
+ provider.getId()
+ "' data of user '"
+ user.getUsername()
+ "' [id="
+ user.getId()
+ "]!");
logger.debug("\tWould have purged '" + provider.getId() + "' data of user '" + user.getUsername()
+ "' [id=" + user.getId() + "]!");
if (logger.isTraceEnabled()) {
for (UserData userData : result) {
logger.trace("\t\t"
+ gson.toJson(userData));
logger.trace("\t\t" + gson.toJson(userData));
}
}
}
} else {
List<UserData> result = provider.getUserData(userId);
if (!result.isEmpty()) {
logger.warn("\tPurge '"
+ provider.getId()
+ "' data of user '"
+ user.getUsername()
+ "' [id="
+ user.getId()
+ "]!");
logger.warn("\tPurge '" + provider.getId() + "' data of user '" + user.getUsername() + "' [id="
+ user.getId() + "]!");
if (logger.isTraceEnabled()) {
for (UserData userData : result) {
logger.trace("\t\t"
+ gson.toJson(userData));
logger.trace("\t\t" + gson.toJson(userData));
}
}
provider.purgeUserData(userId);
@ -185,11 +160,7 @@ public class UserDataManager implements SmartInitializingSingleton {
}
if (!dry) {
logger.warn("Purged all data of user '"
+ user.getUsername()
+ "' [id="
+ user.getId()
+ "]!");
logger.warn("Purged all data of user '" + user.getUsername() + "' [id=" + user.getId() + "]!");
}
}

View File

@ -161,8 +161,7 @@ public class UserDomainManager implements UserDataProvider {
* @throws NamingException the naming exception
*/
public boolean validate(UserDomain userDomain) throws NamingException {
Attributes attributes = dirContext.getAttributes("_bstly." + userDomain.getDomain(),
new String[] { "TXT" });
Attributes attributes = dirContext.getAttributes("_bstly." + userDomain.getDomain(), new String[] { "TXT" });
NamingEnumeration<? extends Attribute> attributeEnumeration = attributes.getAll();
while (attributeEnumeration.hasMore()) {

View File

@ -87,8 +87,7 @@ public class UserManager implements UserDataProvider {
* @return the by bstly email
*/
public User getByBstlyEmail(String email) {
String username = email.replace("@"
+ userEmailDomain, "");
String username = email.replace("@" + userEmailDomain, "");
return getByUsername(username);
}
@ -109,9 +108,7 @@ public class UserManager implements UserDataProvider {
* @return the password hash
*/
public String getPasswordHash(Long id) {
Assert.isTrue(userRepository.existsById(id), "User with id '"
+ id
+ "' not exists!");
Assert.isTrue(userRepository.existsById(id), "User with id '" + id + "' not exists!");
return userRepository.findById(id).get().getPasswordHash();
}
@ -123,9 +120,7 @@ public class UserManager implements UserDataProvider {
* @return the user
*/
public User setPassword(Long id, String password) {
Assert.isTrue(userRepository.existsById(id), "User with id '"
+ id
+ "' not exists!");
Assert.isTrue(userRepository.existsById(id), "User with id '" + id + "' not exists!");
User user = userRepository.findById(id).get();
user.setPasswordHash(passwordEncoder.encode(password));
return userRepository.save(user);
@ -141,9 +136,7 @@ public class UserManager implements UserDataProvider {
*/
public User create(String username, String password, UserStatus status) {
Assert.isTrue(!userRepository.exists(qUser.username.equalsIgnoreCase(username)),
"Username '"
+ username
+ "' already exists!");
"Username '" + username + "' already exists!");
User user = new User();
user.setUsername(username);
if (StringUtils.hasText(password)) {
@ -178,9 +171,7 @@ public class UserManager implements UserDataProvider {
* @return the user
*/
public User update(User user) {
Assert.isTrue(userRepository.existsById(user.getId()), "User with id '"
+ user.getId()
+ "' not exists!");
Assert.isTrue(userRepository.existsById(user.getId()), "User with id '" + user.getId() + "' not exists!");
User merge = get(user.getId());
merge.setUsername(user.getUsername());
@ -201,9 +192,7 @@ public class UserManager implements UserDataProvider {
* @param user the user
*/
public void delete(User user) {
Assert.isTrue(userRepository.existsById(user.getId()), "User with id '"
+ user.getId()
+ "' not exists!");
Assert.isTrue(userRepository.existsById(user.getId()), "User with id '" + user.getId() + "' not exists!");
File publicKey = new File(getPublicKeyPath(user.getUsername()));
if (publicKey.exists()) {
@ -222,9 +211,7 @@ public class UserManager implements UserDataProvider {
* @return the bstly email
*/
public String getBstlyEmail(String username) {
return username
+ "@"
+ userEmailDomain;
return username + "@" + userEmailDomain;
}
/**
@ -250,8 +237,7 @@ public class UserManager implements UserDataProvider {
FileWriter myWriter = new FileWriter(publicKeyPath);
myWriter.write(publicKey);
myWriter.close();
String command = "gpg --import "
+ publicKeyPath;
String command = "gpg --import " + publicKeyPath;
Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
@ -266,10 +252,7 @@ public class UserManager implements UserDataProvider {
* @return the public key path
*/
public String getPublicKeyPath(String username) {
return userDataDirectory
+ username
+ File.separator
+ "public.key";
return userDataDirectory + username + File.separator + "public.key";
}
/**
@ -281,10 +264,7 @@ public class UserManager implements UserDataProvider {
public void passwordReset(User user, ServletOutputStream outputStream) {
// TODO: change to public key profile field
String resetToken = RandomStringUtils.random(64, true, true);
String command = "echo \""
+ resetToken
+ "\" | gpg -ear "
+ getBstlyEmail(user.getUsername())
String command = "echo \"" + resetToken + "\" | gpg -ear " + getBstlyEmail(user.getUsername())
+ " --always-trust";
user.setResetToken(resetToken);
@ -293,10 +273,8 @@ public class UserManager implements UserDataProvider {
ProcessBuilder b = new ProcessBuilder("/bin/bash", "-c", command);
Process process = b.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
BufferedReader errorReader = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
int c;
while ((c = reader.read()) != -1) {
outputStream.write(c);
@ -328,8 +306,7 @@ public class UserManager implements UserDataProvider {
* @param user the user
*/
protected void deleteSessionsForUser(User user) {
Map<String, ? extends Session> usersSessions = sessionRepository
.findByPrincipalName(user.getUsername());
Map<String, ? extends Session> usersSessions = sessionRepository.findByPrincipalName(user.getUsername());
for (Session session : usersSessions.values()) {
sessionRepository.deleteById(session.getId());
}
@ -363,16 +340,10 @@ public class UserManager implements UserDataProvider {
user.setDisabled(true);
user.setLocked(true);
user = update(user);
logger.warn("User '"
+ user.getUsername()
+ "' ["
+ user.getId()
+ "] should be purged!");
logger.warn("User '" + user.getUsername() + "' [" + user.getId() + "] should be purged!");
} else {
logger.error("No user found for ["
+ userId
+ "]!");
logger.error("No user found for [" + userId + "]!");
}
}

View File

@ -37,8 +37,7 @@ public class UserProfileFieldManager implements UserDataProvider {
*/
public UserProfileField get(Long target, String name) {
return userProfileFieldRepository
.findOne(qUserProfileField.name.eq(name).and(qUserProfileField.target.eq(target)))
.orElse(null);
.findOne(qUserProfileField.name.eq(name).and(qUserProfileField.target.eq(target))).orElse(null);
}
/**
@ -48,8 +47,8 @@ public class UserProfileFieldManager implements UserDataProvider {
* @return the all by target
*/
public List<UserProfileField> getAllByTarget(Long target) {
return Lists.newArrayList(userProfileFieldRepository.findAll(
qUserProfileField.target.eq(target), Sort.by("index", "name").ascending()));
return Lists.newArrayList(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target),
Sort.by("index", "name").ascending()));
}
/**
@ -72,11 +71,9 @@ public class UserProfileFieldManager implements UserDataProvider {
* @param visibilities the visibilities
* @return the all by target and visibilities
*/
public List<UserProfileField> getAllByTargetAndVisibilities(Long target,
List<Visibility> visibilities) {
public List<UserProfileField> getAllByTargetAndVisibilities(Long target, List<Visibility> visibilities) {
return Lists.newArrayList(userProfileFieldRepository.findAll(
qUserProfileField.target.eq(target)
.and(qUserProfileField.visibility.in(visibilities)),
qUserProfileField.target.eq(target).and(qUserProfileField.visibility.in(visibilities)),
Sort.by("index", "name").ascending()));
}
@ -98,16 +95,11 @@ public class UserProfileFieldManager implements UserDataProvider {
*/
public void delete(Long target, String name) {
Assert.isTrue(
userProfileFieldRepository.exists(
qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))),
"ProfileField '"
+ name
+ "' for target + '"
+ target
+ "' not exists!");
userProfileFieldRepository
.exists(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))),
"ProfileField '" + name + "' for target + '" + target + "' not exists!");
UserProfileField delete = userProfileFieldRepository
.findOne(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name)))
.get();
.findOne(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))).get();
userProfileFieldRepository.delete(delete);
}
@ -117,8 +109,7 @@ public class UserProfileFieldManager implements UserDataProvider {
* @param target the target
*/
public void deleteAll(Long target) {
userProfileFieldRepository
.deleteAll(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target)));
userProfileFieldRepository.deleteAll(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target)));
}
/*

View File

@ -50,27 +50,30 @@ public class UserTotpManager implements SecondFactorProvider<UserTotp> {
return "totp";
}
/*
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#supports(java.lang.String)
* @see
* de.bstly.we.security.businesslogic.SecondFactorProvider#supports(java.lang.
* String)
*/
@Override
public boolean supports(String provider) {
return getId().equals(provider);
}
/*
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#isEnabled(java.lang.Long)
* @see
* de.bstly.we.security.businesslogic.SecondFactorProvider#isEnabled(java.lang.
* Long)
*/
@Override
public boolean isEnabled(Long userId) {
return userTotpRepository
.exists(qUserTotp.target.eq(userId).and(qUserTotp.enabled.isTrue()));
return userTotpRepository.exists(qUserTotp.target.eq(userId).and(qUserTotp.enabled.isTrue()));
}
/*
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#validate(java.lang.Long, java.lang.String)
* @see
* de.bstly.we.security.businesslogic.SecondFactorProvider#validate(java.lang.
* Long, java.lang.String)
*/
@Override
public boolean validate(Long userId, String code) {
@ -83,18 +86,19 @@ public class UserTotpManager implements SecondFactorProvider<UserTotp> {
return false;
}
/*
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#get(java.lang.Long)
* @see
* de.bstly.we.security.businesslogic.SecondFactorProvider#get(java.lang.Long)
*/
@Override
public UserTotp get(Long userId) {
return userTotpRepository.findOne(qUserTotp.target.eq(userId)).orElse(null);
}
/*
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#create(java.lang.Long)
* @see
* de.bstly.we.security.businesslogic.SecondFactorProvider#create(java.lang.
* Long)
*/
@Override
public UserTotp create(Long userId) {
@ -105,8 +109,8 @@ public class UserTotpManager implements SecondFactorProvider<UserTotp> {
userTotp.setSecret(secretGenerator.generate());
User user = userManager.get(userId);
QrData data = qrDataFactory.newBuilder().label(user.getUsername())
.secret(userTotp.getSecret()).issuer("we.bstly").build();
QrData data = qrDataFactory.newBuilder().label(user.getUsername()).secret(userTotp.getSecret())
.issuer("we.bstly").build();
userTotp.setQrData(data.getUri());
userTotp.setRecoveryCodes(Lists.newArrayList(recoveryCodeGenerator.generateCodes(16)));
return userTotpRepository.save(userTotp);
@ -114,15 +118,15 @@ public class UserTotpManager implements SecondFactorProvider<UserTotp> {
return userTotpRepository.findOne(qUserTotp.target.eq(userId)).orElse(null);
}
/*
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#enable(java.lang.Long, java.lang.String)
* @see
* de.bstly.we.security.businesslogic.SecondFactorProvider#enable(java.lang.
* Long, java.lang.String)
*/
@Override
public boolean enable(Long userId, String code) {
if (validate(userId, code)) {
UserTotp userTotp = userTotpRepository.findOne(qUserTotp.target.eq(userId))
.orElse(null);
UserTotp userTotp = userTotpRepository.findOne(qUserTotp.target.eq(userId)).orElse(null);
userTotp.setEnabled(true);
userTotpRepository.save(userTotp);
return true;
@ -130,9 +134,10 @@ public class UserTotpManager implements SecondFactorProvider<UserTotp> {
return false;
}
/*
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#delete(java.lang.Long)
* @see
* de.bstly.we.security.businesslogic.SecondFactorProvider#delete(java.lang.
* Long)
*/
@Override
public void delete(Long userId) {

View File

@ -66,11 +66,7 @@ public class VoucherMappingManager {
* @return the voucher mapping
*/
public VoucherMapping create(String name, int voucher, String quota, boolean isFree) {
Assert.isTrue(!exists(name), "QuotaMapping for voucher '"
+ voucher
+ "' with '"
+ name
+ "' already exists!");
Assert.isTrue(!exists(name), "QuotaMapping for voucher '" + voucher + "' with '" + name + "' already exists!");
VoucherMapping voucherMapping = new VoucherMapping();
voucherMapping.setName(name);
@ -87,12 +83,8 @@ public class VoucherMappingManager {
* @return the voucher mapping
*/
public VoucherMapping update(VoucherMapping voucherMapping) {
Assert.isTrue(
voucherMapping.getId() != null
&& voucherMappingRepository.existsById(voucherMapping.getId()),
"VoucherMapping '"
+ voucherMapping.getId()
+ "' does not exists!");
Assert.isTrue(voucherMapping.getId() != null && voucherMappingRepository.existsById(voucherMapping.getId()),
"VoucherMapping '" + voucherMapping.getId() + "' does not exists!");
return voucherMappingRepository.save(voucherMapping);
}
@ -103,9 +95,7 @@ public class VoucherMappingManager {
* @param id the id
*/
public void delete(Long id) {
Assert.isTrue(voucherMappingRepository.existsById(id), "VoucherMapping '"
+ id
+ "' does not exists!");
Assert.isTrue(voucherMappingRepository.existsById(id), "VoucherMapping '" + id + "' does not exists!");
voucherMappingRepository.deleteById(id);
}

View File

@ -20,12 +20,11 @@ import de.bstly.we.event.AbstractModelEventType;
import de.bstly.we.model.AbstractModel;
/**
* The listener interface for receiving abstractModelEvent events.
* The class that is interested in processing a abstractModelEvent
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addAbstractModelEventListener<code> method. When
* the abstractModelEvent event occurs, that object's appropriate
* The listener interface for receiving abstractModelEvent events. The class
* that is interested in processing a abstractModelEvent event implements this
* interface, and the object created with that class is registered with a
* component using the component's <code>addAbstractModelEventListener<code>
* method. When the abstractModelEvent event occurs, that object's appropriate
* method is invoked.
*
* @see AbstractModelEventEvent

View File

@ -59,8 +59,7 @@ public class InstantHelper {
* @return the instant
*/
public static Instant minus(Instant instant, long amountToAdd, TemporalUnit unit) {
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit)
.toInstant();
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit).toInstant();
}
/**
@ -73,12 +72,10 @@ public class InstantHelper {
public static Instant truncate(Instant instant, TemporalUnit unit) {
if (ChronoUnit.YEARS.equals(unit)) {
instant = instant.truncatedTo(ChronoUnit.DAYS);
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC)
.with(ChronoField.DAY_OF_YEAR, 1L).toInstant();
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_YEAR, 1L).toInstant();
} else if (ChronoUnit.MONTHS.equals(unit)) {
instant = instant.truncatedTo(ChronoUnit.DAYS);
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC)
.with(ChronoField.DAY_OF_MONTH, 1L).toInstant();
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_MONTH, 1L).toInstant();
}
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).truncatedTo(unit).toInstant();

View File

@ -96,8 +96,8 @@ public class Authentication2FAController extends BaseController {
}
for (SecondFactorProvider<?> provider : secondFactorProviderManager.getEnabled(userId)) {
SecondFactorProviderModel enabledProvider = new SecondFactorProviderModel(
provider.getId(), provider instanceof SecondFactorRequestProvider<?>);
SecondFactorProviderModel enabledProvider = new SecondFactorProviderModel(provider.getId(),
provider instanceof SecondFactorRequestProvider<?>);
result.remove(enabledProvider);
}
return result;
@ -179,8 +179,7 @@ public class Authentication2FAController extends BaseController {
*/
@PreAuthorize("authentication.authenticated")
@PatchMapping("/{id}")
public void enableSecondFactor(@PathVariable("id") String providerId,
@RequestBody String token) {
public void enableSecondFactor(@PathVariable("id") String providerId, @RequestBody String token) {
SecondFactorProvider<?> provider = secondFactorProviderManager.getProvider(providerId);
if (provider == null) {

View File

@ -62,8 +62,8 @@ public class AuthenticationController extends BaseController {
*/
@PreAuthorize("isAnonymous()")
@PostMapping("/password/request")
public void passwordRequest(@RequestBody String username, HttpServletRequest req,
HttpServletResponse resp) throws IOException {
public void passwordRequest(@RequestBody String username, HttpServletRequest req, HttpServletResponse resp)
throws IOException {
User user = userManager.getByUsername(username);
if (user != null) {
@ -83,8 +83,8 @@ public class AuthenticationController extends BaseController {
*/
@PreAuthorize("isAnonymous()")
@PostMapping("/password/reset")
public void passwordReset(@RequestBody PasswordResetModel passwordResetModel,
HttpServletRequest req, HttpServletResponse resp) {
public void passwordReset(@RequestBody PasswordResetModel passwordResetModel, HttpServletRequest req,
HttpServletResponse resp) {
User user = userManager.getByResetToken(passwordResetModel.getToken().trim());
if (user == null) {

View File

@ -147,8 +147,7 @@ public class ItemController extends BaseController {
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
}
tokenSessionManager.applyTokens(user.getId(),
tokenSessionManager.getTokenFromSession(session));
tokenSessionManager.applyTokens(user.getId(), tokenSessionManager.getTokenFromSession(session));
tokenSessionManager.removeTokensFromSession(session);
}

View File

@ -59,8 +59,7 @@ public class PermissionController extends BaseController {
}
for (String token : tokenSessionManager.getTokenFromSession(session)) {
permissions
.addAll(tokenSessionManager.getPermissionsForToken(getCurrentUserId(), token));
permissions.addAll(tokenSessionManager.getPermissionsForToken(getCurrentUserId(), token));
}
return permissions;

View File

@ -82,8 +82,8 @@ public class PermissionManagementController extends BaseController {
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping
public Permission createPermission(@RequestBody Permission permission) {
return permissionManager.create(permission.getTarget(), permission.getName(),
permission.isAddon(), permission.getStarts(), permission.getExpires());
return permissionManager.create(permission.getTarget(), permission.getName(), permission.isAddon(),
permission.getStarts(), permission.getExpires());
}
/**
@ -131,8 +131,7 @@ public class PermissionManagementController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/{name}/clone/{clone}")
public List<Permission> clone(@PathVariable("name") String name,
@PathVariable("clone") String clone) {
public List<Permission> clone(@PathVariable("name") String name, @PathVariable("clone") String clone) {
if (name.equals(clone)) {
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
}

View File

@ -49,11 +49,9 @@ public class PermissionMappingController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping
public Page<PermissionMapping> getPermissionMappings(
@RequestParam("page") Optional<Integer> pageParameter,
public Page<PermissionMapping> getPermissionMappings(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter) {
return permissionMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10),
"item", true);
return permissionMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "item", true);
}
/**
@ -71,12 +69,11 @@ public class PermissionMappingController extends BaseController {
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
}
return permissionMappingManager.create(permissionMapping.getItem(),
permissionMapping.getNames(), permissionMapping.getLifetime(),
permissionMapping.getLifetimeUnit(), permissionMapping.isLifetimeRound(),
permissionMapping.isAddon(), permissionMapping.getProduct(),
permissionMapping.getStarts(), permissionMapping.getExpires(),
permissionMapping.getStartsQuestion(), permissionMapping.getExpiresQuestion());
return permissionMappingManager.create(permissionMapping.getItem(), permissionMapping.getNames(),
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit(),
permissionMapping.isLifetimeRound(), permissionMapping.isAddon(), permissionMapping.getProduct(),
permissionMapping.getStarts(), permissionMapping.getExpires(), permissionMapping.getStartsQuestion(),
permissionMapping.getExpiresQuestion());
}
/**
@ -87,8 +84,7 @@ public class PermissionMappingController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/list")
public List<PermissionMapping> createList(
@RequestBody List<PermissionMapping> permissionMappings) {
public List<PermissionMapping> createList(@RequestBody List<PermissionMapping> permissionMappings) {
List<PermissionMapping> result = Lists.newArrayList();
for (PermissionMapping permissionMapping : permissionMappings) {
Errors errors = new RequestBodyErrors(permissionMapping);
@ -97,10 +93,9 @@ public class PermissionMappingController extends BaseController {
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
}
result.add(permissionMappingManager.create(permissionMapping.getItem(),
permissionMapping.getNames(), permissionMapping.getLifetime(),
permissionMapping.getLifetimeUnit(), permissionMapping.isLifetimeRound(),
permissionMapping.isAddon(), permissionMapping.getProduct(),
result.add(permissionMappingManager.create(permissionMapping.getItem(), permissionMapping.getNames(),
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit(),
permissionMapping.isLifetimeRound(), permissionMapping.isAddon(), permissionMapping.getProduct(),
permissionMapping.getStarts(), permissionMapping.getExpires(),
permissionMapping.getStartsQuestion(), permissionMapping.getExpiresQuestion()));
}
@ -132,8 +127,7 @@ public class PermissionMappingController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PatchMapping("/list")
public List<PermissionMapping> updateList(
@RequestBody List<PermissionMapping> permissionMappings) {
public List<PermissionMapping> updateList(@RequestBody List<PermissionMapping> permissionMappings) {
List<PermissionMapping> result = Lists.newArrayList();
for (PermissionMapping permissionMapping : permissionMappings) {
Errors errors = new RequestBodyErrors(permissionMapping);

View File

@ -58,10 +58,8 @@ public class PretixApiController extends BaseController {
}
}
gson.toJson(
pretixManager.request(pretixRequest.getPath(), pretixRequest.getMethod(),
gson.toJsonTree(pretixRequest.getPayload()), queryParemeters),
response.getWriter());
gson.toJson(pretixManager.request(pretixRequest.getPath(), pretixRequest.getMethod(),
gson.toJsonTree(pretixRequest.getPayload()), queryParemeters), response.getWriter());
} catch (WebClientResponseException e) {
throw new EntityResponseStatusException(e.getMessage(), e.getStatusCode());
}

View File

@ -98,8 +98,8 @@ public class QuotaManagementController extends BaseController {
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
}
return quotaManager.create(quota.getTarget(), quota.getName(), quota.getValue(),
quota.getUnit(), quota.isDisposable());
return quotaManager.create(quota.getTarget(), quota.getName(), quota.getValue(), quota.getUnit(),
quota.isDisposable());
}
/**

View File

@ -49,11 +49,9 @@ public class QuotaMappingController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping
public Page<QuotaMapping> getQuotaMappings(
@RequestParam("page") Optional<Integer> pageParameter,
public Page<QuotaMapping> getQuotaMappings(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter) {
return quotaMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name",
true);
return quotaMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", true);
}
/**
@ -74,9 +72,9 @@ public class QuotaMappingController extends BaseController {
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
}
return quotaMappingManager.create(quotaMapping.getItems(), quotaMapping.getName(),
quotaMapping.getValue(), quotaMapping.getUnit(), quotaMapping.isAppend(),
quotaMapping.getProducts(), quotaMapping.isDisposable());
return quotaMappingManager.create(quotaMapping.getItems(), quotaMapping.getName(), quotaMapping.getValue(),
quotaMapping.getUnit(), quotaMapping.isAppend(), quotaMapping.getProducts(),
quotaMapping.isDisposable());
}
/**

View File

@ -58,8 +58,7 @@ public class SystemController extends BaseController {
public List<SystemProperty> getProperties(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter) {
Sort sort = Sort.by("key").ascending();
return systemPropertyRepository
.findAll(PageRequest.of(pageParameter.orElse(0), sizeParameter.orElse(10), sort))
return systemPropertyRepository.findAll(PageRequest.of(pageParameter.orElse(0), sizeParameter.orElse(10), sort))
.getContent();
}

View File

@ -46,8 +46,7 @@ public class SystemProfileFieldController extends BaseController {
@GetMapping
public Page<SystemProfileField> get(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter) {
return systemProfileFieldManager.get(pageParameter.orElse(0), sizeParameter.orElse(10),
"name", true);
return systemProfileFieldManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", true);
}
/**
@ -88,8 +87,7 @@ public class SystemProfileFieldController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/list")
public List<SystemProfileField> updateList(
@RequestBody List<SystemProfileField> systemProfileFields) {
public List<SystemProfileField> updateList(@RequestBody List<SystemProfileField> systemProfileFields) {
List<SystemProfileField> result = Lists.newArrayList();
for (SystemProfileField systemProfileField : systemProfileFields) {

View File

@ -131,8 +131,7 @@ public class UserAliasController extends BaseController {
Quota aliasCreation = quotaManager.get(getCurrentUserId(), Quotas.ALIAS_CREATION);
if (aliasCreation == null) {
aliasCreation = quotaManager.create(getCurrentUserId(), Quotas.ALIAS_CREATION, 0, "#",
true);
aliasCreation = quotaManager.create(getCurrentUserId(), Quotas.ALIAS_CREATION, 0, "#", true);
}
aliasCreation.setValue(aliasCreation.getValue() + 1);

View File

@ -165,8 +165,7 @@ public class UserController extends BaseController {
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
}
User user = userManager.create(userModel.getUsername(), userModel.getPassword(),
userModel.getStatus());
User user = userManager.create(userModel.getUsername(), userModel.getPassword(), userModel.getStatus());
for (UserProfileField userProfileField : userModel.getProfileFields()) {
userProfileField.setTarget(user.getId());
@ -210,8 +209,8 @@ public class UserController extends BaseController {
User user = userManager.get(getCurrentUserId());
if (!StringUtils.hasText(passwordModel.getOld()) || !passwordEncoder
.matches(passwordModel.getOld(), userManager.getPasswordHash(user.getId()))) {
if (!StringUtils.hasText(passwordModel.getOld())
|| !passwordEncoder.matches(passwordModel.getOld(), userManager.getPasswordHash(user.getId()))) {
throw new EntityResponseStatusException(HttpStatus.UNAUTHORIZED);
}
@ -235,8 +234,7 @@ public class UserController extends BaseController {
User user = userManager.get(getCurrentUserId());
if (StringUtils.hasText(userModel.getOld())) {
Errors errors = new RequestBodyErrors(userModel);
if (!passwordEncoder.matches(userModel.getOld(),
userManager.getPasswordHash(getCurrentUserId()))) {
if (!passwordEncoder.matches(userModel.getOld(), userManager.getPasswordHash(getCurrentUserId()))) {
throw new EntityResponseStatusException(HttpStatus.UNAUTHORIZED);
}

View File

@ -71,8 +71,7 @@ public class UserDataManagementController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/purge/{username}")
public void purgeByUsername(@PathVariable("username") String username,
@RequestParam("dry") boolean dry) {
public void purgeByUsername(@PathVariable("username") String username, @RequestParam("dry") boolean dry) {
User user = userManager.getByUsername(username);
if (user == null) {

View File

@ -54,15 +54,13 @@ public class UserDomainController extends BaseController {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
}
if (userDomain.getVisibility() == null) {
userDomain.setVisibility(Visibility.PRIVATE);
}
userDomain.setTarget(getCurrentUserId());
userDomain.setValidated(false);
userDomain.setSecret(
RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true));
userDomain.setSecret(RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true));
Errors errors = new RequestBodyErrors(userDomain);

View File

@ -100,8 +100,7 @@ public class UserDomainManagementController extends BaseController {
if (userDomain.getId() == null) {
userDomain.setValidated(false);
userDomain.setSecret(
RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true));
userDomain.setSecret(RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true));
}
return userDomainManager.save(userDomain);

View File

@ -130,15 +130,13 @@ public class UserManagementController extends BaseController {
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
}
User user = userManager.create(userModel.getUsername(), userModel.getPassword(),
userModel.getStatus());
User user = userManager.create(userModel.getUsername(), userModel.getPassword(), userModel.getStatus());
if (userModel.getPermissionMappings() != null) {
for (PermissionMapping permissionMapping : userModel.getPermissionMappings()) {
for (String name : permissionMapping.getNames()) {
permissionManager.create(user.getId(), name, permissionMapping.isAddon(), null,
InstantHelper.plus(Instant.now(), permissionMapping.getLifetime(),
permissionMapping.getLifetimeUnit()));
permissionManager.create(user.getId(), name, permissionMapping.isAddon(), null, InstantHelper
.plus(Instant.now(), permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit()));
}
}
}
@ -159,8 +157,8 @@ public class UserManagementController extends BaseController {
if (userModel.getQuotas() != null) {
for (Quota quota : userModel.getQuotas()) {
quotaManager.create(user.getId(), quota.getName(), quota.getValue(),
quota.getUnit(), quota.isDisposable());
quotaManager.create(user.getId(), quota.getName(), quota.getValue(), quota.getUnit(),
quota.isDisposable());
}
}
@ -217,8 +215,7 @@ public class UserManagementController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/purge")
public void purge(@RequestParam("username") Optional<String> username,
@RequestParam("dry") Optional<Boolean> dry) {
public void purge(@RequestParam("username") Optional<String> username, @RequestParam("dry") Optional<Boolean> dry) {
if (username.isPresent()) {
User user = userManager.getByUsername(username.get());

View File

@ -138,8 +138,7 @@ public class UserProfileFieldController extends BaseController {
}
profileFields.addAll(
userProfileFieldManager.getAllByTargetAndVisibilities(user.getId(), visibilities));
profileFields.addAll(userProfileFieldManager.getAllByTargetAndVisibilities(user.getId(), visibilities));
if (profileFields.isEmpty()) {
throttleForbidden();

View File

@ -49,11 +49,9 @@ public class VoucherMappingController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping
public Page<VoucherMapping> getVoucherMappings(
@RequestParam("page") Optional<Integer> pageParameter,
public Page<VoucherMapping> getVoucherMappings(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter) {
return voucherMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name",
true);
return voucherMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", true);
}
/**
@ -98,9 +96,8 @@ public class VoucherMappingController extends BaseController {
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
}
result.add(voucherMappingManager.create(voucherMapping.getName(),
voucherMapping.getVoucher(), voucherMapping.getQuota(),
voucherMapping.isFree()));
result.add(voucherMappingManager.create(voucherMapping.getName(), voucherMapping.getVoucher(),
voucherMapping.getQuota(), voucherMapping.isFree()));
}
return result;
}

View File

@ -29,9 +29,10 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
private Gson gson = new Gson();
/*
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#supports(org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class)
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
* supports(org.springframework.core.MethodParameter, java.lang.reflect.Type,
* java.lang.Class)
*/
@Override
public boolean supports(MethodParameter methodParameter, Type targetType,
@ -40,7 +41,10 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
}
/*
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#beforeBodyRead(org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class)
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
* beforeBodyRead(org.springframework.http.HttpInputMessage,
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
* java.lang.Class)
*/
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
@ -48,9 +52,11 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
return inputMessage;
}
/*
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#afterBodyRead(java.lang.Object, org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class)
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
* afterBodyRead(java.lang.Object, org.springframework.http.HttpInputMessage,
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
* java.lang.Class)
*/
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
@ -59,9 +65,11 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
return body;
}
/*
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#handleEmptyBody(java.lang.Object, org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class)
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
* handleEmptyBody(java.lang.Object, org.springframework.http.HttpInputMessage,
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
* java.lang.Class)
*/
@Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
@ -69,18 +77,23 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
return body;
}
/*
* @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#supports(org.springframework.core.MethodParameter, java.lang.Class)
* @see
* org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#
* supports(org.springframework.core.MethodParameter, java.lang.Class)
*/
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return converterType == StringHttpMessageConverter.class;
}
/*
* @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#beforeBodyWrite(java.lang.Object, org.springframework.core.MethodParameter, org.springframework.http.MediaType, java.lang.Class, org.springframework.http.server.ServerHttpRequest, org.springframework.http.server.ServerHttpResponse)
* @see
* org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#
* beforeBodyWrite(java.lang.Object, org.springframework.core.MethodParameter,
* org.springframework.http.MediaType, java.lang.Class,
* org.springframework.http.server.ServerHttpRequest,
* org.springframework.http.server.ServerHttpResponse)
*/
@Override
public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType,

View File

@ -33,9 +33,10 @@ public class RequestBodyErrors extends AbstractBindingResult {
return target;
}
/*
* @see org.springframework.validation.AbstractBindingResult#getActualFieldValue(java.lang.String)
* @see
* org.springframework.validation.AbstractBindingResult#getActualFieldValue(java
* .lang.String)
*/
@Override
protected Object getActualFieldValue(String field) {

View File

@ -100,7 +100,7 @@ public class TokenSessionManager {
}
permissions.addAll(permissionManager.getForItem(userId, item,
orderPosition.get("answers").getAsJsonArray(),lastPaymentDate, null));
orderPosition.get("answers").getAsJsonArray(), lastPaymentDate, null));
}
} catch (Exception e) {
// ignore
@ -179,8 +179,8 @@ public class TokenSessionManager {
throw new Exception("This should not happen!");
}
permissionManager.applyItem(userId, item,
position.get("answers").getAsJsonArray(), lastPaymentDate, null);
permissionManager.applyItem(userId, item, position.get("answers").getAsJsonArray(), lastPaymentDate,
null);
permissionMappings.addAll(permissionMappingManager.getAllByItem(item));
quotaManager.applyItem(userId, item);
quotaMappings.addAll(quotaMappingManager.getAllByItem(item));
@ -236,8 +236,7 @@ public class TokenSessionManager {
}
if (StringUtils.hasLength(tokens)) {
tokens += ","
+ secret;
tokens += "," + secret;
} else {
tokens = secret;
}
@ -261,8 +260,7 @@ public class TokenSessionManager {
for (String token : ((String) sessionAttribute).split(",")) {
if (!token.equals(secret)) {
if (StringUtils.hasLength(tokens)) {
tokens += ","
+ secret;
tokens += "," + secret;
} else {
tokens = secret;
}
@ -292,8 +290,7 @@ public class TokenSessionManager {
protected Authentication createNewAuth(Authentication auth, LocalUserDetails details) {
Authentication newAuth = null;
if (auth instanceof UsernamePasswordAuthenticationToken) {
newAuth = new UsernamePasswordAuthenticationToken(details, auth.getCredentials(),
details.getAuthorities());
newAuth = new UsernamePasswordAuthenticationToken(details, auth.getCredentials(), details.getAuthorities());
} else {
newAuth = new LocalAnonymousAuthenticationToken(details);
}

View File

@ -46,9 +46,9 @@ public class PasswordModelValidator implements Validator {
return clazz.isAssignableFrom(PasswordModel.class);
}
/*
* @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
* @see org.springframework.validation.Validator#validate(java.lang.Object,
* org.springframework.validation.Errors)
*/
@Override
public void validate(Object target, Errors errors) {

View File

@ -51,8 +51,8 @@ public class UserDomainValidator implements Validator {
UserDomain existingDomain = userDomainManager.getByDomain(userDomain.getDomain());
if (existingDomain != null && (userDomain.getId() == null
|| !(existingDomain.getId().equals(userDomain.getId())))) {
if (existingDomain != null
&& (userDomain.getId() == null || !(existingDomain.getId().equals(userDomain.getId())))) {
errors.rejectValue("domain", "NOT_VALID");
return;
}

View File

@ -65,8 +65,7 @@ public class UserModelValidator implements Validator {
*/
public void validateUsername(String username, String field, Errors errors) {
for (String systemUsername : systemPropertyManager.get(RESERVED_USERNAMES, "").split(",")) {
if (StringUtils.hasText(systemUsername)
&& (username.toLowerCase().equals(systemUsername)
if (StringUtils.hasText(systemUsername) && (username.toLowerCase().equals(systemUsername)
|| username.toLowerCase().matches(systemUsername))) {
errors.rejectValue(field, "NOT_VALID");
break;

View File

@ -40,8 +40,7 @@ public class UserProfileFieldValidator implements Validator {
private DoubleValidator doubleValidator = DoubleValidator.getInstance();
private EmailValidator emailValidator = EmailValidator.getInstance();
private UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_ALL_SCHEMES);
private List<String> validBoolean = Lists.newArrayList("true", "True", "TRUE", "1", "false",
"False", "FALSE", "0");
private List<String> validBoolean = Lists.newArrayList("true", "True", "TRUE", "1", "false", "False", "FALSE", "0");
/*
* @see org.springframework.validation.Validator#supports(java.lang.Class)
@ -65,8 +64,7 @@ public class UserProfileFieldValidator implements Validator {
errors.rejectValue("name", "TOO_LONG");
}
SystemProfileField systemProfileField = systemProfileFieldManager
.get(userProfileField.getName());
SystemProfileField systemProfileField = systemProfileFieldManager.get(userProfileField.getName());
if (systemProfileField != null) {
if (!systemProfileField.getType().equals(userProfileField.getType())) {

View File

@ -283,25 +283,11 @@ public class PermissionMapping {
@Converter
public static class ChronoUnitConverter implements AttributeConverter<ChronoUnit, String> {
/*
* @see javax.persistence.AttributeConverter#convertToDatabaseColumn(java.lang.Object)
*/
/*
* @see javax.persistence.AttributeConverter#convertToDatabaseColumn(java.lang.
* Object)
*/
@Override
public String convertToDatabaseColumn(ChronoUnit chronoUnit) {
return chronoUnit.name();
}
/*
* @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang.Object)
*/
/*
* @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang.
* Object)
*/
@Override
public ChronoUnit convertToEntityAttribute(String value) {
return ChronoUnit.valueOf(value);

View File

@ -20,8 +20,7 @@ import de.bstly.we.model.UserProfileField.UserProfileFieldId;
*/
@Entity
@IdClass(UserProfileFieldId.class)
@Table(name = "profile_fields", uniqueConstraints = @UniqueConstraint(columnNames = { "target",
"name" }))
@Table(name = "profile_fields", uniqueConstraints = @UniqueConstraint(columnNames = { "target", "name" }))
public class UserProfileField implements UserData {
@Id

View File

@ -13,7 +13,6 @@ import de.bstly.we.model.Permission;
* The Interface PermissionRepository.
*/
@Repository
public interface PermissionRepository
extends JpaRepository<Permission, Long>, QuerydslPredicateExecutor<Permission> {
public interface PermissionRepository extends JpaRepository<Permission, Long>, QuerydslPredicateExecutor<Permission> {
}

View File

@ -13,7 +13,7 @@ import de.bstly.we.model.SystemProfileField;
* The Interface SystemProfileFieldRepository.
*/
@Repository
public interface SystemProfileFieldRepository extends JpaRepository<SystemProfileField, String>,
QuerydslPredicateExecutor<SystemProfileField> {
public interface SystemProfileFieldRepository
extends JpaRepository<SystemProfileField, String>, QuerydslPredicateExecutor<SystemProfileField> {
}

View File

@ -13,7 +13,6 @@ import de.bstly.we.model.UserAlias;
* The Interface UserAliasRepository.
*/
@Repository
public interface UserAliasRepository
extends JpaRepository<UserAlias, Long>, QuerydslPredicateExecutor<UserAlias> {
public interface UserAliasRepository extends JpaRepository<UserAlias, Long>, QuerydslPredicateExecutor<UserAlias> {
}

View File

@ -13,7 +13,6 @@ import de.bstly.we.model.UserDomain;
* The Interface UserDomainRepository.
*/
@Repository
public interface UserDomainRepository
extends JpaRepository<UserDomain, Long>, QuerydslPredicateExecutor<UserDomain> {
public interface UserDomainRepository extends JpaRepository<UserDomain, Long>, QuerydslPredicateExecutor<UserDomain> {
}

View File

@ -15,7 +15,6 @@ import de.bstly.we.model.UserProfileField.UserProfileFieldId;
*/
@Repository
public interface UserProfileFieldRepository
extends JpaRepository<UserProfileField, UserProfileFieldId>,
QuerydslPredicateExecutor<UserProfileField> {
extends JpaRepository<UserProfileField, UserProfileFieldId>, QuerydslPredicateExecutor<UserProfileField> {
}

View File

@ -33,9 +33,11 @@ public class LocalAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPo
super(loginFormUrl);
};
/*
* @see org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint#commence(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
* @see org.springframework.security.web.authentication.
* LoginUrlAuthenticationEntryPoint#commence(javax.servlet.http.
* HttpServletRequest, javax.servlet.http.HttpServletResponse,
* org.springframework.security.core.AuthenticationException)
*/
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,

View File

@ -10,7 +10,9 @@ import org.springframework.security.authentication.dao.DaoAuthenticationProvider
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Component;
import de.bstly.we.security.businesslogic.SecondFactorProvider;
import de.bstly.we.security.businesslogic.SecondFactorProviderManager;
@ -21,14 +23,25 @@ import de.bstly.we.security.token.LocalSecondFactorAuthenticationToken;
/**
* The Class LocalAuthenticationProvider.
*/
@Component
public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
@Autowired
private SecondFactorProviderManager secondFactorProviderManager;
/**
* Instantiates a new local authentication provider.
*
* @param userDetailService the user detail service
*/
public LocalAuthenticationProvider(UserDetailsService userDetailService) {
setUserDetailsService(userDetailService);
}
/*
* @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
* @see org.springframework.security.authentication.dao.
* AbstractUserDetailsAuthenticationProvider#authenticate(org.springframework.
* security.core.Authentication)
*/
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
@ -38,8 +51,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
if (auth.getPrincipal() instanceof LocalUserDetails) {
LocalUserDetails details = (LocalUserDetails) auth.getPrincipal();
if (!secondFactorProviderManager.getEnabled(details.getUserId()).isEmpty()) {
PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(
details, "", AuthorityUtils.createAuthorityList("ROLE_PRE_AUTH_USER"));
PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(details, "",
AuthorityUtils.createAuthorityList("ROLE_PRE_AUTH_USER"));
newAuth.setAuthenticated(false);
return newAuth;
}
@ -57,8 +70,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
.getProvider(secondFactorAuth.getProvider());
if (provider == null) {
throw new SecondFactorAuthenticationException(
"invalid provider: " + secondFactorAuth.getProvider(), details);
throw new SecondFactorAuthenticationException("invalid provider: " + secondFactorAuth.getProvider(),
details);
}
if (!provider.isEnabled(details.getUserId())) {
@ -70,8 +83,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
return new UsernamePasswordAuthenticationToken(details, auth.getCredentials(),
details.getAuthorities());
} else {
PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(
details, "", auth.getAuthorities());
PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(details, "",
auth.getAuthorities());
newAuth.setAuthenticated(false);
return newAuth;
}
@ -82,7 +95,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
}
/*
* @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider#supports(java.lang.Class)
* @see org.springframework.security.authentication.dao.
* AbstractUserDetailsAuthenticationProvider#supports(java.lang.Class)
*/
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication))
@ -93,8 +107,7 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
/**
* The Class SecondFactorAuthenticationException.
*/
public static class SecondFactorAuthenticationException
extends InsufficientAuthenticationException {
public static class SecondFactorAuthenticationException extends InsufficientAuthenticationException {
private LocalUserDetails principal;

View File

@ -26,9 +26,10 @@ public class LocalRememberMeServices extends PersistentTokenBasedRememberMeServi
super(key, userDetailsService, tokenRepository);
}
/*
* @see org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices#rememberMeRequested(javax.servlet.http.HttpServletRequest, java.lang.String)
* @see org.springframework.security.web.authentication.rememberme.
* AbstractRememberMeServices#rememberMeRequested(javax.servlet.http.
* HttpServletRequest, java.lang.String)
*/
@Override
protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {

View File

@ -4,12 +4,11 @@
package de.bstly.we.security;
/**
* The listener interface for receiving localServletContext events.
* The class that is interested in processing a localServletContext
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addLocalServletContextListener<code> method. When
* the localServletContext event occurs, that object's appropriate
* The listener interface for receiving localServletContext events. The class
* that is interested in processing a localServletContext event implements this
* interface, and the object created with that class is registered with a
* component using the component's <code>addLocalServletContextListener<code>
* method. When the localServletContext event occurs, that object's appropriate
* method is invoked.
*
* @see LocalServletContextEvent

View File

@ -1,5 +1,6 @@
package de.bstly.we.security;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
@ -14,10 +15,14 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import de.bstly.we.businesslogic.PermissionManager;
import de.bstly.we.businesslogic.UserManager;
import com.google.common.collect.Lists;
import de.bstly.we.model.Permission;
import de.bstly.we.model.QPermission;
import de.bstly.we.model.QUser;
import de.bstly.we.model.User;
import de.bstly.we.repository.PermissionRepository;
import de.bstly.we.repository.UserRepository;
import de.bstly.we.security.model.LocalUserDetails;
/**
@ -27,23 +32,26 @@ import de.bstly.we.security.model.LocalUserDetails;
public class LocalUserDetailsService implements UserDetailsService {
@Autowired
private UserManager userManager;
private UserRepository userRepository;
@Autowired
private PermissionManager permissionManager;
private PermissionRepository permissionRepository;
private QUser qUser = QUser.user;
private QPermission qPermission = QPermission.permission;
/*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
* @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userManager.getByUsername(username);
User user = userRepository.findOne(qUser.username.equalsIgnoreCase(username)).orElse(null);
if (user != null) {
String password = userManager.getPasswordHash(user.getId());
String password = userRepository.findById(user.getId()).get().getPasswordHash();
if (password == null) {
throw new AuthenticationCredentialsNotFoundException(
"No password found: " + username);
throw new AuthenticationCredentialsNotFoundException("No password found: " + username);
}
if (user.isDisabled()) {
@ -75,8 +83,8 @@ public class LocalUserDetailsService implements UserDetailsService {
// }
// Create user details
LocalUserDetails userDetails = new LocalUserDetails(user.getId(), user.getUsername(),
password, authorities);
LocalUserDetails userDetails = new LocalUserDetails(user.getId(), user.getUsername(), password,
authorities);
return userDetails;
}
@ -93,7 +101,9 @@ public class LocalUserDetailsService implements UserDetailsService {
*/
public Set<GrantedAuthority> getAuthoritiesForUser(Long userId) {
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for (Permission permission : permissionManager.getNotExpiresByTarget(userId)) {
for (Permission permission : Lists.newArrayList(
permissionRepository.findAll(qPermission.target.eq(userId).and(qPermission.expires.after(Instant.now())
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))))) {
authorities.add(new SimpleGrantedAuthority(permission.getName()));
}
return authorities;

View File

@ -0,0 +1,25 @@
/**
*
*/
package de.bstly.we.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
/**
* The Class PasswordEncoderConfig.
*/
@Configuration
public class PasswordEncoderConfig {
/**
* Password encoder.
*
* @return the argon 2 password encoder
*/
@Bean(name = "passwordEncoder")
public Argon2PasswordEncoder passwordEncoder() {
return new Argon2PasswordEncoder();
}
}

View File

@ -11,14 +11,13 @@ import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@ -33,6 +32,7 @@ import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import de.bstly.we.controller.support.TokenSessionManager;
import de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter;
import de.bstly.we.security.filter.LocalAnonymousAuthenticationFilter;
import de.bstly.we.security.filter.RestAuthenticationFilter;
@ -55,11 +55,15 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;
@Autowired
private RestAuthenticationFailureHandler restAuthenticationFailureHandler;
@Autowired
private LocalAccessDeniedHandler localAccessDeniedHandler;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private TokenSessionManager tokenSessionManager;
@Autowired
private LocalAuthenticationProvider localAuthenticationProvider;
@Value("${server.servlet.session.cookie.secure:false}")
private boolean secureCookie;
@ -84,12 +88,14 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
*/
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
localAuthenticationProvider.setPasswordEncoder(passwordEncoder);
auth.authenticationProvider(localAuthenticationProvider);
}
/*
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
* @see org.springframework.security.config.annotation.web.configuration.
* WebSecurityConfigurerAdapter#configure(org.springframework.security.config.
* annotation.web.builders.HttpSecurity)
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
@ -102,26 +108,21 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
// disable deprectated xss protection
.headers().xssProtection().disable().and()
// form login
.formLogin().loginPage(loginUrl).usernameParameter("username")
.passwordParameter("password").loginProcessingUrl("/auth/login")
.defaultSuccessUrl(loginTargetUrl)
.formLogin().loginPage(loginUrl).usernameParameter("username").passwordParameter("password")
.loginProcessingUrl("/auth/login").defaultSuccessUrl(loginTargetUrl)
.successHandler(formAuthenticationSuccessHandler())
.failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl + "?error"))
.and()
.failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl + "?error")).and()
// remember me
.rememberMe().rememberMeServices(rememberMeServices()).and()
// form totp
.addFilterBefore(formSecondFactorAuthenticationFilter(),
LocalAnonymousAuthenticationFilter.class)
.addFilterBefore(formSecondFactorAuthenticationFilter(), LocalAnonymousAuthenticationFilter.class)
// rest login
.addFilterBefore(restAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(restAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
// rest totp
.addFilterAfter(restSecondFactorAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class)
.addFilterAfter(restSecondFactorAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
// Logout
.logout().logoutUrl("/auth/logout")
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()).and()
.logout().logoutUrl("/auth/logout").logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
.and()
// exception
.exceptionHandling().accessDeniedHandler(localAccessDeniedHandler)
.authenticationEntryPoint(localAuthenticationEntryPoint()).and()
@ -155,29 +156,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
return source;
}
/**
* Dao authentication provider.
*
* @return the dao authentication provider
*/
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
LocalAuthenticationProvider provider = new LocalAuthenticationProvider();
provider.setUserDetailsService(localUserDetailsService);
provider.setPasswordEncoder(passwordEncoder());
return provider;
}
/**
* Password encoder.
*
* @return the argon 2 password encoder
*/
@Bean(name = "passwordEncoder")
public Argon2PasswordEncoder passwordEncoder() {
return new Argon2PasswordEncoder();
}
/**
* Local anonymous authentication filter.
*
@ -195,10 +173,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
*/
@Bean
public LocalAuthenticationEntryPoint localAuthenticationEntryPoint() {
LocalAuthenticationEntryPoint localAuthenticationEntryPoint = new LocalAuthenticationEntryPoint(
loginUrl);
localAuthenticationEntryPoint
.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
LocalAuthenticationEntryPoint localAuthenticationEntryPoint = new LocalAuthenticationEntryPoint(loginUrl);
localAuthenticationEntryPoint.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
return localAuthenticationEntryPoint;
}
@ -211,14 +187,25 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public FormAuthenticationSuccessHandler formAuthenticationSuccessHandler() {
FormAuthenticationSuccessHandler formAuthenticationSuccessHandler = new FormAuthenticationSuccessHandler(
loginTargetUrl, SecurityConfig.KEEP_PARAM);
rememberMeServices(), tokenSessionManager, loginTargetUrl, SecurityConfig.KEEP_PARAM);
formAuthenticationSuccessHandler.setTotpRedirectUrl(secondFactorUrl);
formAuthenticationSuccessHandler.setTargetUrlParameter("forward");
formAuthenticationSuccessHandler
.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
formAuthenticationSuccessHandler.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
return formAuthenticationSuccessHandler;
}
/**
* Rest authentication success handler.
*
* @return the rest authentication success handler
*/
@Bean
public RestAuthenticationSuccessHandler restAuthenticationSuccessHandler() {
RestAuthenticationSuccessHandler restAuthenticationSuccessHandler = new RestAuthenticationSuccessHandler(
rememberMeServices(), tokenSessionManager);
return restAuthenticationSuccessHandler;
}
/**
* Form second factor authentication filter.
*
@ -226,13 +213,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
* @throws Exception the exception
*/
@Bean
public FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter()
throws Exception {
public FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter() throws Exception {
FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter = new FormSecondFactorAuthenticationFilter(
"/auth/login/2fa");
formSecondFactorAuthenticationFilter.setAuthenticationManager(authenticationManager());
formSecondFactorAuthenticationFilter
.setAuthenticationSuccessHandler(formAuthenticationSuccessHandler());
formSecondFactorAuthenticationFilter.setAuthenticationSuccessHandler(formAuthenticationSuccessHandler());
formSecondFactorAuthenticationFilter.setRememberMeServices(rememberMeServices());
return formSecondFactorAuthenticationFilter;
}
@ -245,10 +230,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
*/
@Bean
public RestAuthenticationFilter restAuthenticationFilter() throws Exception {
RestAuthenticationFilter restAuthenticationFilter = new RestAuthenticationFilter(
"/auth/restlogin");
RestAuthenticationFilter restAuthenticationFilter = new RestAuthenticationFilter("/auth/restlogin");
restAuthenticationFilter.setAuthenticationManager(authenticationManager());
restAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);
restAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler());
restAuthenticationFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
return restAuthenticationFilter;
}
@ -260,15 +244,12 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
* @throws Exception the exception
*/
@Bean
public RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter()
throws Exception {
public RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter() throws Exception {
RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter = new RestSecondFactorAuthenticationFilter(
"/auth/restlogin/2fa");
restSecondFactorAuthenticationFilter.setAuthenticationManager(authenticationManager());
restSecondFactorAuthenticationFilter
.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);
restSecondFactorAuthenticationFilter
.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
restSecondFactorAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler());
restSecondFactorAuthenticationFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
restSecondFactorAuthenticationFilter.setRememberMeServices(rememberMeServices());
return restSecondFactorAuthenticationFilter;
}
@ -302,8 +283,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
*/
@Bean
public RememberMeServices rememberMeServices() {
PersistentTokenBasedRememberMeServices rememberMeServices = new LocalRememberMeServices(
KEEP_PARAM, localUserDetailsService, persistentTokenRepository());
PersistentTokenBasedRememberMeServices rememberMeServices = new LocalRememberMeServices(KEEP_PARAM,
localUserDetailsService, persistentTokenRepository());
rememberMeServices.setCookieName("SESSION_" + KEEP_PARAM.toUpperCase());
rememberMeServices.setParameter(KEEP_PARAM);
rememberMeServices.setUseSecureCookie(secureCookie);

View File

@ -26,16 +26,15 @@ public class SecondFactorProviderManager implements SmartInitializingSingleton {
*/
private List<SecondFactorProvider<?>> providers;
/*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
* @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/
@Override
public void afterSingletonsInstantiated() {
providers = Lists.newArrayList();
for (SecondFactorProvider<?> provider : context.getBeansOfType(SecondFactorProvider.class)
.values()) {
for (SecondFactorProvider<?> provider : context.getBeansOfType(SecondFactorProvider.class).values()) {
providers.add(provider);
}
}

View File

@ -10,8 +10,7 @@ import de.bstly.we.model.SecondFactor;
*
* @param <T> the generic type
*/
public interface SecondFactorRequestProvider<T extends SecondFactor>
extends SecondFactorProvider<T> {
public interface SecondFactorRequestProvider<T extends SecondFactor> extends SecondFactorProvider<T> {
/**
* Request.

View File

@ -40,24 +40,22 @@ public class FormSecondFactorAuthenticationFilter extends AbstractAuthentication
super(defaultFilterProcessesUrl);
}
/*
* @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
* @see org.springframework.security.web.authentication.
* AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet.
* http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response)
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null
|| !(authentication instanceof PreAuthenticatedAuthenticationToken)
if (authentication == null || !(authentication instanceof PreAuthenticatedAuthenticationToken)
|| !(authentication.getPrincipal() instanceof LocalUserDetails)) {
throw new InsufficientAuthenticationException("login first!");
}
@ -75,14 +73,15 @@ public class FormSecondFactorAuthenticationFilter extends AbstractAuthentication
}
/*
* @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#unsuccessfulAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
* @see org.springframework.security.web.authentication.
* AbstractAuthenticationProcessingFilter#unsuccessfulAuthentication(javax.
* servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
* org.springframework.security.core.AuthenticationException)
*/
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, AuthenticationException failed)
throws IOException, ServletException {
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request failed: " + failed.toString(), failed);
logger.debug("Updated SecurityContextHolder to contain null Authentication");

View File

@ -32,22 +32,25 @@ public class LocalAnonymousAuthenticationFilter extends AnonymousAuthenticationF
super(KEY);
}
/*
* @see org.springframework.security.web.authentication.AnonymousAuthenticationFilter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
* @see
* org.springframework.security.web.authentication.AnonymousAuthenticationFilter
* #doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
* javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
if (SecurityContextHolder.getContext().getAuthentication() == null) {
SecurityContextHolder.getContext()
.setAuthentication(createAuthentication((HttpServletRequest) req));
SecurityContextHolder.getContext().setAuthentication(createAuthentication((HttpServletRequest) req));
}
chain.doFilter(req, res);
}
/*
* @see org.springframework.security.web.authentication.AnonymousAuthenticationFilter#createAuthentication(javax.servlet.http.HttpServletRequest)
* @see
* org.springframework.security.web.authentication.AnonymousAuthenticationFilter
* #createAuthentication(javax.servlet.http.HttpServletRequest)
*/
@Override
protected Authentication createAuthentication(HttpServletRequest request) {

View File

@ -44,16 +44,16 @@ public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFi
}
/*
* @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
* @see org.springframework.security.web.authentication.
* AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet.
* http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response)
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
try {
@ -77,8 +77,7 @@ public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFi
}
Authentication authRequest = new UsernamePasswordAuthenticationToken(
loginModel.get(usernameKey).getAsString(),
loginModel.get(passwordKey).getAsString());
loginModel.get(usernameKey).getAsString(), loginModel.get(passwordKey).getAsString());
return this.getAuthenticationManager().authenticate(authRequest);
} catch (JsonMappingException | JsonParseException exception) {
throw new AuthenticationCredentialsNotFoundException("Bad request");

View File

@ -39,24 +39,22 @@ public class RestSecondFactorAuthenticationFilter extends FormSecondFactorAuthen
super(defaultFilterProcessesUrl);
}
/*
* @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
* @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter#
* attemptAuthentication(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response)
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null
|| !(authentication instanceof PreAuthenticatedAuthenticationToken)
if (authentication == null || !(authentication instanceof PreAuthenticatedAuthenticationToken)
|| !(authentication.getPrincipal() instanceof LocalUserDetails)) {
throw new InsufficientAuthenticationException("login first!");
}
@ -79,10 +77,8 @@ public class RestSecondFactorAuthenticationFilter extends FormSecondFactorAuthen
String provider = model2FA.get(SPRING_SECURITY_FORM_2FA_PROVIDER_KEY).getAsString();
String code = model2FA.get(SPRING_SECURITY_FORM_2FA_CODE_KEY).getAsString();
if (model2FA.has(SecurityConfig.KEEP_PARAM)
&& model2FA.get(SecurityConfig.KEEP_PARAM).isJsonPrimitive()) {
request.setAttribute(SecurityConfig.KEEP_PARAM,
model2FA.get(SecurityConfig.KEEP_PARAM).getAsString());
if (model2FA.has(SecurityConfig.KEEP_PARAM) && model2FA.get(SecurityConfig.KEEP_PARAM).isJsonPrimitive()) {
request.setAttribute(SecurityConfig.KEEP_PARAM, model2FA.get(SecurityConfig.KEEP_PARAM).getAsString());
}
LocalUserDetails details = (LocalUserDetails) authentication.getPrincipal();
@ -93,14 +89,15 @@ public class RestSecondFactorAuthenticationFilter extends FormSecondFactorAuthen
}
}
/*
* @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter#unsuccessfulAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
* @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter#
* unsuccessfulAuthentication(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse,
* org.springframework.security.core.AuthenticationException)
*/
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, AuthenticationException failed)
throws IOException, ServletException {
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request failed: " + failed.toString(), failed);
logger.debug("Updated SecurityContextHolder to contain null Authentication");

View File

@ -7,7 +7,6 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
@ -24,13 +23,10 @@ import de.bstly.we.security.token.LocalSecondFactorAuthenticationToken;
/**
* The Class FormAuthenticationSuccessHandler.
*/
public class FormAuthenticationSuccessHandler
extends SavedRequestAwareAuthenticationSuccessHandler {
public class FormAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Autowired
protected RememberMeServices rememberMeServices;
@Autowired
protected TokenSessionManager tokenSessionManager;
protected final RememberMeServices rememberMeServices;
protected final TokenSessionManager tokenSessionManager;
private String totpRedirectUrl;
private String rememberMeParameter;
@ -40,33 +36,44 @@ public class FormAuthenticationSuccessHandler
/**
* Instantiates a new form authentication success handler.
*
* @param rememberMeServices the remember me services
* @param tokenSessionManager the token session manager
* @param rememberMeParameter the remember me parameter
*/
public FormAuthenticationSuccessHandler(String rememberMeParameter) {
public FormAuthenticationSuccessHandler(RememberMeServices rememberMeServices,
TokenSessionManager tokenSessionManager, String rememberMeParameter) {
this.rememberMeServices = rememberMeServices;
this.tokenSessionManager = tokenSessionManager;
this.rememberMeParameter = rememberMeParameter;
}
/**
* Instantiates a new form authentication success handler.
*
* @param rememberMeServices the remember me services
* @param tokenSessionManager the token session manager
* @param defaultTargetUrl the default target url
* @param rememberMeParameter the remember me parameter
*/
public FormAuthenticationSuccessHandler(String defaultTargetUrl, String rememberMeParameter) {
public FormAuthenticationSuccessHandler(RememberMeServices rememberMeServices,
TokenSessionManager tokenSessionManager, String defaultTargetUrl, String rememberMeParameter) {
this.rememberMeServices = rememberMeServices;
this.tokenSessionManager = tokenSessionManager;
setDefaultTargetUrl(defaultTargetUrl);
this.rememberMeParameter = rememberMeParameter;
}
/*
* @see org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
* @see org.springframework.security.web.authentication.
* SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax.
* servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
* org.springframework.security.core.Authentication)
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
if (!authentication.isAuthenticated()
&& authentication instanceof PreAuthenticatedAuthenticationToken) {
if (!authentication.isAuthenticated() && authentication instanceof PreAuthenticatedAuthenticationToken) {
rememberMeServices.loginFail(request, response);
boolean keep = false;
String paramValue = request.getParameter(rememberMeParameter);
@ -77,23 +84,20 @@ public class FormAuthenticationSuccessHandler
}
}
if (authentication.getAuthorities() != null && authentication.getAuthorities()
.containsAll(LocalSecondFactorAuthenticationToken.AUTHORITIES)) {
if (authentication.getAuthorities() != null
&& authentication.getAuthorities().containsAll(LocalSecondFactorAuthenticationToken.AUTHORITIES)) {
getRedirectStrategy().sendRedirect(request, response,
totpRedirectUrl + "?error" + (keep ? "&keep" : ""));
} else {
getRedirectStrategy().sendRedirect(request, response,
totpRedirectUrl + (keep ? "?keep" : ""));
getRedirectStrategy().sendRedirect(request, response, totpRedirectUrl + (keep ? "?keep" : ""));
}
} else {
rememberMeServices.loginSuccess(request, response, authentication);
for (RequestMatcher matcher : requestMatchers) {
if (matcher.matches(request)) {
getRedirectStrategy().sendRedirect(request, response,
request.getRequestURI() + (request.getQueryString() != null
? "?" + request.getQueryString()
: ""));
getRedirectStrategy().sendRedirect(request, response, request.getRequestURI()
+ (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
return;
}
}

View File

@ -17,9 +17,12 @@ import org.springframework.stereotype.Component;
@Component
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {
/*
* @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
* @see
* org.springframework.security.web.authentication.AuthenticationFailureHandler#
* onAuthenticationFailure(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse,
* org.springframework.security.core.AuthenticationException)
*/
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,

View File

@ -8,26 +8,32 @@ import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.security.web.authentication.RememberMeServices;
import de.bstly.we.controller.support.TokenSessionManager;
import de.bstly.we.security.SecurityConfig;
/**
* The Class RestAuthenticationSuccessHandler.
*/
@Component
public class RestAuthenticationSuccessHandler extends FormAuthenticationSuccessHandler {
/**
* Instantiates a new rest authentication success handler.
*
* @param rememberMeServices the remember me services
* @param tokenSessionManager the token session manager
*/
public RestAuthenticationSuccessHandler() {
super(SecurityConfig.KEEP_PARAM);
public RestAuthenticationSuccessHandler(RememberMeServices rememberMeServices,
TokenSessionManager tokenSessionManager) {
super(rememberMeServices, tokenSessionManager, SecurityConfig.KEEP_PARAM);
}
/*
* @see de.bstly.we.security.handler.FormAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
* @see de.bstly.we.security.handler.FormAuthenticationSuccessHandler#
* onAuthenticationSuccess(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse,
* org.springframework.security.core.Authentication)
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,

View File

@ -19,8 +19,7 @@ public class LocalAnonymousAuthenticationToken extends AnonymousAuthenticationTo
*/
private static final long serialVersionUID = 1L;
public static final String ANONYMOUS_USERNAME = "anonymous";
public static final List<GrantedAuthority> AUTHORITIES = AuthorityUtils
.createAuthorityList("ROLE_ANONYMOUS");
public static final List<GrantedAuthority> AUTHORITIES = AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");
/**
* Instantiates a new local anonymous authentication token.

View File

@ -21,8 +21,7 @@ public class LocalSecondFactorAuthenticationToken extends AbstractAuthentication
*/
private static final long serialVersionUID = 1L;
public static final String ROLE_REQUIRE_2FA = "ROLE_REQUIRE_2FA";
public static final List<GrantedAuthority> AUTHORITIES = AuthorityUtils
.createAuthorityList(ROLE_REQUIRE_2FA);
public static final List<GrantedAuthority> AUTHORITIES = AuthorityUtils.createAuthorityList(ROLE_REQUIRE_2FA);
/**
*
*/
@ -37,8 +36,7 @@ public class LocalSecondFactorAuthenticationToken extends AbstractAuthentication
* @param provider the provider
* @param code the code
*/
public LocalSecondFactorAuthenticationToken(LocalUserDetails principal, String provider,
String code) {
public LocalSecondFactorAuthenticationToken(LocalUserDetails principal, String provider, String code) {
super(AUTHORITIES);
this.principal = principal;
this.provider = provider;

View File

@ -80,12 +80,10 @@ public class EmailManager {
UserProfileField primaryEmailUserProfileField = userProfileFieldManager.get(user.getId(),
UserProfileFields.PROFILE_FIELD_EMAIL_PRIMARY);
if (primaryEmailUserProfileField != null
&& "true".equals(primaryEmailUserProfileField.getValue())) {
if (primaryEmailUserProfileField != null && "true".equals(primaryEmailUserProfileField.getValue())) {
UserProfileField emailUserProfileField = userProfileFieldManager.get(user.getId(),
UserProfileFields.PROFILE_FIELD_EMAIL);
if (emailUserProfileField != null
&& StringUtils.hasText(emailUserProfileField.getValue())) {
if (emailUserProfileField != null && StringUtils.hasText(emailUserProfileField.getValue())) {
email = emailUserProfileField.getValue();
}
}

View File

@ -54,8 +54,7 @@ public class EmailController extends BaseController {
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/test")
public MailMessage sendTest(@RequestBody String to) {
return emailManager.sendText(to, "no-reply@we.bstly.de", "Test Email",
"Test from we.bstly");
return emailManager.sendText(to, "no-reply@we.bstly.de", "Test Email", "Test from we.bstly");
}
/**
@ -80,8 +79,7 @@ public class EmailController extends BaseController {
UserProfileField localeUserProfileField = userProfileFieldManager.get(user.getId(),
UserProfileFields.PROFILE_FIELD_LOCALE);
if (localeUserProfileField != null
&& StringUtils.hasText(localeUserProfileField.getValue())) {
if (localeUserProfileField != null && StringUtils.hasText(localeUserProfileField.getValue())) {
userMailModel.setLocale(localeUserProfileField.getValue());
}
@ -91,6 +89,4 @@ public class EmailController extends BaseController {
return result;
}
}

View File

@ -13,7 +13,6 @@ import de.bstly.we.i18n.model.I18n;
* The Interface I18nRepository.
*/
@Repository
public interface I18nRepository
extends JpaRepository<I18n, String>, QuerydslPredicateExecutor<I18n> {
public interface I18nRepository extends JpaRepository<I18n, String>, QuerydslPredicateExecutor<I18n> {
}

View File

@ -70,8 +70,7 @@ public class InviteManager implements UserDataProvider {
*/
public Page<Invite> get(int page, int size, String search) {
if (StringUtils.hasText(search)) {
return inviteRepository.findAll(qInvite.note.containsIgnoreCase(search),
PageRequest.of(page, size));
return inviteRepository.findAll(qInvite.note.containsIgnoreCase(search), PageRequest.of(page, size));
}
return inviteRepository.findAll(PageRequest.of(page, size));
}
@ -99,8 +98,8 @@ public class InviteManager implements UserDataProvider {
* @param redeemed the redeemed
* @return the by owner
*/
public Page<Invite> getByOwner(Long owner, String quota, int page, int size, String sortBy,
boolean descending, String search, String redeemed) {
public Page<Invite> getByOwner(Long owner, String quota, int page, int size, String sortBy, boolean descending,
String search, String redeemed) {
PageRequest pageRequest = PageRequest.of(page, size,
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending());
@ -137,8 +136,7 @@ public class InviteManager implements UserDataProvider {
* @param redeemed the redeemed
* @return the others
*/
public Page<Invite> getOthers(Long owner, String quota, int page, int size, String search,
String redeemed) {
public Page<Invite> getOthers(Long owner, String quota, int page, int size, String search, String redeemed) {
BooleanBuilder query = new BooleanBuilder();
query.and(qInvite.owner.ne(owner));
@ -173,8 +171,7 @@ public class InviteManager implements UserDataProvider {
}
}
InviteMapping inviteMapping = inviteMappingManager.getByItemAndQuota(invite.getItem(),
invite.getQuota());
InviteMapping inviteMapping = inviteMappingManager.getByItemAndQuota(invite.getItem(), invite.getQuota());
Assert.notNull(inviteMapping, "No mapping for item!");
if (StringUtils.hasLength(inviteMapping.getCodeLink())) {
invite.setCodeLink(String.format(inviteMapping.getCodeLink(), invite.getCode()));

View File

@ -51,8 +51,7 @@ public class InviteMappingManager {
* @return the by item and quota
*/
public InviteMapping getByItemAndQuota(int item, String quota) {
return inviteMappingRepository
.findOne(qInviteMapping.item.eq(item).and(qInviteMapping.quota.eq(quota)))
return inviteMappingRepository.findOne(qInviteMapping.item.eq(item).and(qInviteMapping.quota.eq(quota)))
.orElse(null);
}
@ -98,8 +97,8 @@ public class InviteMappingManager {
*/
public InviteMapping save(InviteMapping inviteMapping) {
for (Invite invite : inviteRepository.findAll(qInvite.item.eq(inviteMapping.getItem())
.and(qInvite.quota.eq(inviteMapping.getQuota())))) {
for (Invite invite : inviteRepository
.findAll(qInvite.item.eq(inviteMapping.getItem()).and(qInvite.quota.eq(inviteMapping.getQuota())))) {
if (StringUtils.hasText(inviteMapping.getCodeLink())) {
String codeLink = String.format(inviteMapping.getCodeLink(), invite.getCode());
if (!codeLink.equals(invite.getCodeLink())) {

View File

@ -119,8 +119,8 @@ public class InviteController extends BaseController {
throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE);
}
return permissionManager.getForItem(null, invite.getItem(), new JsonArray(),
invite.getStarts(), invite.getExpires());
return permissionManager.getForItem(null, invite.getItem(), new JsonArray(), invite.getStarts(),
invite.getExpires());
}
/**
@ -162,15 +162,14 @@ public class InviteController extends BaseController {
throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE);
}
if (invite.isRedeemed()
|| invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) {
if (invite.isRedeemed() || invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) {
throw new EntityResponseStatusException(HttpStatus.GONE);
}
boolean register = false;
for (Permission permission : permissionManager.getForItem(null, invite.getItem(),
new JsonArray(), invite.getStarts(), invite.getExpires())) {
for (Permission permission : permissionManager.getForItem(null, invite.getItem(), new JsonArray(),
invite.getStarts(), invite.getExpires())) {
if (permission.getExpires().isAfter(Instant.now()) && !permission.isAddon()) {
register = true;
break;
@ -200,8 +199,7 @@ public class InviteController extends BaseController {
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
}
User user = userManager.create(userModel.getUsername(), userModel.getPassword(),
userModel.getStatus());
User user = userManager.create(userModel.getUsername(), userModel.getPassword(), userModel.getStatus());
Long userId = user.getId();
@ -218,8 +216,7 @@ public class InviteController extends BaseController {
userProfileField = userProfileFieldManager.save(userProfileField);
}
permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(),
invite.getExpires());
permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(), invite.getExpires());
quotaManager.applyItem(userId, invite.getItem());
invite.setRedeemed(true);
@ -241,15 +238,13 @@ public class InviteController extends BaseController {
throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE);
}
if (invite.isRedeemed()
|| invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) {
if (invite.isRedeemed() || invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) {
throw new EntityResponseStatusException(HttpStatus.GONE);
}
Long userId = getCurrentUserId();
permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(),
invite.getExpires());
permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(), invite.getExpires());
quotaManager.applyItem(userId, invite.getItem());
invite.setRedeemed(true);
@ -273,16 +268,14 @@ public class InviteController extends BaseController {
@GetMapping
public Page<Invite> getInvites(@RequestParam("quota") Optional<String> quotaParameter,
@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter,
@RequestParam("sort") Optional<String> sortParamater,
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("sort") Optional<String> sortParamater,
@RequestParam("desc") Optional<Boolean> descParameter,
@RequestParam("search") Optional<String> searchParameter,
@RequestParam("redeemed") Optional<String> redeemedParameter) {
return inviteManager.getByOwner(getCurrentUserId(), quotaParameter.orElse(""),
pageParameter.orElse(0), sizeParameter.orElse(10), sortParamater.orElse("id"),
descParameter.orElse(false), searchParameter.orElse(null),
redeemedParameter.orElse(null));
return inviteManager.getByOwner(getCurrentUserId(), quotaParameter.orElse(""), pageParameter.orElse(0),
sizeParameter.orElse(10), sortParamater.orElse("id"), descParameter.orElse(false),
searchParameter.orElse(null), redeemedParameter.orElse(null));
}
/**
@ -304,15 +297,13 @@ public class InviteController extends BaseController {
@RequestParam("redeemed") Optional<String> redeemedParameter) {
InviteMapping inviteMapping = inviteMappingManager.get(quota);
Quota inviteQuota = quotaManager.get(getCurrentUserId(),
InviteMapping.QUOTA_PREFIX + quota);
Quota inviteQuota = quotaManager.get(getCurrentUserId(), InviteMapping.QUOTA_PREFIX + quota);
if (inviteMapping == null || inviteQuota == null || inviteQuota.getValue() < 1) {
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
}
Page<Invite> page = inviteManager.getOthers(getCurrentUserId(), quota,
pageParameter.orElse(0), sizeParameter.orElse(10), searchParameter.orElse(null),
redeemedParameter.orElse(null));
Page<Invite> page = inviteManager.getOthers(getCurrentUserId(), quota, pageParameter.orElse(0),
sizeParameter.orElse(10), searchParameter.orElse(null), redeemedParameter.orElse(null));
for (Invite invite : page.getContent()) {
invite.setCode(null);
invite.setCodeLink(null);
@ -333,11 +324,9 @@ public class InviteController extends BaseController {
*/
@PreAuthorize("isAuthenticated()")
@PostMapping("/{quota}")
public Invite createInvite(@PathVariable("quota") String quota,
@RequestBody Invite inviteModel) {
public Invite createInvite(@PathVariable("quota") String quota, @RequestBody Invite inviteModel) {
InviteMapping inviteMapping = inviteMappingManager.get(quota);
Quota inviteQuota = quotaManager.get(getCurrentUserId(),
InviteMapping.QUOTA_PREFIX + quota);
Quota inviteQuota = quotaManager.get(getCurrentUserId(), InviteMapping.QUOTA_PREFIX + quota);
if (inviteMapping == null || inviteQuota == null || inviteQuota.getValue() < 1) {
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
}
@ -348,10 +337,8 @@ public class InviteController extends BaseController {
Invite invite = new Invite();
invite.setOwner(getCurrentUserId());
invite.setStarts(inviteMapping.getStarts() != null ? inviteMapping.getStarts()
: inviteModel.getStarts());
invite.setExpires(inviteMapping.getExpires() != null ? inviteMapping.getExpires()
: inviteModel.getExpires());
invite.setStarts(inviteMapping.getStarts() != null ? inviteMapping.getStarts() : inviteModel.getStarts());
invite.setExpires(inviteMapping.getExpires() != null ? inviteMapping.getExpires() : inviteModel.getExpires());
invite.setItem(inviteMapping.getItem());
invite.setQuota(inviteMapping.getQuota());

View File

@ -52,8 +52,7 @@ public class InviteManagingController extends BaseController {
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping
public Page<Invite> getInvites(@RequestParam("page") Optional<Integer> page,
@RequestParam("size") Optional<Integer> size,
@RequestParam("search") Optional<String> search) {
@RequestParam("size") Optional<Integer> size, @RequestParam("search") Optional<String> search) {
return inviteManager.get(page.orElse(0), size.orElse(10), search.orElse(null));
}
@ -66,8 +65,8 @@ public class InviteManagingController extends BaseController {
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping
public Invite createOrUpdate(@RequestBody Invite invite) {
if (invite.getItem() == null || inviteMappingManager.getByItemAndQuota(invite.getItem(),
invite.getQuota()) == null) {
if (invite.getItem() == null
|| inviteMappingManager.getByItemAndQuota(invite.getItem(), invite.getQuota()) == null) {
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
}

View File

@ -47,11 +47,9 @@ public class InviteMappingController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping
public Page<InviteMapping> getInviteMappings(
@RequestParam("page") Optional<Integer> pageParameter,
public Page<InviteMapping> getInviteMappings(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter) {
return inviteMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "quota",
true);
return inviteMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "quota", true);
}
/**

View File

@ -13,6 +13,5 @@ import de.bstly.we.invite.model.Invite;
* The Interface InviteRepository.
*/
@Repository
public interface InviteRepository
extends JpaRepository<Invite, Long>, QuerydslPredicateExecutor<Invite> {
public interface InviteRepository extends JpaRepository<Invite, Long>, QuerydslPredicateExecutor<Invite> {
}

View File

@ -26,6 +26,7 @@
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>9.21</version>
</dependency>
</dependencies>
</project>

View File

@ -117,8 +117,8 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro
* @return the page
*/
public Page<JitsiRoom> get(int page, int size, String sortBy, boolean descending) {
return jitsiRoomRepository.findAll(PageRequest.of(page, size,
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
return jitsiRoomRepository.findAll(
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
}
/**
@ -131,14 +131,13 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro
* @param descending the descending
* @return the for user id
*/
public Page<JitsiRoom> getForUserId(Long userId, int page, int size, String sortBy,
boolean descending) {
public Page<JitsiRoom> getForUserId(Long userId, int page, int size, String sortBy, boolean descending) {
// delete expired rooms
jitsiRoomRepository.deleteAll(jitsiRoomRepository.findAll(
qJitsiRoom.owner.eq(userId).and(qJitsiRoom.expires.before(Instant.now()))));
jitsiRoomRepository.deleteAll(
jitsiRoomRepository.findAll(qJitsiRoom.owner.eq(userId).and(qJitsiRoom.expires.before(Instant.now()))));
return jitsiRoomRepository.findAll(qJitsiRoom.owner.eq(userId), PageRequest.of(page, size,
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
return jitsiRoomRepository.findAll(qJitsiRoom.owner.eq(userId),
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
}
/**
@ -152,8 +151,8 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro
* @return the jitsi room
* @throws JOSEException the JOSE exception
*/
public JitsiRoom create(Long owner, String room, Instant starts, Instant moderationStarts,
Instant expires) throws JOSEException {
public JitsiRoom create(Long owner, String room, Instant starts, Instant moderationStarts, Instant expires)
throws JOSEException {
JitsiRoom jitsiRoom = new JitsiRoom();
jitsiRoom.setOwner(owner);
jitsiRoom.setRoom(room);
@ -190,8 +189,7 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro
bodyBuilder.notBeforeTime(Date.from(jitsiRoom.getStarts()));
}
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.HS256).type(JOSEObjectType.JWT)
.build();
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.HS256).type(JOSEObjectType.JWT).build();
SignedJWT token = new SignedJWT(jwsHeader, bodyBuilder.build());
token.sign(signer);
@ -206,15 +204,13 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro
jitsiRoom.setModerationToken(moderationToken.serialize());
jitsiRoom.setUrl(String.format(urlFormat, jitsiRoom.getRoom(), jitsiRoom.getToken()));
jitsiRoom.setModerationUrl(
String.format(urlFormat, jitsiRoom.getRoom(), jitsiRoom.getModerationToken()));
jitsiRoom.setModerationUrl(String.format(urlFormat, jitsiRoom.getRoom(), jitsiRoom.getModerationToken()));
if (StringUtils.hasText(jitsiRoom.getCode())) {
ShortenedUrl shortenedUrl = shortenedUrlManager.get(jitsiRoom.getCode());
if (shortenedUrl != null) {
shortenedUrl.setUrl(jitsiRoom.getUrl());
shortenedUrl.setNote("JitsiRoom: "
+ jitsiRoom.getRoom());
shortenedUrl.setNote("JitsiRoom: " + jitsiRoom.getRoom());
shortenedUrl.setExpires(jitsiRoom.getExpires());
shortenedUrlManager.save(shortenedUrl);
jitsiRoom.setOrgUrl(jitsiRoom.getUrl());
@ -234,10 +230,8 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro
* @return the jitsi room
*/
public JitsiRoom createShortenedUrl(JitsiRoom jitsiRoom) {
ShortenedUrl shortenedUrl = shortenedUrlManager.create(jitsiRoom.getOwner(),
jitsiRoom.getUrl(), "JitsiRoom: "
+ jitsiRoom.getRoom(),
null, jitsiRoom.getExpires(), null, false, true);
ShortenedUrl shortenedUrl = shortenedUrlManager.create(jitsiRoom.getOwner(), jitsiRoom.getUrl(),
"JitsiRoom: " + jitsiRoom.getRoom(), null, jitsiRoom.getExpires(), null, false, true);
jitsiRoom.setOrgUrl(jitsiRoom.getUrl());
jitsiRoom.setCode(shortenedUrl.getCode());
jitsiRoom.setUrl(shortenedUrl.getLink());
@ -254,8 +248,7 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro
if (quota) {
Quota jitsiRoomsQuota = quotaManager.get(jitsiRoom.getOwner(), JitsiQuotas.JITSI_MEET);
if (jitsiRoomsQuota == null) {
jitsiRoomsQuota = quotaManager.create(jitsiRoom.getOwner(), JitsiQuotas.JITSI_MEET,
0, "#", true);
jitsiRoomsQuota = quotaManager.create(jitsiRoom.getOwner(), JitsiQuotas.JITSI_MEET, 0, "#", true);
}
jitsiRoomsQuota.setValue(jitsiRoomsQuota.getValue() + 1);
@ -263,8 +256,8 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro
}
if (StringUtils.hasText(jitsiRoom.getCode())) {
ShortenedUrl shortenedUrl = shortenedUrlRepository
.findOne(qShortenedUrl.code.eq(jitsiRoom.getCode())).orElse(null);
ShortenedUrl shortenedUrl = shortenedUrlRepository.findOne(qShortenedUrl.code.eq(jitsiRoom.getCode()))
.orElse(null);
if (shortenedUrl != null) {
if (quota) {
Quota shortenedUrlsQuota = quotaManager.get(shortenedUrl.getOwner(),
@ -293,8 +286,7 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro
* @param quota the quota
*/
public void deleteAll(Long owner, boolean quota) {
List<JitsiRoom> jitsiRooms = Lists
.newArrayList(jitsiRoomRepository.findAll(qJitsiRoom.owner.eq(owner)));
List<JitsiRoom> jitsiRooms = Lists.newArrayList(jitsiRoomRepository.findAll(qJitsiRoom.owner.eq(owner)));
for (JitsiRoom jitsiRoom : jitsiRooms) {
delete(jitsiRoom, quota);
@ -336,7 +328,6 @@ public class JitsiRoomManager implements SmartInitializingSingleton, UserDataPro
*/
@Scheduled(cron = "0 */5 * * * *")
protected void clearExpiredRooms() {
jitsiRoomRepository
.deleteAll(jitsiRoomRepository.findAll(qJitsiRoom.expires.before(Instant.now())));
jitsiRoomRepository.deleteAll(jitsiRoomRepository.findAll(qJitsiRoom.expires.before(Instant.now())));
}
}

View File

@ -25,9 +25,9 @@ public class UrlShortenerSync implements ApplicationListener<AbstractModelEvent>
private JitsiRoomRepository jitsiRoomRepository;
private QJitsiRoom qJitsiRoom = QJitsiRoom.jitsiRoom;
/*
* @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent)
* @see org.springframework.context.ApplicationListener#onApplicationEvent(org.
* springframework.context.ApplicationEvent)
*/
@Override
public void onApplicationEvent(AbstractModelEvent event) {
@ -35,8 +35,8 @@ public class UrlShortenerSync implements ApplicationListener<AbstractModelEvent>
if (AbstractModelEventType.PRE_REMOVE.equals(event.getType())) {
ShortenedUrl shortenedUrl = (ShortenedUrl) event.getModel();
JitsiRoom jitsiRoom = jitsiRoomRepository
.findOne(qJitsiRoom.code.eq(shortenedUrl.getCode())).orElse(null);
JitsiRoom jitsiRoom = jitsiRoomRepository.findOne(qJitsiRoom.code.eq(shortenedUrl.getCode()))
.orElse(null);
if (jitsiRoom != null) {
jitsiRoom.setUrl(jitsiRoom.getOrgUrl());
jitsiRoom.setCode(null);
@ -45,8 +45,8 @@ public class UrlShortenerSync implements ApplicationListener<AbstractModelEvent>
}
} else if (AbstractModelEventType.POST_UPDATE.equals(event.getType())) {
ShortenedUrl shortenedUrl = (ShortenedUrl) event.getModel();
JitsiRoom jitsiRoom = jitsiRoomRepository
.findOne(qJitsiRoom.code.eq(shortenedUrl.getCode())).orElse(null);
JitsiRoom jitsiRoom = jitsiRoomRepository.findOne(qJitsiRoom.code.eq(shortenedUrl.getCode()))
.orElse(null);
if (jitsiRoom != null) {
if (!StringUtils.hasText(jitsiRoom.getOrgUrl())) {
jitsiRoom.setOrgUrl(jitsiRoom.getUrl());

View File

@ -65,16 +65,15 @@ public class JitsiRoomController extends BaseController {
@PreAuthorize("isAuthenticated()")
@GetMapping
public Page<JitsiRoom> getJitsiRooms(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter,
@RequestParam("sort") Optional<String> sortParameter,
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("sort") Optional<String> sortParameter,
@RequestParam("desc") Optional<Boolean> descParameter) {
if (!permissionManager.hasPermission(getCurrentUserId(), JitsiPermissions.JITSI_MEET)) {
jitsiRoomManager.deleteAll(getCurrentUserId(), false);
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
}
return jitsiRoomManager.getForUserId(getCurrentUserId(), pageParameter.orElse(0),
sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false));
return jitsiRoomManager.getForUserId(getCurrentUserId(), pageParameter.orElse(0), sizeParameter.orElse(10),
sortParameter.orElse("id"), descParameter.orElse(false));
}
/**
@ -115,8 +114,8 @@ public class JitsiRoomController extends BaseController {
jitsiRoomsQuota = quotaManager.update(jitsiRoomsQuota);
try {
return jitsiRoomManager.create(jitsiRoom.getOwner(), jitsiRoom.getRoom(),
jitsiRoom.getStarts(), jitsiRoom.getModerationStarts(), jitsiRoom.getExpires());
return jitsiRoomManager.create(jitsiRoom.getOwner(), jitsiRoom.getRoom(), jitsiRoom.getStarts(),
jitsiRoom.getModerationStarts(), jitsiRoom.getExpires());
} catch (JOSEException e) {
jitsiRoomsQuota.setValue(jitsiRoomsQuota.getValue() - 1);
jitsiRoomsQuota = quotaManager.update(jitsiRoomsQuota);
@ -182,14 +181,12 @@ public class JitsiRoomController extends BaseController {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
}
if (!permissionManager.hasPermission(getCurrentUserId(),
ShortenedUrlPermissions.URL_SHORTENER)
if (!permissionManager.hasPermission(getCurrentUserId(), ShortenedUrlPermissions.URL_SHORTENER)
|| !permissionManager.isFullUser(getCurrentUserId())) {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
}
Quota shortenedUrlsQuota = quotaManager.get(getCurrentUserId(),
ShortenedUrlQuotas.URL_SHORTENER);
Quota shortenedUrlsQuota = quotaManager.get(getCurrentUserId(), ShortenedUrlQuotas.URL_SHORTENER);
if (shortenedUrlsQuota == null || shortenedUrlsQuota.getValue() < 1) {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
}

View File

@ -85,8 +85,7 @@ public class JitsiRoomManagementController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@DeleteMapping("/{id}")
public void deleteJitsiRoom(@PathVariable("id") Long id,
@RequestParam("quota") Optional<Boolean> quota) {
public void deleteJitsiRoom(@PathVariable("id") Long id, @RequestParam("quota") Optional<Boolean> quota) {
JitsiRoom jitsiRoom = jitsiRoomManager.get(id);
if (jitsiRoom == null) {
@ -104,8 +103,7 @@ public class JitsiRoomManagementController extends BaseController {
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@DeleteMapping("/all/{owner}")
public void deleteAll(@PathVariable("owner") Long owner,
@RequestParam("quota") Optional<Boolean> quota) {
public void deleteAll(@PathVariable("owner") Long owner, @RequestParam("quota") Optional<Boolean> quota) {
jitsiRoomManager.deleteAll(owner, quota.isPresent() && quota.get().booleanValue());
}

View File

@ -100,10 +100,8 @@ public class JitsiRoomValidator implements Validator {
* @param errors the errors
*/
public void validateRoom(String roomName, Errors errors) {
for (String systemRoomName : systemPropertyManager.get(RESERVED_JITSI_ROOMS, "")
.split(",")) {
if (StringUtils.hasText(systemRoomName)
&& (roomName.toLowerCase().equals(systemRoomName)
for (String systemRoomName : systemPropertyManager.get(RESERVED_JITSI_ROOMS, "").split(",")) {
if (StringUtils.hasText(systemRoomName) && (roomName.toLowerCase().equals(systemRoomName)
|| roomName.toLowerCase().matches(systemRoomName))) {
errors.rejectValue("room", "NOT_VALID");
return;
@ -124,13 +122,11 @@ public class JitsiRoomValidator implements Validator {
}
if (jitsiRoom.getModerationStarts() != null) {
jitsiRoom.setModerationStarts(
InstantHelper.truncate(jitsiRoom.getModerationStarts(), ChronoUnit.SECONDS));
jitsiRoom.setModerationStarts(InstantHelper.truncate(jitsiRoom.getModerationStarts(), ChronoUnit.SECONDS));
}
if (jitsiRoom.getExpires() != null) {
jitsiRoom
.setExpires(InstantHelper.truncate(jitsiRoom.getExpires(), ChronoUnit.SECONDS));
jitsiRoom.setExpires(InstantHelper.truncate(jitsiRoom.getExpires(), ChronoUnit.SECONDS));
}
// no moderation start without start
@ -151,8 +147,7 @@ public class JitsiRoomValidator implements Validator {
// exlude self
.and(qJitsiRoom.id.ne(jitsiRoom.getId() == null ? -1L : jitsiRoom.getId()))
// expires null or after now
.and(qJitsiRoom.expires.isNull()
.or(qJitsiRoom.expires.after(Instant.now()))))) {
.and(qJitsiRoom.expires.isNull().or(qJitsiRoom.expires.after(Instant.now()))))) {
errors.rejectValue("room", "NOT_VALID");
}
} else
@ -164,8 +159,7 @@ public class JitsiRoomValidator implements Validator {
// expires null or after now
.and(qJitsiRoom.expires.isNull().or(qJitsiRoom.expires.after(Instant.now())))
// start null or before expires
.and(qJitsiRoom.starts.isNull()
.or(qJitsiRoom.starts.before(jitsiRoom.getExpires()))))) {
.and(qJitsiRoom.starts.isNull().or(qJitsiRoom.starts.before(jitsiRoom.getExpires()))))) {
errors.rejectValue("expires", "NOT_VALID");
}
}
@ -176,22 +170,22 @@ public class JitsiRoomValidator implements Validator {
.and(qJitsiRoom.id.ne(jitsiRoom.getId() == null ? -1L : jitsiRoom.getId()))
// expires null or after room start
.and(qJitsiRoom.expires.isNull()
.or(qJitsiRoom.expires.after(jitsiRoom.getModerationStarts() != null
? jitsiRoom.getModerationStarts()
.or(qJitsiRoom.expires
.after(jitsiRoom.getModerationStarts() != null ? jitsiRoom.getModerationStarts()
: jitsiRoom.getStarts()))))) {
errors.rejectValue("starts", "NOT_VALID");
}
} else
// expiry + start
if (jitsiRoom.getExpires() != null && jitsiRoom.getStarts() != null) {
if (jitsiRoom.getStarts().isAfter(jitsiRoom.getExpires())
|| jitsiRoomRepository.exists(qJitsiRoom.room.eq(jitsiRoom.getRoom())
if (jitsiRoom.getStarts().isAfter(jitsiRoom
.getExpires()) || jitsiRoomRepository.exists(
qJitsiRoom.room.eq(jitsiRoom.getRoom())
// exlude self
.and(qJitsiRoom.id
.ne(jitsiRoom.getId() == null ? -1L : jitsiRoom.getId()))
.and(qJitsiRoom.id.ne(jitsiRoom.getId() == null ? -1L : jitsiRoom.getId()))
// expires null or after room start
.and(qJitsiRoom.expires.isNull().or(
qJitsiRoom.expires.after(jitsiRoom.getModerationStarts() != null
.and(qJitsiRoom.expires.isNull()
.or(qJitsiRoom.expires.after(jitsiRoom.getModerationStarts() != null
? jitsiRoom.getModerationStarts()
: jitsiRoom.getStarts())))
// start null or before expires

View File

@ -13,6 +13,5 @@ import de.bstly.we.jitsi.model.JitsiRoom;
* The Interface JitsiRoomRepository.
*/
@Repository
public interface JitsiRoomRepository
extends JpaRepository<JitsiRoom, Long>, QuerydslPredicateExecutor<JitsiRoom> {
public interface JitsiRoomRepository extends JpaRepository<JitsiRoom, Long>, QuerydslPredicateExecutor<JitsiRoom> {
}

View File

@ -21,6 +21,7 @@
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>9.21</version>
</dependency>
</dependencies>
</project>

View File

@ -97,8 +97,8 @@ public class JwtKeyManager {
*/
@Transactional
public JwtKey getLatest(String name, boolean createDefault) {
List<JwtKey> jwtKeys = Lists.newArrayList(jwtKeyRepository.findAll(qJwtKey.name.eq(name),
PageRequest.of(0, 1, Sort.by(Order.desc("created")))));
List<JwtKey> jwtKeys = Lists.newArrayList(
jwtKeyRepository.findAll(qJwtKey.name.eq(name), PageRequest.of(0, 1, Sort.by(Order.desc("created")))));
JwtKey jwtKey = null;
@ -107,8 +107,8 @@ public class JwtKeyManager {
}
if (jwtKey != null) {
if (jwtKey.getLifetime() == -1L || jwtKey.getExpires()
.isAfter(Instant.now().plus(jwtKey.getLifetime(), ChronoUnit.SECONDS))) {
if (jwtKey.getLifetime() == -1L
|| jwtKey.getExpires().isAfter(Instant.now().plus(jwtKey.getLifetime(), ChronoUnit.SECONDS))) {
return jwtKey;
}
@ -150,7 +150,8 @@ public class JwtKeyManager {
@Transactional
public JwtKey getByCreated(String name, Instant created) {
return jwtKeyRepository
.findOne(qJwtKey.name.eq(name)
.findOne(
qJwtKey.name.eq(name)
.and(qJwtKey.created.before(created)
.and(qJwtKey.lifetime.eq(-1L).or(qJwtKey.expires.after(created)))))
.orElse(null);
@ -171,8 +172,8 @@ public class JwtKeyManager {
try {
KeyType keyType = KeyType.parse(jwtKey.getKeyType());
if (KeyType.EC.equals(keyType)) {
jwk = new ECKeyGenerator(Curve.parse(jwtKey.getKeyParameter()))
.keyUse(KeyUse.parse(jwtKey.getKeyUse())).keyID(keyID).generate();
jwk = new ECKeyGenerator(Curve.parse(jwtKey.getKeyParameter())).keyUse(KeyUse.parse(jwtKey.getKeyUse()))
.keyID(keyID).generate();
} else if (KeyType.OCT.equals(keyType)) {
jwk = new OctetKeyPairGenerator(Curve.parse(jwtKey.getKeyParameter()))
.keyUse(KeyUse.parse(jwtKey.getKeyUse())).keyID(keyID).generate();

View File

@ -46,8 +46,7 @@ public class JwtUserManager {
* @return the signed JWT
* @throws JOSEException the JOSE exception
*/
public SignedJWT createSignedJwt(Long userId, Object data, String issuer, Long lifetime)
throws JOSEException {
public SignedJWT createSignedJwt(Long userId, Object data, String issuer, Long lifetime) throws JOSEException {
User user = userManager.get(userId);
if (user == null) {
@ -61,8 +60,7 @@ public class JwtUserManager {
claimsSetBuilder.issueTime(new Date());
if (lifetime != null && lifetime > 0) {
claimsSetBuilder
.expirationTime(Date.from(Instant.now().plus(lifetime, ChronoUnit.SECONDS)));
claimsSetBuilder.expirationTime(Date.from(Instant.now().plus(lifetime, ChronoUnit.SECONDS)));
}
if (data != null) {
@ -71,8 +69,7 @@ public class JwtUserManager {
JwtKey jwtKey = jwtKeyManager.getLatest(JWT_USER_DATA_KEY_NAME, true);
JWSHeader.Builder headerBuilder = new JWSHeader.Builder(
jwtKeyManager.getJwsAlgorithm(jwtKey));
JWSHeader.Builder headerBuilder = new JWSHeader.Builder(jwtKeyManager.getJwsAlgorithm(jwtKey));
headerBuilder.keyID(jwtKey.getKeyID());
headerBuilder.type(JOSEObjectType.JWT);

View File

@ -50,17 +50,13 @@ public class JwtUserDataController extends BaseController {
public String createSignedJwtAuth(HttpServletRequest request) {
String issuer = jwtUserIssuer;
if (!StringUtils.hasText(issuer)) {
issuer = request.getScheme()
+ "://"
+ request.getServerName();
issuer = request.getScheme() + "://" + request.getServerName();
if (request.getServerPort() != 443 && request.getServerPort() != 80) {
issuer += ":"
+ request.getServerPort();
issuer += ":" + request.getServerPort();
}
}
try {
return jwtUserDataManager.createSignedJwt(getCurrentUserId(), null, issuer, 120L)
.serialize();
return jwtUserDataManager.createSignedJwt(getCurrentUserId(), null, issuer, 120L).serialize();
} catch (JOSEException e) {
e.printStackTrace();
throw new EntityResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
@ -79,17 +75,13 @@ public class JwtUserDataController extends BaseController {
public String createSignedJwt(@RequestBody Object data, HttpServletRequest request) {
String issuer = jwtUserIssuer;
if (!StringUtils.hasText(issuer)) {
issuer = request.getScheme()
+ "://"
+ request.getServerName();
issuer = request.getScheme() + "://" + request.getServerName();
if (request.getServerPort() != 443 && request.getServerPort() != 80) {
issuer += ":"
+ request.getServerPort();
issuer += ":" + request.getServerPort();
}
}
try {
return jwtUserDataManager.createSignedJwt(getCurrentUserId(), data, issuer, -1L)
.serialize();
return jwtUserDataManager.createSignedJwt(getCurrentUserId(), data, issuer, -1L).serialize();
} catch (JOSEException e) {
e.printStackTrace();
throw new EntityResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
@ -105,8 +97,7 @@ public class JwtUserDataController extends BaseController {
* @return the object
*/
@PostMapping("verify")
public Object verfiy(@RequestBody String serialized, HttpServletRequest request,
HttpServletResponse response) {
public Object verfiy(@RequestBody String serialized, HttpServletRequest request, HttpServletResponse response) {
try {
SignedJWT signedJwt = SignedJWT.parse(serialized);
if (jwtUserDataManager.verify(signedJwt)) {

View File

@ -13,6 +13,5 @@ import de.bstly.we.jwt.model.JwtKey;
* The Interface JwtKeyRepository.
*/
@Repository
public interface JwtKeyRepository
extends JpaRepository<JwtKey, Long>, QuerydslPredicateExecutor<JwtKey> {
public interface JwtKeyRepository extends JpaRepository<JwtKey, Long>, QuerydslPredicateExecutor<JwtKey> {
}

Some files were not shown because too many files have changed in this diff Show More