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

@ -20,7 +20,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication @SpringBootApplication
@EnableScheduling @EnableScheduling
public class Application extends SpringBootServletInitializer { public class Application extends SpringBootServletInitializer {
/** /**
* The main method. * The main method.
* *
@ -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 @Override
public void onStartup(ServletContext servletContext) throws ServletException { public void onStartup(ServletContext servletContext) throws ServletException {

View File

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

View File

@ -68,69 +68,65 @@ public class BorrowRequestManager implements UserDataProvider {
/** /**
* Gets the for user. * Gets the for user.
* *
* @param userId the user id * @param userId the user id
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param sortBy the sort by * @param sortBy the sort by
* @param descending the descending * @param descending the descending
* @return the for user * @return the for user
*/ */
public Page<BorrowRequest> getForUser(Long userId, int page, int size, String sortBy, public Page<BorrowRequest> getForUser(Long userId, int page, int size, String sortBy, boolean descending) {
boolean descending) { return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId),
return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId), PageRequest.of(page, PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
} }
/** /**
* Gets the for user and status. * Gets the for user and status.
* *
* @param userId the user id * @param userId the user id
* @param status the status * @param status the status
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param sortBy the sort by * @param sortBy the sort by
* @param descending the descending * @param descending the descending
* @return the for user and status * @return the for user and status
*/ */
public Page<BorrowRequest> getForUserAndStatus(Long userId, BorrowRequestStatus status, public Page<BorrowRequest> getForUserAndStatus(Long userId, BorrowRequestStatus status, int page, int size,
int page, int size, String sortBy, boolean descending) { String sortBy, boolean descending) {
return borrowRequestRepository.findAll( return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId).and(qBorrowRequest.status.eq(status)),
qBorrowRequest.user.eq(userId).and(qBorrowRequest.status.eq(status)), PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
PageRequest.of(page, size,
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
} }
/** /**
* Gets the for owner. * Gets the for owner.
* *
* @param userId the user id * @param userId the user id
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param sortBy the sort by * @param sortBy the sort by
* @param descending the descending * @param descending the descending
* @return the for owner * @return the for owner
*/ */
public Page<BorrowRequest> getForOwner(Long userId, int page, int size, String sortBy, public Page<BorrowRequest> getForOwner(Long userId, int page, int size, String sortBy, boolean descending) {
boolean descending) { return borrowRequestRepository.findAllByOwner(userId,
return borrowRequestRepository.findAllByOwner(userId, PageRequest.of(page, size, PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
} }
/** /**
* Gets the for owner and status. * Gets the for owner and status.
* *
* @param userId the user id * @param userId the user id
* @param status the status * @param status the status
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param sortBy the sort by * @param sortBy the sort by
* @param descending the descending * @param descending the descending
* @return the for owner and status * @return the for owner and status
*/ */
public Page<BorrowRequest> getForOwnerAndStatus(Long userId, BorrowRequestStatus status, public Page<BorrowRequest> getForOwnerAndStatus(Long userId, BorrowRequestStatus status, int page, int size,
int page, int size, String sortBy, boolean descending) { String sortBy, boolean descending) {
return borrowRequestRepository.findAllByOwnerAndStatus(userId, status, PageRequest.of(page, return borrowRequestRepository.findAllByOwnerAndStatus(userId, status,
size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending())); PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
} }
/** /**
@ -165,7 +161,7 @@ public class BorrowRequestManager implements UserDataProvider {
* Creates the code. * Creates the code.
* *
* @param borrowRequest the borrow request * @param borrowRequest the borrow request
* @param issuer the issuer * @param issuer the issuer
* @return the signed JWT * @return the signed JWT
* @throws JOSEException the JOSE exception * @throws JOSEException the JOSE exception
*/ */
@ -207,8 +203,7 @@ public class BorrowRequestManager implements UserDataProvider {
JwtKey jwtKey = jwtKeyManager.getLatest(JWT_BORROW_KEY_NAME, true); JwtKey jwtKey = jwtKeyManager.getLatest(JWT_BORROW_KEY_NAME, true);
JWSHeader.Builder headerBuilder = new JWSHeader.Builder( JWSHeader.Builder headerBuilder = new JWSHeader.Builder(jwtKeyManager.getJwsAlgorithm(jwtKey));
jwtKeyManager.getJwsAlgorithm(jwtKey));
headerBuilder.keyID(jwtKey.getKeyID()); headerBuilder.keyID(jwtKey.getKeyID());
headerBuilder.type(JOSEObjectType.JWT); headerBuilder.type(JOSEObjectType.JWT);
@ -222,7 +217,7 @@ public class BorrowRequestManager implements UserDataProvider {
* *
* @param jwt the jwt * @param jwt the jwt
* @return true, if successful * @return true, if successful
* @throws JOSEException the JOSE exception * @throws JOSEException the JOSE exception
* @throws ParseException the parse exception * @throws ParseException the parse exception
*/ */
public boolean verify(SignedJWT jwt) throws JOSEException, ParseException { public boolean verify(SignedJWT jwt) throws JOSEException, ParseException {
@ -233,9 +228,7 @@ public class BorrowRequestManager implements UserDataProvider {
JwtKey jwtKey = jwtKeyManager.getByKeyID(jwt.getHeader().getKeyID()); JwtKey jwtKey = jwtKeyManager.getByKeyID(jwt.getHeader().getKeyID());
if (jwtKey == null) { if (jwtKey == null) {
throw new KeySourceException("No key found for given KeyID! (" throw new KeySourceException("No key found for given KeyID! (" + jwt.getHeader().getKeyID() + ")");
+ jwt.getHeader().getKeyID()
+ ")");
} }
if (jwt.getJWTClaimsSet() == null) { if (jwt.getJWTClaimsSet() == null) {
@ -259,14 +252,13 @@ public class BorrowRequestManager implements UserDataProvider {
@Override @Override
public List<UserData> getUserData(Long userId) { public List<UserData> getUserData(Long userId) {
List<UserData> result = Lists.newArrayList(); List<UserData> result = Lists.newArrayList();
Iterator<BorrowRequest> userRequests = borrowRequestRepository Iterator<BorrowRequest> userRequests = borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId))
.findAll(qBorrowRequest.user.eq(userId)).iterator(); .iterator();
while (userRequests.hasNext()) { while (userRequests.hasNext()) {
result.add(userRequests.next()); result.add(userRequests.next());
} }
Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId) Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId).iterator();
.iterator();
while (ownerRequests.hasNext()) { while (ownerRequests.hasNext()) {
result.add(ownerRequests.next()); result.add(ownerRequests.next());
} }
@ -279,14 +271,13 @@ public class BorrowRequestManager implements UserDataProvider {
*/ */
@Override @Override
public void purgeUserData(Long userId) { public void purgeUserData(Long userId) {
Iterator<BorrowRequest> userRequests = borrowRequestRepository Iterator<BorrowRequest> userRequests = borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId))
.findAll(qBorrowRequest.user.eq(userId)).iterator(); .iterator();
while (userRequests.hasNext()) { while (userRequests.hasNext()) {
delete(userRequests.next()); delete(userRequests.next());
} }
Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId) Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId).iterator();
.iterator();
while (ownerRequests.hasNext()) { while (ownerRequests.hasNext()) {
delete(ownerRequests.next()); delete(ownerRequests.next());
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -33,7 +33,7 @@ public interface BorrowRequestRepository
/** /**
* Find all by owner. * Find all by owner.
* *
* @param owner the owner * @param owner the owner
* @param pageable the pageable * @param pageable the pageable
* @return the page * @return the page
*/ */
@ -43,13 +43,13 @@ public interface BorrowRequestRepository
/** /**
* Find all by owner and status. * Find all by owner and status.
* *
* @param owner the owner * @param owner the owner
* @param status the status * @param status the status
* @param pageable the pageable * @param pageable the pageable
* @return the page * @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") @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, Page<BorrowRequest> findAllByOwnerAndStatus(@Param("owner") Long owner, @Param("status") BorrowRequestStatus status,
@Param("status") BorrowRequestStatus status, Pageable pageable); Pageable pageable);
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -33,13 +33,12 @@ public class QuotaManager implements UserDataProvider {
* Gets the. * Gets the.
* *
* @param target the target * @param target the target
* @param name the name * @param name the name
* @return the quota * @return the quota
*/ */
public Quota get(Long target, String name) { public Quota get(Long target, String name) {
if (target != null && name != null) { if (target != null && name != null) {
return quotaRepository.findOne(qQuota.name.eq(name).and(qQuota.target.eq(target))) return quotaRepository.findOne(qQuota.name.eq(name).and(qQuota.target.eq(target))).orElse(null);
.orElse(null);
} }
return null; return null;
} }
@ -75,8 +74,7 @@ public class QuotaManager implements UserDataProvider {
*/ */
public List<Quota> getNotExpiresByTarget(Long target) { public List<Quota> getNotExpiresByTarget(Long target) {
if (target != null) { if (target != null) {
return Lists.newArrayList( return Lists.newArrayList(quotaRepository.findAll(qQuota.target.eq(target).and(qQuota.value.gt(0))));
quotaRepository.findAll(qQuota.target.eq(target).and(qQuota.value.gt(0))));
} }
return Lists.newArrayList(); return Lists.newArrayList();
} }
@ -85,21 +83,21 @@ public class QuotaManager implements UserDataProvider {
* Checks for quota. * Checks for quota.
* *
* @param target the target * @param target the target
* @param name the name * @param name the name
* @return true, if successful * @return true, if successful
*/ */
public boolean hasQuota(Long target, String name) { public boolean hasQuota(Long target, String name) {
return target != null && quotaRepository return target != null
.exists(qQuota.name.eq(name).and(qQuota.target.eq(target)).and(qQuota.value.gt(0))); && quotaRepository.exists(qQuota.name.eq(name).and(qQuota.target.eq(target)).and(qQuota.value.gt(0)));
} }
/** /**
* Creates the. * Creates the.
* *
* @param target the target * @param target the target
* @param name the name * @param name the name
* @param value the value * @param value the value
* @param unit the unit * @param unit the unit
* @param disposable the disposable * @param disposable the disposable
* @return the quota * @return the quota
*/ */
@ -121,17 +119,10 @@ public class QuotaManager implements UserDataProvider {
* @return the quota * @return the quota
*/ */
public Quota update(Quota quota) { public Quota update(Quota quota) {
Assert.isTrue( Assert.isTrue(quotaRepository.exists(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))),
quotaRepository.exists( "Quota '" + quota.getName() + "' for target + '" + quota.getTarget() + "' not exists!");
qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))),
"Quota '"
+ quota.getName()
+ "' for target + '"
+ quota.getTarget()
+ "' not exists!");
Quota updateQuota = quotaRepository Quota updateQuota = quotaRepository
.findOne(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))) .findOne(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))).get();
.get();
updateQuota.setValue(quota.getValue()); updateQuota.setValue(quota.getValue());
updateQuota.setUnit(quota.getUnit()); updateQuota.setUnit(quota.getUnit());
updateQuota.setDisposable(quota.isDisposable()); updateQuota.setDisposable(quota.isDisposable());
@ -141,7 +132,7 @@ public class QuotaManager implements UserDataProvider {
/** /**
* Clone. * Clone.
* *
* @param name the name * @param name the name
* @param clone the clone * @param clone the clone
* @param value the value * @param value the value
* @return the list * @return the list
@ -150,10 +141,9 @@ public class QuotaManager implements UserDataProvider {
List<Quota> quotas = Lists.newArrayList(); List<Quota> quotas = Lists.newArrayList();
for (Quota quota : quotaRepository.findAll(qQuota.name.eq(name))) { for (Quota quota : quotaRepository.findAll(qQuota.name.eq(name))) {
if (!quotaRepository if (!quotaRepository.exists(qQuota.name.eq(clone).and(qQuota.target.eq(quota.getTarget())))) {
.exists(qQuota.name.eq(clone).and(qQuota.target.eq(quota.getTarget())))) { quotas.add(create(quota.getTarget(), clone, value >= 0 ? value : quota.getValue(), quota.getUnit(),
quotas.add(create(quota.getTarget(), clone, value >= 0 ? value : quota.getValue(), quota.isDisposable()));
quota.getUnit(), quota.isDisposable()));
} }
} }
@ -164,17 +154,12 @@ public class QuotaManager implements UserDataProvider {
* Delete. * Delete.
* *
* @param target the target * @param target the target
* @param name the name * @param name the name
*/ */
public void delete(Long target, String name) { public void delete(Long target, String name) {
Assert.isTrue(quotaRepository.exists(qQuota.target.eq(target).and(qQuota.name.eq(name))), Assert.isTrue(quotaRepository.exists(qQuota.target.eq(target).and(qQuota.name.eq(name))),
"Quota '" "Quota '" + name + "' for target + '" + target + "' not exists!");
+ name Quota delete = quotaRepository.findOne(qQuota.target.eq(target).and(qQuota.name.eq(name))).get();
+ "' for target + '"
+ target
+ "' not exists!");
Quota delete = quotaRepository.findOne(qQuota.target.eq(target).and(qQuota.name.eq(name)))
.get();
quotaRepository.delete(delete); quotaRepository.delete(delete);
} }
@ -200,7 +185,7 @@ public class QuotaManager implements UserDataProvider {
* Adds the for item. * Adds the for item.
* *
* @param target the target * @param target the target
* @param item the item * @param item the item
* @param quotas the quotas * @param quotas the quotas
*/ */
public void addForItem(Long target, Integer item, List<Quota> quotas) { public void addForItem(Long target, Integer item, List<Quota> quotas) {
@ -208,9 +193,8 @@ public class QuotaManager implements UserDataProvider {
boolean added = false; boolean added = false;
for (Quota quota : quotas) { for (Quota quota : quotas) {
if (quota.getName().equals(quotaMapping.getName())) { if (quota.getName().equals(quotaMapping.getName())) {
quota.setValue( quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() : quotaMapping.getValue());
: quotaMapping.getValue());
added = true; added = true;
} }
} }
@ -219,9 +203,8 @@ public class QuotaManager implements UserDataProvider {
if (target != null && hasQuota(target, quotaMapping.getName())) { if (target != null && hasQuota(target, quotaMapping.getName())) {
Quota quota = get(target, quotaMapping.getName()); Quota quota = get(target, quotaMapping.getName());
quota.setValue( quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() : quotaMapping.getValue());
: quotaMapping.getValue());
quotas.add(quota); quotas.add(quota);
added = true; added = true;
@ -242,18 +225,18 @@ public class QuotaManager implements UserDataProvider {
* Apply item. * Apply item.
* *
* @param target the target * @param target the target
* @param item the item * @param item the item
*/ */
public void applyItem(Long target, Integer item) { public void applyItem(Long target, Integer item) {
for (QuotaMapping quotaMapping : quotaMappingManager.getAllByItem(item)) { for (QuotaMapping quotaMapping : quotaMappingManager.getAllByItem(item)) {
Quota quota = get(target, quotaMapping.getName()); Quota quota = get(target, quotaMapping.getName());
if (quota == null) { if (quota == null) {
quota = create(target, quotaMapping.getName(), quotaMapping.getValue(), quota = create(target, quotaMapping.getName(), quotaMapping.getValue(), quotaMapping.getUnit(),
quotaMapping.getUnit(), quotaMapping.isDisposable()); quotaMapping.isDisposable());
} else { } else {
quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() quota.setValue(
: quotaMapping.getValue()); quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() : quotaMapping.getValue());
quota = update(quota); quota = update(quota);
} }

View File

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

View File

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

View File

@ -44,9 +44,9 @@ public class SystemProfileFieldManager {
/** /**
* Gets the. * Gets the.
* *
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param sortBy the sort by * @param sortBy the sort by
* @param descending the descending * @param descending the descending
* @return the page * @return the page
*/ */

View File

@ -42,13 +42,12 @@ public class SystemPropertyManager {
/** /**
* Gets the. * Gets the.
* *
* @param key the key * @param key the key
* @param defaultValue the default value * @param defaultValue the default value
* @return the string * @return the string
*/ */
public String get(String key, String defaultValue) { public String get(String key, String defaultValue) {
return systemPropertyRepository.findById(key).orElse(new SystemProperty(key, defaultValue)) return systemPropertyRepository.findById(key).orElse(new SystemProperty(key, defaultValue)).getValue();
.getValue();
} }
/** /**
@ -64,7 +63,7 @@ public class SystemPropertyManager {
/** /**
* Gets the boolean. * Gets the boolean.
* *
* @param key the key * @param key the key
* @param defaultValue the default value * @param defaultValue the default value
* @return the boolean * @return the boolean
*/ */
@ -85,7 +84,7 @@ public class SystemPropertyManager {
/** /**
* Gets the integer. * Gets the integer.
* *
* @param key the key * @param key the key
* @param defaultValue the default value * @param defaultValue the default value
* @return the integer * @return the integer
*/ */
@ -106,7 +105,7 @@ public class SystemPropertyManager {
/** /**
* Gets the long. * Gets the long.
* *
* @param key the key * @param key the key
* @param defaultValue the default value * @param defaultValue the default value
* @return the long * @return the long
*/ */
@ -117,7 +116,7 @@ public class SystemPropertyManager {
/** /**
* Adds the. * Adds the.
* *
* @param key the key * @param key the key
* @param value the value * @param value the value
*/ */
public void add(String key, String value) { public void add(String key, String value) {
@ -129,7 +128,7 @@ public class SystemPropertyManager {
/** /**
* Update. * Update.
* *
* @param key the key * @param key the key
* @param value the value * @param value the value
*/ */
public void update(String key, String value) { public void update(String key, String value) {
@ -143,7 +142,7 @@ public class SystemPropertyManager {
/** /**
* Sets the. * Sets the.
* *
* @param key the key * @param key the key
* @param value the value * @param value the value
*/ */
public void set(String key, String value) { public void set(String key, String value) {

View File

@ -89,9 +89,9 @@ public class UserAliasManager implements UserDataProvider {
/** /**
* Gets the. * Gets the.
* *
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param sortBy the sort by * @param sortBy the sort by
* @param descending the descending * @param descending the descending
* @return the page * @return the page
*/ */

View File

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

View File

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

View File

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

View File

@ -32,13 +32,12 @@ public class UserProfileFieldManager implements UserDataProvider {
* Gets the. * Gets the.
* *
* @param target the target * @param target the target
* @param name the name * @param name the name
* @return the user profile field * @return the user profile field
*/ */
public UserProfileField get(Long target, String name) { public UserProfileField get(Long target, String name) {
return userProfileFieldRepository return userProfileFieldRepository
.findOne(qUserProfileField.name.eq(name).and(qUserProfileField.target.eq(target))) .findOne(qUserProfileField.name.eq(name).and(qUserProfileField.target.eq(target))).orElse(null);
.orElse(null);
} }
/** /**
@ -48,15 +47,15 @@ public class UserProfileFieldManager implements UserDataProvider {
* @return the all by target * @return the all by target
*/ */
public List<UserProfileField> getAllByTarget(Long target) { public List<UserProfileField> getAllByTarget(Long target) {
return Lists.newArrayList(userProfileFieldRepository.findAll( return Lists.newArrayList(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target),
qUserProfileField.target.eq(target), Sort.by("index", "name").ascending())); Sort.by("index", "name").ascending()));
} }
/** /**
* Gets the by target filtered. * Gets the by target filtered.
* *
* @param target the target * @param target the target
* @param names the names * @param names the names
* @return the by target filtered * @return the by target filtered
*/ */
public List<UserProfileField> getByTargetFiltered(Long target, List<String> names) { public List<UserProfileField> getByTargetFiltered(Long target, List<String> names) {
@ -68,15 +67,13 @@ public class UserProfileFieldManager implements UserDataProvider {
/** /**
* Gets the all by target and visibilities. * Gets the all by target and visibilities.
* *
* @param target the target * @param target the target
* @param visibilities the visibilities * @param visibilities the visibilities
* @return the all by target and visibilities * @return the all by target and visibilities
*/ */
public List<UserProfileField> getAllByTargetAndVisibilities(Long target, public List<UserProfileField> getAllByTargetAndVisibilities(Long target, List<Visibility> visibilities) {
List<Visibility> visibilities) {
return Lists.newArrayList(userProfileFieldRepository.findAll( return Lists.newArrayList(userProfileFieldRepository.findAll(
qUserProfileField.target.eq(target) qUserProfileField.target.eq(target).and(qUserProfileField.visibility.in(visibilities)),
.and(qUserProfileField.visibility.in(visibilities)),
Sort.by("index", "name").ascending())); Sort.by("index", "name").ascending()));
} }
@ -94,20 +91,15 @@ public class UserProfileFieldManager implements UserDataProvider {
* Delete. * Delete.
* *
* @param target the target * @param target the target
* @param name the name * @param name the name
*/ */
public void delete(Long target, String name) { public void delete(Long target, String name) {
Assert.isTrue( Assert.isTrue(
userProfileFieldRepository.exists( userProfileFieldRepository
qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))), .exists(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))),
"ProfileField '" "ProfileField '" + name + "' for target + '" + target + "' not exists!");
+ name
+ "' for target + '"
+ target
+ "' not exists!");
UserProfileField delete = userProfileFieldRepository UserProfileField delete = userProfileFieldRepository
.findOne(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))) .findOne(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))).get();
.get();
userProfileFieldRepository.delete(delete); userProfileFieldRepository.delete(delete);
} }
@ -117,8 +109,7 @@ public class UserProfileFieldManager implements UserDataProvider {
* @param target the target * @param target the target
*/ */
public void deleteAll(Long target) { public void deleteAll(Long target) {
userProfileFieldRepository userProfileFieldRepository.deleteAll(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target)));
.deleteAll(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target)));
} }
/* /*

View File

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

View File

@ -59,18 +59,14 @@ public class VoucherMappingManager {
/** /**
* Creates the. * Creates the.
* *
* @param name the name * @param name the name
* @param voucher the voucher * @param voucher the voucher
* @param quota the quota * @param quota the quota
* @param isFree the is free * @param isFree the is free
* @return the voucher mapping * @return the voucher mapping
*/ */
public VoucherMapping create(String name, int voucher, String quota, boolean isFree) { public VoucherMapping create(String name, int voucher, String quota, boolean isFree) {
Assert.isTrue(!exists(name), "QuotaMapping for voucher '" Assert.isTrue(!exists(name), "QuotaMapping for voucher '" + voucher + "' with '" + name + "' already exists!");
+ voucher
+ "' with '"
+ name
+ "' already exists!");
VoucherMapping voucherMapping = new VoucherMapping(); VoucherMapping voucherMapping = new VoucherMapping();
voucherMapping.setName(name); voucherMapping.setName(name);
@ -87,12 +83,8 @@ public class VoucherMappingManager {
* @return the voucher mapping * @return the voucher mapping
*/ */
public VoucherMapping update(VoucherMapping voucherMapping) { public VoucherMapping update(VoucherMapping voucherMapping) {
Assert.isTrue( Assert.isTrue(voucherMapping.getId() != null && voucherMappingRepository.existsById(voucherMapping.getId()),
voucherMapping.getId() != null "VoucherMapping '" + voucherMapping.getId() + "' does not exists!");
&& voucherMappingRepository.existsById(voucherMapping.getId()),
"VoucherMapping '"
+ voucherMapping.getId()
+ "' does not exists!");
return voucherMappingRepository.save(voucherMapping); return voucherMappingRepository.save(voucherMapping);
} }
@ -103,18 +95,16 @@ public class VoucherMappingManager {
* @param id the id * @param id the id
*/ */
public void delete(Long id) { public void delete(Long id) {
Assert.isTrue(voucherMappingRepository.existsById(id), "VoucherMapping '" Assert.isTrue(voucherMappingRepository.existsById(id), "VoucherMapping '" + id + "' does not exists!");
+ id
+ "' does not exists!");
voucherMappingRepository.deleteById(id); voucherMappingRepository.deleteById(id);
} }
/** /**
* Gets the. * Gets the.
* *
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param sortBy the sort by * @param sortBy the sort by
* @param descending the descending * @param descending the descending
* @return the page * @return the page
*/ */

View File

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

View File

@ -20,7 +20,7 @@ public class InstantHelper {
* Plus. * Plus.
* *
* @param instant the instant * @param instant the instant
* @param amount the amount * @param amount the amount
* @return the instant * @return the instant
*/ */
public static Instant plus(Instant instant, TemporalAmount amount) { public static Instant plus(Instant instant, TemporalAmount amount) {
@ -30,9 +30,9 @@ public class InstantHelper {
/** /**
* Plus. * Plus.
* *
* @param instant the instant * @param instant the instant
* @param amountToAdd the amount to add * @param amountToAdd the amount to add
* @param unit the unit * @param unit the unit
* @return the instant * @return the instant
*/ */
public static Instant plus(Instant instant, long amountToAdd, TemporalUnit unit) { public static Instant plus(Instant instant, long amountToAdd, TemporalUnit unit) {
@ -43,7 +43,7 @@ public class InstantHelper {
* Minus. * Minus.
* *
* @param instant the instant * @param instant the instant
* @param amount the amount * @param amount the amount
* @return the instant * @return the instant
*/ */
public static Instant minus(Instant instant, TemporalAmount amount) { public static Instant minus(Instant instant, TemporalAmount amount) {
@ -53,32 +53,29 @@ public class InstantHelper {
/** /**
* Minus. * Minus.
* *
* @param instant the instant * @param instant the instant
* @param amountToAdd the amount to add * @param amountToAdd the amount to add
* @param unit the unit * @param unit the unit
* @return the instant * @return the instant
*/ */
public static Instant minus(Instant instant, long amountToAdd, TemporalUnit unit) { public static Instant minus(Instant instant, long amountToAdd, TemporalUnit unit) {
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit) return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit).toInstant();
.toInstant();
} }
/** /**
* Truncate. * Truncate.
* *
* @param instant the instant * @param instant the instant
* @param unit the unit * @param unit the unit
* @return the instant * @return the instant
*/ */
public static Instant truncate(Instant instant, TemporalUnit unit) { public static Instant truncate(Instant instant, TemporalUnit unit) {
if (ChronoUnit.YEARS.equals(unit)) { if (ChronoUnit.YEARS.equals(unit)) {
instant = instant.truncatedTo(ChronoUnit.DAYS); instant = instant.truncatedTo(ChronoUnit.DAYS);
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC) return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_YEAR, 1L).toInstant();
.with(ChronoField.DAY_OF_YEAR, 1L).toInstant();
} else if (ChronoUnit.MONTHS.equals(unit)) { } else if (ChronoUnit.MONTHS.equals(unit)) {
instant = instant.truncatedTo(ChronoUnit.DAYS); instant = instant.truncatedTo(ChronoUnit.DAYS);
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC) return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_MONTH, 1L).toInstant();
.with(ChronoField.DAY_OF_MONTH, 1L).toInstant();
} }
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).truncatedTo(unit).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)) { for (SecondFactorProvider<?> provider : secondFactorProviderManager.getEnabled(userId)) {
SecondFactorProviderModel enabledProvider = new SecondFactorProviderModel( SecondFactorProviderModel enabledProvider = new SecondFactorProviderModel(provider.getId(),
provider.getId(), provider instanceof SecondFactorRequestProvider<?>); provider instanceof SecondFactorRequestProvider<?>);
result.remove(enabledProvider); result.remove(enabledProvider);
} }
return result; return result;
@ -175,12 +175,11 @@ public class Authentication2FAController extends BaseController {
* Enable second factor. * Enable second factor.
* *
* @param providerId the provider id * @param providerId the provider id
* @param token the token * @param token the token
*/ */
@PreAuthorize("authentication.authenticated") @PreAuthorize("authentication.authenticated")
@PatchMapping("/{id}") @PatchMapping("/{id}")
public void enableSecondFactor(@PathVariable("id") String providerId, public void enableSecondFactor(@PathVariable("id") String providerId, @RequestBody String token) {
@RequestBody String token) {
SecondFactorProvider<?> provider = secondFactorProviderManager.getProvider(providerId); SecondFactorProvider<?> provider = secondFactorProviderManager.getProvider(providerId);
if (provider == null) { if (provider == null) {

View File

@ -56,14 +56,14 @@ public class AuthenticationController extends BaseController {
* Password request. * Password request.
* *
* @param username the username * @param username the username
* @param req the req * @param req the req
* @param resp the resp * @param resp the resp
* @throws IOException Signals that an I/O exception has occurred. * @throws IOException Signals that an I/O exception has occurred.
*/ */
@PreAuthorize("isAnonymous()") @PreAuthorize("isAnonymous()")
@PostMapping("/password/request") @PostMapping("/password/request")
public void passwordRequest(@RequestBody String username, HttpServletRequest req, public void passwordRequest(@RequestBody String username, HttpServletRequest req, HttpServletResponse resp)
HttpServletResponse resp) throws IOException { throws IOException {
User user = userManager.getByUsername(username); User user = userManager.getByUsername(username);
if (user != null) { if (user != null) {
@ -78,13 +78,13 @@ public class AuthenticationController extends BaseController {
* Password reset. * Password reset.
* *
* @param passwordResetModel the password reset model * @param passwordResetModel the password reset model
* @param req the req * @param req the req
* @param resp the resp * @param resp the resp
*/ */
@PreAuthorize("isAnonymous()") @PreAuthorize("isAnonymous()")
@PostMapping("/password/reset") @PostMapping("/password/reset")
public void passwordReset(@RequestBody PasswordResetModel passwordResetModel, public void passwordReset(@RequestBody PasswordResetModel passwordResetModel, HttpServletRequest req,
HttpServletRequest req, HttpServletResponse resp) { HttpServletResponse resp) {
User user = userManager.getByResetToken(passwordResetModel.getToken().trim()); User user = userManager.getByResetToken(passwordResetModel.getToken().trim());
if (user == null) { if (user == null) {

View File

@ -80,7 +80,7 @@ public class ItemController extends BaseController {
/** /**
* Adds the item. * Adds the item.
* *
* @param secret the secret * @param secret the secret
* @param session the session * @param session the session
*/ */
@PutMapping("") @PutMapping("")
@ -99,7 +99,7 @@ public class ItemController extends BaseController {
/** /**
* Removes the item. * Removes the item.
* *
* @param secret the secret * @param secret the secret
* @param session the session * @param session the session
*/ */
@DeleteMapping @DeleteMapping
@ -131,7 +131,7 @@ public class ItemController extends BaseController {
* Redeem for user. * Redeem for user.
* *
* @param username the username * @param username the username
* @param session the session * @param session the session
*/ */
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@PostMapping("/{username}") @PostMapping("/{username}")
@ -147,8 +147,7 @@ public class ItemController extends BaseController {
throw new EntityResponseStatusException(HttpStatus.CONFLICT); throw new EntityResponseStatusException(HttpStatus.CONFLICT);
} }
tokenSessionManager.applyTokens(user.getId(), tokenSessionManager.applyTokens(user.getId(), tokenSessionManager.getTokenFromSession(session));
tokenSessionManager.getTokenFromSession(session));
tokenSessionManager.removeTokensFromSession(session); tokenSessionManager.removeTokensFromSession(session);
} }

View File

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

View File

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

View File

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

View File

@ -41,9 +41,9 @@ public class PretixApiController extends BaseController {
* Debug. * Debug.
* *
* @param pretixRequest the pretix request * @param pretixRequest the pretix request
* @param response the response * @param response the response
* @throws JsonIOException the json IO exception * @throws JsonIOException the json IO exception
* @throws IOException Signals that an I/O exception has occurred. * @throws IOException Signals that an I/O exception has occurred.
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/debug") @PostMapping("/debug")
@ -58,10 +58,8 @@ public class PretixApiController extends BaseController {
} }
} }
gson.toJson( gson.toJson(pretixManager.request(pretixRequest.getPath(), pretixRequest.getMethod(),
pretixManager.request(pretixRequest.getPath(), pretixRequest.getMethod(), gson.toJsonTree(pretixRequest.getPayload()), queryParemeters), response.getWriter());
gson.toJsonTree(pretixRequest.getPayload()), queryParemeters),
response.getWriter());
} catch (WebClientResponseException e) { } catch (WebClientResponseException e) {
throw new EntityResponseStatusException(e.getMessage(), e.getStatusCode()); throw new EntityResponseStatusException(e.getMessage(), e.getStatusCode());
} }

View File

@ -98,8 +98,8 @@ public class QuotaManagementController extends BaseController {
throw new EntityResponseStatusException(HttpStatus.CONFLICT); throw new EntityResponseStatusException(HttpStatus.CONFLICT);
} }
return quotaManager.create(quota.getTarget(), quota.getName(), quota.getValue(), return quotaManager.create(quota.getTarget(), quota.getName(), quota.getValue(), quota.getUnit(),
quota.getUnit(), quota.isDisposable()); quota.isDisposable());
} }
/** /**
@ -143,7 +143,7 @@ public class QuotaManagementController extends BaseController {
/** /**
* Clone. * Clone.
* *
* @param name the name * @param name the name
* @param clone the clone * @param clone the clone
* @param value the value * @param value the value
* @return the list * @return the list

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -67,12 +67,11 @@ public class UserDataManagementController extends BaseController {
* Purge by username. * Purge by username.
* *
* @param username the username * @param username the username
* @param dry the dry * @param dry the dry
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/purge/{username}") @PostMapping("/purge/{username}")
public void purgeByUsername(@PathVariable("username") String username, public void purgeByUsername(@PathVariable("username") String username, @RequestParam("dry") boolean dry) {
@RequestParam("dry") boolean dry) {
User user = userManager.getByUsername(username); User user = userManager.getByUsername(username);
if (user == null) { if (user == null) {

View File

@ -53,16 +53,14 @@ public class UserDomainController extends BaseController {
if (!permissionManager.isFullUser(getCurrentUserId())) { if (!permissionManager.isFullUser(getCurrentUserId())) {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
} }
if (userDomain.getVisibility() == null) { if (userDomain.getVisibility() == null) {
userDomain.setVisibility(Visibility.PRIVATE); userDomain.setVisibility(Visibility.PRIVATE);
} }
userDomain.setTarget(getCurrentUserId()); userDomain.setTarget(getCurrentUserId());
userDomain.setValidated(false); userDomain.setValidated(false);
userDomain.setSecret( userDomain.setSecret(RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true));
RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true));
Errors errors = new RequestBodyErrors(userDomain); Errors errors = new RequestBodyErrors(userDomain);
@ -92,7 +90,7 @@ public class UserDomainController extends BaseController {
if (oldDomain == null) { if (oldDomain == null) {
throw new EntityResponseStatusException(HttpStatus.CONFLICT); throw new EntityResponseStatusException(HttpStatus.CONFLICT);
} }
if (!oldDomain.getTarget().equals(getCurrentUserId())) { if (!oldDomain.getTarget().equals(getCurrentUserId())) {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
} }

View File

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

View File

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

View File

@ -138,8 +138,7 @@ public class UserProfileFieldController extends BaseController {
} }
profileFields.addAll( profileFields.addAll(userProfileFieldManager.getAllByTargetAndVisibilities(user.getId(), visibilities));
userProfileFieldManager.getAllByTargetAndVisibilities(user.getId(), visibilities));
if (profileFields.isEmpty()) { if (profileFields.isEmpty()) {
throttleForbidden(); throttleForbidden();
@ -178,7 +177,7 @@ public class UserProfileFieldController extends BaseController {
* Gets the field for user. * Gets the field for user.
* *
* @param username the username * @param username the username
* @param name the name * @param name the name
* @return the field for user * @return the field for user
*/ */
@GetMapping("/{username}/field/{name}") @GetMapping("/{username}/field/{name}")

View File

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

View File

@ -14,7 +14,7 @@ public class SecondFactorProviderModel {
/** /**
* Instantiates a new second factor provider model. * Instantiates a new second factor provider model.
* *
* @param id the id * @param id the id
* @param request the request * @param request the request
*/ */
public SecondFactorProviderModel(String id, boolean request) { public SecondFactorProviderModel(String id, boolean request) {

View File

@ -20,7 +20,7 @@ public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
* Handle response entity status exception. * Handle response entity status exception.
* *
* @param exception the exception * @param exception the exception
* @param request the request * @param request the request
* @return the response entity * @return the response entity
*/ */
@ExceptionHandler(value = { EntityResponseStatusException.class }) @ExceptionHandler(value = { EntityResponseStatusException.class })

View File

@ -37,7 +37,7 @@ public class EntityResponseStatusException extends NestedRuntimeException {
/** /**
* Instantiates a new entity response status exception. * Instantiates a new entity response status exception.
* *
* @param body the body * @param body the body
* @param status the status * @param status the status
*/ */
public EntityResponseStatusException(@Nullable Object body, HttpStatus status) { public EntityResponseStatusException(@Nullable Object body, HttpStatus status) {
@ -47,9 +47,9 @@ public class EntityResponseStatusException extends NestedRuntimeException {
/** /**
* Instantiates a new entity response status exception. * Instantiates a new entity response status exception.
* *
* @param body the body * @param body the body
* @param status the status * @param status the status
* @param cause the cause * @param cause the cause
*/ */
public EntityResponseStatusException(@Nullable Object body, HttpStatus status, @Nullable Throwable cause) { public EntityResponseStatusException(@Nullable Object body, HttpStatus status, @Nullable Throwable cause) {
super(null, cause); super(null, cause);

View File

@ -29,9 +29,10 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
private Gson gson = new Gson(); 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 @Override
public boolean supports(MethodParameter methodParameter, Type targetType, 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 @Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
@ -48,9 +52,11 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
return inputMessage; 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 @Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
@ -59,9 +65,11 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
return body; 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 @Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
@ -69,18 +77,23 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
return body; 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 @Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return converterType == StringHttpMessageConverter.class; 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 @Override
public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType, public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType,

View File

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

View File

@ -55,7 +55,7 @@ public class TokenSessionManager {
* Gets the permission mappings for token. * Gets the permission mappings for token.
* *
* @param userId the user id * @param userId the user id
* @param token the token * @param token the token
* @return the permission mappings for token * @return the permission mappings for token
*/ */
public List<PermissionMapping> getPermissionMappingsForToken(Long userId, String token) { public List<PermissionMapping> getPermissionMappingsForToken(Long userId, String token) {
@ -79,7 +79,7 @@ public class TokenSessionManager {
* Gets the permissions for token. * Gets the permissions for token.
* *
* @param userId the user id * @param userId the user id
* @param token the token * @param token the token
* @return the permissions for token * @return the permissions for token
*/ */
public List<Permission> getPermissionsForToken(Long userId, String token) { public List<Permission> getPermissionsForToken(Long userId, String token) {
@ -100,7 +100,7 @@ public class TokenSessionManager {
} }
permissions.addAll(permissionManager.getForItem(userId, item, permissions.addAll(permissionManager.getForItem(userId, item,
orderPosition.get("answers").getAsJsonArray(),lastPaymentDate, null)); orderPosition.get("answers").getAsJsonArray(), lastPaymentDate, null));
} }
} catch (Exception e) { } catch (Exception e) {
// ignore // ignore
@ -113,7 +113,7 @@ public class TokenSessionManager {
* Gets the quota mappings for token. * Gets the quota mappings for token.
* *
* @param userId the user id * @param userId the user id
* @param token the token * @param token the token
* @return the quota mappings for token * @return the quota mappings for token
*/ */
public List<QuotaMapping> getQuotaMappingsForToken(Long userId, String token) { public List<QuotaMapping> getQuotaMappingsForToken(Long userId, String token) {
@ -137,7 +137,7 @@ public class TokenSessionManager {
* Adds the quotas for token. * Adds the quotas for token.
* *
* @param userId the user id * @param userId the user id
* @param token the token * @param token the token
* @param quotas the quotas * @param quotas the quotas
*/ */
public void addQuotasForToken(Long userId, String token, List<Quota> quotas) { public void addQuotasForToken(Long userId, String token, List<Quota> quotas) {
@ -179,8 +179,8 @@ public class TokenSessionManager {
throw new Exception("This should not happen!"); throw new Exception("This should not happen!");
} }
permissionManager.applyItem(userId, item, permissionManager.applyItem(userId, item, position.get("answers").getAsJsonArray(), lastPaymentDate,
position.get("answers").getAsJsonArray(), lastPaymentDate, null); null);
permissionMappings.addAll(permissionMappingManager.getAllByItem(item)); permissionMappings.addAll(permissionMappingManager.getAllByItem(item));
quotaManager.applyItem(userId, item); quotaManager.applyItem(userId, item);
quotaMappings.addAll(quotaMappingManager.getAllByItem(item)); quotaMappings.addAll(quotaMappingManager.getAllByItem(item));
@ -222,7 +222,7 @@ public class TokenSessionManager {
/** /**
* Adds the token to session. * Adds the token to session.
* *
* @param secret the secret * @param secret the secret
* @param session the session * @param session the session
*/ */
public void addTokenToSession(String secret, HttpSession session) { public void addTokenToSession(String secret, HttpSession session) {
@ -236,8 +236,7 @@ public class TokenSessionManager {
} }
if (StringUtils.hasLength(tokens)) { if (StringUtils.hasLength(tokens)) {
tokens += "," tokens += "," + secret;
+ secret;
} else { } else {
tokens = secret; tokens = secret;
} }
@ -249,7 +248,7 @@ public class TokenSessionManager {
/** /**
* Removes the token from session. * Removes the token from session.
* *
* @param secret the secret * @param secret the secret
* @param session the session * @param session the session
*/ */
public void removeTokenFromSession(String secret, HttpSession session) { public void removeTokenFromSession(String secret, HttpSession session) {
@ -261,8 +260,7 @@ public class TokenSessionManager {
for (String token : ((String) sessionAttribute).split(",")) { for (String token : ((String) sessionAttribute).split(",")) {
if (!token.equals(secret)) { if (!token.equals(secret)) {
if (StringUtils.hasLength(tokens)) { if (StringUtils.hasLength(tokens)) {
tokens += "," tokens += "," + secret;
+ secret;
} else { } else {
tokens = secret; tokens = secret;
} }
@ -285,15 +283,14 @@ public class TokenSessionManager {
/** /**
* Creates the new auth. * Creates the new auth.
* *
* @param auth the auth * @param auth the auth
* @param details the details * @param details the details
* @return the authentication * @return the authentication
*/ */
protected Authentication createNewAuth(Authentication auth, LocalUserDetails details) { protected Authentication createNewAuth(Authentication auth, LocalUserDetails details) {
Authentication newAuth = null; Authentication newAuth = null;
if (auth instanceof UsernamePasswordAuthenticationToken) { if (auth instanceof UsernamePasswordAuthenticationToken) {
newAuth = new UsernamePasswordAuthenticationToken(details, auth.getCredentials(), newAuth = new UsernamePasswordAuthenticationToken(details, auth.getCredentials(), details.getAuthorities());
details.getAuthorities());
} else { } else {
newAuth = new LocalAnonymousAuthenticationToken(details); newAuth = new LocalAnonymousAuthenticationToken(details);
} }

View File

@ -46,9 +46,9 @@ public class PasswordModelValidator implements Validator {
return clazz.isAssignableFrom(PasswordModel.class); 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 @Override
public void validate(Object target, Errors errors) { public void validate(Object target, Errors errors) {

View File

@ -16,7 +16,7 @@ import de.bstly.we.model.UserAlias;
*/ */
@Component @Component
public class UserAliasValidator implements Validator { public class UserAliasValidator implements Validator {
@Autowired @Autowired
private UserModelValidator userModelValidator; private UserModelValidator userModelValidator;

View File

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

View File

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

View File

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

View File

@ -23,7 +23,7 @@ public class AbstractModelEvent extends ApplicationEvent {
/** /**
* Instantiates a new abstract model event. * Instantiates a new abstract model event.
* *
* @param type the type * @param type the type
* @param model the model * @param model the model
*/ */
public AbstractModelEvent(AbstractModelEventType type, AbstractModel model) { public AbstractModelEvent(AbstractModelEventType type, AbstractModel model) {

View File

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

View File

@ -33,7 +33,7 @@ public class SystemProperty {
/** /**
* Instantiates a new system property. * Instantiates a new system property.
* *
* @param key the key * @param key the key
* @param value the value * @param value the value
*/ */
public SystemProperty(String key, String value) { public SystemProperty(String key, String value) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -33,9 +33,11 @@ public class LocalAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPo
super(loginFormUrl); 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 @Override
public void commence(HttpServletRequest request, HttpServletResponse response, 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.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils; 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.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Component;
import de.bstly.we.security.businesslogic.SecondFactorProvider; import de.bstly.we.security.businesslogic.SecondFactorProvider;
import de.bstly.we.security.businesslogic.SecondFactorProviderManager; import de.bstly.we.security.businesslogic.SecondFactorProviderManager;
@ -21,14 +23,25 @@ import de.bstly.we.security.token.LocalSecondFactorAuthenticationToken;
/** /**
* The Class LocalAuthenticationProvider. * The Class LocalAuthenticationProvider.
*/ */
@Component
public class LocalAuthenticationProvider extends DaoAuthenticationProvider { public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
@Autowired @Autowired
private SecondFactorProviderManager secondFactorProviderManager; 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 @Override
public Authentication authenticate(Authentication auth) throws AuthenticationException { public Authentication authenticate(Authentication auth) throws AuthenticationException {
@ -38,8 +51,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
if (auth.getPrincipal() instanceof LocalUserDetails) { if (auth.getPrincipal() instanceof LocalUserDetails) {
LocalUserDetails details = (LocalUserDetails) auth.getPrincipal(); LocalUserDetails details = (LocalUserDetails) auth.getPrincipal();
if (!secondFactorProviderManager.getEnabled(details.getUserId()).isEmpty()) { if (!secondFactorProviderManager.getEnabled(details.getUserId()).isEmpty()) {
PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken( PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(details, "",
details, "", AuthorityUtils.createAuthorityList("ROLE_PRE_AUTH_USER")); AuthorityUtils.createAuthorityList("ROLE_PRE_AUTH_USER"));
newAuth.setAuthenticated(false); newAuth.setAuthenticated(false);
return newAuth; return newAuth;
} }
@ -57,8 +70,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
.getProvider(secondFactorAuth.getProvider()); .getProvider(secondFactorAuth.getProvider());
if (provider == null) { if (provider == null) {
throw new SecondFactorAuthenticationException( throw new SecondFactorAuthenticationException("invalid provider: " + secondFactorAuth.getProvider(),
"invalid provider: " + secondFactorAuth.getProvider(), details); details);
} }
if (!provider.isEnabled(details.getUserId())) { if (!provider.isEnabled(details.getUserId())) {
@ -70,8 +83,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
return new UsernamePasswordAuthenticationToken(details, auth.getCredentials(), return new UsernamePasswordAuthenticationToken(details, auth.getCredentials(),
details.getAuthorities()); details.getAuthorities());
} else { } else {
PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken( PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(details, "",
details, "", auth.getAuthorities()); auth.getAuthorities());
newAuth.setAuthenticated(false); newAuth.setAuthenticated(false);
return newAuth; 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) { public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)) return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication))
@ -93,8 +107,7 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
/** /**
* The Class SecondFactorAuthenticationException. * The Class SecondFactorAuthenticationException.
*/ */
public static class SecondFactorAuthenticationException public static class SecondFactorAuthenticationException extends InsufficientAuthenticationException {
extends InsufficientAuthenticationException {
private LocalUserDetails principal; private LocalUserDetails principal;
@ -106,7 +119,7 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
/** /**
* Instantiates a new second factor authentication exception. * Instantiates a new second factor authentication exception.
* *
* @param message the message * @param message the message
* @param principal the principal * @param principal the principal
*/ */
public SecondFactorAuthenticationException(String message, LocalUserDetails principal) { public SecondFactorAuthenticationException(String message, LocalUserDetails principal) {

View File

@ -17,18 +17,19 @@ public class LocalRememberMeServices extends PersistentTokenBasedRememberMeServi
/** /**
* Instantiates a new local remember me services. * Instantiates a new local remember me services.
* *
* @param key the key * @param key the key
* @param userDetailsService the user details service * @param userDetailsService the user details service
* @param tokenRepository the token repository * @param tokenRepository the token repository
*/ */
public LocalRememberMeServices(String key, UserDetailsService userDetailsService, public LocalRememberMeServices(String key, UserDetailsService userDetailsService,
PersistentTokenRepository tokenRepository) { PersistentTokenRepository tokenRepository) {
super(key, userDetailsService, tokenRepository); 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 @Override
protected boolean rememberMeRequested(HttpServletRequest request, String parameter) { protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {

View File

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

View File

@ -1,5 +1,6 @@
package de.bstly.we.security; package de.bstly.we.security;
import java.time.Instant;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; 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.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import de.bstly.we.businesslogic.PermissionManager; import com.google.common.collect.Lists;
import de.bstly.we.businesslogic.UserManager;
import de.bstly.we.model.Permission; 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.model.User;
import de.bstly.we.repository.PermissionRepository;
import de.bstly.we.repository.UserRepository;
import de.bstly.we.security.model.LocalUserDetails; import de.bstly.we.security.model.LocalUserDetails;
/** /**
@ -27,23 +32,26 @@ import de.bstly.we.security.model.LocalUserDetails;
public class LocalUserDetailsService implements UserDetailsService { public class LocalUserDetailsService implements UserDetailsService {
@Autowired @Autowired
private UserManager userManager; private UserRepository userRepository;
@Autowired @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 @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 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) { if (user != null) {
String password = userManager.getPasswordHash(user.getId()); String password = userRepository.findById(user.getId()).get().getPasswordHash();
if (password == null) { if (password == null) {
throw new AuthenticationCredentialsNotFoundException( throw new AuthenticationCredentialsNotFoundException("No password found: " + username);
"No password found: " + username);
} }
if (user.isDisabled()) { if (user.isDisabled()) {
@ -75,8 +83,8 @@ public class LocalUserDetailsService implements UserDetailsService {
// } // }
// Create user details // Create user details
LocalUserDetails userDetails = new LocalUserDetails(user.getId(), user.getUsername(), LocalUserDetails userDetails = new LocalUserDetails(user.getId(), user.getUsername(), password,
password, authorities); authorities);
return userDetails; return userDetails;
} }
@ -93,7 +101,9 @@ public class LocalUserDetailsService implements UserDetailsService {
*/ */
public Set<GrantedAuthority> getAuthoritiesForUser(Long userId) { public Set<GrantedAuthority> getAuthoritiesForUser(Long userId) {
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); 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())); authorities.add(new SimpleGrantedAuthority(permission.getName()));
} }
return authorities; 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.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; 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.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 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.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy; 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.RememberMeServices;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 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.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 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.FormSecondFactorAuthenticationFilter;
import de.bstly.we.security.filter.LocalAnonymousAuthenticationFilter; import de.bstly.we.security.filter.LocalAnonymousAuthenticationFilter;
import de.bstly.we.security.filter.RestAuthenticationFilter; import de.bstly.we.security.filter.RestAuthenticationFilter;
@ -55,11 +55,15 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired @Autowired
private DataSource dataSource; private DataSource dataSource;
@Autowired @Autowired
private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;
@Autowired
private RestAuthenticationFailureHandler restAuthenticationFailureHandler; private RestAuthenticationFailureHandler restAuthenticationFailureHandler;
@Autowired @Autowired
private LocalAccessDeniedHandler localAccessDeniedHandler; private LocalAccessDeniedHandler localAccessDeniedHandler;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private TokenSessionManager tokenSessionManager;
@Autowired
private LocalAuthenticationProvider localAuthenticationProvider;
@Value("${server.servlet.session.cookie.secure:false}") @Value("${server.servlet.session.cookie.secure:false}")
private boolean secureCookie; private boolean secureCookie;
@ -84,12 +88,14 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
*/ */
@Autowired @Autowired
public void configureAuthentication(AuthenticationManagerBuilder auth) throws Exception { 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 @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
@ -102,26 +108,21 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
// disable deprectated xss protection // disable deprectated xss protection
.headers().xssProtection().disable().and() .headers().xssProtection().disable().and()
// form login // form login
.formLogin().loginPage(loginUrl).usernameParameter("username") .formLogin().loginPage(loginUrl).usernameParameter("username").passwordParameter("password")
.passwordParameter("password").loginProcessingUrl("/auth/login") .loginProcessingUrl("/auth/login").defaultSuccessUrl(loginTargetUrl)
.defaultSuccessUrl(loginTargetUrl)
.successHandler(formAuthenticationSuccessHandler()) .successHandler(formAuthenticationSuccessHandler())
.failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl + "?error")) .failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl + "?error")).and()
.and()
// remember me // remember me
.rememberMe().rememberMeServices(rememberMeServices()).and() .rememberMe().rememberMeServices(rememberMeServices()).and()
// form totp // form totp
.addFilterBefore(formSecondFactorAuthenticationFilter(), .addFilterBefore(formSecondFactorAuthenticationFilter(), LocalAnonymousAuthenticationFilter.class)
LocalAnonymousAuthenticationFilter.class)
// rest login // rest login
.addFilterBefore(restAuthenticationFilter(), .addFilterBefore(restAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
UsernamePasswordAuthenticationFilter.class)
// rest totp // rest totp
.addFilterAfter(restSecondFactorAuthenticationFilter(), .addFilterAfter(restSecondFactorAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
UsernamePasswordAuthenticationFilter.class)
// Logout // Logout
.logout().logoutUrl("/auth/logout") .logout().logoutUrl("/auth/logout").logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()).and() .and()
// exception // exception
.exceptionHandling().accessDeniedHandler(localAccessDeniedHandler) .exceptionHandling().accessDeniedHandler(localAccessDeniedHandler)
.authenticationEntryPoint(localAuthenticationEntryPoint()).and() .authenticationEntryPoint(localAuthenticationEntryPoint()).and()
@ -155,29 +156,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
return source; 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. * Local anonymous authentication filter.
* *
@ -195,10 +173,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
*/ */
@Bean @Bean
public LocalAuthenticationEntryPoint localAuthenticationEntryPoint() { public LocalAuthenticationEntryPoint localAuthenticationEntryPoint() {
LocalAuthenticationEntryPoint localAuthenticationEntryPoint = new LocalAuthenticationEntryPoint( LocalAuthenticationEntryPoint localAuthenticationEntryPoint = new LocalAuthenticationEntryPoint(loginUrl);
loginUrl); localAuthenticationEntryPoint.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
localAuthenticationEntryPoint
.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
return localAuthenticationEntryPoint; return localAuthenticationEntryPoint;
} }
@ -211,14 +187,25 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean @Bean
public FormAuthenticationSuccessHandler formAuthenticationSuccessHandler() { public FormAuthenticationSuccessHandler formAuthenticationSuccessHandler() {
FormAuthenticationSuccessHandler formAuthenticationSuccessHandler = new FormAuthenticationSuccessHandler( FormAuthenticationSuccessHandler formAuthenticationSuccessHandler = new FormAuthenticationSuccessHandler(
loginTargetUrl, SecurityConfig.KEEP_PARAM); rememberMeServices(), tokenSessionManager, loginTargetUrl, SecurityConfig.KEEP_PARAM);
formAuthenticationSuccessHandler.setTotpRedirectUrl(secondFactorUrl); formAuthenticationSuccessHandler.setTotpRedirectUrl(secondFactorUrl);
formAuthenticationSuccessHandler.setTargetUrlParameter("forward"); formAuthenticationSuccessHandler.setTargetUrlParameter("forward");
formAuthenticationSuccessHandler formAuthenticationSuccessHandler.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
return formAuthenticationSuccessHandler; 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. * Form second factor authentication filter.
* *
@ -226,13 +213,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
* @throws Exception the exception * @throws Exception the exception
*/ */
@Bean @Bean
public FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter() public FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter() throws Exception {
throws Exception {
FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter = new FormSecondFactorAuthenticationFilter( FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter = new FormSecondFactorAuthenticationFilter(
"/auth/login/2fa"); "/auth/login/2fa");
formSecondFactorAuthenticationFilter.setAuthenticationManager(authenticationManager()); formSecondFactorAuthenticationFilter.setAuthenticationManager(authenticationManager());
formSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter.setAuthenticationSuccessHandler(formAuthenticationSuccessHandler());
.setAuthenticationSuccessHandler(formAuthenticationSuccessHandler());
formSecondFactorAuthenticationFilter.setRememberMeServices(rememberMeServices()); formSecondFactorAuthenticationFilter.setRememberMeServices(rememberMeServices());
return formSecondFactorAuthenticationFilter; return formSecondFactorAuthenticationFilter;
} }
@ -245,10 +230,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
*/ */
@Bean @Bean
public RestAuthenticationFilter restAuthenticationFilter() throws Exception { public RestAuthenticationFilter restAuthenticationFilter() throws Exception {
RestAuthenticationFilter restAuthenticationFilter = new RestAuthenticationFilter( RestAuthenticationFilter restAuthenticationFilter = new RestAuthenticationFilter("/auth/restlogin");
"/auth/restlogin");
restAuthenticationFilter.setAuthenticationManager(authenticationManager()); restAuthenticationFilter.setAuthenticationManager(authenticationManager());
restAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler); restAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler());
restAuthenticationFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler); restAuthenticationFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
return restAuthenticationFilter; return restAuthenticationFilter;
} }
@ -260,15 +244,12 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
* @throws Exception the exception * @throws Exception the exception
*/ */
@Bean @Bean
public RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter() public RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter() throws Exception {
throws Exception {
RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter = new RestSecondFactorAuthenticationFilter( RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter = new RestSecondFactorAuthenticationFilter(
"/auth/restlogin/2fa"); "/auth/restlogin/2fa");
restSecondFactorAuthenticationFilter.setAuthenticationManager(authenticationManager()); restSecondFactorAuthenticationFilter.setAuthenticationManager(authenticationManager());
restSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler());
.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler); restSecondFactorAuthenticationFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
restSecondFactorAuthenticationFilter
.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
restSecondFactorAuthenticationFilter.setRememberMeServices(rememberMeServices()); restSecondFactorAuthenticationFilter.setRememberMeServices(rememberMeServices());
return restSecondFactorAuthenticationFilter; return restSecondFactorAuthenticationFilter;
} }
@ -302,8 +283,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
*/ */
@Bean @Bean
public RememberMeServices rememberMeServices() { public RememberMeServices rememberMeServices() {
PersistentTokenBasedRememberMeServices rememberMeServices = new LocalRememberMeServices( PersistentTokenBasedRememberMeServices rememberMeServices = new LocalRememberMeServices(KEEP_PARAM,
KEEP_PARAM, localUserDetailsService, persistentTokenRepository()); localUserDetailsService, persistentTokenRepository());
rememberMeServices.setCookieName("SESSION_" + KEEP_PARAM.toUpperCase()); rememberMeServices.setCookieName("SESSION_" + KEEP_PARAM.toUpperCase());
rememberMeServices.setParameter(KEEP_PARAM); rememberMeServices.setParameter(KEEP_PARAM);
rememberMeServices.setUseSecureCookie(secureCookie); rememberMeServices.setUseSecureCookie(secureCookie);

View File

@ -38,7 +38,7 @@ public interface SecondFactorProvider<T extends SecondFactor> extends UserDataPr
* Validate. * Validate.
* *
* @param userId the user id * @param userId the user id
* @param code the code * @param code the code
* @return true, if successful * @return true, if successful
*/ */
boolean validate(Long userId, String code); boolean validate(Long userId, String code);
@ -63,7 +63,7 @@ public interface SecondFactorProvider<T extends SecondFactor> extends UserDataPr
* Enable. * Enable.
* *
* @param userId the user id * @param userId the user id
* @param code the code * @param code the code
* @return true, if successful * @return true, if successful
*/ */
boolean enable(Long userId, String code); boolean enable(Long userId, String code);

View File

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

View File

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

View File

@ -40,24 +40,22 @@ public class FormSecondFactorAuthenticationFilter extends AbstractAuthentication
super(defaultFilterProcessesUrl); 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 @Override
public Authentication attemptAuthentication(HttpServletRequest request, public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
HttpServletResponse response)
throws AuthenticationException, IOException, ServletException { throws AuthenticationException, IOException, ServletException {
if (!request.getMethod().equals("POST")) { if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException( throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
"Authentication method not supported: " + request.getMethod());
} }
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null if (authentication == null || !(authentication instanceof PreAuthenticatedAuthenticationToken)
|| !(authentication instanceof PreAuthenticatedAuthenticationToken)
|| !(authentication.getPrincipal() instanceof LocalUserDetails)) { || !(authentication.getPrincipal() instanceof LocalUserDetails)) {
throw new InsufficientAuthenticationException("login first!"); 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 @Override
protected void unsuccessfulAuthentication(HttpServletRequest request, protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
HttpServletResponse response, AuthenticationException failed) AuthenticationException failed) throws IOException, ServletException {
throws IOException, ServletException {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Authentication request failed: " + failed.toString(), failed); logger.debug("Authentication request failed: " + failed.toString(), failed);
logger.debug("Updated SecurityContextHolder to contain null Authentication"); logger.debug("Updated SecurityContextHolder to contain null Authentication");

View File

@ -32,22 +32,25 @@ public class LocalAnonymousAuthenticationFilter extends AnonymousAuthenticationF
super(KEY); 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 @Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException { throws IOException, ServletException {
if (SecurityContextHolder.getContext().getAuthentication() == null) { if (SecurityContextHolder.getContext().getAuthentication() == null) {
SecurityContextHolder.getContext() SecurityContextHolder.getContext().setAuthentication(createAuthentication((HttpServletRequest) req));
.setAuthentication(createAuthentication((HttpServletRequest) req));
} }
chain.doFilter(req, res); 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 @Override
protected Authentication createAuthentication(HttpServletRequest request) { 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 @Override
public Authentication attemptAuthentication(HttpServletRequest request, public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
HttpServletResponse response)
throws AuthenticationException, IOException, ServletException { throws AuthenticationException, IOException, ServletException {
if (!request.getMethod().equals("POST")) { if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException( throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
"Authentication method not supported: " + request.getMethod());
} }
try { try {
@ -77,8 +77,7 @@ public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFi
} }
Authentication authRequest = new UsernamePasswordAuthenticationToken( Authentication authRequest = new UsernamePasswordAuthenticationToken(
loginModel.get(usernameKey).getAsString(), loginModel.get(usernameKey).getAsString(), loginModel.get(passwordKey).getAsString());
loginModel.get(passwordKey).getAsString());
return this.getAuthenticationManager().authenticate(authRequest); return this.getAuthenticationManager().authenticate(authRequest);
} catch (JsonMappingException | JsonParseException exception) { } catch (JsonMappingException | JsonParseException exception) {
throw new AuthenticationCredentialsNotFoundException("Bad request"); throw new AuthenticationCredentialsNotFoundException("Bad request");

View File

@ -39,24 +39,22 @@ public class RestSecondFactorAuthenticationFilter extends FormSecondFactorAuthen
super(defaultFilterProcessesUrl); 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 @Override
public Authentication attemptAuthentication(HttpServletRequest request, public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
HttpServletResponse response)
throws AuthenticationException, IOException, ServletException { throws AuthenticationException, IOException, ServletException {
if (!request.getMethod().equals("POST")) { if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException( throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
"Authentication method not supported: " + request.getMethod());
} }
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null if (authentication == null || !(authentication instanceof PreAuthenticatedAuthenticationToken)
|| !(authentication instanceof PreAuthenticatedAuthenticationToken)
|| !(authentication.getPrincipal() instanceof LocalUserDetails)) { || !(authentication.getPrincipal() instanceof LocalUserDetails)) {
throw new InsufficientAuthenticationException("login first!"); 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 provider = model2FA.get(SPRING_SECURITY_FORM_2FA_PROVIDER_KEY).getAsString();
String code = model2FA.get(SPRING_SECURITY_FORM_2FA_CODE_KEY).getAsString(); String code = model2FA.get(SPRING_SECURITY_FORM_2FA_CODE_KEY).getAsString();
if (model2FA.has(SecurityConfig.KEEP_PARAM) if (model2FA.has(SecurityConfig.KEEP_PARAM) && model2FA.get(SecurityConfig.KEEP_PARAM).isJsonPrimitive()) {
&& model2FA.get(SecurityConfig.KEEP_PARAM).isJsonPrimitive()) { request.setAttribute(SecurityConfig.KEEP_PARAM, model2FA.get(SecurityConfig.KEEP_PARAM).getAsString());
request.setAttribute(SecurityConfig.KEEP_PARAM,
model2FA.get(SecurityConfig.KEEP_PARAM).getAsString());
} }
LocalUserDetails details = (LocalUserDetails) authentication.getPrincipal(); 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 @Override
protected void unsuccessfulAuthentication(HttpServletRequest request, protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
HttpServletResponse response, AuthenticationException failed) AuthenticationException failed) throws IOException, ServletException {
throws IOException, ServletException {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Authentication request failed: " + failed.toString(), failed); logger.debug("Authentication request failed: " + failed.toString(), failed);
logger.debug("Updated SecurityContextHolder to contain null Authentication"); 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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.RememberMeServices; import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
@ -24,13 +23,10 @@ import de.bstly.we.security.token.LocalSecondFactorAuthenticationToken;
/** /**
* The Class FormAuthenticationSuccessHandler. * The Class FormAuthenticationSuccessHandler.
*/ */
public class FormAuthenticationSuccessHandler public class FormAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
extends SavedRequestAwareAuthenticationSuccessHandler {
@Autowired protected final RememberMeServices rememberMeServices;
protected RememberMeServices rememberMeServices; protected final TokenSessionManager tokenSessionManager;
@Autowired
protected TokenSessionManager tokenSessionManager;
private String totpRedirectUrl; private String totpRedirectUrl;
private String rememberMeParameter; private String rememberMeParameter;
@ -40,33 +36,44 @@ public class FormAuthenticationSuccessHandler
/** /**
* Instantiates a new form authentication success handler. * 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 * @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; this.rememberMeParameter = rememberMeParameter;
} }
/** /**
* Instantiates a new form authentication success handler. * Instantiates a new form authentication success handler.
* *
* @param defaultTargetUrl the default target url * @param rememberMeServices the remember me services
* @param tokenSessionManager the token session manager
* @param defaultTargetUrl the default target url
* @param rememberMeParameter the remember me parameter * @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); setDefaultTargetUrl(defaultTargetUrl);
this.rememberMeParameter = rememberMeParameter; 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 @Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException { Authentication authentication) throws ServletException, IOException {
if (!authentication.isAuthenticated() if (!authentication.isAuthenticated() && authentication instanceof PreAuthenticatedAuthenticationToken) {
&& authentication instanceof PreAuthenticatedAuthenticationToken) {
rememberMeServices.loginFail(request, response); rememberMeServices.loginFail(request, response);
boolean keep = false; boolean keep = false;
String paramValue = request.getParameter(rememberMeParameter); String paramValue = request.getParameter(rememberMeParameter);
@ -77,23 +84,20 @@ public class FormAuthenticationSuccessHandler
} }
} }
if (authentication.getAuthorities() != null && authentication.getAuthorities() if (authentication.getAuthorities() != null
.containsAll(LocalSecondFactorAuthenticationToken.AUTHORITIES)) { && authentication.getAuthorities().containsAll(LocalSecondFactorAuthenticationToken.AUTHORITIES)) {
getRedirectStrategy().sendRedirect(request, response, getRedirectStrategy().sendRedirect(request, response,
totpRedirectUrl + "?error" + (keep ? "&keep" : "")); totpRedirectUrl + "?error" + (keep ? "&keep" : ""));
} else { } else {
getRedirectStrategy().sendRedirect(request, response, getRedirectStrategy().sendRedirect(request, response, totpRedirectUrl + (keep ? "?keep" : ""));
totpRedirectUrl + (keep ? "?keep" : ""));
} }
} else { } else {
rememberMeServices.loginSuccess(request, response, authentication); rememberMeServices.loginSuccess(request, response, authentication);
for (RequestMatcher matcher : requestMatchers) { for (RequestMatcher matcher : requestMatchers) {
if (matcher.matches(request)) { if (matcher.matches(request)) {
getRedirectStrategy().sendRedirect(request, response, getRedirectStrategy().sendRedirect(request, response, request.getRequestURI()
request.getRequestURI() + (request.getQueryString() != null + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
? "?" + request.getQueryString()
: ""));
return; return;
} }
} }

View File

@ -17,9 +17,12 @@ import org.springframework.stereotype.Component;
@Component @Component
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler { 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 @Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,

View File

@ -8,30 +8,36 @@ import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication; 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; import de.bstly.we.security.SecurityConfig;
/** /**
* The Class RestAuthenticationSuccessHandler. * The Class RestAuthenticationSuccessHandler.
*/ */
@Component
public class RestAuthenticationSuccessHandler extends FormAuthenticationSuccessHandler { public class RestAuthenticationSuccessHandler extends FormAuthenticationSuccessHandler {
/** /**
* Instantiates a new rest authentication success handler. * Instantiates a new rest authentication success handler.
*
* @param rememberMeServices the remember me services
* @param tokenSessionManager the token session manager
*/ */
public RestAuthenticationSuccessHandler() { public RestAuthenticationSuccessHandler(RememberMeServices rememberMeServices,
super(SecurityConfig.KEEP_PARAM); 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 @Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException { Authentication authentication) throws IOException, ServletException {
if (!authentication.isAuthenticated()) { if (!authentication.isAuthenticated()) {
rememberMeServices.loginFail(request, response); rememberMeServices.loginFail(request, response);
response.sendError(HttpStatus.PRECONDITION_REQUIRED.value(), response.sendError(HttpStatus.PRECONDITION_REQUIRED.value(),

View File

@ -22,9 +22,9 @@ public class LocalUserDetails extends User {
/** /**
* Instantiates a new local user details. * Instantiates a new local user details.
* *
* @param userId the user id * @param userId the user id
* @param username the username * @param username the username
* @param password the password * @param password the password
* @param authorities the authorities * @param authorities the authorities
*/ */
public LocalUserDetails(Long userId, String username, String password, public LocalUserDetails(Long userId, String username, String password,

View File

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

View File

@ -21,8 +21,7 @@ public class LocalSecondFactorAuthenticationToken extends AbstractAuthentication
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public static final String ROLE_REQUIRE_2FA = "ROLE_REQUIRE_2FA"; public static final String ROLE_REQUIRE_2FA = "ROLE_REQUIRE_2FA";
public static final List<GrantedAuthority> AUTHORITIES = AuthorityUtils public static final List<GrantedAuthority> AUTHORITIES = AuthorityUtils.createAuthorityList(ROLE_REQUIRE_2FA);
.createAuthorityList(ROLE_REQUIRE_2FA);
/** /**
* *
*/ */
@ -34,11 +33,10 @@ public class LocalSecondFactorAuthenticationToken extends AbstractAuthentication
* Instantiates a new local second factor authentication token. * Instantiates a new local second factor authentication token.
* *
* @param principal the principal * @param principal the principal
* @param provider the provider * @param provider the provider
* @param code the code * @param code the code
*/ */
public LocalSecondFactorAuthenticationToken(LocalUserDetails principal, String provider, public LocalSecondFactorAuthenticationToken(LocalUserDetails principal, String provider, String code) {
String code) {
super(AUTHORITIES); super(AUTHORITIES);
this.principal = principal; this.principal = principal;
this.provider = provider; this.provider = provider;

View File

@ -32,10 +32,10 @@ public class EmailManager {
/** /**
* Send text. * Send text.
* *
* @param to the to * @param to the to
* @param from the from * @param from the from
* @param subject the subject * @param subject the subject
* @param text the text * @param text the text
* @return the mail message * @return the mail message
*/ */
public MailMessage sendText(String to, String from, String subject, String text) { public MailMessage sendText(String to, String from, String subject, String text) {
@ -52,10 +52,10 @@ public class EmailManager {
/** /**
* Send bcc. * Send bcc.
* *
* @param bcc the bcc * @param bcc the bcc
* @param from the from * @param from the from
* @param subject the subject * @param subject the subject
* @param text the text * @param text the text
* @return the mail message * @return the mail message
*/ */
public MailMessage sendBcc(String[] bcc, String from, String subject, String text) { public MailMessage sendBcc(String[] bcc, String from, String subject, String text) {
@ -80,12 +80,10 @@ public class EmailManager {
UserProfileField primaryEmailUserProfileField = userProfileFieldManager.get(user.getId(), UserProfileField primaryEmailUserProfileField = userProfileFieldManager.get(user.getId(),
UserProfileFields.PROFILE_FIELD_EMAIL_PRIMARY); UserProfileFields.PROFILE_FIELD_EMAIL_PRIMARY);
if (primaryEmailUserProfileField != null if (primaryEmailUserProfileField != null && "true".equals(primaryEmailUserProfileField.getValue())) {
&& "true".equals(primaryEmailUserProfileField.getValue())) {
UserProfileField emailUserProfileField = userProfileFieldManager.get(user.getId(), UserProfileField emailUserProfileField = userProfileFieldManager.get(user.getId(),
UserProfileFields.PROFILE_FIELD_EMAIL); UserProfileFields.PROFILE_FIELD_EMAIL);
if (emailUserProfileField != null if (emailUserProfileField != null && StringUtils.hasText(emailUserProfileField.getValue())) {
&& StringUtils.hasText(emailUserProfileField.getValue())) {
email = emailUserProfileField.getValue(); email = emailUserProfileField.getValue();
} }
} }

View File

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

View File

@ -16,7 +16,7 @@ public class UserMailModel {
* Instantiates a new user mail model. * Instantiates a new user mail model.
* *
* @param username the username * @param username the username
* @param email the email * @param email the email
*/ */
public UserMailModel(String username, String email) { public UserMailModel(String username, String email) {
super(); super();

View File

@ -70,7 +70,7 @@ public class I18nManager {
* Extend json object. * Extend json object.
* *
* @param dest the dest * @param dest the dest
* @param src the src * @param src the src
*/ */
protected void extendJsonObject(JsonObject dest, JsonObject src) { protected void extendJsonObject(JsonObject dest, JsonObject src) {
for (Entry<String, JsonElement> srcEntry : src.entrySet()) { for (Entry<String, JsonElement> srcEntry : src.entrySet()) {
@ -92,7 +92,7 @@ public class I18nManager {
/** /**
* Adds the label. * Adds the label.
* *
* @param locale the locale * @param locale the locale
* @param newLabel the new label * @param newLabel the new label
* @return the i 18 n * @return the i 18 n
*/ */
@ -116,7 +116,7 @@ public class I18nManager {
* Sets the label. * Sets the label.
* *
* @param locale the locale * @param locale the locale
* @param label the label * @param label the label
* @return the i 18 n * @return the i 18 n
*/ */
public I18n setLabel(String locale, JsonObject label) { public I18n setLabel(String locale, JsonObject label) {

View File

@ -51,11 +51,11 @@ public class I18nController extends BaseController {
/** /**
* Gets the label. * Gets the label.
* *
* @param locale the locale * @param locale the locale
* @param response the response * @param response the response
* @return the label * @return the label
* @throws JsonIOException the json IO exception * @throws JsonIOException the json IO exception
* @throws IOException Signals that an I/O exception has occurred. * @throws IOException Signals that an I/O exception has occurred.
*/ */
@GetMapping("/{locale}") @GetMapping("/{locale}")
public void getLabel(@PathVariable("locale") String locale, HttpServletResponse response) public void getLabel(@PathVariable("locale") String locale, HttpServletResponse response)
@ -71,7 +71,7 @@ public class I18nController extends BaseController {
* Sets the label. * Sets the label.
* *
* @param locale the locale * @param locale the locale
* @param label the label * @param label the label
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/{locale}") @PostMapping("/{locale}")
@ -87,7 +87,7 @@ public class I18nController extends BaseController {
* Adds the label. * Adds the label.
* *
* @param locale the locale * @param locale the locale
* @param label the label * @param label the label
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@PutMapping("/{locale}") @PutMapping("/{locale}")

View File

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

View File

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

View File

@ -46,22 +46,21 @@ public class InviteMappingManager {
/** /**
* Gets the by item and quota. * Gets the by item and quota.
* *
* @param item the item * @param item the item
* @param quota the quota * @param quota the quota
* @return the by item and quota * @return the by item and quota
*/ */
public InviteMapping getByItemAndQuota(int item, String quota) { public InviteMapping getByItemAndQuota(int item, String quota) {
return inviteMappingRepository return inviteMappingRepository.findOne(qInviteMapping.item.eq(item).and(qInviteMapping.quota.eq(quota)))
.findOne(qInviteMapping.item.eq(item).and(qInviteMapping.quota.eq(quota)))
.orElse(null); .orElse(null);
} }
/** /**
* Gets the. * Gets the.
* *
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param sortBy the sort by * @param sortBy the sort by
* @param descending the descending * @param descending the descending
* @return the page * @return the page
*/ */
@ -73,9 +72,9 @@ public class InviteMappingManager {
/** /**
* Creates the. * Creates the.
* *
* @param quota the quota * @param quota the quota
* @param item the item * @param item the item
* @param starts the starts * @param starts the starts
* @param expires the expires * @param expires the expires
* @return the invite mapping * @return the invite mapping
*/ */
@ -98,8 +97,8 @@ public class InviteMappingManager {
*/ */
public InviteMapping save(InviteMapping inviteMapping) { public InviteMapping save(InviteMapping inviteMapping) {
for (Invite invite : inviteRepository.findAll(qInvite.item.eq(inviteMapping.getItem()) for (Invite invite : inviteRepository
.and(qInvite.quota.eq(inviteMapping.getQuota())))) { .findAll(qInvite.item.eq(inviteMapping.getItem()).and(qInvite.quota.eq(inviteMapping.getQuota())))) {
if (StringUtils.hasText(inviteMapping.getCodeLink())) { if (StringUtils.hasText(inviteMapping.getCodeLink())) {
String codeLink = String.format(inviteMapping.getCodeLink(), invite.getCode()); String codeLink = String.format(inviteMapping.getCodeLink(), invite.getCode());
if (!codeLink.equals(invite.getCodeLink())) { if (!codeLink.equals(invite.getCodeLink())) {
@ -120,17 +119,17 @@ public class InviteMappingManager {
invite.setUrl(null); invite.setUrl(null);
inviteRepository.save(invite); inviteRepository.save(invite);
} }
if (!invite.getStarts().equals(inviteMapping.getStarts())) { if (!invite.getStarts().equals(inviteMapping.getStarts())) {
invite.setStarts(inviteMapping.getStarts()); invite.setStarts(inviteMapping.getStarts());
inviteRepository.save(invite); inviteRepository.save(invite);
} }
if (!invite.getExpires().equals(inviteMapping.getExpires())) { if (!invite.getExpires().equals(inviteMapping.getExpires())) {
invite.setExpires(inviteMapping.getExpires()); invite.setExpires(inviteMapping.getExpires());
inviteRepository.save(invite); inviteRepository.save(invite);
} }
} }
return inviteMappingRepository.save(inviteMapping); return inviteMappingRepository.save(inviteMapping);

View File

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

View File

@ -44,16 +44,15 @@ public class InviteManagingController extends BaseController {
/** /**
* Gets the invites. * Gets the invites.
* *
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param search the search * @param search the search
* @return the invites * @return the invites
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping @GetMapping
public Page<Invite> getInvites(@RequestParam("page") Optional<Integer> page, public Page<Invite> getInvites(@RequestParam("page") Optional<Integer> page,
@RequestParam("size") Optional<Integer> size, @RequestParam("size") Optional<Integer> size, @RequestParam("search") Optional<String> search) {
@RequestParam("search") Optional<String> search) {
return inviteManager.get(page.orElse(0), size.orElse(10), search.orElse(null)); 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')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping @PostMapping
public Invite createOrUpdate(@RequestBody Invite invite) { public Invite createOrUpdate(@RequestBody Invite invite) {
if (invite.getItem() == null || inviteMappingManager.getByItemAndQuota(invite.getItem(), if (invite.getItem() == null
invite.getQuota()) == null) { || inviteMappingManager.getByItemAndQuota(invite.getItem(), invite.getQuota()) == null) {
throw new EntityResponseStatusException(HttpStatus.CONFLICT); throw new EntityResponseStatusException(HttpStatus.CONFLICT);
} }

View File

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

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