upgrade spring, add javadoc, formatting
This commit is contained in:
parent
8ebed47574
commit
eb829bfa26
@ -20,7 +20,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
public class Application extends SpringBootServletInitializer {
|
||||
|
||||
|
||||
/**
|
||||
* 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
|
||||
public void onStartup(ServletContext servletContext) throws ServletException {
|
||||
|
@ -108,52 +108,49 @@ public class BorrowItemManager implements UserDataProvider {
|
||||
/**
|
||||
* Gets the.
|
||||
*
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @param search the search
|
||||
* @param search the search
|
||||
* @return the page
|
||||
*/
|
||||
public Page<BorrowItem> get(int page, int size, String sortBy, boolean descending,
|
||||
String search) {
|
||||
public Page<BorrowItem> get(int page, int size, String sortBy, boolean descending, String search) {
|
||||
|
||||
if (StringUtils.hasText(search)) {
|
||||
return borrowItemRepository.findAll(
|
||||
qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search)),
|
||||
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending()
|
||||
: Sort.by(sortBy).ascending()));
|
||||
return borrowItemRepository
|
||||
.findAll(qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search)), PageRequest
|
||||
.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
}
|
||||
|
||||
return borrowItemRepository.findAll(PageRequest.of(page, size,
|
||||
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
return borrowItemRepository.findAll(
|
||||
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the for user.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param userId the user id
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @param search the search
|
||||
* @param search the search
|
||||
* @return the for user
|
||||
*/
|
||||
public Page<BorrowItem> getForUser(Long userId, int page, int size, String sortBy,
|
||||
boolean descending, String search) {
|
||||
public Page<BorrowItem> getForUser(Long userId, int page, int size, String sortBy, boolean descending,
|
||||
String search) {
|
||||
|
||||
BooleanBuilder query = new BooleanBuilder();
|
||||
|
||||
query.and(qBorrowItem.owner.eq(userId));
|
||||
|
||||
if (StringUtils.hasText(search)) {
|
||||
query.and(
|
||||
qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search)));
|
||||
query.and(qBorrowItem.name.contains(search).or(qBorrowItem.description.contains(search)));
|
||||
}
|
||||
|
||||
return borrowItemRepository.findAll(query.getValue(), PageRequest.of(page, size,
|
||||
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
return borrowItemRepository.findAll(query.getValue(),
|
||||
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -165,10 +162,10 @@ public class BorrowItemManager implements UserDataProvider {
|
||||
public BorrowItem save(BorrowItem borrowItem) {
|
||||
|
||||
if (borrowItem.getId() != null && !borrowItem.getId().equals(0L)) {
|
||||
borrowItemManualSlotRepository.deleteAll(borrowItemManualSlotRepository
|
||||
.findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId())));
|
||||
borrowItemPeriodSlotRepository.deleteAll(borrowItemPeriodSlotRepository
|
||||
.findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId())));
|
||||
borrowItemManualSlotRepository.deleteAll(
|
||||
borrowItemManualSlotRepository.findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId())));
|
||||
borrowItemPeriodSlotRepository.deleteAll(
|
||||
borrowItemPeriodSlotRepository.findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId())));
|
||||
}
|
||||
|
||||
List<? extends BorrowItemSlot> slots = borrowItem.getSlots();
|
||||
@ -216,12 +213,11 @@ public class BorrowItemManager implements UserDataProvider {
|
||||
* @param borrowItem the borrow item
|
||||
*/
|
||||
public void delete(BorrowItem borrowItem) {
|
||||
borrowItemManualSlotRepository.deleteAll(borrowItemManualSlotRepository
|
||||
.findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId())));
|
||||
borrowItemPeriodSlotRepository.deleteAll(borrowItemPeriodSlotRepository
|
||||
.findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId())));
|
||||
borrowRequestRepository.deleteAll(
|
||||
borrowRequestRepository.findAll(qBorrowRequest.item.eq(borrowItem.getId())));
|
||||
borrowItemManualSlotRepository
|
||||
.deleteAll(borrowItemManualSlotRepository.findAll(qBorrowItemManualSlot.item.eq(borrowItem.getId())));
|
||||
borrowItemPeriodSlotRepository
|
||||
.deleteAll(borrowItemPeriodSlotRepository.findAll(qBorrowItemPeriodSlot.item.eq(borrowItem.getId())));
|
||||
borrowRequestRepository.deleteAll(borrowRequestRepository.findAll(qBorrowRequest.item.eq(borrowItem.getId())));
|
||||
|
||||
borrowItemRepository.delete(borrowItem);
|
||||
}
|
||||
@ -233,8 +229,7 @@ public class BorrowItemManager implements UserDataProvider {
|
||||
*/
|
||||
public void delete(Long id) {
|
||||
BorrowItem borrowItem = get(id);
|
||||
Assert.notNull(borrowItem, "Invalid borrow item id: "
|
||||
+ id);
|
||||
Assert.notNull(borrowItem, "Invalid borrow item id: " + id);
|
||||
delete(borrowItem);
|
||||
}
|
||||
|
||||
@ -244,12 +239,8 @@ public class BorrowItemManager implements UserDataProvider {
|
||||
* @param borrowItem the borrow item
|
||||
*/
|
||||
public void notifyOwner(BorrowItem borrowItem) {
|
||||
Assert.isTrue(
|
||||
borrowItem.getEmailNotification() != null
|
||||
&& borrowItem.getEmailNotification().booleanValue(),
|
||||
"Email notification not enabled for '"
|
||||
+ borrowItem.getId()
|
||||
+ "'!");
|
||||
Assert.isTrue(borrowItem.getEmailNotification() != null && borrowItem.getEmailNotification().booleanValue(),
|
||||
"Email notification not enabled for '" + borrowItem.getId() + "'!");
|
||||
String email = borrowItem.getEmail();
|
||||
|
||||
if (!StringUtils.hasText(email)) {
|
||||
@ -276,8 +267,7 @@ public class BorrowItemManager implements UserDataProvider {
|
||||
public List<UserData> getUserData(Long userId) {
|
||||
List<UserData> result = Lists.newArrayList();
|
||||
|
||||
Iterator<BorrowItem> items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId))
|
||||
.iterator();
|
||||
Iterator<BorrowItem> items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId)).iterator();
|
||||
while (items.hasNext()) {
|
||||
result.add(items.next());
|
||||
}
|
||||
@ -290,8 +280,7 @@ public class BorrowItemManager implements UserDataProvider {
|
||||
*/
|
||||
@Override
|
||||
public void purgeUserData(Long userId) {
|
||||
Iterator<BorrowItem> items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId))
|
||||
.iterator();
|
||||
Iterator<BorrowItem> items = borrowItemRepository.findAll(qBorrowItem.owner.eq(userId)).iterator();
|
||||
while (items.hasNext()) {
|
||||
delete(items.next());
|
||||
}
|
||||
|
@ -68,69 +68,65 @@ public class BorrowRequestManager implements UserDataProvider {
|
||||
/**
|
||||
* Gets the for user.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param userId the user id
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the for user
|
||||
*/
|
||||
public Page<BorrowRequest> getForUser(Long userId, int page, int size, String sortBy,
|
||||
boolean descending) {
|
||||
return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId), PageRequest.of(page,
|
||||
size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
public Page<BorrowRequest> getForUser(Long userId, int page, int size, String sortBy, boolean descending) {
|
||||
return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId),
|
||||
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the for user and status.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param status the status
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param userId the user id
|
||||
* @param status the status
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the for user and status
|
||||
*/
|
||||
public Page<BorrowRequest> getForUserAndStatus(Long userId, BorrowRequestStatus status,
|
||||
int page, int size, String sortBy, boolean descending) {
|
||||
return borrowRequestRepository.findAll(
|
||||
qBorrowRequest.user.eq(userId).and(qBorrowRequest.status.eq(status)),
|
||||
PageRequest.of(page, size,
|
||||
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
public Page<BorrowRequest> getForUserAndStatus(Long userId, BorrowRequestStatus status, int page, int size,
|
||||
String sortBy, boolean descending) {
|
||||
return borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId).and(qBorrowRequest.status.eq(status)),
|
||||
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the for owner.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param userId the user id
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the for owner
|
||||
*/
|
||||
public Page<BorrowRequest> getForOwner(Long userId, int page, int size, String sortBy,
|
||||
boolean descending) {
|
||||
return borrowRequestRepository.findAllByOwner(userId, PageRequest.of(page, size,
|
||||
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
public Page<BorrowRequest> getForOwner(Long userId, int page, int size, String sortBy, boolean descending) {
|
||||
return borrowRequestRepository.findAllByOwner(userId,
|
||||
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the for owner and status.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param status the status
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param userId the user id
|
||||
* @param status the status
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the for owner and status
|
||||
*/
|
||||
public Page<BorrowRequest> getForOwnerAndStatus(Long userId, BorrowRequestStatus status,
|
||||
int page, int size, String sortBy, boolean descending) {
|
||||
return borrowRequestRepository.findAllByOwnerAndStatus(userId, status, PageRequest.of(page,
|
||||
size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
public Page<BorrowRequest> getForOwnerAndStatus(Long userId, BorrowRequestStatus status, int page, int size,
|
||||
String sortBy, boolean descending) {
|
||||
return borrowRequestRepository.findAllByOwnerAndStatus(userId, status,
|
||||
PageRequest.of(page, size, descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending()));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -165,7 +161,7 @@ public class BorrowRequestManager implements UserDataProvider {
|
||||
* Creates the code.
|
||||
*
|
||||
* @param borrowRequest the borrow request
|
||||
* @param issuer the issuer
|
||||
* @param issuer the issuer
|
||||
* @return the signed JWT
|
||||
* @throws JOSEException the JOSE exception
|
||||
*/
|
||||
@ -207,8 +203,7 @@ public class BorrowRequestManager implements UserDataProvider {
|
||||
|
||||
JwtKey jwtKey = jwtKeyManager.getLatest(JWT_BORROW_KEY_NAME, true);
|
||||
|
||||
JWSHeader.Builder headerBuilder = new JWSHeader.Builder(
|
||||
jwtKeyManager.getJwsAlgorithm(jwtKey));
|
||||
JWSHeader.Builder headerBuilder = new JWSHeader.Builder(jwtKeyManager.getJwsAlgorithm(jwtKey));
|
||||
headerBuilder.keyID(jwtKey.getKeyID());
|
||||
headerBuilder.type(JOSEObjectType.JWT);
|
||||
|
||||
@ -222,7 +217,7 @@ public class BorrowRequestManager implements UserDataProvider {
|
||||
*
|
||||
* @param jwt the jwt
|
||||
* @return true, if successful
|
||||
* @throws JOSEException the JOSE exception
|
||||
* @throws JOSEException the JOSE exception
|
||||
* @throws ParseException the parse exception
|
||||
*/
|
||||
public boolean verify(SignedJWT jwt) throws JOSEException, ParseException {
|
||||
@ -233,9 +228,7 @@ public class BorrowRequestManager implements UserDataProvider {
|
||||
|
||||
JwtKey jwtKey = jwtKeyManager.getByKeyID(jwt.getHeader().getKeyID());
|
||||
if (jwtKey == null) {
|
||||
throw new KeySourceException("No key found for given KeyID! ("
|
||||
+ jwt.getHeader().getKeyID()
|
||||
+ ")");
|
||||
throw new KeySourceException("No key found for given KeyID! (" + jwt.getHeader().getKeyID() + ")");
|
||||
}
|
||||
|
||||
if (jwt.getJWTClaimsSet() == null) {
|
||||
@ -259,14 +252,13 @@ public class BorrowRequestManager implements UserDataProvider {
|
||||
@Override
|
||||
public List<UserData> getUserData(Long userId) {
|
||||
List<UserData> result = Lists.newArrayList();
|
||||
Iterator<BorrowRequest> userRequests = borrowRequestRepository
|
||||
.findAll(qBorrowRequest.user.eq(userId)).iterator();
|
||||
Iterator<BorrowRequest> userRequests = borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId))
|
||||
.iterator();
|
||||
while (userRequests.hasNext()) {
|
||||
result.add(userRequests.next());
|
||||
}
|
||||
|
||||
Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId)
|
||||
.iterator();
|
||||
Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId).iterator();
|
||||
while (ownerRequests.hasNext()) {
|
||||
result.add(ownerRequests.next());
|
||||
}
|
||||
@ -279,14 +271,13 @@ public class BorrowRequestManager implements UserDataProvider {
|
||||
*/
|
||||
@Override
|
||||
public void purgeUserData(Long userId) {
|
||||
Iterator<BorrowRequest> userRequests = borrowRequestRepository
|
||||
.findAll(qBorrowRequest.user.eq(userId)).iterator();
|
||||
Iterator<BorrowRequest> userRequests = borrowRequestRepository.findAll(qBorrowRequest.user.eq(userId))
|
||||
.iterator();
|
||||
while (userRequests.hasNext()) {
|
||||
delete(userRequests.next());
|
||||
}
|
||||
|
||||
Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId)
|
||||
.iterator();
|
||||
Iterator<BorrowRequest> ownerRequests = borrowRequestRepository.findAllByOwner(userId).iterator();
|
||||
while (ownerRequests.hasNext()) {
|
||||
delete(ownerRequests.next());
|
||||
}
|
||||
|
@ -46,19 +46,18 @@ public class BorrowItemController extends BaseController {
|
||||
/**
|
||||
* Gets the borrow items.
|
||||
*
|
||||
* @param pageParameter the page parameter
|
||||
* @param sizeParameter the size parameter
|
||||
* @param sortParameter the sort parameter
|
||||
* @param descParameter the desc parameter
|
||||
* @param pageParameter the page parameter
|
||||
* @param sizeParameter the size parameter
|
||||
* @param sortParameter the sort parameter
|
||||
* @param descParameter the desc parameter
|
||||
* @param searchParameter the search parameter
|
||||
* @param ownerParameter the owner parameter
|
||||
* @param ownerParameter the owner parameter
|
||||
* @return the borrow items
|
||||
*/
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@GetMapping
|
||||
public Page<BorrowItem> getBorrowItems(@RequestParam("page") Optional<Integer> pageParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter,
|
||||
@RequestParam("sort") Optional<String> sortParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("sort") Optional<String> sortParameter,
|
||||
@RequestParam("desc") Optional<Boolean> descParameter,
|
||||
@RequestParam("search") Optional<String> searchParameter,
|
||||
@RequestParam("owner") Optional<Boolean> ownerParameter) {
|
||||
@ -71,17 +70,15 @@ public class BorrowItemController extends BaseController {
|
||||
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
borrowItems = borrowItemManager.getForUser(getCurrentUserId(), pageParameter.orElse(0),
|
||||
sizeParameter.orElse(10), sortParameter.orElse("id"),
|
||||
descParameter.orElse(false), searchParameter.orElse(null));
|
||||
sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false),
|
||||
searchParameter.orElse(null));
|
||||
} else {
|
||||
if (!permissionManager.hasPermission(getCurrentUserId(),
|
||||
BorrowPermissions.BORROW_REQUESTS)
|
||||
if (!permissionManager.hasPermission(getCurrentUserId(), BorrowPermissions.BORROW_REQUESTS)
|
||||
|| !permissionManager.isFullUser(getCurrentUserId())) {
|
||||
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
borrowItems = borrowItemManager.get(pageParameter.orElse(0), sizeParameter.orElse(10),
|
||||
sortParameter.orElse("id"), descParameter.orElse(false),
|
||||
searchParameter.orElse(null));
|
||||
sortParameter.orElse("id"), descParameter.orElse(false), searchParameter.orElse(null));
|
||||
}
|
||||
|
||||
for (BorrowItem borrowItem : borrowItems.getContent()) {
|
||||
|
@ -66,19 +66,17 @@ public class BorrowRequestController extends BaseController {
|
||||
/**
|
||||
* Gets the borrow requests.
|
||||
*
|
||||
* @param pageParameter the page parameter
|
||||
* @param sizeParameter the size parameter
|
||||
* @param sortParameter the sort parameter
|
||||
* @param descParameter the desc parameter
|
||||
* @param pageParameter the page parameter
|
||||
* @param sizeParameter the size parameter
|
||||
* @param sortParameter the sort parameter
|
||||
* @param descParameter the desc parameter
|
||||
* @param ownerParameter the owner parameter
|
||||
* @return the borrow requests
|
||||
*/
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@GetMapping
|
||||
public Page<BorrowRequest> getBorrowRequests(
|
||||
@RequestParam("page") Optional<Integer> pageParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter,
|
||||
@RequestParam("sort") Optional<String> sortParameter,
|
||||
public Page<BorrowRequest> getBorrowRequests(@RequestParam("page") Optional<Integer> pageParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("sort") Optional<String> sortParameter,
|
||||
@RequestParam("desc") Optional<Boolean> descParameter,
|
||||
@RequestParam("owner") Optional<Boolean> ownerParameter) {
|
||||
|
||||
@ -89,18 +87,15 @@ public class BorrowRequestController extends BaseController {
|
||||
|| !permissionManager.isFullUser(getCurrentUserId())) {
|
||||
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
borrowRequests = borrowRequestManager.getForOwner(getCurrentUserId(),
|
||||
pageParameter.orElse(0), sizeParameter.orElse(10), sortParameter.orElse("id"),
|
||||
descParameter.orElse(false));
|
||||
borrowRequests = borrowRequestManager.getForOwner(getCurrentUserId(), pageParameter.orElse(0),
|
||||
sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false));
|
||||
} else {
|
||||
if (!permissionManager.hasPermission(getCurrentUserId(),
|
||||
BorrowPermissions.BORROW_REQUESTS)
|
||||
if (!permissionManager.hasPermission(getCurrentUserId(), BorrowPermissions.BORROW_REQUESTS)
|
||||
|| !permissionManager.isFullUser(getCurrentUserId())) {
|
||||
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
borrowRequests = borrowRequestManager.getForUser(getCurrentUserId(),
|
||||
pageParameter.orElse(0), sizeParameter.orElse(10), sortParameter.orElse("id"),
|
||||
descParameter.orElse(false));
|
||||
borrowRequests = borrowRequestManager.getForUser(getCurrentUserId(), pageParameter.orElse(0),
|
||||
sizeParameter.orElse(10), sortParameter.orElse("id"), descParameter.orElse(false));
|
||||
}
|
||||
|
||||
for (BorrowRequest borrowRequest : borrowRequests.getContent()) {
|
||||
@ -153,8 +148,7 @@ public class BorrowRequestController extends BaseController {
|
||||
}
|
||||
|
||||
if (borrowRequest.getId() == null || borrowRequest.getId().equals(0L)) {
|
||||
if (borrowItem.getEmailNotification() != null
|
||||
&& borrowItem.getEmailNotification().booleanValue()) {
|
||||
if (borrowItem.getEmailNotification() != null && borrowItem.getEmailNotification().booleanValue()) {
|
||||
borrowItemManager.notifyOwner(borrowItem);
|
||||
}
|
||||
}
|
||||
@ -212,7 +206,7 @@ public class BorrowRequestController extends BaseController {
|
||||
/**
|
||||
* Gets the code.
|
||||
*
|
||||
* @param id the id
|
||||
* @param id the id
|
||||
* @param request the request
|
||||
* @return the code
|
||||
*/
|
||||
@ -230,12 +224,9 @@ public class BorrowRequestController extends BaseController {
|
||||
|
||||
String issuer = jwtBorrowIssuer;
|
||||
if (!StringUtils.hasText(issuer)) {
|
||||
issuer = request.getScheme()
|
||||
+ "://"
|
||||
+ request.getServerName();
|
||||
issuer = request.getScheme() + "://" + request.getServerName();
|
||||
if (request.getServerPort() != 443 && request.getServerPort() != 80) {
|
||||
issuer += ":"
|
||||
+ request.getServerPort();
|
||||
issuer += ":" + request.getServerPort();
|
||||
}
|
||||
}
|
||||
try {
|
||||
@ -250,21 +241,19 @@ public class BorrowRequestController extends BaseController {
|
||||
* Verfiy.
|
||||
*
|
||||
* @param serialized the serialized
|
||||
* @param request the request
|
||||
* @param response the response
|
||||
* @param request the request
|
||||
* @param response the response
|
||||
* @return the object
|
||||
*/
|
||||
@PostMapping("verify")
|
||||
public Object verfiy(@RequestBody String serialized, HttpServletRequest request,
|
||||
HttpServletResponse response) {
|
||||
public Object verfiy(@RequestBody String serialized, HttpServletRequest request, HttpServletResponse response) {
|
||||
try {
|
||||
SignedJWT signedJwt = SignedJWT.parse(serialized);
|
||||
Errors errors = new RequestBodyErrors(signedJwt);
|
||||
borrowJwtValidator.validate(signedJwt, errors);
|
||||
if (errors.hasErrors()) {
|
||||
if (errors.getGlobalErrors().isEmpty()) {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(),
|
||||
HttpStatus.PRECONDITION_FAILED);
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.PRECONDITION_FAILED);
|
||||
} else {
|
||||
throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE);
|
||||
}
|
||||
|
@ -48,13 +48,11 @@ public class BorrowItemValidator implements Validator {
|
||||
errors.rejectValue("availability", "REQUIRED");
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(borrowItem.getUrl())
|
||||
&& !urlValidator.isValid(borrowItem.getUrl())) {
|
||||
if (StringUtils.hasText(borrowItem.getUrl()) && !urlValidator.isValid(borrowItem.getUrl())) {
|
||||
errors.rejectValue("url", "INVALID_URL");
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(borrowItem.getEmail())
|
||||
&& !emailValidator.isValid(borrowItem.getEmail())) {
|
||||
if (StringUtils.hasText(borrowItem.getEmail()) && !emailValidator.isValid(borrowItem.getEmail())) {
|
||||
errors.rejectValue("email", "INVALID_EMAIL");
|
||||
}
|
||||
|
||||
@ -64,18 +62,15 @@ public class BorrowItemValidator implements Validator {
|
||||
errors.rejectValue("maxDuration", "INVALID");
|
||||
}
|
||||
|
||||
if (borrowItem.getAvailability() != null && borrowItem.getSlots() != null
|
||||
&& !borrowItem.getSlots().isEmpty()) {
|
||||
if (borrowItem.getAvailability() != null && borrowItem.getSlots() != null && !borrowItem.getSlots().isEmpty()) {
|
||||
for (BorrowItemSlot borrowItemSlot : borrowItem.getSlots()) {
|
||||
switch (borrowItem.getAvailability()) {
|
||||
case MANUAL:
|
||||
if (borrowItemSlot instanceof BorrowItemManualSlot) {
|
||||
BorrowItemManualSlot borrowItemManualSlot = (BorrowItemManualSlot) borrowItemSlot;
|
||||
if (borrowItemManualSlot.getStart() == null
|
||||
|| borrowItemManualSlot.getEnd() == null) {
|
||||
if (borrowItemManualSlot.getStart() == null || borrowItemManualSlot.getEnd() == null) {
|
||||
errors.rejectValue("slots", "MISSING_DATES");
|
||||
} else if (borrowItemManualSlot.getStart()
|
||||
.isAfter(borrowItemManualSlot.getEnd())) {
|
||||
} else if (borrowItemManualSlot.getStart().isAfter(borrowItemManualSlot.getEnd())) {
|
||||
errors.rejectValue("slots", "INVALID_DATES");
|
||||
}
|
||||
}
|
||||
@ -83,18 +78,14 @@ public class BorrowItemValidator implements Validator {
|
||||
case PERIOD:
|
||||
if (borrowItemSlot instanceof BorrowItemPeriodSlot) {
|
||||
BorrowItemPeriodSlot borrowItemPeriodSlot = (BorrowItemPeriodSlot) borrowItemSlot;
|
||||
if (borrowItemPeriodSlot.getStartDay() == null
|
||||
|| borrowItemPeriodSlot.getStartTime() == null
|
||||
if (borrowItemPeriodSlot.getStartDay() == null || borrowItemPeriodSlot.getStartTime() == null
|
||||
|| borrowItemPeriodSlot.getEndDay() == null
|
||||
|| borrowItemPeriodSlot.getEndTime() == null) {
|
||||
errors.rejectValue("slots", "MISSING_DATES");
|
||||
} else if (borrowItemPeriodSlot.getStartDay()
|
||||
.compareTo(borrowItemPeriodSlot.getEndDay()) > 0) {
|
||||
} else if (borrowItemPeriodSlot.getStartDay().compareTo(borrowItemPeriodSlot.getEndDay()) > 0) {
|
||||
errors.rejectValue("slots", "INVALID_DAY");
|
||||
} else if (borrowItemPeriodSlot.getStartDay()
|
||||
.compareTo(borrowItemPeriodSlot.getEndDay()) == 0
|
||||
&& borrowItemPeriodSlot.getStartTime()
|
||||
.isAfter(borrowItemPeriodSlot.getEndTime())) {
|
||||
} else if (borrowItemPeriodSlot.getStartDay().compareTo(borrowItemPeriodSlot.getEndDay()) == 0
|
||||
&& borrowItemPeriodSlot.getStartTime().isAfter(borrowItemPeriodSlot.getEndTime())) {
|
||||
errors.rejectValue("slots", "INVALID_TIME");
|
||||
}
|
||||
}
|
||||
|
@ -111,8 +111,7 @@ public class BorrowJwtValidator implements Validator {
|
||||
}
|
||||
|
||||
try {
|
||||
if (!BorrowRequestStatus.valueOf(claims.getStringClaim("status"))
|
||||
.equals(BorrowRequestStatus.ACCEPTED)) {
|
||||
if (!BorrowRequestStatus.valueOf(claims.getStringClaim("status")).equals(BorrowRequestStatus.ACCEPTED)) {
|
||||
errors.rejectValue("status", "INVALID");
|
||||
}
|
||||
} catch (ParseException e) {
|
||||
|
@ -66,6 +66,13 @@ public class BorrowRequestValidator implements Validator {
|
||||
validateTime(borrowRequest, borrowItem, errors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate time.
|
||||
*
|
||||
* @param borrowRequest the borrow request
|
||||
* @param borrowItem the borrow item
|
||||
* @param errors the errors
|
||||
*/
|
||||
public void validateTime(BorrowRequest borrowRequest, BorrowItem borrowItem, Errors errors) {
|
||||
if (borrowRequest.getStarts() == null) {
|
||||
errors.rejectValue("starts", "REQUIRED");
|
||||
@ -77,16 +84,14 @@ public class BorrowRequestValidator implements Validator {
|
||||
return;
|
||||
}
|
||||
|
||||
borrowRequest
|
||||
.setStarts(InstantHelper.truncate(borrowRequest.getStarts(), ChronoUnit.SECONDS));
|
||||
borrowRequest.setStarts(InstantHelper.truncate(borrowRequest.getStarts(), ChronoUnit.SECONDS));
|
||||
borrowRequest.setEnds(InstantHelper.truncate(borrowRequest.getEnds(), ChronoUnit.SECONDS));
|
||||
|
||||
// expiry + start
|
||||
if (borrowRequest.getStarts().isAfter(borrowRequest.getEnds())
|
||||
|| borrowRequestRepository.exists(qBorrowRequest.item.eq(borrowRequest.getItem())
|
||||
// exlude self
|
||||
.and(qBorrowRequest.id
|
||||
.ne(borrowRequest.getId() == null ? -1L : borrowRequest.getId()))
|
||||
.and(qBorrowRequest.id.ne(borrowRequest.getId() == null ? -1L : borrowRequest.getId()))
|
||||
// accepted
|
||||
.and(qBorrowRequest.status.eq(BorrowRequestStatus.ACCEPTED))
|
||||
// expires after start
|
||||
@ -96,8 +101,8 @@ public class BorrowRequestValidator implements Validator {
|
||||
errors.rejectValue("starts", "ALREADY_USED");
|
||||
errors.rejectValue("ends", "ALREADY_USED");
|
||||
} else {
|
||||
if (borrowItem.getMinDuration() != null && borrowItem.getMinDuration().compareTo(
|
||||
Duration.between(borrowRequest.getEnds(), borrowRequest.getStarts())) > 0) {
|
||||
if (borrowItem.getMinDuration() != null && borrowItem.getMinDuration()
|
||||
.compareTo(Duration.between(borrowRequest.getEnds(), borrowRequest.getStarts())) > 0) {
|
||||
errors.rejectValue("starts", "TOO_SHORT");
|
||||
errors.rejectValue("ends", "TOO_SHORT");
|
||||
} else if (borrowItem.getMaxDuration() != null
|
||||
@ -119,12 +124,10 @@ public class BorrowRequestValidator implements Validator {
|
||||
for (BorrowItemSlot borrowItemSlot : borrowItem.getSlots()) {
|
||||
if (borrowItemSlot instanceof BorrowItemManualSlot) {
|
||||
BorrowItemManualSlot borrowItemManualSlot = (BorrowItemManualSlot) borrowItemSlot;
|
||||
if (borrowRequest.getStarts()
|
||||
.compareTo(borrowItemManualSlot.getStart()) >= 0) {
|
||||
if (borrowRequest.getStarts().compareTo(borrowItemManualSlot.getStart()) >= 0) {
|
||||
validStart = true;
|
||||
}
|
||||
if (borrowRequest.getEnds()
|
||||
.compareTo(borrowItemManualSlot.getEnd()) <= 0) {
|
||||
if (borrowRequest.getEnds().compareTo(borrowItemManualSlot.getEnd()) <= 0) {
|
||||
validEnd = true;
|
||||
}
|
||||
if (validStart && validEnd) {
|
||||
@ -140,8 +143,7 @@ public class BorrowRequestValidator implements Validator {
|
||||
BorrowItemPeriodSlot borrowItemPeriodSlot = (BorrowItemPeriodSlot) borrowItemSlot;
|
||||
if (borrowRequest.getStarts().atZone(ZoneOffset.UTC).getDayOfWeek()
|
||||
.compareTo(borrowItemPeriodSlot.getStartDay()) >= 0
|
||||
&& LocalTime
|
||||
.ofInstant(borrowRequest.getStarts(), ZoneOffset.UTC)
|
||||
&& LocalTime.ofInstant(borrowRequest.getStarts(), ZoneOffset.UTC)
|
||||
.compareTo(borrowItemPeriodSlot.getStartTime()) >= 0) {
|
||||
validStart = true;
|
||||
}
|
||||
|
@ -13,6 +13,6 @@ import de.bstly.we.borrow.model.BorrowItemManualSlot;
|
||||
* The Interface BorrowItemManualSlotRepository.
|
||||
*/
|
||||
@Repository
|
||||
public interface BorrowItemManualSlotRepository extends JpaRepository<BorrowItemManualSlot, Long>,
|
||||
QuerydslPredicateExecutor<BorrowItemManualSlot> {
|
||||
public interface BorrowItemManualSlotRepository
|
||||
extends JpaRepository<BorrowItemManualSlot, Long>, QuerydslPredicateExecutor<BorrowItemManualSlot> {
|
||||
}
|
||||
|
@ -13,6 +13,6 @@ import de.bstly.we.borrow.model.BorrowItemPeriodSlot;
|
||||
* The Interface BorrowItemPeriodSlotRepository.
|
||||
*/
|
||||
@Repository
|
||||
public interface BorrowItemPeriodSlotRepository extends JpaRepository<BorrowItemPeriodSlot, Long>,
|
||||
QuerydslPredicateExecutor<BorrowItemPeriodSlot> {
|
||||
public interface BorrowItemPeriodSlotRepository
|
||||
extends JpaRepository<BorrowItemPeriodSlot, Long>, QuerydslPredicateExecutor<BorrowItemPeriodSlot> {
|
||||
}
|
||||
|
@ -13,6 +13,5 @@ import de.bstly.we.borrow.model.BorrowItem;
|
||||
* The Interface BorrowItemRepository.
|
||||
*/
|
||||
@Repository
|
||||
public interface BorrowItemRepository
|
||||
extends JpaRepository<BorrowItem, Long>, QuerydslPredicateExecutor<BorrowItem> {
|
||||
public interface BorrowItemRepository extends JpaRepository<BorrowItem, Long>, QuerydslPredicateExecutor<BorrowItem> {
|
||||
}
|
||||
|
@ -33,7 +33,7 @@ public interface BorrowRequestRepository
|
||||
/**
|
||||
* Find all by owner.
|
||||
*
|
||||
* @param owner the owner
|
||||
* @param owner the owner
|
||||
* @param pageable the pageable
|
||||
* @return the page
|
||||
*/
|
||||
@ -43,13 +43,13 @@ public interface BorrowRequestRepository
|
||||
/**
|
||||
* Find all by owner and status.
|
||||
*
|
||||
* @param owner the owner
|
||||
* @param status the status
|
||||
* @param owner the owner
|
||||
* @param status the status
|
||||
* @param pageable the pageable
|
||||
* @return the page
|
||||
*/
|
||||
@Query("SELECT request FROM BorrowRequest request INNER JOIN BorrowItem as item ON request.item = item.id WHERE item.owner = :owner AND request.status = :status")
|
||||
Page<BorrowRequest> findAllByOwnerAndStatus(@Param("owner") Long owner,
|
||||
@Param("status") BorrowRequestStatus status, Pageable pageable);
|
||||
Page<BorrowRequest> findAllByOwnerAndStatus(@Param("owner") Long owner, @Param("status") BorrowRequestStatus status,
|
||||
Pageable pageable);
|
||||
|
||||
}
|
||||
|
14
core/pom.xml
14
core/pom.xml
@ -7,7 +7,7 @@
|
||||
<artifactId>webstly-main</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
|
||||
|
||||
<name>core</name>
|
||||
<artifactId>webstly-core</artifactId>
|
||||
|
||||
@ -56,6 +56,12 @@
|
||||
<version>1.7</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>31.1-jre</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
@ -64,7 +70,7 @@
|
||||
<dependency>
|
||||
<groupId>org.passay</groupId>
|
||||
<artifactId>passay</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<version>1.6.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@ -76,7 +82,7 @@
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>1.66</version>
|
||||
<version>1.70</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@ -87,7 +93,7 @@
|
||||
<dependency>
|
||||
<groupId>javax.measure</groupId>
|
||||
<artifactId>unit-api</artifactId>
|
||||
<version>2.1.2</version>
|
||||
<version>2.1.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
@ -42,13 +42,13 @@ public class PermissionManager implements UserDataProvider {
|
||||
* Gets the.
|
||||
*
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @return the list
|
||||
*/
|
||||
public List<Permission> get(Long target, String name) {
|
||||
if (target != null && StringUtils.hasText(name)) {
|
||||
return Lists.newArrayList(permissionRepository
|
||||
.findAll(qPermission.target.eq(target).and(qPermission.name.eq(name))));
|
||||
return Lists.newArrayList(
|
||||
permissionRepository.findAll(qPermission.target.eq(target).and(qPermission.name.eq(name))));
|
||||
}
|
||||
return Lists.newArrayList();
|
||||
}
|
||||
@ -57,15 +57,14 @@ public class PermissionManager implements UserDataProvider {
|
||||
* Gets the not expires.
|
||||
*
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @return the not expires
|
||||
*/
|
||||
public List<Permission> getNotExpires(Long target, String name) {
|
||||
if (target != null && StringUtils.hasText(name)) {
|
||||
return Lists.newArrayList(permissionRepository
|
||||
.findAll(qPermission.target.eq(target).and(qPermission.name.eq(name))
|
||||
.and(qPermission.expires.after(Instant.now()).and(qPermission.starts
|
||||
.isNull().or(qPermission.starts.before(Instant.now()))))));
|
||||
return Lists.newArrayList(permissionRepository.findAll(qPermission.target.eq(target)
|
||||
.and(qPermission.name.eq(name)).and(qPermission.expires.after(Instant.now())
|
||||
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))));
|
||||
}
|
||||
return Lists.newArrayList();
|
||||
}
|
||||
@ -91,9 +90,9 @@ public class PermissionManager implements UserDataProvider {
|
||||
*/
|
||||
public List<Permission> getNotExpiresByTarget(Long target) {
|
||||
if (target != null) {
|
||||
return Lists.newArrayList(permissionRepository.findAll(qPermission.target.eq(target)
|
||||
.and(qPermission.expires.after(Instant.now()).and(qPermission.starts.isNull()
|
||||
.or(qPermission.starts.before(Instant.now()))))));
|
||||
return Lists.newArrayList(permissionRepository
|
||||
.findAll(qPermission.target.eq(target).and(qPermission.expires.after(Instant.now())
|
||||
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))));
|
||||
}
|
||||
return Lists.newArrayList();
|
||||
}
|
||||
@ -106,9 +105,9 @@ public class PermissionManager implements UserDataProvider {
|
||||
*/
|
||||
public List<Permission> getNotExpiresByName(String name) {
|
||||
if (name != null) {
|
||||
return Lists.newArrayList(permissionRepository.findAll(qPermission.name.eq(name)
|
||||
.and(qPermission.expires.after(Instant.now()).and(qPermission.starts.isNull()
|
||||
.or(qPermission.starts.before(Instant.now()))))));
|
||||
return Lists.newArrayList(
|
||||
permissionRepository.findAll(qPermission.name.eq(name).and(qPermission.expires.after(Instant.now())
|
||||
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))));
|
||||
}
|
||||
return Lists.newArrayList();
|
||||
}
|
||||
@ -121,8 +120,8 @@ public class PermissionManager implements UserDataProvider {
|
||||
*/
|
||||
public List<Permission> getNotExpiresByTargetIgnoreStart(Long target) {
|
||||
if (target != null) {
|
||||
return Lists.newArrayList(permissionRepository.findAll(
|
||||
qPermission.target.eq(target).and(qPermission.expires.after(Instant.now()))));
|
||||
return Lists.newArrayList(permissionRepository
|
||||
.findAll(qPermission.target.eq(target).and(qPermission.expires.after(Instant.now()))));
|
||||
}
|
||||
return Lists.newArrayList();
|
||||
}
|
||||
@ -134,16 +133,16 @@ public class PermissionManager implements UserDataProvider {
|
||||
* @return true, if is full user
|
||||
*/
|
||||
public boolean isFullUser(Long target) {
|
||||
return permissionRepository.exists(qPermission.target.eq(target)
|
||||
.and(qPermission.addon.isFalse()).and(qPermission.expires.after(Instant.now()).and(
|
||||
qPermission.starts.isNull().or(qPermission.starts.before(Instant.now())))));
|
||||
return permissionRepository.exists(qPermission.target.eq(target).and(qPermission.addon.isFalse())
|
||||
.and(qPermission.expires.after(Instant.now())
|
||||
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now())))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for permission.
|
||||
*
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @return true, if successful
|
||||
*/
|
||||
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)
|
||||
.and(qPermission.target.eq(target))
|
||||
.and(qPermission.expires.after(Instant.now()).and(
|
||||
qPermission.starts.isNull().or(qPermission.starts.before(Instant.now())))));
|
||||
.and(qPermission.target.eq(target)).and(qPermission.expires.after(Instant.now())
|
||||
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now())))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the.
|
||||
*
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param addon the addon
|
||||
* @param starts the starts
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param addon the addon
|
||||
* @param starts the starts
|
||||
* @param expires the expires
|
||||
* @return the permission
|
||||
*/
|
||||
public Permission create(Long target, String name, boolean addon, Instant starts,
|
||||
Instant expires) {
|
||||
public Permission create(Long target, String name, boolean addon, Instant starts, Instant expires) {
|
||||
Permission newPermission = new Permission();
|
||||
newPermission.setTarget(target);
|
||||
newPermission.setName(name);
|
||||
@ -186,11 +183,8 @@ public class PermissionManager implements UserDataProvider {
|
||||
* @return the permission
|
||||
*/
|
||||
public Permission update(Permission permission) {
|
||||
Assert.isTrue(permissionRepository.existsById(permission.getId()), "Permission '"
|
||||
+ permission.getName()
|
||||
+ "' for target + '"
|
||||
+ permission.getTarget()
|
||||
+ "' not exists!");
|
||||
Assert.isTrue(permissionRepository.existsById(permission.getId()),
|
||||
"Permission '" + permission.getName() + "' for target + '" + permission.getTarget() + "' not exists!");
|
||||
Permission updatePermission = permissionRepository.getById(permission.getId());
|
||||
updatePermission.setStarts(permission.getStarts());
|
||||
updatePermission.setExpires(permission.getExpires());
|
||||
@ -201,7 +195,7 @@ public class PermissionManager implements UserDataProvider {
|
||||
/**
|
||||
* Clone.
|
||||
*
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @param clone the clone
|
||||
* @return the list
|
||||
*/
|
||||
@ -210,11 +204,11 @@ public class PermissionManager implements UserDataProvider {
|
||||
|
||||
for (Permission permission : permissionRepository
|
||||
.findAll(qPermission.name.eq(name).and(qPermission.expires.after(Instant.now())))) {
|
||||
if (!permissionRepository.exists(
|
||||
qPermission.name.eq(clone).and(qPermission.target.eq(permission.getTarget()))
|
||||
if (!permissionRepository
|
||||
.exists(qPermission.name.eq(clone).and(qPermission.target.eq(permission.getTarget()))
|
||||
.and(qPermission.expires.goe(permission.getExpires())))) {
|
||||
permissions.add(create(permission.getTarget(), clone, permission.isAddon(),
|
||||
permission.getStarts(), permission.getExpires()));
|
||||
permissions.add(create(permission.getTarget(), clone, permission.isAddon(), permission.getStarts(),
|
||||
permission.getExpires()));
|
||||
}
|
||||
}
|
||||
|
||||
@ -225,7 +219,7 @@ public class PermissionManager implements UserDataProvider {
|
||||
* Delete.
|
||||
*
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
*/
|
||||
public void delete(Long target, String name) {
|
||||
for (Permission permission : get(target, name)) {
|
||||
@ -254,14 +248,13 @@ public class PermissionManager implements UserDataProvider {
|
||||
/**
|
||||
* Apply item.
|
||||
*
|
||||
* @param target the target
|
||||
* @param item the item
|
||||
* @param target the target
|
||||
* @param item the item
|
||||
* @param answers the answers
|
||||
* @param starts the starts
|
||||
* @param starts the starts
|
||||
* @param expires the expires
|
||||
*/
|
||||
public void applyItem(Long target, Integer item, JsonArray answers, Instant starts,
|
||||
Instant expires) {
|
||||
public void applyItem(Long target, Integer item, JsonArray answers, Instant starts, Instant expires) {
|
||||
for (Permission permission : getForItem(target, item, answers, starts, expires)) {
|
||||
permissionRepository.save(permission);
|
||||
}
|
||||
@ -270,15 +263,14 @@ public class PermissionManager implements UserDataProvider {
|
||||
/**
|
||||
* Gets the for item.
|
||||
*
|
||||
* @param target the target
|
||||
* @param item the item
|
||||
* @param target the target
|
||||
* @param item the item
|
||||
* @param answers the answers
|
||||
* @param starts the starts
|
||||
* @param starts the starts
|
||||
* @param expires the expires
|
||||
* @return the for item
|
||||
*/
|
||||
public List<Permission> getForItem(Long target, Integer item, JsonArray answers, Instant starts,
|
||||
Instant expires) {
|
||||
public List<Permission> getForItem(Long target, Integer item, JsonArray answers, Instant starts, Instant expires) {
|
||||
List<Permission> permissions = Lists.newArrayList();
|
||||
for (PermissionMapping permissionMapping : permissionMappingManager.getAllByItem(item)) {
|
||||
for (String name : permissionMapping.getNames()) {
|
||||
@ -294,51 +286,42 @@ public class PermissionManager implements UserDataProvider {
|
||||
}
|
||||
|
||||
if (permissionMapping.isLifetimeRound()) {
|
||||
permissionStarts = InstantHelper.truncate(permissionStarts,
|
||||
permissionMapping.getLifetimeUnit());
|
||||
permissionStarts = InstantHelper.truncate(permissionStarts, permissionMapping.getLifetimeUnit());
|
||||
}
|
||||
|
||||
if (permissionsExpires == null) {
|
||||
permissionsExpires = InstantHelper.plus(
|
||||
permissionStarts == null ? Instant.now() : permissionStarts,
|
||||
permissionsExpires = InstantHelper.plus(permissionStarts == null ? Instant.now() : permissionStarts,
|
||||
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit());
|
||||
}
|
||||
|
||||
boolean additional = permissionMapping.isAddon();
|
||||
|
||||
for (JsonElement anwser : answers) {
|
||||
if (anwser.isJsonObject()
|
||||
&& anwser.getAsJsonObject().has("question_identifier")) {
|
||||
if (anwser.isJsonObject() && anwser.getAsJsonObject().has("question_identifier")) {
|
||||
if (StringUtils.hasText(permissionMapping.getStartsQuestion())
|
||||
&& permissionMapping.getStartsQuestion()
|
||||
.equals(anwser.getAsJsonObject().get("question_identifier")
|
||||
.getAsString())
|
||||
.equals(anwser.getAsJsonObject().get("question_identifier").getAsString())
|
||||
&& anwser.getAsJsonObject().has("answer")) {
|
||||
String dateTimeString = anwser.getAsJsonObject().get("answer")
|
||||
.getAsString();
|
||||
String dateTimeString = anwser.getAsJsonObject().get("answer").getAsString();
|
||||
if (StringUtils.hasText(dateTimeString)) {
|
||||
dateTimeString = dateTimeString.replace(" ", "T");
|
||||
permissionStarts = OffsetDateTime.parse(dateTimeString).toInstant();
|
||||
permissionsExpires = InstantHelper.plus(permissionStarts,
|
||||
permissionMapping.getLifetime(),
|
||||
permissionMapping.getLifetimeUnit());
|
||||
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit());
|
||||
additional = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(permissionMapping.getExpiresQuestion())
|
||||
&& permissionMapping.getExpiresQuestion()
|
||||
.equals(anwser.getAsJsonObject().get("question_identifier")
|
||||
.getAsString())
|
||||
.equals(anwser.getAsJsonObject().get("question_identifier").getAsString())
|
||||
&& anwser.getAsJsonObject().has("answer")) {
|
||||
String dateTimeString = anwser.getAsJsonObject().get("answer")
|
||||
.getAsString();
|
||||
String dateTimeString = anwser.getAsJsonObject().get("answer").getAsString();
|
||||
if (StringUtils.hasText(dateTimeString)) {
|
||||
dateTimeString = dateTimeString.replace(" ", "T");
|
||||
permissionsExpires = InstantHelper.plus(
|
||||
OffsetDateTime.parse(dateTimeString).toInstant(),
|
||||
permissionMapping.getLifetime(),
|
||||
permissionMapping.getLifetimeUnit());
|
||||
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit());
|
||||
additional = false;
|
||||
}
|
||||
}
|
||||
@ -372,18 +355,17 @@ public class PermissionManager implements UserDataProvider {
|
||||
permission.setStarts(permissionStarts);
|
||||
permission.setExpires(permissionsExpires);
|
||||
} else {
|
||||
if (permission.getStarts() != null
|
||||
&& permission.getStarts().isBefore(Instant.now())) {
|
||||
if (permission.getStarts() != null && permission.getStarts().isBefore(Instant.now())) {
|
||||
permission.setStarts(null);
|
||||
}
|
||||
|
||||
permission.setExpires(InstantHelper.plus(permission.getExpires(),
|
||||
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit()));
|
||||
permission.setExpires(InstantHelper.plus(permission.getExpires(), permissionMapping.getLifetime(),
|
||||
permissionMapping.getLifetimeUnit()));
|
||||
}
|
||||
|
||||
if (permissionMapping.isLifetimeRound()) {
|
||||
permission.setExpires(InstantHelper.truncate(permission.getExpires(),
|
||||
permissionMapping.getLifetimeUnit()));
|
||||
permission.setExpires(
|
||||
InstantHelper.truncate(permission.getExpires(), permissionMapping.getLifetimeUnit()));
|
||||
}
|
||||
|
||||
permissions.add(permission);
|
||||
|
@ -38,8 +38,7 @@ public class PermissionMappingManager {
|
||||
* @return the all by item
|
||||
*/
|
||||
public List<PermissionMapping> getAllByItem(Integer item) {
|
||||
return Lists.newArrayList(
|
||||
permissionMappingRepository.findAll(qPermissionMapping.item.eq(item)));
|
||||
return Lists.newArrayList(permissionMappingRepository.findAll(qPermissionMapping.item.eq(item)));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -49,8 +48,7 @@ public class PermissionMappingManager {
|
||||
* @return the all by name
|
||||
*/
|
||||
public List<PermissionMapping> getAllByName(String name) {
|
||||
return Lists.newArrayList(
|
||||
permissionMappingRepository.findAll(qPermissionMapping.names.contains(name)));
|
||||
return Lists.newArrayList(permissionMappingRepository.findAll(qPermissionMapping.names.contains(name)));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -71,35 +69,32 @@ public class PermissionMappingManager {
|
||||
* @return true, if successful
|
||||
*/
|
||||
public boolean exists(Integer item, String name) {
|
||||
return permissionMappingRepository.exists(
|
||||
qPermissionMapping.item.eq(item).and(qPermissionMapping.names.contains(name)));
|
||||
return permissionMappingRepository
|
||||
.exists(qPermissionMapping.item.eq(item).and(qPermissionMapping.names.contains(name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the.
|
||||
*
|
||||
* @param item the item
|
||||
* @param names the names
|
||||
* @param lifetime the lifetime
|
||||
* @param lifetimeUnit the lifetime unit
|
||||
* @param lifetimeRound the lifetime round
|
||||
* @param addon the addon
|
||||
* @param product the product
|
||||
* @param starts the starts
|
||||
* @param expires the expires
|
||||
* @param startsQuestion the starts question
|
||||
* @param item the item
|
||||
* @param names the names
|
||||
* @param lifetime the lifetime
|
||||
* @param lifetimeUnit the lifetime unit
|
||||
* @param lifetimeRound the lifetime round
|
||||
* @param addon the addon
|
||||
* @param product the product
|
||||
* @param starts the starts
|
||||
* @param expires the expires
|
||||
* @param startsQuestion the starts question
|
||||
* @param expiresQuestion the expires question
|
||||
* @return the permission mapping
|
||||
*/
|
||||
public PermissionMapping create(Integer item, Set<String> names, Long lifetime,
|
||||
ChronoUnit lifetimeUnit, boolean lifetimeRound, boolean addon, String product,
|
||||
Instant starts, Instant expires, String startsQuestion, String expiresQuestion) {
|
||||
public PermissionMapping create(Integer item, Set<String> names, Long lifetime, ChronoUnit lifetimeUnit,
|
||||
boolean lifetimeRound, boolean addon, String product, Instant starts, Instant expires,
|
||||
String startsQuestion, String expiresQuestion) {
|
||||
for (String name : names) {
|
||||
Assert.isTrue(!exists(item, name), "PermissionMapping for item '"
|
||||
+ item
|
||||
+ "' with permission '"
|
||||
+ name
|
||||
+ "' already exists!");
|
||||
Assert.isTrue(!exists(item, name),
|
||||
"PermissionMapping for item '" + item + "' with permission '" + name + "' already exists!");
|
||||
}
|
||||
PermissionMapping permissionMapping = new PermissionMapping();
|
||||
permissionMapping.setItem(item);
|
||||
@ -132,9 +127,7 @@ public class PermissionMappingManager {
|
||||
* @param id the id
|
||||
*/
|
||||
public void delete(Long id) {
|
||||
Assert.isTrue(permissionMappingRepository.existsById(id), "Permission Mapping '"
|
||||
+ id
|
||||
+ "' does not exists!");
|
||||
Assert.isTrue(permissionMappingRepository.existsById(id), "Permission Mapping '" + id + "' does not exists!");
|
||||
PermissionMapping permissionMapping = permissionMappingRepository.findById(id).get();
|
||||
permissionMappingRepository.delete(permissionMapping);
|
||||
}
|
||||
@ -142,9 +135,9 @@ public class PermissionMappingManager {
|
||||
/**
|
||||
* Gets the.
|
||||
*
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the page
|
||||
*/
|
||||
|
@ -91,9 +91,9 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
private int quotaAddons;
|
||||
protected WebClient webClient;
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
|
||||
* @see org.springframework.beans.factory.SmartInitializingSingleton#
|
||||
* afterSingletonsInstantiated()
|
||||
*/
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
@ -119,21 +119,21 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_CHECKINLIST, ""));
|
||||
}
|
||||
if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS)) {
|
||||
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS, environment
|
||||
.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS, "0"));
|
||||
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS,
|
||||
environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS, "0"));
|
||||
}
|
||||
if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS)) {
|
||||
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS, environment
|
||||
.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS, "0"));
|
||||
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS,
|
||||
environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS, "0"));
|
||||
}
|
||||
|
||||
if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM)) {
|
||||
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, environment
|
||||
.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, "0"));
|
||||
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM,
|
||||
environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIP_ITEM, "0"));
|
||||
}
|
||||
if (!systemPropertyManager.has(SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM)) {
|
||||
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, environment
|
||||
.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, "0"));
|
||||
systemPropertyManager.add(SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM,
|
||||
environment.getProperty("we.bstly." + SYSTEM_PROPERTY_PRETIX_MEMBERSHIPFEE_ITEM, "0"));
|
||||
}
|
||||
|
||||
buildWebClient();
|
||||
@ -148,11 +148,9 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
organizer = systemPropertyManager.get(SYSTEM_PROPERTY_PRETIX_ORGANIZER);
|
||||
event = systemPropertyManager.get(SYSTEM_PROPERTY_PRETIX_EVENT);
|
||||
checkinlist = systemPropertyManager.get(SYSTEM_PROPERTY_PRETIX_CHECKINLIST);
|
||||
quotaRegistration = systemPropertyManager
|
||||
.getInteger(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS);
|
||||
quotaRegistration = systemPropertyManager.getInteger(SYSTEM_PROPERTY_PRETIX_QUOTA_REGISTRATIONS);
|
||||
quotaAddons = systemPropertyManager.getInteger(SYSTEM_PROPERTY_PRETIX_QUOTA_ADDONS);
|
||||
webClient = WebClient.builder().baseUrl(host)
|
||||
.defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
|
||||
webClient = WebClient.builder().baseUrl(host).defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
|
||||
.defaultHeader(HttpHeaders.AUTHORIZATION, "Token " + token).build();
|
||||
}
|
||||
|
||||
@ -199,10 +197,8 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
public JsonObject getCheckInItemBySecret(String secret) {
|
||||
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
|
||||
queryParams.add("secret", secret);
|
||||
JsonObject orderPositions = request(
|
||||
String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/",
|
||||
organizer, event, checkinlist),
|
||||
HttpMethod.GET, queryParams).getAsJsonObject();
|
||||
JsonObject orderPositions = request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/",
|
||||
organizer, event, checkinlist), HttpMethod.GET, queryParams).getAsJsonObject();
|
||||
|
||||
JsonArray results = orderPositions.getAsJsonArray("results");
|
||||
if (results.size() == 1) {
|
||||
@ -219,8 +215,7 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
* @return the order
|
||||
*/
|
||||
public JsonObject getOrder(String code) {
|
||||
return request(
|
||||
String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer, event, code),
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer, event, code),
|
||||
HttpMethod.GET).getAsJsonObject();
|
||||
}
|
||||
|
||||
@ -235,15 +230,14 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
queryParams.add("secret", secret);
|
||||
|
||||
JsonObject orderPositions = request(
|
||||
String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event),
|
||||
HttpMethod.GET, queryParams).getAsJsonObject();
|
||||
String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event), HttpMethod.GET,
|
||||
queryParams).getAsJsonObject();
|
||||
|
||||
JsonArray results = orderPositions.getAsJsonArray("results");
|
||||
if (results.size() == 1) {
|
||||
JsonObject orderPosition = results.get(0).getAsJsonObject();
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer,
|
||||
event, orderPosition.get("order").getAsString()), HttpMethod.GET)
|
||||
.getAsJsonObject();
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/", organizer, event,
|
||||
orderPosition.get("order").getAsString()), HttpMethod.GET).getAsJsonObject();
|
||||
}
|
||||
|
||||
return null;
|
||||
@ -256,20 +250,20 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
* @return the json object
|
||||
*/
|
||||
public JsonObject createOrder(JsonObject order) {
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/orders/", organizer, event),
|
||||
HttpMethod.POST, order).getAsJsonObject();
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/orders/", organizer, event), HttpMethod.POST,
|
||||
order).getAsJsonObject();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extend order.
|
||||
*
|
||||
* @param code the code
|
||||
* @param code the code
|
||||
* @param expire the expire
|
||||
* @return the json object
|
||||
*/
|
||||
public JsonObject extendOrder(String code, JsonObject expire) {
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/extend/", organizer,
|
||||
event, code), HttpMethod.POST, expire).getAsJsonObject();
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/extend/", organizer, event, code),
|
||||
HttpMethod.POST, expire).getAsJsonObject();
|
||||
}
|
||||
|
||||
/**
|
||||
@ -278,8 +272,8 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
* @param code the code
|
||||
*/
|
||||
public void sendEmail(String code) {
|
||||
request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/resend_link/", organizer,
|
||||
event, code), HttpMethod.POST);
|
||||
request(String.format("/api/v1/organizers/%s/events/%s/orders/%s/resend_link/", organizer, event, code),
|
||||
HttpMethod.POST);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -293,8 +287,8 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
queryParams.add("secret", secret);
|
||||
|
||||
JsonObject orderPositions = request(
|
||||
String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event),
|
||||
HttpMethod.GET, queryParams).getAsJsonObject();
|
||||
String.format("/api/v1/organizers/%s/events/%s/orderpositions/", organizer, event), HttpMethod.GET,
|
||||
queryParams).getAsJsonObject();
|
||||
|
||||
JsonArray results = orderPositions.getAsJsonArray("results");
|
||||
if (results.size() == 1) {
|
||||
@ -313,8 +307,7 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
*/
|
||||
public Instant getLastPaymentDateForOrder(String order) {
|
||||
JsonArray paymentResults = request(
|
||||
String.format("/api/v1/organizers/%s/events/%s/orders/%s/payments/", organizer,
|
||||
event, order),
|
||||
String.format("/api/v1/organizers/%s/events/%s/orders/%s/payments/", organizer, event, order),
|
||||
HttpMethod.GET).getAsJsonObject().getAsJsonArray("results");
|
||||
|
||||
Instant lastDate = null;
|
||||
@ -343,10 +336,8 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
public JsonObject getCheckInItemByItem(Integer item) {
|
||||
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
|
||||
queryParams.add("item", String.valueOf(item));
|
||||
JsonObject orderPositions = request(
|
||||
String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/",
|
||||
organizer, event, checkinlist),
|
||||
HttpMethod.GET, queryParams).getAsJsonObject();
|
||||
JsonObject orderPositions = request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/",
|
||||
organizer, event, checkinlist), HttpMethod.GET, queryParams).getAsJsonObject();
|
||||
|
||||
JsonArray results = orderPositions.getAsJsonArray("results");
|
||||
if (results.size() == 1) {
|
||||
@ -377,10 +368,8 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
* @return the check in positions
|
||||
*/
|
||||
public JsonObject getCheckInPositions(String idOrSecret) {
|
||||
return request(
|
||||
String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/",
|
||||
organizer, event, checkinlist, idOrSecret),
|
||||
HttpMethod.GET).getAsJsonObject();
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/", organizer, event,
|
||||
checkinlist, idOrSecret), HttpMethod.GET).getAsJsonObject();
|
||||
}
|
||||
|
||||
/**
|
||||
@ -390,8 +379,7 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
* @return the json object
|
||||
*/
|
||||
public JsonObject redeem(String idOrSecret) {
|
||||
return request(String.format(
|
||||
"/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/redeem/", organizer,
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/checkinlists/%s/positions/%s/redeem/", organizer,
|
||||
event, checkinlist, idOrSecret), HttpMethod.POST).getAsJsonObject();
|
||||
}
|
||||
|
||||
@ -424,8 +412,8 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
voucher.addProperty("max_usages", 1);
|
||||
voucher.addProperty("quota", quotaId);
|
||||
voucher.addProperty("block_quota", true);
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/vouchers/", organizer, event),
|
||||
HttpMethod.POST, voucher).getAsJsonObject();
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/vouchers/", organizer, event), HttpMethod.POST,
|
||||
voucher).getAsJsonObject();
|
||||
}
|
||||
|
||||
/**
|
||||
@ -435,8 +423,7 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
* @return the item
|
||||
*/
|
||||
public JsonObject getItem(Integer item) {
|
||||
return request(
|
||||
String.format("/api/v1/organizers/%s/events/%s/items/%s/", organizer, event, item),
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/items/%s/", organizer, event, item),
|
||||
HttpMethod.GET).getAsJsonObject();
|
||||
}
|
||||
|
||||
@ -447,32 +434,31 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
* @return the variations
|
||||
*/
|
||||
public JsonArray getVariations(Integer item) {
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/",
|
||||
organizer, event, item), HttpMethod.GET).getAsJsonObject()
|
||||
.getAsJsonArray("results");
|
||||
return request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/", organizer, event, item),
|
||||
HttpMethod.GET).getAsJsonObject().getAsJsonArray("results");
|
||||
}
|
||||
|
||||
/**
|
||||
* Update variation.
|
||||
*
|
||||
* @param item the item
|
||||
* @param item the item
|
||||
* @param variationId the variation id
|
||||
* @param variation the variation
|
||||
* @param variation the variation
|
||||
*/
|
||||
public void updateVariation(Integer item, Integer variationId, JsonObject variation) {
|
||||
request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer,
|
||||
event, item, variationId), HttpMethod.PATCH, variation);
|
||||
request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer, event, item,
|
||||
variationId), HttpMethod.PATCH, variation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete variation.
|
||||
*
|
||||
* @param item the item
|
||||
* @param item the item
|
||||
* @param variation the variation
|
||||
*/
|
||||
public void deleteVariation(Integer item, Integer variation) {
|
||||
request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer,
|
||||
event, item, variation), HttpMethod.DELETE);
|
||||
request(String.format("/api/v1/organizers/%s/events/%s/items/%s/variations/%s/", organizer, event, item,
|
||||
variation), HttpMethod.DELETE);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -490,7 +476,7 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
/**
|
||||
* Request.
|
||||
*
|
||||
* @param path the path
|
||||
* @param path the path
|
||||
* @param method the method
|
||||
* @return the json element
|
||||
*/
|
||||
@ -501,21 +487,20 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
/**
|
||||
* Request.
|
||||
*
|
||||
* @param path the path
|
||||
* @param method the method
|
||||
* @param path the path
|
||||
* @param method the method
|
||||
* @param queryParameters the query parameters
|
||||
* @return the json element
|
||||
*/
|
||||
public JsonElement request(String path, HttpMethod method,
|
||||
MultiValueMap<String, String> queryParameters) {
|
||||
public JsonElement request(String path, HttpMethod method, MultiValueMap<String, String> queryParameters) {
|
||||
return request(path, method, null, queryParameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request.
|
||||
*
|
||||
* @param path the path
|
||||
* @param method the method
|
||||
* @param path the path
|
||||
* @param method the method
|
||||
* @param payload the payload
|
||||
* @return the json element
|
||||
*/
|
||||
@ -526,9 +511,9 @@ public class PretixManager implements SmartInitializingSingleton {
|
||||
/**
|
||||
* Request.
|
||||
*
|
||||
* @param path the path
|
||||
* @param method the method
|
||||
* @param payload the payload
|
||||
* @param path the path
|
||||
* @param method the method
|
||||
* @param payload the payload
|
||||
* @param queryParameters the query parameters
|
||||
* @return the json element
|
||||
*/
|
||||
|
@ -33,13 +33,12 @@ public class QuotaManager implements UserDataProvider {
|
||||
* Gets the.
|
||||
*
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @return the quota
|
||||
*/
|
||||
public Quota get(Long target, String name) {
|
||||
if (target != null && name != null) {
|
||||
return quotaRepository.findOne(qQuota.name.eq(name).and(qQuota.target.eq(target)))
|
||||
.orElse(null);
|
||||
return quotaRepository.findOne(qQuota.name.eq(name).and(qQuota.target.eq(target))).orElse(null);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@ -75,8 +74,7 @@ public class QuotaManager implements UserDataProvider {
|
||||
*/
|
||||
public List<Quota> getNotExpiresByTarget(Long target) {
|
||||
if (target != null) {
|
||||
return Lists.newArrayList(
|
||||
quotaRepository.findAll(qQuota.target.eq(target).and(qQuota.value.gt(0))));
|
||||
return Lists.newArrayList(quotaRepository.findAll(qQuota.target.eq(target).and(qQuota.value.gt(0))));
|
||||
}
|
||||
return Lists.newArrayList();
|
||||
}
|
||||
@ -85,21 +83,21 @@ public class QuotaManager implements UserDataProvider {
|
||||
* Checks for quota.
|
||||
*
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @return true, if successful
|
||||
*/
|
||||
public boolean hasQuota(Long target, String name) {
|
||||
return target != null && quotaRepository
|
||||
.exists(qQuota.name.eq(name).and(qQuota.target.eq(target)).and(qQuota.value.gt(0)));
|
||||
return target != null
|
||||
&& quotaRepository.exists(qQuota.name.eq(name).and(qQuota.target.eq(target)).and(qQuota.value.gt(0)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the.
|
||||
*
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param value the value
|
||||
* @param unit the unit
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param value the value
|
||||
* @param unit the unit
|
||||
* @param disposable the disposable
|
||||
* @return the quota
|
||||
*/
|
||||
@ -121,17 +119,10 @@ public class QuotaManager implements UserDataProvider {
|
||||
* @return the quota
|
||||
*/
|
||||
public Quota update(Quota quota) {
|
||||
Assert.isTrue(
|
||||
quotaRepository.exists(
|
||||
qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))),
|
||||
"Quota '"
|
||||
+ quota.getName()
|
||||
+ "' for target + '"
|
||||
+ quota.getTarget()
|
||||
+ "' not exists!");
|
||||
Assert.isTrue(quotaRepository.exists(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))),
|
||||
"Quota '" + quota.getName() + "' for target + '" + quota.getTarget() + "' not exists!");
|
||||
Quota updateQuota = quotaRepository
|
||||
.findOne(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName())))
|
||||
.get();
|
||||
.findOne(qQuota.target.eq(quota.getTarget()).and(qQuota.name.eq(quota.getName()))).get();
|
||||
updateQuota.setValue(quota.getValue());
|
||||
updateQuota.setUnit(quota.getUnit());
|
||||
updateQuota.setDisposable(quota.isDisposable());
|
||||
@ -141,7 +132,7 @@ public class QuotaManager implements UserDataProvider {
|
||||
/**
|
||||
* Clone.
|
||||
*
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @param clone the clone
|
||||
* @param value the value
|
||||
* @return the list
|
||||
@ -150,10 +141,9 @@ public class QuotaManager implements UserDataProvider {
|
||||
List<Quota> quotas = Lists.newArrayList();
|
||||
|
||||
for (Quota quota : quotaRepository.findAll(qQuota.name.eq(name))) {
|
||||
if (!quotaRepository
|
||||
.exists(qQuota.name.eq(clone).and(qQuota.target.eq(quota.getTarget())))) {
|
||||
quotas.add(create(quota.getTarget(), clone, value >= 0 ? value : quota.getValue(),
|
||||
quota.getUnit(), quota.isDisposable()));
|
||||
if (!quotaRepository.exists(qQuota.name.eq(clone).and(qQuota.target.eq(quota.getTarget())))) {
|
||||
quotas.add(create(quota.getTarget(), clone, value >= 0 ? value : quota.getValue(), quota.getUnit(),
|
||||
quota.isDisposable()));
|
||||
}
|
||||
}
|
||||
|
||||
@ -164,17 +154,12 @@ public class QuotaManager implements UserDataProvider {
|
||||
* Delete.
|
||||
*
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
*/
|
||||
public void delete(Long target, String name) {
|
||||
Assert.isTrue(quotaRepository.exists(qQuota.target.eq(target).and(qQuota.name.eq(name))),
|
||||
"Quota '"
|
||||
+ name
|
||||
+ "' for target + '"
|
||||
+ target
|
||||
+ "' not exists!");
|
||||
Quota delete = quotaRepository.findOne(qQuota.target.eq(target).and(qQuota.name.eq(name)))
|
||||
.get();
|
||||
"Quota '" + name + "' for target + '" + target + "' not exists!");
|
||||
Quota delete = quotaRepository.findOne(qQuota.target.eq(target).and(qQuota.name.eq(name))).get();
|
||||
quotaRepository.delete(delete);
|
||||
}
|
||||
|
||||
@ -200,7 +185,7 @@ public class QuotaManager implements UserDataProvider {
|
||||
* Adds the for item.
|
||||
*
|
||||
* @param target the target
|
||||
* @param item the item
|
||||
* @param item the item
|
||||
* @param quotas the quotas
|
||||
*/
|
||||
public void addForItem(Long target, Integer item, List<Quota> quotas) {
|
||||
@ -208,9 +193,8 @@ public class QuotaManager implements UserDataProvider {
|
||||
boolean added = false;
|
||||
for (Quota quota : quotas) {
|
||||
if (quota.getName().equals(quotaMapping.getName())) {
|
||||
quota.setValue(
|
||||
quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
|
||||
: quotaMapping.getValue());
|
||||
quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
|
||||
: quotaMapping.getValue());
|
||||
added = true;
|
||||
}
|
||||
}
|
||||
@ -219,9 +203,8 @@ public class QuotaManager implements UserDataProvider {
|
||||
if (target != null && hasQuota(target, quotaMapping.getName())) {
|
||||
Quota quota = get(target, quotaMapping.getName());
|
||||
|
||||
quota.setValue(
|
||||
quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
|
||||
: quotaMapping.getValue());
|
||||
quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
|
||||
: quotaMapping.getValue());
|
||||
|
||||
quotas.add(quota);
|
||||
added = true;
|
||||
@ -242,18 +225,18 @@ public class QuotaManager implements UserDataProvider {
|
||||
* Apply item.
|
||||
*
|
||||
* @param target the target
|
||||
* @param item the item
|
||||
* @param item the item
|
||||
*/
|
||||
public void applyItem(Long target, Integer item) {
|
||||
for (QuotaMapping quotaMapping : quotaMappingManager.getAllByItem(item)) {
|
||||
Quota quota = get(target, quotaMapping.getName());
|
||||
if (quota == null) {
|
||||
quota = create(target, quotaMapping.getName(), quotaMapping.getValue(),
|
||||
quotaMapping.getUnit(), quotaMapping.isDisposable());
|
||||
quota = create(target, quotaMapping.getName(), quotaMapping.getValue(), quotaMapping.getUnit(),
|
||||
quotaMapping.isDisposable());
|
||||
|
||||
} else {
|
||||
quota.setValue(quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue()
|
||||
: quotaMapping.getValue());
|
||||
quota.setValue(
|
||||
quotaMapping.isAppend() ? quota.getValue() + quotaMapping.getValue() : quotaMapping.getValue());
|
||||
quota = update(quota);
|
||||
}
|
||||
|
||||
|
@ -36,8 +36,7 @@ public class QuotaMappingManager {
|
||||
* @return the all by item
|
||||
*/
|
||||
public List<QuotaMapping> getAllByItem(Integer item) {
|
||||
return Lists
|
||||
.newArrayList(quotaMappingRepository.findAll(qQuotaMapping.items.contains(item)));
|
||||
return Lists.newArrayList(quotaMappingRepository.findAll(qQuotaMapping.items.contains(item)));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -58,27 +57,26 @@ public class QuotaMappingManager {
|
||||
* @return true, if successful
|
||||
*/
|
||||
public boolean exists(Integer item, String name) {
|
||||
return quotaMappingRepository
|
||||
.exists(qQuotaMapping.items.contains(item).and(qQuotaMapping.name.eq(name)));
|
||||
return quotaMappingRepository.exists(qQuotaMapping.items.contains(item).and(qQuotaMapping.name.eq(name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the.
|
||||
*
|
||||
* @param items the items
|
||||
* @param name the name
|
||||
* @param value the value
|
||||
* @param unit the unit
|
||||
* @param append the append
|
||||
* @param products the products
|
||||
* @param items the items
|
||||
* @param name the name
|
||||
* @param value the value
|
||||
* @param unit the unit
|
||||
* @param append the append
|
||||
* @param products the products
|
||||
* @param disposable the disposable
|
||||
* @return the quota mapping
|
||||
*/
|
||||
public QuotaMapping create(Set<Integer> items, String name, long value, String unit,
|
||||
boolean append, Set<String> products, boolean disposable) {
|
||||
public QuotaMapping create(Set<Integer> items, String name, long value, String unit, boolean append,
|
||||
Set<String> products, boolean disposable) {
|
||||
for (Integer item : items) {
|
||||
Assert.isTrue(!exists(item, name), "QuotaMapping for item '" + item + "' with quota '"
|
||||
+ name + "' already exists!");
|
||||
Assert.isTrue(!exists(item, name),
|
||||
"QuotaMapping for item '" + item + "' with quota '" + name + "' already exists!");
|
||||
}
|
||||
QuotaMapping quotaMapping = new QuotaMapping();
|
||||
quotaMapping.setItems(items);
|
||||
@ -98,13 +96,10 @@ public class QuotaMappingManager {
|
||||
* @return the quota mapping
|
||||
*/
|
||||
public QuotaMapping update(QuotaMapping quotaMapping) {
|
||||
Assert.isTrue(
|
||||
quotaMapping.getId() != null
|
||||
&& quotaMappingRepository.existsById(quotaMapping.getId()),
|
||||
Assert.isTrue(quotaMapping.getId() != null && quotaMappingRepository.existsById(quotaMapping.getId()),
|
||||
"QuotaMapping '" + quotaMapping.getId() + "' does not exists!");
|
||||
|
||||
QuotaMapping updateQuotaMapping = quotaMappingRepository.findById(quotaMapping.getId())
|
||||
.get();
|
||||
QuotaMapping updateQuotaMapping = quotaMappingRepository.findById(quotaMapping.getId()).get();
|
||||
updateQuotaMapping.setProducts(quotaMapping.getProducts());
|
||||
updateQuotaMapping.setItems(quotaMapping.getItems());
|
||||
updateQuotaMapping.setValue(quotaMapping.getValue());
|
||||
@ -120,17 +115,16 @@ public class QuotaMappingManager {
|
||||
* @param id the id
|
||||
*/
|
||||
public void delete(Long id) {
|
||||
Assert.isTrue(quotaMappingRepository.existsById(id),
|
||||
"QuotaMapping '" + id + "' does not exists!");
|
||||
Assert.isTrue(quotaMappingRepository.existsById(id), "QuotaMapping '" + id + "' does not exists!");
|
||||
quotaMappingRepository.deleteById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the.
|
||||
*
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the page
|
||||
*/
|
||||
|
@ -52,9 +52,9 @@ public class Setup implements SmartInitializingSingleton {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(Setup.class);
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
|
||||
* @see org.springframework.beans.factory.SmartInitializingSingleton#
|
||||
* afterSingletonsInstantiated()
|
||||
*/
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
@ -75,14 +75,12 @@ public class Setup implements SmartInitializingSingleton {
|
||||
Resource resource = resourceLoader.getResource("classpath:usernames.txt");
|
||||
|
||||
if (resource.exists()) {
|
||||
BufferedReader br = new BufferedReader(
|
||||
new InputStreamReader(resource.getInputStream()));
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
|
||||
List<String> usernames = Lists.newArrayList();
|
||||
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
if (StringUtils.hasText(line) && !usernames.contains(line)
|
||||
&& !line.startsWith("#")) {
|
||||
if (StringUtils.hasText(line) && !usernames.contains(line) && !line.startsWith("#")) {
|
||||
usernames.add(line);
|
||||
}
|
||||
}
|
||||
|
@ -44,9 +44,9 @@ public class SystemProfileFieldManager {
|
||||
/**
|
||||
* Gets the.
|
||||
*
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the page
|
||||
*/
|
||||
|
@ -42,13 +42,12 @@ public class SystemPropertyManager {
|
||||
/**
|
||||
* Gets the.
|
||||
*
|
||||
* @param key the key
|
||||
* @param key the key
|
||||
* @param defaultValue the default value
|
||||
* @return the string
|
||||
*/
|
||||
public String get(String key, String defaultValue) {
|
||||
return systemPropertyRepository.findById(key).orElse(new SystemProperty(key, defaultValue))
|
||||
.getValue();
|
||||
return systemPropertyRepository.findById(key).orElse(new SystemProperty(key, defaultValue)).getValue();
|
||||
}
|
||||
|
||||
/**
|
||||
@ -64,7 +63,7 @@ public class SystemPropertyManager {
|
||||
/**
|
||||
* Gets the boolean.
|
||||
*
|
||||
* @param key the key
|
||||
* @param key the key
|
||||
* @param defaultValue the default value
|
||||
* @return the boolean
|
||||
*/
|
||||
@ -85,7 +84,7 @@ public class SystemPropertyManager {
|
||||
/**
|
||||
* Gets the integer.
|
||||
*
|
||||
* @param key the key
|
||||
* @param key the key
|
||||
* @param defaultValue the default value
|
||||
* @return the integer
|
||||
*/
|
||||
@ -106,7 +105,7 @@ public class SystemPropertyManager {
|
||||
/**
|
||||
* Gets the long.
|
||||
*
|
||||
* @param key the key
|
||||
* @param key the key
|
||||
* @param defaultValue the default value
|
||||
* @return the long
|
||||
*/
|
||||
@ -117,7 +116,7 @@ public class SystemPropertyManager {
|
||||
/**
|
||||
* Adds the.
|
||||
*
|
||||
* @param key the key
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
*/
|
||||
public void add(String key, String value) {
|
||||
@ -129,7 +128,7 @@ public class SystemPropertyManager {
|
||||
/**
|
||||
* Update.
|
||||
*
|
||||
* @param key the key
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
*/
|
||||
public void update(String key, String value) {
|
||||
@ -143,7 +142,7 @@ public class SystemPropertyManager {
|
||||
/**
|
||||
* Sets the.
|
||||
*
|
||||
* @param key the key
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
*/
|
||||
public void set(String key, String value) {
|
||||
|
@ -89,9 +89,9 @@ public class UserAliasManager implements UserDataProvider {
|
||||
/**
|
||||
* Gets the.
|
||||
*
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the page
|
||||
*/
|
||||
|
@ -61,9 +61,7 @@ public class UserDataManager implements SmartInitializingSingleton {
|
||||
private Gson gson = new Gson();
|
||||
|
||||
/*
|
||||
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
|
||||
*/
|
||||
/*
|
||||
*
|
||||
* @see org.springframework.beans.factory.SmartInitializingSingleton#
|
||||
* afterSingletonsInstantiated()
|
||||
*/
|
||||
@ -90,8 +88,7 @@ public class UserDataManager implements SmartInitializingSingleton {
|
||||
* @param dry the dry
|
||||
*/
|
||||
public void purge(boolean dry) {
|
||||
long days = systemPropertyManager.getLong(SYSTEM_PROPERTY_USERDATA_DAYS,
|
||||
SYSTEM_PROPERTY_USERDATA_DAYS_DEFAULT);
|
||||
long days = systemPropertyManager.getLong(SYSTEM_PROPERTY_USERDATA_DAYS, SYSTEM_PROPERTY_USERDATA_DAYS_DEFAULT);
|
||||
|
||||
Pageable pageable = PageRequest.of(0, 100, Sort.by("id"));
|
||||
Page<User> page;
|
||||
@ -99,14 +96,12 @@ public class UserDataManager implements SmartInitializingSingleton {
|
||||
page = userRepository.findAll(pageable);
|
||||
for (User user : page.getContent()) {
|
||||
if (!UserStatus.SLEEP.equals(user.getStatus())) {
|
||||
if (permissionManager.getNotExpiresByTargetIgnoreStart(user.getId())
|
||||
.isEmpty()) {
|
||||
if (permissionManager.getNotExpiresByTargetIgnoreStart(user.getId()).isEmpty()) {
|
||||
if (UserStatus.PURGE.equals(user.getStatus())) {
|
||||
purge(user, dry);
|
||||
} else if (UserStatus.NORMAL.equals(user.getStatus())) {
|
||||
Instant last = Instant.MIN;
|
||||
for (Permission permission : permissionManager
|
||||
.getAllByTarget(user.getId())) {
|
||||
for (Permission permission : permissionManager.getAllByTarget(user.getId())) {
|
||||
if (permission.getExpires().isAfter(last)) {
|
||||
last = permission.getExpires();
|
||||
}
|
||||
@ -127,56 +122,36 @@ public class UserDataManager implements SmartInitializingSingleton {
|
||||
* Purge.
|
||||
*
|
||||
* @param user the user
|
||||
* @param dry the dry
|
||||
* @param dry the dry
|
||||
*/
|
||||
public void purge(User user, boolean dry) {
|
||||
Long userId = user.getId();
|
||||
if (dry) {
|
||||
logger.debug("Would purge all data of user '"
|
||||
+ user.getUsername()
|
||||
+ "' [id="
|
||||
+ user.getId()
|
||||
+ "]!");
|
||||
logger.debug("Would purge all data of user '" + user.getUsername() + "' [id=" + user.getId() + "]!");
|
||||
} else {
|
||||
logger.warn("Purge all data of user '"
|
||||
+ user.getUsername()
|
||||
+ "' [id="
|
||||
+ user.getId()
|
||||
+ "]!");
|
||||
logger.warn("Purge all data of user '" + user.getUsername() + "' [id=" + user.getId() + "]!");
|
||||
}
|
||||
|
||||
for (UserDataProvider provider : providers) {
|
||||
if (dry) {
|
||||
List<UserData> result = provider.getUserData(userId);
|
||||
if (!result.isEmpty()) {
|
||||
logger.debug("\tWould have purged '"
|
||||
+ provider.getId()
|
||||
+ "' data of user '"
|
||||
+ user.getUsername()
|
||||
+ "' [id="
|
||||
+ user.getId()
|
||||
+ "]!");
|
||||
logger.debug("\tWould have purged '" + provider.getId() + "' data of user '" + user.getUsername()
|
||||
+ "' [id=" + user.getId() + "]!");
|
||||
if (logger.isTraceEnabled()) {
|
||||
for (UserData userData : result) {
|
||||
logger.trace("\t\t"
|
||||
+ gson.toJson(userData));
|
||||
logger.trace("\t\t" + gson.toJson(userData));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
List<UserData> result = provider.getUserData(userId);
|
||||
if (!result.isEmpty()) {
|
||||
logger.warn("\tPurge '"
|
||||
+ provider.getId()
|
||||
+ "' data of user '"
|
||||
+ user.getUsername()
|
||||
+ "' [id="
|
||||
+ user.getId()
|
||||
+ "]!");
|
||||
logger.warn("\tPurge '" + provider.getId() + "' data of user '" + user.getUsername() + "' [id="
|
||||
+ user.getId() + "]!");
|
||||
if (logger.isTraceEnabled()) {
|
||||
for (UserData userData : result) {
|
||||
logger.trace("\t\t"
|
||||
+ gson.toJson(userData));
|
||||
logger.trace("\t\t" + gson.toJson(userData));
|
||||
}
|
||||
}
|
||||
provider.purgeUserData(userId);
|
||||
@ -185,11 +160,7 @@ public class UserDataManager implements SmartInitializingSingleton {
|
||||
}
|
||||
|
||||
if (!dry) {
|
||||
logger.warn("Purged all data of user '"
|
||||
+ user.getUsername()
|
||||
+ "' [id="
|
||||
+ user.getId()
|
||||
+ "]!");
|
||||
logger.warn("Purged all data of user '" + user.getUsername() + "' [id=" + user.getId() + "]!");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -119,9 +119,9 @@ public class UserDomainManager implements UserDataProvider {
|
||||
/**
|
||||
* Gets the.
|
||||
*
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the page
|
||||
*/
|
||||
@ -161,8 +161,7 @@ public class UserDomainManager implements UserDataProvider {
|
||||
* @throws NamingException the naming exception
|
||||
*/
|
||||
public boolean validate(UserDomain userDomain) throws NamingException {
|
||||
Attributes attributes = dirContext.getAttributes("_bstly." + userDomain.getDomain(),
|
||||
new String[] { "TXT" });
|
||||
Attributes attributes = dirContext.getAttributes("_bstly." + userDomain.getDomain(), new String[] { "TXT" });
|
||||
|
||||
NamingEnumeration<? extends Attribute> attributeEnumeration = attributes.getAll();
|
||||
while (attributeEnumeration.hasMore()) {
|
||||
|
@ -87,8 +87,7 @@ public class UserManager implements UserDataProvider {
|
||||
* @return the by bstly email
|
||||
*/
|
||||
public User getByBstlyEmail(String email) {
|
||||
String username = email.replace("@"
|
||||
+ userEmailDomain, "");
|
||||
String username = email.replace("@" + userEmailDomain, "");
|
||||
return getByUsername(username);
|
||||
}
|
||||
|
||||
@ -109,23 +108,19 @@ public class UserManager implements UserDataProvider {
|
||||
* @return the password hash
|
||||
*/
|
||||
public String getPasswordHash(Long id) {
|
||||
Assert.isTrue(userRepository.existsById(id), "User with id '"
|
||||
+ id
|
||||
+ "' not exists!");
|
||||
Assert.isTrue(userRepository.existsById(id), "User with id '" + id + "' not exists!");
|
||||
return userRepository.findById(id).get().getPasswordHash();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the password.
|
||||
*
|
||||
* @param id the id
|
||||
* @param id the id
|
||||
* @param password the password
|
||||
* @return the user
|
||||
*/
|
||||
public User setPassword(Long id, String password) {
|
||||
Assert.isTrue(userRepository.existsById(id), "User with id '"
|
||||
+ id
|
||||
+ "' not exists!");
|
||||
Assert.isTrue(userRepository.existsById(id), "User with id '" + id + "' not exists!");
|
||||
User user = userRepository.findById(id).get();
|
||||
user.setPasswordHash(passwordEncoder.encode(password));
|
||||
return userRepository.save(user);
|
||||
@ -136,14 +131,12 @@ public class UserManager implements UserDataProvider {
|
||||
*
|
||||
* @param username the username
|
||||
* @param password the password
|
||||
* @param status the status
|
||||
* @param status the status
|
||||
* @return the user
|
||||
*/
|
||||
public User create(String username, String password, UserStatus status) {
|
||||
Assert.isTrue(!userRepository.exists(qUser.username.equalsIgnoreCase(username)),
|
||||
"Username '"
|
||||
+ username
|
||||
+ "' already exists!");
|
||||
"Username '" + username + "' already exists!");
|
||||
User user = new User();
|
||||
user.setUsername(username);
|
||||
if (StringUtils.hasText(password)) {
|
||||
@ -160,9 +153,9 @@ public class UserManager implements UserDataProvider {
|
||||
/**
|
||||
* Gets the.
|
||||
*
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the page
|
||||
*/
|
||||
@ -178,9 +171,7 @@ public class UserManager implements UserDataProvider {
|
||||
* @return the user
|
||||
*/
|
||||
public User update(User user) {
|
||||
Assert.isTrue(userRepository.existsById(user.getId()), "User with id '"
|
||||
+ user.getId()
|
||||
+ "' not exists!");
|
||||
Assert.isTrue(userRepository.existsById(user.getId()), "User with id '" + user.getId() + "' not exists!");
|
||||
|
||||
User merge = get(user.getId());
|
||||
merge.setUsername(user.getUsername());
|
||||
@ -201,9 +192,7 @@ public class UserManager implements UserDataProvider {
|
||||
* @param user the user
|
||||
*/
|
||||
public void delete(User user) {
|
||||
Assert.isTrue(userRepository.existsById(user.getId()), "User with id '"
|
||||
+ user.getId()
|
||||
+ "' not exists!");
|
||||
Assert.isTrue(userRepository.existsById(user.getId()), "User with id '" + user.getId() + "' not exists!");
|
||||
|
||||
File publicKey = new File(getPublicKeyPath(user.getUsername()));
|
||||
if (publicKey.exists()) {
|
||||
@ -222,15 +211,13 @@ public class UserManager implements UserDataProvider {
|
||||
* @return the bstly email
|
||||
*/
|
||||
public String getBstlyEmail(String username) {
|
||||
return username
|
||||
+ "@"
|
||||
+ userEmailDomain;
|
||||
return username + "@" + userEmailDomain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write public key.
|
||||
*
|
||||
* @param username the username
|
||||
* @param username the username
|
||||
* @param publicKey the public key
|
||||
*/
|
||||
public void writePublicKey(String username, String publicKey) {
|
||||
@ -250,8 +237,7 @@ public class UserManager implements UserDataProvider {
|
||||
FileWriter myWriter = new FileWriter(publicKeyPath);
|
||||
myWriter.write(publicKey);
|
||||
myWriter.close();
|
||||
String command = "gpg --import "
|
||||
+ publicKeyPath;
|
||||
String command = "gpg --import " + publicKeyPath;
|
||||
Runtime.getRuntime().exec(command);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
@ -266,25 +252,19 @@ public class UserManager implements UserDataProvider {
|
||||
* @return the public key path
|
||||
*/
|
||||
public String getPublicKeyPath(String username) {
|
||||
return userDataDirectory
|
||||
+ username
|
||||
+ File.separator
|
||||
+ "public.key";
|
||||
return userDataDirectory + username + File.separator + "public.key";
|
||||
}
|
||||
|
||||
/**
|
||||
* Password reset.
|
||||
*
|
||||
* @param user the user
|
||||
* @param user the user
|
||||
* @param outputStream the output stream
|
||||
*/
|
||||
public void passwordReset(User user, ServletOutputStream outputStream) {
|
||||
// TODO: change to public key profile field
|
||||
String resetToken = RandomStringUtils.random(64, true, true);
|
||||
String command = "echo \""
|
||||
+ resetToken
|
||||
+ "\" | gpg -ear "
|
||||
+ getBstlyEmail(user.getUsername())
|
||||
String command = "echo \"" + resetToken + "\" | gpg -ear " + getBstlyEmail(user.getUsername())
|
||||
+ " --always-trust";
|
||||
|
||||
user.setResetToken(resetToken);
|
||||
@ -293,10 +273,8 @@ public class UserManager implements UserDataProvider {
|
||||
ProcessBuilder b = new ProcessBuilder("/bin/bash", "-c", command);
|
||||
Process process = b.start();
|
||||
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(process.getInputStream()));
|
||||
BufferedReader errorReader = new BufferedReader(
|
||||
new InputStreamReader(process.getErrorStream()));
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
|
||||
int c;
|
||||
while ((c = reader.read()) != -1) {
|
||||
outputStream.write(c);
|
||||
@ -328,8 +306,7 @@ public class UserManager implements UserDataProvider {
|
||||
* @param user the user
|
||||
*/
|
||||
protected void deleteSessionsForUser(User user) {
|
||||
Map<String, ? extends Session> usersSessions = sessionRepository
|
||||
.findByPrincipalName(user.getUsername());
|
||||
Map<String, ? extends Session> usersSessions = sessionRepository.findByPrincipalName(user.getUsername());
|
||||
for (Session session : usersSessions.values()) {
|
||||
sessionRepository.deleteById(session.getId());
|
||||
}
|
||||
@ -363,16 +340,10 @@ public class UserManager implements UserDataProvider {
|
||||
user.setDisabled(true);
|
||||
user.setLocked(true);
|
||||
user = update(user);
|
||||
logger.warn("User '"
|
||||
+ user.getUsername()
|
||||
+ "' ["
|
||||
+ user.getId()
|
||||
+ "] should be purged!");
|
||||
logger.warn("User '" + user.getUsername() + "' [" + user.getId() + "] should be purged!");
|
||||
|
||||
} else {
|
||||
logger.error("No user found for ["
|
||||
+ userId
|
||||
+ "]!");
|
||||
logger.error("No user found for [" + userId + "]!");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -32,13 +32,12 @@ public class UserProfileFieldManager implements UserDataProvider {
|
||||
* Gets the.
|
||||
*
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @return the user profile field
|
||||
*/
|
||||
public UserProfileField get(Long target, String name) {
|
||||
return userProfileFieldRepository
|
||||
.findOne(qUserProfileField.name.eq(name).and(qUserProfileField.target.eq(target)))
|
||||
.orElse(null);
|
||||
.findOne(qUserProfileField.name.eq(name).and(qUserProfileField.target.eq(target))).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -48,15 +47,15 @@ public class UserProfileFieldManager implements UserDataProvider {
|
||||
* @return the all by target
|
||||
*/
|
||||
public List<UserProfileField> getAllByTarget(Long target) {
|
||||
return Lists.newArrayList(userProfileFieldRepository.findAll(
|
||||
qUserProfileField.target.eq(target), Sort.by("index", "name").ascending()));
|
||||
return Lists.newArrayList(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target),
|
||||
Sort.by("index", "name").ascending()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the by target filtered.
|
||||
*
|
||||
* @param target the target
|
||||
* @param names the names
|
||||
* @param names the names
|
||||
* @return the by target filtered
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* @param target the target
|
||||
* @param target the target
|
||||
* @param visibilities the visibilities
|
||||
* @return the all by target and visibilities
|
||||
*/
|
||||
public List<UserProfileField> getAllByTargetAndVisibilities(Long target,
|
||||
List<Visibility> visibilities) {
|
||||
public List<UserProfileField> getAllByTargetAndVisibilities(Long target, List<Visibility> visibilities) {
|
||||
return Lists.newArrayList(userProfileFieldRepository.findAll(
|
||||
qUserProfileField.target.eq(target)
|
||||
.and(qUserProfileField.visibility.in(visibilities)),
|
||||
qUserProfileField.target.eq(target).and(qUserProfileField.visibility.in(visibilities)),
|
||||
Sort.by("index", "name").ascending()));
|
||||
}
|
||||
|
||||
@ -94,20 +91,15 @@ public class UserProfileFieldManager implements UserDataProvider {
|
||||
* Delete.
|
||||
*
|
||||
* @param target the target
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
*/
|
||||
public void delete(Long target, String name) {
|
||||
Assert.isTrue(
|
||||
userProfileFieldRepository.exists(
|
||||
qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))),
|
||||
"ProfileField '"
|
||||
+ name
|
||||
+ "' for target + '"
|
||||
+ target
|
||||
+ "' not exists!");
|
||||
userProfileFieldRepository
|
||||
.exists(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))),
|
||||
"ProfileField '" + name + "' for target + '" + target + "' not exists!");
|
||||
UserProfileField delete = userProfileFieldRepository
|
||||
.findOne(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name)))
|
||||
.get();
|
||||
.findOne(qUserProfileField.target.eq(target).and(qUserProfileField.name.eq(name))).get();
|
||||
userProfileFieldRepository.delete(delete);
|
||||
}
|
||||
|
||||
@ -117,8 +109,7 @@ public class UserProfileFieldManager implements UserDataProvider {
|
||||
* @param target the target
|
||||
*/
|
||||
public void deleteAll(Long target) {
|
||||
userProfileFieldRepository
|
||||
.deleteAll(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target)));
|
||||
userProfileFieldRepository.deleteAll(userProfileFieldRepository.findAll(qUserProfileField.target.eq(target)));
|
||||
}
|
||||
|
||||
/*
|
||||
|
@ -50,27 +50,30 @@ public class UserTotpManager implements SecondFactorProvider<UserTotp> {
|
||||
return "totp";
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#supports(java.lang.String)
|
||||
* @see
|
||||
* de.bstly.we.security.businesslogic.SecondFactorProvider#supports(java.lang.
|
||||
* String)
|
||||
*/
|
||||
@Override
|
||||
public boolean supports(String provider) {
|
||||
return getId().equals(provider);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#isEnabled(java.lang.Long)
|
||||
* @see
|
||||
* de.bstly.we.security.businesslogic.SecondFactorProvider#isEnabled(java.lang.
|
||||
* Long)
|
||||
*/
|
||||
@Override
|
||||
public boolean isEnabled(Long userId) {
|
||||
return userTotpRepository
|
||||
.exists(qUserTotp.target.eq(userId).and(qUserTotp.enabled.isTrue()));
|
||||
return userTotpRepository.exists(qUserTotp.target.eq(userId).and(qUserTotp.enabled.isTrue()));
|
||||
}
|
||||
|
||||
/*
|
||||
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#validate(java.lang.Long, java.lang.String)
|
||||
* @see
|
||||
* de.bstly.we.security.businesslogic.SecondFactorProvider#validate(java.lang.
|
||||
* Long, java.lang.String)
|
||||
*/
|
||||
@Override
|
||||
public boolean validate(Long userId, String code) {
|
||||
@ -83,18 +86,19 @@ public class UserTotpManager implements SecondFactorProvider<UserTotp> {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#get(java.lang.Long)
|
||||
* @see
|
||||
* de.bstly.we.security.businesslogic.SecondFactorProvider#get(java.lang.Long)
|
||||
*/
|
||||
@Override
|
||||
public UserTotp get(Long userId) {
|
||||
return userTotpRepository.findOne(qUserTotp.target.eq(userId)).orElse(null);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#create(java.lang.Long)
|
||||
* @see
|
||||
* de.bstly.we.security.businesslogic.SecondFactorProvider#create(java.lang.
|
||||
* Long)
|
||||
*/
|
||||
@Override
|
||||
public UserTotp create(Long userId) {
|
||||
@ -105,8 +109,8 @@ public class UserTotpManager implements SecondFactorProvider<UserTotp> {
|
||||
userTotp.setSecret(secretGenerator.generate());
|
||||
|
||||
User user = userManager.get(userId);
|
||||
QrData data = qrDataFactory.newBuilder().label(user.getUsername())
|
||||
.secret(userTotp.getSecret()).issuer("we.bstly").build();
|
||||
QrData data = qrDataFactory.newBuilder().label(user.getUsername()).secret(userTotp.getSecret())
|
||||
.issuer("we.bstly").build();
|
||||
userTotp.setQrData(data.getUri());
|
||||
userTotp.setRecoveryCodes(Lists.newArrayList(recoveryCodeGenerator.generateCodes(16)));
|
||||
return userTotpRepository.save(userTotp);
|
||||
@ -114,15 +118,15 @@ public class UserTotpManager implements SecondFactorProvider<UserTotp> {
|
||||
return userTotpRepository.findOne(qUserTotp.target.eq(userId)).orElse(null);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#enable(java.lang.Long, java.lang.String)
|
||||
* @see
|
||||
* de.bstly.we.security.businesslogic.SecondFactorProvider#enable(java.lang.
|
||||
* Long, java.lang.String)
|
||||
*/
|
||||
@Override
|
||||
public boolean enable(Long userId, String code) {
|
||||
if (validate(userId, code)) {
|
||||
UserTotp userTotp = userTotpRepository.findOne(qUserTotp.target.eq(userId))
|
||||
.orElse(null);
|
||||
UserTotp userTotp = userTotpRepository.findOne(qUserTotp.target.eq(userId)).orElse(null);
|
||||
userTotp.setEnabled(true);
|
||||
userTotpRepository.save(userTotp);
|
||||
return true;
|
||||
@ -130,9 +134,10 @@ public class UserTotpManager implements SecondFactorProvider<UserTotp> {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see de.bstly.we.security.businesslogic.SecondFactorProvider#delete(java.lang.Long)
|
||||
* @see
|
||||
* de.bstly.we.security.businesslogic.SecondFactorProvider#delete(java.lang.
|
||||
* Long)
|
||||
*/
|
||||
@Override
|
||||
public void delete(Long userId) {
|
||||
|
@ -59,18 +59,14 @@ public class VoucherMappingManager {
|
||||
/**
|
||||
* Creates the.
|
||||
*
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @param voucher the voucher
|
||||
* @param quota the quota
|
||||
* @param isFree the is free
|
||||
* @param quota the quota
|
||||
* @param isFree the is free
|
||||
* @return the voucher mapping
|
||||
*/
|
||||
public VoucherMapping create(String name, int voucher, String quota, boolean isFree) {
|
||||
Assert.isTrue(!exists(name), "QuotaMapping for voucher '"
|
||||
+ voucher
|
||||
+ "' with '"
|
||||
+ name
|
||||
+ "' already exists!");
|
||||
Assert.isTrue(!exists(name), "QuotaMapping for voucher '" + voucher + "' with '" + name + "' already exists!");
|
||||
|
||||
VoucherMapping voucherMapping = new VoucherMapping();
|
||||
voucherMapping.setName(name);
|
||||
@ -87,12 +83,8 @@ public class VoucherMappingManager {
|
||||
* @return the voucher mapping
|
||||
*/
|
||||
public VoucherMapping update(VoucherMapping voucherMapping) {
|
||||
Assert.isTrue(
|
||||
voucherMapping.getId() != null
|
||||
&& voucherMappingRepository.existsById(voucherMapping.getId()),
|
||||
"VoucherMapping '"
|
||||
+ voucherMapping.getId()
|
||||
+ "' does not exists!");
|
||||
Assert.isTrue(voucherMapping.getId() != null && voucherMappingRepository.existsById(voucherMapping.getId()),
|
||||
"VoucherMapping '" + voucherMapping.getId() + "' does not exists!");
|
||||
|
||||
return voucherMappingRepository.save(voucherMapping);
|
||||
}
|
||||
@ -103,18 +95,16 @@ public class VoucherMappingManager {
|
||||
* @param id the id
|
||||
*/
|
||||
public void delete(Long id) {
|
||||
Assert.isTrue(voucherMappingRepository.existsById(id), "VoucherMapping '"
|
||||
+ id
|
||||
+ "' does not exists!");
|
||||
Assert.isTrue(voucherMappingRepository.existsById(id), "VoucherMapping '" + id + "' does not exists!");
|
||||
voucherMappingRepository.deleteById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the.
|
||||
*
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the page
|
||||
*/
|
||||
|
@ -20,12 +20,11 @@ import de.bstly.we.event.AbstractModelEventType;
|
||||
import de.bstly.we.model.AbstractModel;
|
||||
|
||||
/**
|
||||
* The listener interface for receiving abstractModelEvent events.
|
||||
* The class that is interested in processing a abstractModelEvent
|
||||
* event implements this interface, and the object created
|
||||
* with that class is registered with a component using the
|
||||
* component's <code>addAbstractModelEventListener<code> method. When
|
||||
* the abstractModelEvent event occurs, that object's appropriate
|
||||
* The listener interface for receiving abstractModelEvent events. The class
|
||||
* that is interested in processing a abstractModelEvent event implements this
|
||||
* interface, and the object created with that class is registered with a
|
||||
* component using the component's <code>addAbstractModelEventListener<code>
|
||||
* method. When the abstractModelEvent event occurs, that object's appropriate
|
||||
* method is invoked.
|
||||
*
|
||||
* @see AbstractModelEventEvent
|
||||
|
@ -20,7 +20,7 @@ public class InstantHelper {
|
||||
* Plus.
|
||||
*
|
||||
* @param instant the instant
|
||||
* @param amount the amount
|
||||
* @param amount the amount
|
||||
* @return the instant
|
||||
*/
|
||||
public static Instant plus(Instant instant, TemporalAmount amount) {
|
||||
@ -30,9 +30,9 @@ public class InstantHelper {
|
||||
/**
|
||||
* Plus.
|
||||
*
|
||||
* @param instant the instant
|
||||
* @param instant the instant
|
||||
* @param amountToAdd the amount to add
|
||||
* @param unit the unit
|
||||
* @param unit the unit
|
||||
* @return the instant
|
||||
*/
|
||||
public static Instant plus(Instant instant, long amountToAdd, TemporalUnit unit) {
|
||||
@ -43,7 +43,7 @@ public class InstantHelper {
|
||||
* Minus.
|
||||
*
|
||||
* @param instant the instant
|
||||
* @param amount the amount
|
||||
* @param amount the amount
|
||||
* @return the instant
|
||||
*/
|
||||
public static Instant minus(Instant instant, TemporalAmount amount) {
|
||||
@ -53,32 +53,29 @@ public class InstantHelper {
|
||||
/**
|
||||
* Minus.
|
||||
*
|
||||
* @param instant the instant
|
||||
* @param instant the instant
|
||||
* @param amountToAdd the amount to add
|
||||
* @param unit the unit
|
||||
* @param unit the unit
|
||||
* @return the instant
|
||||
*/
|
||||
public static Instant minus(Instant instant, long amountToAdd, TemporalUnit unit) {
|
||||
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit)
|
||||
.toInstant();
|
||||
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit).toInstant();
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncate.
|
||||
*
|
||||
* @param instant the instant
|
||||
* @param unit the unit
|
||||
* @param unit the unit
|
||||
* @return the instant
|
||||
*/
|
||||
public static Instant truncate(Instant instant, TemporalUnit unit) {
|
||||
if (ChronoUnit.YEARS.equals(unit)) {
|
||||
instant = instant.truncatedTo(ChronoUnit.DAYS);
|
||||
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC)
|
||||
.with(ChronoField.DAY_OF_YEAR, 1L).toInstant();
|
||||
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_YEAR, 1L).toInstant();
|
||||
} else if (ChronoUnit.MONTHS.equals(unit)) {
|
||||
instant = instant.truncatedTo(ChronoUnit.DAYS);
|
||||
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC)
|
||||
.with(ChronoField.DAY_OF_MONTH, 1L).toInstant();
|
||||
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_MONTH, 1L).toInstant();
|
||||
}
|
||||
|
||||
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).truncatedTo(unit).toInstant();
|
||||
|
@ -96,8 +96,8 @@ public class Authentication2FAController extends BaseController {
|
||||
}
|
||||
|
||||
for (SecondFactorProvider<?> provider : secondFactorProviderManager.getEnabled(userId)) {
|
||||
SecondFactorProviderModel enabledProvider = new SecondFactorProviderModel(
|
||||
provider.getId(), provider instanceof SecondFactorRequestProvider<?>);
|
||||
SecondFactorProviderModel enabledProvider = new SecondFactorProviderModel(provider.getId(),
|
||||
provider instanceof SecondFactorRequestProvider<?>);
|
||||
result.remove(enabledProvider);
|
||||
}
|
||||
return result;
|
||||
@ -175,12 +175,11 @@ public class Authentication2FAController extends BaseController {
|
||||
* Enable second factor.
|
||||
*
|
||||
* @param providerId the provider id
|
||||
* @param token the token
|
||||
* @param token the token
|
||||
*/
|
||||
@PreAuthorize("authentication.authenticated")
|
||||
@PatchMapping("/{id}")
|
||||
public void enableSecondFactor(@PathVariable("id") String providerId,
|
||||
@RequestBody String token) {
|
||||
public void enableSecondFactor(@PathVariable("id") String providerId, @RequestBody String token) {
|
||||
SecondFactorProvider<?> provider = secondFactorProviderManager.getProvider(providerId);
|
||||
|
||||
if (provider == null) {
|
||||
|
@ -56,14 +56,14 @@ public class AuthenticationController extends BaseController {
|
||||
* Password request.
|
||||
*
|
||||
* @param username the username
|
||||
* @param req the req
|
||||
* @param resp the resp
|
||||
* @param req the req
|
||||
* @param resp the resp
|
||||
* @throws IOException Signals that an I/O exception has occurred.
|
||||
*/
|
||||
@PreAuthorize("isAnonymous()")
|
||||
@PostMapping("/password/request")
|
||||
public void passwordRequest(@RequestBody String username, HttpServletRequest req,
|
||||
HttpServletResponse resp) throws IOException {
|
||||
public void passwordRequest(@RequestBody String username, HttpServletRequest req, HttpServletResponse resp)
|
||||
throws IOException {
|
||||
User user = userManager.getByUsername(username);
|
||||
|
||||
if (user != null) {
|
||||
@ -78,13 +78,13 @@ public class AuthenticationController extends BaseController {
|
||||
* Password reset.
|
||||
*
|
||||
* @param passwordResetModel the password reset model
|
||||
* @param req the req
|
||||
* @param resp the resp
|
||||
* @param req the req
|
||||
* @param resp the resp
|
||||
*/
|
||||
@PreAuthorize("isAnonymous()")
|
||||
@PostMapping("/password/reset")
|
||||
public void passwordReset(@RequestBody PasswordResetModel passwordResetModel,
|
||||
HttpServletRequest req, HttpServletResponse resp) {
|
||||
public void passwordReset(@RequestBody PasswordResetModel passwordResetModel, HttpServletRequest req,
|
||||
HttpServletResponse resp) {
|
||||
User user = userManager.getByResetToken(passwordResetModel.getToken().trim());
|
||||
|
||||
if (user == null) {
|
||||
|
@ -80,7 +80,7 @@ public class ItemController extends BaseController {
|
||||
/**
|
||||
* Adds the item.
|
||||
*
|
||||
* @param secret the secret
|
||||
* @param secret the secret
|
||||
* @param session the session
|
||||
*/
|
||||
@PutMapping("")
|
||||
@ -99,7 +99,7 @@ public class ItemController extends BaseController {
|
||||
/**
|
||||
* Removes the item.
|
||||
*
|
||||
* @param secret the secret
|
||||
* @param secret the secret
|
||||
* @param session the session
|
||||
*/
|
||||
@DeleteMapping
|
||||
@ -131,7 +131,7 @@ public class ItemController extends BaseController {
|
||||
* Redeem for user.
|
||||
*
|
||||
* @param username the username
|
||||
* @param session the session
|
||||
* @param session the session
|
||||
*/
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@PostMapping("/{username}")
|
||||
@ -147,8 +147,7 @@ public class ItemController extends BaseController {
|
||||
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
tokenSessionManager.applyTokens(user.getId(),
|
||||
tokenSessionManager.getTokenFromSession(session));
|
||||
tokenSessionManager.applyTokens(user.getId(), tokenSessionManager.getTokenFromSession(session));
|
||||
tokenSessionManager.removeTokensFromSession(session);
|
||||
}
|
||||
|
||||
|
@ -59,8 +59,7 @@ public class PermissionController extends BaseController {
|
||||
}
|
||||
|
||||
for (String token : tokenSessionManager.getTokenFromSession(session)) {
|
||||
permissions
|
||||
.addAll(tokenSessionManager.getPermissionsForToken(getCurrentUserId(), token));
|
||||
permissions.addAll(tokenSessionManager.getPermissionsForToken(getCurrentUserId(), token));
|
||||
}
|
||||
|
||||
return permissions;
|
||||
|
@ -82,8 +82,8 @@ public class PermissionManagementController extends BaseController {
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping
|
||||
public Permission createPermission(@RequestBody Permission permission) {
|
||||
return permissionManager.create(permission.getTarget(), permission.getName(),
|
||||
permission.isAddon(), permission.getStarts(), permission.getExpires());
|
||||
return permissionManager.create(permission.getTarget(), permission.getName(), permission.isAddon(),
|
||||
permission.getStarts(), permission.getExpires());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -125,14 +125,13 @@ public class PermissionManagementController extends BaseController {
|
||||
/**
|
||||
* Clone.
|
||||
*
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @param clone the clone
|
||||
* @return the list
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/{name}/clone/{clone}")
|
||||
public List<Permission> clone(@PathVariable("name") String name,
|
||||
@PathVariable("clone") String clone) {
|
||||
public List<Permission> clone(@PathVariable("name") String name, @PathVariable("clone") String clone) {
|
||||
if (name.equals(clone)) {
|
||||
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
|
||||
}
|
||||
|
@ -49,11 +49,9 @@ public class PermissionMappingController extends BaseController {
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping
|
||||
public Page<PermissionMapping> getPermissionMappings(
|
||||
@RequestParam("page") Optional<Integer> pageParameter,
|
||||
public Page<PermissionMapping> getPermissionMappings(@RequestParam("page") Optional<Integer> pageParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter) {
|
||||
return permissionMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10),
|
||||
"item", true);
|
||||
return permissionMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "item", true);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -71,12 +69,11 @@ public class PermissionMappingController extends BaseController {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
return permissionMappingManager.create(permissionMapping.getItem(),
|
||||
permissionMapping.getNames(), permissionMapping.getLifetime(),
|
||||
permissionMapping.getLifetimeUnit(), permissionMapping.isLifetimeRound(),
|
||||
permissionMapping.isAddon(), permissionMapping.getProduct(),
|
||||
permissionMapping.getStarts(), permissionMapping.getExpires(),
|
||||
permissionMapping.getStartsQuestion(), permissionMapping.getExpiresQuestion());
|
||||
return permissionMappingManager.create(permissionMapping.getItem(), permissionMapping.getNames(),
|
||||
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit(),
|
||||
permissionMapping.isLifetimeRound(), permissionMapping.isAddon(), permissionMapping.getProduct(),
|
||||
permissionMapping.getStarts(), permissionMapping.getExpires(), permissionMapping.getStartsQuestion(),
|
||||
permissionMapping.getExpiresQuestion());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -87,8 +84,7 @@ public class PermissionMappingController extends BaseController {
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/list")
|
||||
public List<PermissionMapping> createList(
|
||||
@RequestBody List<PermissionMapping> permissionMappings) {
|
||||
public List<PermissionMapping> createList(@RequestBody List<PermissionMapping> permissionMappings) {
|
||||
List<PermissionMapping> result = Lists.newArrayList();
|
||||
for (PermissionMapping permissionMapping : permissionMappings) {
|
||||
Errors errors = new RequestBodyErrors(permissionMapping);
|
||||
@ -97,10 +93,9 @@ public class PermissionMappingController extends BaseController {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
result.add(permissionMappingManager.create(permissionMapping.getItem(),
|
||||
permissionMapping.getNames(), permissionMapping.getLifetime(),
|
||||
permissionMapping.getLifetimeUnit(), permissionMapping.isLifetimeRound(),
|
||||
permissionMapping.isAddon(), permissionMapping.getProduct(),
|
||||
result.add(permissionMappingManager.create(permissionMapping.getItem(), permissionMapping.getNames(),
|
||||
permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit(),
|
||||
permissionMapping.isLifetimeRound(), permissionMapping.isAddon(), permissionMapping.getProduct(),
|
||||
permissionMapping.getStarts(), permissionMapping.getExpires(),
|
||||
permissionMapping.getStartsQuestion(), permissionMapping.getExpiresQuestion()));
|
||||
}
|
||||
@ -132,8 +127,7 @@ public class PermissionMappingController extends BaseController {
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PatchMapping("/list")
|
||||
public List<PermissionMapping> updateList(
|
||||
@RequestBody List<PermissionMapping> permissionMappings) {
|
||||
public List<PermissionMapping> updateList(@RequestBody List<PermissionMapping> permissionMappings) {
|
||||
List<PermissionMapping> result = Lists.newArrayList();
|
||||
for (PermissionMapping permissionMapping : permissionMappings) {
|
||||
Errors errors = new RequestBodyErrors(permissionMapping);
|
||||
|
@ -41,9 +41,9 @@ public class PretixApiController extends BaseController {
|
||||
* Debug.
|
||||
*
|
||||
* @param pretixRequest the pretix request
|
||||
* @param response the response
|
||||
* @param response the response
|
||||
* @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')")
|
||||
@PostMapping("/debug")
|
||||
@ -58,10 +58,8 @@ public class PretixApiController extends BaseController {
|
||||
}
|
||||
}
|
||||
|
||||
gson.toJson(
|
||||
pretixManager.request(pretixRequest.getPath(), pretixRequest.getMethod(),
|
||||
gson.toJsonTree(pretixRequest.getPayload()), queryParemeters),
|
||||
response.getWriter());
|
||||
gson.toJson(pretixManager.request(pretixRequest.getPath(), pretixRequest.getMethod(),
|
||||
gson.toJsonTree(pretixRequest.getPayload()), queryParemeters), response.getWriter());
|
||||
} catch (WebClientResponseException e) {
|
||||
throw new EntityResponseStatusException(e.getMessage(), e.getStatusCode());
|
||||
}
|
||||
|
@ -98,8 +98,8 @@ public class QuotaManagementController extends BaseController {
|
||||
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
return quotaManager.create(quota.getTarget(), quota.getName(), quota.getValue(),
|
||||
quota.getUnit(), quota.isDisposable());
|
||||
return quotaManager.create(quota.getTarget(), quota.getName(), quota.getValue(), quota.getUnit(),
|
||||
quota.isDisposable());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -143,7 +143,7 @@ public class QuotaManagementController extends BaseController {
|
||||
/**
|
||||
* Clone.
|
||||
*
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @param clone the clone
|
||||
* @param value the value
|
||||
* @return the list
|
||||
|
@ -49,11 +49,9 @@ public class QuotaMappingController extends BaseController {
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping
|
||||
public Page<QuotaMapping> getQuotaMappings(
|
||||
@RequestParam("page") Optional<Integer> pageParameter,
|
||||
public Page<QuotaMapping> getQuotaMappings(@RequestParam("page") Optional<Integer> pageParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter) {
|
||||
return quotaMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name",
|
||||
true);
|
||||
return quotaMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", true);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -74,9 +72,9 @@ public class QuotaMappingController extends BaseController {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
return quotaMappingManager.create(quotaMapping.getItems(), quotaMapping.getName(),
|
||||
quotaMapping.getValue(), quotaMapping.getUnit(), quotaMapping.isAppend(),
|
||||
quotaMapping.getProducts(), quotaMapping.isDisposable());
|
||||
return quotaMappingManager.create(quotaMapping.getItems(), quotaMapping.getName(), quotaMapping.getValue(),
|
||||
quotaMapping.getUnit(), quotaMapping.isAppend(), quotaMapping.getProducts(),
|
||||
quotaMapping.isDisposable());
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -58,8 +58,7 @@ public class SystemController extends BaseController {
|
||||
public List<SystemProperty> getProperties(@RequestParam("page") Optional<Integer> pageParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter) {
|
||||
Sort sort = Sort.by("key").ascending();
|
||||
return systemPropertyRepository
|
||||
.findAll(PageRequest.of(pageParameter.orElse(0), sizeParameter.orElse(10), sort))
|
||||
return systemPropertyRepository.findAll(PageRequest.of(pageParameter.orElse(0), sizeParameter.orElse(10), sort))
|
||||
.getContent();
|
||||
}
|
||||
|
||||
|
@ -46,8 +46,7 @@ public class SystemProfileFieldController extends BaseController {
|
||||
@GetMapping
|
||||
public Page<SystemProfileField> get(@RequestParam("page") Optional<Integer> pageParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter) {
|
||||
return systemProfileFieldManager.get(pageParameter.orElse(0), sizeParameter.orElse(10),
|
||||
"name", true);
|
||||
return systemProfileFieldManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", true);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -88,8 +87,7 @@ public class SystemProfileFieldController extends BaseController {
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/list")
|
||||
public List<SystemProfileField> updateList(
|
||||
@RequestBody List<SystemProfileField> systemProfileFields) {
|
||||
public List<SystemProfileField> updateList(@RequestBody List<SystemProfileField> systemProfileFields) {
|
||||
List<SystemProfileField> result = Lists.newArrayList();
|
||||
|
||||
for (SystemProfileField systemProfileField : systemProfileFields) {
|
||||
|
@ -131,8 +131,7 @@ public class UserAliasController extends BaseController {
|
||||
|
||||
Quota aliasCreation = quotaManager.get(getCurrentUserId(), Quotas.ALIAS_CREATION);
|
||||
if (aliasCreation == null) {
|
||||
aliasCreation = quotaManager.create(getCurrentUserId(), Quotas.ALIAS_CREATION, 0, "#",
|
||||
true);
|
||||
aliasCreation = quotaManager.create(getCurrentUserId(), Quotas.ALIAS_CREATION, 0, "#", true);
|
||||
}
|
||||
|
||||
aliasCreation.setValue(aliasCreation.getValue() + 1);
|
||||
|
@ -89,7 +89,7 @@ public class UserController extends BaseController {
|
||||
* Check model.
|
||||
*
|
||||
* @param userModel the user model
|
||||
* @param session the session
|
||||
* @param session the session
|
||||
* @return the user model
|
||||
*/
|
||||
@PostMapping("/model")
|
||||
@ -108,7 +108,7 @@ public class UserController extends BaseController {
|
||||
* Register.
|
||||
*
|
||||
* @param userModel the user model
|
||||
* @param session the session
|
||||
* @param session the session
|
||||
* @return the user model
|
||||
*/
|
||||
@PreAuthorize("isAnonymous()")
|
||||
@ -165,8 +165,7 @@ public class UserController extends BaseController {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
User user = userManager.create(userModel.getUsername(), userModel.getPassword(),
|
||||
userModel.getStatus());
|
||||
User user = userManager.create(userModel.getUsername(), userModel.getPassword(), userModel.getStatus());
|
||||
|
||||
for (UserProfileField userProfileField : userModel.getProfileFields()) {
|
||||
userProfileField.setTarget(user.getId());
|
||||
@ -210,8 +209,8 @@ public class UserController extends BaseController {
|
||||
|
||||
User user = userManager.get(getCurrentUserId());
|
||||
|
||||
if (!StringUtils.hasText(passwordModel.getOld()) || !passwordEncoder
|
||||
.matches(passwordModel.getOld(), userManager.getPasswordHash(user.getId()))) {
|
||||
if (!StringUtils.hasText(passwordModel.getOld())
|
||||
|| !passwordEncoder.matches(passwordModel.getOld(), userManager.getPasswordHash(user.getId()))) {
|
||||
throw new EntityResponseStatusException(HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@ -235,8 +234,7 @@ public class UserController extends BaseController {
|
||||
User user = userManager.get(getCurrentUserId());
|
||||
if (StringUtils.hasText(userModel.getOld())) {
|
||||
Errors errors = new RequestBodyErrors(userModel);
|
||||
if (!passwordEncoder.matches(userModel.getOld(),
|
||||
userManager.getPasswordHash(getCurrentUserId()))) {
|
||||
if (!passwordEncoder.matches(userModel.getOld(), userManager.getPasswordHash(getCurrentUserId()))) {
|
||||
throw new EntityResponseStatusException(HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
|
@ -67,12 +67,11 @@ public class UserDataManagementController extends BaseController {
|
||||
* Purge by username.
|
||||
*
|
||||
* @param username the username
|
||||
* @param dry the dry
|
||||
* @param dry the dry
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/purge/{username}")
|
||||
public void purgeByUsername(@PathVariable("username") String username,
|
||||
@RequestParam("dry") boolean dry) {
|
||||
public void purgeByUsername(@PathVariable("username") String username, @RequestParam("dry") boolean dry) {
|
||||
User user = userManager.getByUsername(username);
|
||||
|
||||
if (user == null) {
|
||||
|
@ -53,16 +53,14 @@ public class UserDomainController extends BaseController {
|
||||
if (!permissionManager.isFullUser(getCurrentUserId())) {
|
||||
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (userDomain.getVisibility() == null) {
|
||||
userDomain.setVisibility(Visibility.PRIVATE);
|
||||
}
|
||||
|
||||
userDomain.setTarget(getCurrentUserId());
|
||||
userDomain.setValidated(false);
|
||||
userDomain.setSecret(
|
||||
RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true));
|
||||
userDomain.setSecret(RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true));
|
||||
|
||||
Errors errors = new RequestBodyErrors(userDomain);
|
||||
|
||||
@ -92,7 +90,7 @@ public class UserDomainController extends BaseController {
|
||||
if (oldDomain == null) {
|
||||
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
|
||||
if (!oldDomain.getTarget().equals(getCurrentUserId())) {
|
||||
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
@ -100,8 +100,7 @@ public class UserDomainManagementController extends BaseController {
|
||||
|
||||
if (userDomain.getId() == null) {
|
||||
userDomain.setValidated(false);
|
||||
userDomain.setSecret(
|
||||
RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true));
|
||||
userDomain.setSecret(RandomStringUtils.random(UserDomainManager.DEFAULT_SECRET_LENGTH, true, true));
|
||||
}
|
||||
|
||||
return userDomainManager.save(userDomain);
|
||||
|
@ -130,15 +130,13 @@ public class UserManagementController extends BaseController {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
User user = userManager.create(userModel.getUsername(), userModel.getPassword(),
|
||||
userModel.getStatus());
|
||||
User user = userManager.create(userModel.getUsername(), userModel.getPassword(), userModel.getStatus());
|
||||
|
||||
if (userModel.getPermissionMappings() != null) {
|
||||
for (PermissionMapping permissionMapping : userModel.getPermissionMappings()) {
|
||||
for (String name : permissionMapping.getNames()) {
|
||||
permissionManager.create(user.getId(), name, permissionMapping.isAddon(), null,
|
||||
InstantHelper.plus(Instant.now(), permissionMapping.getLifetime(),
|
||||
permissionMapping.getLifetimeUnit()));
|
||||
permissionManager.create(user.getId(), name, permissionMapping.isAddon(), null, InstantHelper
|
||||
.plus(Instant.now(), permissionMapping.getLifetime(), permissionMapping.getLifetimeUnit()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -159,8 +157,8 @@ public class UserManagementController extends BaseController {
|
||||
|
||||
if (userModel.getQuotas() != null) {
|
||||
for (Quota quota : userModel.getQuotas()) {
|
||||
quotaManager.create(user.getId(), quota.getName(), quota.getValue(),
|
||||
quota.getUnit(), quota.isDisposable());
|
||||
quotaManager.create(user.getId(), quota.getName(), quota.getValue(), quota.getUnit(),
|
||||
quota.isDisposable());
|
||||
}
|
||||
}
|
||||
|
||||
@ -213,12 +211,11 @@ public class UserManagementController extends BaseController {
|
||||
* Purge.
|
||||
*
|
||||
* @param username the username
|
||||
* @param dry the dry
|
||||
* @param dry the dry
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/purge")
|
||||
public void purge(@RequestParam("username") Optional<String> username,
|
||||
@RequestParam("dry") Optional<Boolean> dry) {
|
||||
public void purge(@RequestParam("username") Optional<String> username, @RequestParam("dry") Optional<Boolean> dry) {
|
||||
|
||||
if (username.isPresent()) {
|
||||
User user = userManager.getByUsername(username.get());
|
||||
|
@ -138,8 +138,7 @@ public class UserProfileFieldController extends BaseController {
|
||||
|
||||
}
|
||||
|
||||
profileFields.addAll(
|
||||
userProfileFieldManager.getAllByTargetAndVisibilities(user.getId(), visibilities));
|
||||
profileFields.addAll(userProfileFieldManager.getAllByTargetAndVisibilities(user.getId(), visibilities));
|
||||
|
||||
if (profileFields.isEmpty()) {
|
||||
throttleForbidden();
|
||||
@ -178,7 +177,7 @@ public class UserProfileFieldController extends BaseController {
|
||||
* Gets the field for user.
|
||||
*
|
||||
* @param username the username
|
||||
* @param name the name
|
||||
* @param name the name
|
||||
* @return the field for user
|
||||
*/
|
||||
@GetMapping("/{username}/field/{name}")
|
||||
|
@ -49,11 +49,9 @@ public class VoucherMappingController extends BaseController {
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping
|
||||
public Page<VoucherMapping> getVoucherMappings(
|
||||
@RequestParam("page") Optional<Integer> pageParameter,
|
||||
public Page<VoucherMapping> getVoucherMappings(@RequestParam("page") Optional<Integer> pageParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter) {
|
||||
return voucherMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name",
|
||||
true);
|
||||
return voucherMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "name", true);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -98,9 +96,8 @@ public class VoucherMappingController extends BaseController {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
result.add(voucherMappingManager.create(voucherMapping.getName(),
|
||||
voucherMapping.getVoucher(), voucherMapping.getQuota(),
|
||||
voucherMapping.isFree()));
|
||||
result.add(voucherMappingManager.create(voucherMapping.getName(), voucherMapping.getVoucher(),
|
||||
voucherMapping.getQuota(), voucherMapping.isFree()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
@ -14,7 +14,7 @@ public class SecondFactorProviderModel {
|
||||
/**
|
||||
* Instantiates a new second factor provider model.
|
||||
*
|
||||
* @param id the id
|
||||
* @param id the id
|
||||
* @param request the request
|
||||
*/
|
||||
public SecondFactorProviderModel(String id, boolean request) {
|
||||
|
@ -20,7 +20,7 @@ public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
* Handle response entity status exception.
|
||||
*
|
||||
* @param exception the exception
|
||||
* @param request the request
|
||||
* @param request the request
|
||||
* @return the response entity
|
||||
*/
|
||||
@ExceptionHandler(value = { EntityResponseStatusException.class })
|
||||
|
@ -37,7 +37,7 @@ public class EntityResponseStatusException extends NestedRuntimeException {
|
||||
/**
|
||||
* Instantiates a new entity response status exception.
|
||||
*
|
||||
* @param body the body
|
||||
* @param body the body
|
||||
* @param status the status
|
||||
*/
|
||||
public EntityResponseStatusException(@Nullable Object body, HttpStatus status) {
|
||||
@ -47,9 +47,9 @@ public class EntityResponseStatusException extends NestedRuntimeException {
|
||||
/**
|
||||
* Instantiates a new entity response status exception.
|
||||
*
|
||||
* @param body the body
|
||||
* @param body the body
|
||||
* @param status the status
|
||||
* @param cause the cause
|
||||
* @param cause the cause
|
||||
*/
|
||||
public EntityResponseStatusException(@Nullable Object body, HttpStatus status, @Nullable Throwable cause) {
|
||||
super(null, cause);
|
||||
|
@ -29,9 +29,10 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
|
||||
|
||||
private Gson gson = new Gson();
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#supports(org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class)
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
|
||||
* supports(org.springframework.core.MethodParameter, java.lang.reflect.Type,
|
||||
* java.lang.Class)
|
||||
*/
|
||||
@Override
|
||||
public boolean supports(MethodParameter methodParameter, Type targetType,
|
||||
@ -40,7 +41,10 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#beforeBodyRead(org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class)
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
|
||||
* beforeBodyRead(org.springframework.http.HttpInputMessage,
|
||||
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
|
||||
* java.lang.Class)
|
||||
*/
|
||||
@Override
|
||||
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
|
||||
@ -48,9 +52,11 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
|
||||
return inputMessage;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#afterBodyRead(java.lang.Object, org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class)
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
|
||||
* afterBodyRead(java.lang.Object, org.springframework.http.HttpInputMessage,
|
||||
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
|
||||
* java.lang.Class)
|
||||
*/
|
||||
@Override
|
||||
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
|
||||
@ -59,9 +65,11 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
|
||||
return body;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#handleEmptyBody(java.lang.Object, org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class)
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
|
||||
* handleEmptyBody(java.lang.Object, org.springframework.http.HttpInputMessage,
|
||||
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
|
||||
* java.lang.Class)
|
||||
*/
|
||||
@Override
|
||||
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
|
||||
@ -69,18 +77,23 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
|
||||
return body;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#supports(org.springframework.core.MethodParameter, java.lang.Class)
|
||||
* @see
|
||||
* org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#
|
||||
* supports(org.springframework.core.MethodParameter, java.lang.Class)
|
||||
*/
|
||||
@Override
|
||||
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
|
||||
return converterType == StringHttpMessageConverter.class;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#beforeBodyWrite(java.lang.Object, org.springframework.core.MethodParameter, org.springframework.http.MediaType, java.lang.Class, org.springframework.http.server.ServerHttpRequest, org.springframework.http.server.ServerHttpResponse)
|
||||
* @see
|
||||
* org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#
|
||||
* beforeBodyWrite(java.lang.Object, org.springframework.core.MethodParameter,
|
||||
* org.springframework.http.MediaType, java.lang.Class,
|
||||
* org.springframework.http.server.ServerHttpRequest,
|
||||
* org.springframework.http.server.ServerHttpResponse)
|
||||
*/
|
||||
@Override
|
||||
public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType,
|
||||
|
@ -33,9 +33,10 @@ public class RequestBodyErrors extends AbstractBindingResult {
|
||||
return target;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.validation.AbstractBindingResult#getActualFieldValue(java.lang.String)
|
||||
* @see
|
||||
* org.springframework.validation.AbstractBindingResult#getActualFieldValue(java
|
||||
* .lang.String)
|
||||
*/
|
||||
@Override
|
||||
protected Object getActualFieldValue(String field) {
|
||||
|
@ -55,7 +55,7 @@ public class TokenSessionManager {
|
||||
* Gets the permission mappings for token.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param token the token
|
||||
* @param token the token
|
||||
* @return the permission mappings for token
|
||||
*/
|
||||
public List<PermissionMapping> getPermissionMappingsForToken(Long userId, String token) {
|
||||
@ -79,7 +79,7 @@ public class TokenSessionManager {
|
||||
* Gets the permissions for token.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param token the token
|
||||
* @param token the token
|
||||
* @return the permissions for token
|
||||
*/
|
||||
public List<Permission> getPermissionsForToken(Long userId, String token) {
|
||||
@ -100,7 +100,7 @@ public class TokenSessionManager {
|
||||
}
|
||||
|
||||
permissions.addAll(permissionManager.getForItem(userId, item,
|
||||
orderPosition.get("answers").getAsJsonArray(),lastPaymentDate, null));
|
||||
orderPosition.get("answers").getAsJsonArray(), lastPaymentDate, null));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// ignore
|
||||
@ -113,7 +113,7 @@ public class TokenSessionManager {
|
||||
* Gets the quota mappings for token.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param token the token
|
||||
* @param token the token
|
||||
* @return the quota mappings for token
|
||||
*/
|
||||
public List<QuotaMapping> getQuotaMappingsForToken(Long userId, String token) {
|
||||
@ -137,7 +137,7 @@ public class TokenSessionManager {
|
||||
* Adds the quotas for token.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param token the token
|
||||
* @param token the token
|
||||
* @param quotas the 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!");
|
||||
}
|
||||
|
||||
permissionManager.applyItem(userId, item,
|
||||
position.get("answers").getAsJsonArray(), lastPaymentDate, null);
|
||||
permissionManager.applyItem(userId, item, position.get("answers").getAsJsonArray(), lastPaymentDate,
|
||||
null);
|
||||
permissionMappings.addAll(permissionMappingManager.getAllByItem(item));
|
||||
quotaManager.applyItem(userId, item);
|
||||
quotaMappings.addAll(quotaMappingManager.getAllByItem(item));
|
||||
@ -222,7 +222,7 @@ public class TokenSessionManager {
|
||||
/**
|
||||
* Adds the token to session.
|
||||
*
|
||||
* @param secret the secret
|
||||
* @param secret the secret
|
||||
* @param session the session
|
||||
*/
|
||||
public void addTokenToSession(String secret, HttpSession session) {
|
||||
@ -236,8 +236,7 @@ public class TokenSessionManager {
|
||||
}
|
||||
|
||||
if (StringUtils.hasLength(tokens)) {
|
||||
tokens += ","
|
||||
+ secret;
|
||||
tokens += "," + secret;
|
||||
} else {
|
||||
tokens = secret;
|
||||
}
|
||||
@ -249,7 +248,7 @@ public class TokenSessionManager {
|
||||
/**
|
||||
* Removes the token from session.
|
||||
*
|
||||
* @param secret the secret
|
||||
* @param secret the secret
|
||||
* @param session the session
|
||||
*/
|
||||
public void removeTokenFromSession(String secret, HttpSession session) {
|
||||
@ -261,8 +260,7 @@ public class TokenSessionManager {
|
||||
for (String token : ((String) sessionAttribute).split(",")) {
|
||||
if (!token.equals(secret)) {
|
||||
if (StringUtils.hasLength(tokens)) {
|
||||
tokens += ","
|
||||
+ secret;
|
||||
tokens += "," + secret;
|
||||
} else {
|
||||
tokens = secret;
|
||||
}
|
||||
@ -285,15 +283,14 @@ public class TokenSessionManager {
|
||||
/**
|
||||
* Creates the new auth.
|
||||
*
|
||||
* @param auth the auth
|
||||
* @param auth the auth
|
||||
* @param details the details
|
||||
* @return the authentication
|
||||
*/
|
||||
protected Authentication createNewAuth(Authentication auth, LocalUserDetails details) {
|
||||
Authentication newAuth = null;
|
||||
if (auth instanceof UsernamePasswordAuthenticationToken) {
|
||||
newAuth = new UsernamePasswordAuthenticationToken(details, auth.getCredentials(),
|
||||
details.getAuthorities());
|
||||
newAuth = new UsernamePasswordAuthenticationToken(details, auth.getCredentials(), details.getAuthorities());
|
||||
} else {
|
||||
newAuth = new LocalAnonymousAuthenticationToken(details);
|
||||
}
|
||||
|
@ -46,9 +46,9 @@ public class PasswordModelValidator implements Validator {
|
||||
return clazz.isAssignableFrom(PasswordModel.class);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
|
||||
* @see org.springframework.validation.Validator#validate(java.lang.Object,
|
||||
* org.springframework.validation.Errors)
|
||||
*/
|
||||
@Override
|
||||
public void validate(Object target, Errors errors) {
|
||||
|
@ -16,7 +16,7 @@ import de.bstly.we.model.UserAlias;
|
||||
*/
|
||||
@Component
|
||||
public class UserAliasValidator implements Validator {
|
||||
|
||||
|
||||
@Autowired
|
||||
private UserModelValidator userModelValidator;
|
||||
|
||||
|
@ -51,8 +51,8 @@ public class UserDomainValidator implements Validator {
|
||||
|
||||
UserDomain existingDomain = userDomainManager.getByDomain(userDomain.getDomain());
|
||||
|
||||
if (existingDomain != null && (userDomain.getId() == null
|
||||
|| !(existingDomain.getId().equals(userDomain.getId())))) {
|
||||
if (existingDomain != null
|
||||
&& (userDomain.getId() == null || !(existingDomain.getId().equals(userDomain.getId())))) {
|
||||
errors.rejectValue("domain", "NOT_VALID");
|
||||
return;
|
||||
}
|
||||
|
@ -60,14 +60,13 @@ public class UserModelValidator implements Validator {
|
||||
* Validate username.
|
||||
*
|
||||
* @param username the username
|
||||
* @param field the field
|
||||
* @param errors the errors
|
||||
* @param field the field
|
||||
* @param errors the errors
|
||||
*/
|
||||
public void validateUsername(String username, String field, Errors errors) {
|
||||
for (String systemUsername : systemPropertyManager.get(RESERVED_USERNAMES, "").split(",")) {
|
||||
if (StringUtils.hasText(systemUsername)
|
||||
&& (username.toLowerCase().equals(systemUsername)
|
||||
|| username.toLowerCase().matches(systemUsername))) {
|
||||
if (StringUtils.hasText(systemUsername) && (username.toLowerCase().equals(systemUsername)
|
||||
|| username.toLowerCase().matches(systemUsername))) {
|
||||
errors.rejectValue(field, "NOT_VALID");
|
||||
break;
|
||||
}
|
||||
|
@ -40,8 +40,7 @@ public class UserProfileFieldValidator implements Validator {
|
||||
private DoubleValidator doubleValidator = DoubleValidator.getInstance();
|
||||
private EmailValidator emailValidator = EmailValidator.getInstance();
|
||||
private UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_ALL_SCHEMES);
|
||||
private List<String> validBoolean = Lists.newArrayList("true", "True", "TRUE", "1", "false",
|
||||
"False", "FALSE", "0");
|
||||
private List<String> validBoolean = Lists.newArrayList("true", "True", "TRUE", "1", "false", "False", "FALSE", "0");
|
||||
|
||||
/*
|
||||
* @see org.springframework.validation.Validator#supports(java.lang.Class)
|
||||
@ -65,8 +64,7 @@ public class UserProfileFieldValidator implements Validator {
|
||||
errors.rejectValue("name", "TOO_LONG");
|
||||
}
|
||||
|
||||
SystemProfileField systemProfileField = systemProfileFieldManager
|
||||
.get(userProfileField.getName());
|
||||
SystemProfileField systemProfileField = systemProfileFieldManager.get(userProfileField.getName());
|
||||
|
||||
if (systemProfileField != null) {
|
||||
if (!systemProfileField.getType().equals(userProfileField.getType())) {
|
||||
|
@ -23,7 +23,7 @@ public class AbstractModelEvent extends ApplicationEvent {
|
||||
/**
|
||||
* Instantiates a new abstract model event.
|
||||
*
|
||||
* @param type the type
|
||||
* @param type the type
|
||||
* @param model the model
|
||||
*/
|
||||
public AbstractModelEvent(AbstractModelEventType type, AbstractModel model) {
|
||||
|
@ -283,25 +283,11 @@ public class PermissionMapping {
|
||||
@Converter
|
||||
public static class ChronoUnitConverter implements AttributeConverter<ChronoUnit, String> {
|
||||
|
||||
/*
|
||||
* @see javax.persistence.AttributeConverter#convertToDatabaseColumn(java.lang.Object)
|
||||
*/
|
||||
/*
|
||||
* @see javax.persistence.AttributeConverter#convertToDatabaseColumn(java.lang.
|
||||
* Object)
|
||||
*/
|
||||
@Override
|
||||
public String convertToDatabaseColumn(ChronoUnit chronoUnit) {
|
||||
return chronoUnit.name();
|
||||
}
|
||||
|
||||
/*
|
||||
* @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang.Object)
|
||||
*/
|
||||
/*
|
||||
* @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang.
|
||||
* Object)
|
||||
*/
|
||||
@Override
|
||||
public ChronoUnit convertToEntityAttribute(String value) {
|
||||
return ChronoUnit.valueOf(value);
|
||||
|
@ -33,7 +33,7 @@ public class SystemProperty {
|
||||
/**
|
||||
* Instantiates a new system property.
|
||||
*
|
||||
* @param key the key
|
||||
* @param key the key
|
||||
* @param value the value
|
||||
*/
|
||||
public SystemProperty(String key, String value) {
|
||||
|
@ -20,8 +20,7 @@ import de.bstly.we.model.UserProfileField.UserProfileFieldId;
|
||||
*/
|
||||
@Entity
|
||||
@IdClass(UserProfileFieldId.class)
|
||||
@Table(name = "profile_fields", uniqueConstraints = @UniqueConstraint(columnNames = { "target",
|
||||
"name" }))
|
||||
@Table(name = "profile_fields", uniqueConstraints = @UniqueConstraint(columnNames = { "target", "name" }))
|
||||
public class UserProfileField implements UserData {
|
||||
|
||||
@Id
|
||||
|
@ -13,7 +13,6 @@ import de.bstly.we.model.Permission;
|
||||
* The Interface PermissionRepository.
|
||||
*/
|
||||
@Repository
|
||||
public interface PermissionRepository
|
||||
extends JpaRepository<Permission, Long>, QuerydslPredicateExecutor<Permission> {
|
||||
public interface PermissionRepository extends JpaRepository<Permission, Long>, QuerydslPredicateExecutor<Permission> {
|
||||
|
||||
}
|
||||
|
@ -13,7 +13,7 @@ import de.bstly.we.model.SystemProfileField;
|
||||
* The Interface SystemProfileFieldRepository.
|
||||
*/
|
||||
@Repository
|
||||
public interface SystemProfileFieldRepository extends JpaRepository<SystemProfileField, String>,
|
||||
QuerydslPredicateExecutor<SystemProfileField> {
|
||||
public interface SystemProfileFieldRepository
|
||||
extends JpaRepository<SystemProfileField, String>, QuerydslPredicateExecutor<SystemProfileField> {
|
||||
|
||||
}
|
||||
|
@ -13,7 +13,6 @@ import de.bstly.we.model.UserAlias;
|
||||
* The Interface UserAliasRepository.
|
||||
*/
|
||||
@Repository
|
||||
public interface UserAliasRepository
|
||||
extends JpaRepository<UserAlias, Long>, QuerydslPredicateExecutor<UserAlias> {
|
||||
public interface UserAliasRepository extends JpaRepository<UserAlias, Long>, QuerydslPredicateExecutor<UserAlias> {
|
||||
|
||||
}
|
||||
|
@ -13,7 +13,6 @@ import de.bstly.we.model.UserDomain;
|
||||
* The Interface UserDomainRepository.
|
||||
*/
|
||||
@Repository
|
||||
public interface UserDomainRepository
|
||||
extends JpaRepository<UserDomain, Long>, QuerydslPredicateExecutor<UserDomain> {
|
||||
public interface UserDomainRepository extends JpaRepository<UserDomain, Long>, QuerydslPredicateExecutor<UserDomain> {
|
||||
|
||||
}
|
||||
|
@ -15,7 +15,6 @@ import de.bstly.we.model.UserProfileField.UserProfileFieldId;
|
||||
*/
|
||||
@Repository
|
||||
public interface UserProfileFieldRepository
|
||||
extends JpaRepository<UserProfileField, UserProfileFieldId>,
|
||||
QuerydslPredicateExecutor<UserProfileField> {
|
||||
extends JpaRepository<UserProfileField, UserProfileFieldId>, QuerydslPredicateExecutor<UserProfileField> {
|
||||
|
||||
}
|
||||
|
@ -33,9 +33,11 @@ public class LocalAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPo
|
||||
super(loginFormUrl);
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint#commence(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
|
||||
* @see org.springframework.security.web.authentication.
|
||||
* LoginUrlAuthenticationEntryPoint#commence(javax.servlet.http.
|
||||
* HttpServletRequest, javax.servlet.http.HttpServletResponse,
|
||||
* org.springframework.security.core.AuthenticationException)
|
||||
*/
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response,
|
||||
|
@ -10,7 +10,9 @@ import org.springframework.security.authentication.dao.DaoAuthenticationProvider
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import de.bstly.we.security.businesslogic.SecondFactorProvider;
|
||||
import de.bstly.we.security.businesslogic.SecondFactorProviderManager;
|
||||
@ -21,14 +23,25 @@ import de.bstly.we.security.token.LocalSecondFactorAuthenticationToken;
|
||||
/**
|
||||
* The Class LocalAuthenticationProvider.
|
||||
*/
|
||||
@Component
|
||||
public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
|
||||
|
||||
@Autowired
|
||||
private SecondFactorProviderManager secondFactorProviderManager;
|
||||
|
||||
/**
|
||||
* Instantiates a new local authentication provider.
|
||||
*
|
||||
* @param userDetailService the user detail service
|
||||
*/
|
||||
public LocalAuthenticationProvider(UserDetailsService userDetailService) {
|
||||
setUserDetailsService(userDetailService);
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
|
||||
* @see org.springframework.security.authentication.dao.
|
||||
* AbstractUserDetailsAuthenticationProvider#authenticate(org.springframework.
|
||||
* security.core.Authentication)
|
||||
*/
|
||||
@Override
|
||||
public Authentication authenticate(Authentication auth) throws AuthenticationException {
|
||||
@ -38,8 +51,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
|
||||
if (auth.getPrincipal() instanceof LocalUserDetails) {
|
||||
LocalUserDetails details = (LocalUserDetails) auth.getPrincipal();
|
||||
if (!secondFactorProviderManager.getEnabled(details.getUserId()).isEmpty()) {
|
||||
PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(
|
||||
details, "", AuthorityUtils.createAuthorityList("ROLE_PRE_AUTH_USER"));
|
||||
PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(details, "",
|
||||
AuthorityUtils.createAuthorityList("ROLE_PRE_AUTH_USER"));
|
||||
newAuth.setAuthenticated(false);
|
||||
return newAuth;
|
||||
}
|
||||
@ -57,8 +70,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
|
||||
.getProvider(secondFactorAuth.getProvider());
|
||||
|
||||
if (provider == null) {
|
||||
throw new SecondFactorAuthenticationException(
|
||||
"invalid provider: " + secondFactorAuth.getProvider(), details);
|
||||
throw new SecondFactorAuthenticationException("invalid provider: " + secondFactorAuth.getProvider(),
|
||||
details);
|
||||
}
|
||||
|
||||
if (!provider.isEnabled(details.getUserId())) {
|
||||
@ -70,8 +83,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
|
||||
return new UsernamePasswordAuthenticationToken(details, auth.getCredentials(),
|
||||
details.getAuthorities());
|
||||
} else {
|
||||
PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(
|
||||
details, "", auth.getAuthorities());
|
||||
PreAuthenticatedAuthenticationToken newAuth = new PreAuthenticatedAuthenticationToken(details, "",
|
||||
auth.getAuthorities());
|
||||
newAuth.setAuthenticated(false);
|
||||
return newAuth;
|
||||
}
|
||||
@ -82,7 +95,8 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider#supports(java.lang.Class)
|
||||
* @see org.springframework.security.authentication.dao.
|
||||
* AbstractUserDetailsAuthenticationProvider#supports(java.lang.Class)
|
||||
*/
|
||||
public boolean supports(Class<?> authentication) {
|
||||
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication))
|
||||
@ -93,8 +107,7 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
|
||||
/**
|
||||
* The Class SecondFactorAuthenticationException.
|
||||
*/
|
||||
public static class SecondFactorAuthenticationException
|
||||
extends InsufficientAuthenticationException {
|
||||
public static class SecondFactorAuthenticationException extends InsufficientAuthenticationException {
|
||||
|
||||
private LocalUserDetails principal;
|
||||
|
||||
@ -106,7 +119,7 @@ public class LocalAuthenticationProvider extends DaoAuthenticationProvider {
|
||||
/**
|
||||
* Instantiates a new second factor authentication exception.
|
||||
*
|
||||
* @param message the message
|
||||
* @param message the message
|
||||
* @param principal the principal
|
||||
*/
|
||||
public SecondFactorAuthenticationException(String message, LocalUserDetails principal) {
|
||||
|
@ -17,18 +17,19 @@ public class LocalRememberMeServices extends PersistentTokenBasedRememberMeServi
|
||||
/**
|
||||
* Instantiates a new local remember me services.
|
||||
*
|
||||
* @param key the key
|
||||
* @param key the key
|
||||
* @param userDetailsService the user details service
|
||||
* @param tokenRepository the token repository
|
||||
* @param tokenRepository the token repository
|
||||
*/
|
||||
public LocalRememberMeServices(String key, UserDetailsService userDetailsService,
|
||||
PersistentTokenRepository 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
|
||||
protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {
|
||||
|
@ -4,12 +4,11 @@
|
||||
package de.bstly.we.security;
|
||||
|
||||
/**
|
||||
* The listener interface for receiving localServletContext events.
|
||||
* The class that is interested in processing a localServletContext
|
||||
* event implements this interface, and the object created
|
||||
* with that class is registered with a component using the
|
||||
* component's <code>addLocalServletContextListener<code> method. When
|
||||
* the localServletContext event occurs, that object's appropriate
|
||||
* The listener interface for receiving localServletContext events. The class
|
||||
* that is interested in processing a localServletContext event implements this
|
||||
* interface, and the object created with that class is registered with a
|
||||
* component using the component's <code>addLocalServletContextListener<code>
|
||||
* method. When the localServletContext event occurs, that object's appropriate
|
||||
* method is invoked.
|
||||
*
|
||||
* @see LocalServletContextEvent
|
||||
|
@ -1,5 +1,6 @@
|
||||
package de.bstly.we.security;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@ -14,10 +15,14 @@ import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import de.bstly.we.businesslogic.PermissionManager;
|
||||
import de.bstly.we.businesslogic.UserManager;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import de.bstly.we.model.Permission;
|
||||
import de.bstly.we.model.QPermission;
|
||||
import de.bstly.we.model.QUser;
|
||||
import de.bstly.we.model.User;
|
||||
import de.bstly.we.repository.PermissionRepository;
|
||||
import de.bstly.we.repository.UserRepository;
|
||||
import de.bstly.we.security.model.LocalUserDetails;
|
||||
|
||||
/**
|
||||
@ -27,23 +32,26 @@ import de.bstly.we.security.model.LocalUserDetails;
|
||||
public class LocalUserDetailsService implements UserDetailsService {
|
||||
|
||||
@Autowired
|
||||
private UserManager userManager;
|
||||
private UserRepository userRepository;
|
||||
@Autowired
|
||||
private PermissionManager permissionManager;
|
||||
private PermissionRepository permissionRepository;
|
||||
|
||||
private QUser qUser = QUser.user;
|
||||
private QPermission qPermission = QPermission.permission;
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
|
||||
* @see org.springframework.security.core.userdetails.UserDetailsService#
|
||||
* loadUserByUsername(java.lang.String)
|
||||
*/
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
User user = userManager.getByUsername(username);
|
||||
User user = userRepository.findOne(qUser.username.equalsIgnoreCase(username)).orElse(null);
|
||||
|
||||
if (user != null) {
|
||||
String password = userManager.getPasswordHash(user.getId());
|
||||
String password = userRepository.findById(user.getId()).get().getPasswordHash();
|
||||
|
||||
if (password == null) {
|
||||
throw new AuthenticationCredentialsNotFoundException(
|
||||
"No password found: " + username);
|
||||
throw new AuthenticationCredentialsNotFoundException("No password found: " + username);
|
||||
}
|
||||
|
||||
if (user.isDisabled()) {
|
||||
@ -75,8 +83,8 @@ public class LocalUserDetailsService implements UserDetailsService {
|
||||
// }
|
||||
|
||||
// Create user details
|
||||
LocalUserDetails userDetails = new LocalUserDetails(user.getId(), user.getUsername(),
|
||||
password, authorities);
|
||||
LocalUserDetails userDetails = new LocalUserDetails(user.getId(), user.getUsername(), password,
|
||||
authorities);
|
||||
|
||||
return userDetails;
|
||||
}
|
||||
@ -93,7 +101,9 @@ public class LocalUserDetailsService implements UserDetailsService {
|
||||
*/
|
||||
public Set<GrantedAuthority> getAuthoritiesForUser(Long userId) {
|
||||
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
|
||||
for (Permission permission : permissionManager.getNotExpiresByTarget(userId)) {
|
||||
for (Permission permission : Lists.newArrayList(
|
||||
permissionRepository.findAll(qPermission.target.eq(userId).and(qPermission.expires.after(Instant.now())
|
||||
.and(qPermission.starts.isNull().or(qPermission.starts.before(Instant.now()))))))) {
|
||||
authorities.add(new SimpleGrantedAuthority(permission.getName()));
|
||||
}
|
||||
return authorities;
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
@ -11,14 +11,13 @@ import javax.sql.DataSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.authentication.RememberMeServices;
|
||||
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
@ -33,6 +32,7 @@ import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import de.bstly.we.controller.support.TokenSessionManager;
|
||||
import de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter;
|
||||
import de.bstly.we.security.filter.LocalAnonymousAuthenticationFilter;
|
||||
import de.bstly.we.security.filter.RestAuthenticationFilter;
|
||||
@ -55,11 +55,15 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Autowired
|
||||
private DataSource dataSource;
|
||||
@Autowired
|
||||
private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;
|
||||
@Autowired
|
||||
private RestAuthenticationFailureHandler restAuthenticationFailureHandler;
|
||||
@Autowired
|
||||
private LocalAccessDeniedHandler localAccessDeniedHandler;
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
@Autowired
|
||||
private TokenSessionManager tokenSessionManager;
|
||||
@Autowired
|
||||
private LocalAuthenticationProvider localAuthenticationProvider;
|
||||
|
||||
@Value("${server.servlet.session.cookie.secure:false}")
|
||||
private boolean secureCookie;
|
||||
@ -84,12 +88,14 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
*/
|
||||
@Autowired
|
||||
public void configureAuthentication(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.authenticationProvider(daoAuthenticationProvider());
|
||||
localAuthenticationProvider.setPasswordEncoder(passwordEncoder);
|
||||
auth.authenticationProvider(localAuthenticationProvider);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
|
||||
* @see org.springframework.security.config.annotation.web.configuration.
|
||||
* WebSecurityConfigurerAdapter#configure(org.springframework.security.config.
|
||||
* annotation.web.builders.HttpSecurity)
|
||||
*/
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
@ -102,26 +108,21 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
// disable deprectated xss protection
|
||||
.headers().xssProtection().disable().and()
|
||||
// form login
|
||||
.formLogin().loginPage(loginUrl).usernameParameter("username")
|
||||
.passwordParameter("password").loginProcessingUrl("/auth/login")
|
||||
.defaultSuccessUrl(loginTargetUrl)
|
||||
.formLogin().loginPage(loginUrl).usernameParameter("username").passwordParameter("password")
|
||||
.loginProcessingUrl("/auth/login").defaultSuccessUrl(loginTargetUrl)
|
||||
.successHandler(formAuthenticationSuccessHandler())
|
||||
.failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl + "?error"))
|
||||
.and()
|
||||
.failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl + "?error")).and()
|
||||
// remember me
|
||||
.rememberMe().rememberMeServices(rememberMeServices()).and()
|
||||
// form totp
|
||||
.addFilterBefore(formSecondFactorAuthenticationFilter(),
|
||||
LocalAnonymousAuthenticationFilter.class)
|
||||
.addFilterBefore(formSecondFactorAuthenticationFilter(), LocalAnonymousAuthenticationFilter.class)
|
||||
// rest login
|
||||
.addFilterBefore(restAuthenticationFilter(),
|
||||
UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(restAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
|
||||
// rest totp
|
||||
.addFilterAfter(restSecondFactorAuthenticationFilter(),
|
||||
UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(restSecondFactorAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
|
||||
// Logout
|
||||
.logout().logoutUrl("/auth/logout")
|
||||
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()).and()
|
||||
.logout().logoutUrl("/auth/logout").logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
|
||||
.and()
|
||||
// exception
|
||||
.exceptionHandling().accessDeniedHandler(localAccessDeniedHandler)
|
||||
.authenticationEntryPoint(localAuthenticationEntryPoint()).and()
|
||||
@ -155,29 +156,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
return source;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dao authentication provider.
|
||||
*
|
||||
* @return the dao authentication provider
|
||||
*/
|
||||
@Bean
|
||||
public DaoAuthenticationProvider daoAuthenticationProvider() {
|
||||
LocalAuthenticationProvider provider = new LocalAuthenticationProvider();
|
||||
provider.setUserDetailsService(localUserDetailsService);
|
||||
provider.setPasswordEncoder(passwordEncoder());
|
||||
return provider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Password encoder.
|
||||
*
|
||||
* @return the argon 2 password encoder
|
||||
*/
|
||||
@Bean(name = "passwordEncoder")
|
||||
public Argon2PasswordEncoder passwordEncoder() {
|
||||
return new Argon2PasswordEncoder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Local anonymous authentication filter.
|
||||
*
|
||||
@ -195,10 +173,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
*/
|
||||
@Bean
|
||||
public LocalAuthenticationEntryPoint localAuthenticationEntryPoint() {
|
||||
LocalAuthenticationEntryPoint localAuthenticationEntryPoint = new LocalAuthenticationEntryPoint(
|
||||
loginUrl);
|
||||
localAuthenticationEntryPoint
|
||||
.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
|
||||
LocalAuthenticationEntryPoint localAuthenticationEntryPoint = new LocalAuthenticationEntryPoint(loginUrl);
|
||||
localAuthenticationEntryPoint.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
|
||||
|
||||
return localAuthenticationEntryPoint;
|
||||
}
|
||||
@ -211,14 +187,25 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Bean
|
||||
public FormAuthenticationSuccessHandler formAuthenticationSuccessHandler() {
|
||||
FormAuthenticationSuccessHandler formAuthenticationSuccessHandler = new FormAuthenticationSuccessHandler(
|
||||
loginTargetUrl, SecurityConfig.KEEP_PARAM);
|
||||
rememberMeServices(), tokenSessionManager, loginTargetUrl, SecurityConfig.KEEP_PARAM);
|
||||
formAuthenticationSuccessHandler.setTotpRedirectUrl(secondFactorUrl);
|
||||
formAuthenticationSuccessHandler.setTargetUrlParameter("forward");
|
||||
formAuthenticationSuccessHandler
|
||||
.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
|
||||
formAuthenticationSuccessHandler.addRequestMatcher(new AntPathRequestMatcher("/oidc/authorize"));
|
||||
return formAuthenticationSuccessHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rest authentication success handler.
|
||||
*
|
||||
* @return the rest authentication success handler
|
||||
*/
|
||||
@Bean
|
||||
public RestAuthenticationSuccessHandler restAuthenticationSuccessHandler() {
|
||||
RestAuthenticationSuccessHandler restAuthenticationSuccessHandler = new RestAuthenticationSuccessHandler(
|
||||
rememberMeServices(), tokenSessionManager);
|
||||
return restAuthenticationSuccessHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Form second factor authentication filter.
|
||||
*
|
||||
@ -226,13 +213,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
* @throws Exception the exception
|
||||
*/
|
||||
@Bean
|
||||
public FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter()
|
||||
throws Exception {
|
||||
public FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter() throws Exception {
|
||||
FormSecondFactorAuthenticationFilter formSecondFactorAuthenticationFilter = new FormSecondFactorAuthenticationFilter(
|
||||
"/auth/login/2fa");
|
||||
formSecondFactorAuthenticationFilter.setAuthenticationManager(authenticationManager());
|
||||
formSecondFactorAuthenticationFilter
|
||||
.setAuthenticationSuccessHandler(formAuthenticationSuccessHandler());
|
||||
formSecondFactorAuthenticationFilter.setAuthenticationSuccessHandler(formAuthenticationSuccessHandler());
|
||||
formSecondFactorAuthenticationFilter.setRememberMeServices(rememberMeServices());
|
||||
return formSecondFactorAuthenticationFilter;
|
||||
}
|
||||
@ -245,10 +230,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
*/
|
||||
@Bean
|
||||
public RestAuthenticationFilter restAuthenticationFilter() throws Exception {
|
||||
RestAuthenticationFilter restAuthenticationFilter = new RestAuthenticationFilter(
|
||||
"/auth/restlogin");
|
||||
RestAuthenticationFilter restAuthenticationFilter = new RestAuthenticationFilter("/auth/restlogin");
|
||||
restAuthenticationFilter.setAuthenticationManager(authenticationManager());
|
||||
restAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);
|
||||
restAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler());
|
||||
restAuthenticationFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
|
||||
return restAuthenticationFilter;
|
||||
}
|
||||
@ -260,15 +244,12 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
* @throws Exception the exception
|
||||
*/
|
||||
@Bean
|
||||
public RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter()
|
||||
throws Exception {
|
||||
public RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter() throws Exception {
|
||||
RestSecondFactorAuthenticationFilter restSecondFactorAuthenticationFilter = new RestSecondFactorAuthenticationFilter(
|
||||
"/auth/restlogin/2fa");
|
||||
restSecondFactorAuthenticationFilter.setAuthenticationManager(authenticationManager());
|
||||
restSecondFactorAuthenticationFilter
|
||||
.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);
|
||||
restSecondFactorAuthenticationFilter
|
||||
.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
|
||||
restSecondFactorAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler());
|
||||
restSecondFactorAuthenticationFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
|
||||
restSecondFactorAuthenticationFilter.setRememberMeServices(rememberMeServices());
|
||||
return restSecondFactorAuthenticationFilter;
|
||||
}
|
||||
@ -302,8 +283,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
*/
|
||||
@Bean
|
||||
public RememberMeServices rememberMeServices() {
|
||||
PersistentTokenBasedRememberMeServices rememberMeServices = new LocalRememberMeServices(
|
||||
KEEP_PARAM, localUserDetailsService, persistentTokenRepository());
|
||||
PersistentTokenBasedRememberMeServices rememberMeServices = new LocalRememberMeServices(KEEP_PARAM,
|
||||
localUserDetailsService, persistentTokenRepository());
|
||||
rememberMeServices.setCookieName("SESSION_" + KEEP_PARAM.toUpperCase());
|
||||
rememberMeServices.setParameter(KEEP_PARAM);
|
||||
rememberMeServices.setUseSecureCookie(secureCookie);
|
||||
|
@ -38,7 +38,7 @@ public interface SecondFactorProvider<T extends SecondFactor> extends UserDataPr
|
||||
* Validate.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param code the code
|
||||
* @param code the code
|
||||
* @return true, if successful
|
||||
*/
|
||||
boolean validate(Long userId, String code);
|
||||
@ -63,7 +63,7 @@ public interface SecondFactorProvider<T extends SecondFactor> extends UserDataPr
|
||||
* Enable.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param code the code
|
||||
* @param code the code
|
||||
* @return true, if successful
|
||||
*/
|
||||
boolean enable(Long userId, String code);
|
||||
|
@ -26,16 +26,15 @@ public class SecondFactorProviderManager implements SmartInitializingSingleton {
|
||||
*/
|
||||
private List<SecondFactorProvider<?>> providers;
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
|
||||
* @see org.springframework.beans.factory.SmartInitializingSingleton#
|
||||
* afterSingletonsInstantiated()
|
||||
*/
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
providers = Lists.newArrayList();
|
||||
|
||||
for (SecondFactorProvider<?> provider : context.getBeansOfType(SecondFactorProvider.class)
|
||||
.values()) {
|
||||
for (SecondFactorProvider<?> provider : context.getBeansOfType(SecondFactorProvider.class).values()) {
|
||||
providers.add(provider);
|
||||
}
|
||||
}
|
||||
|
@ -10,8 +10,7 @@ import de.bstly.we.model.SecondFactor;
|
||||
*
|
||||
* @param <T> the generic type
|
||||
*/
|
||||
public interface SecondFactorRequestProvider<T extends SecondFactor>
|
||||
extends SecondFactorProvider<T> {
|
||||
public interface SecondFactorRequestProvider<T extends SecondFactor> extends SecondFactorProvider<T> {
|
||||
|
||||
/**
|
||||
* Request.
|
||||
|
@ -40,24 +40,22 @@ public class FormSecondFactorAuthenticationFilter extends AbstractAuthentication
|
||||
super(defaultFilterProcessesUrl);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
|
||||
* @see org.springframework.security.web.authentication.
|
||||
* AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet.
|
||||
* http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
|
||||
*/
|
||||
@Override
|
||||
public Authentication attemptAuthentication(HttpServletRequest request,
|
||||
HttpServletResponse response)
|
||||
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
|
||||
throws AuthenticationException, IOException, ServletException {
|
||||
|
||||
if (!request.getMethod().equals("POST")) {
|
||||
throw new AuthenticationServiceException(
|
||||
"Authentication method not supported: " + request.getMethod());
|
||||
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
|
||||
}
|
||||
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (authentication == null
|
||||
|| !(authentication instanceof PreAuthenticatedAuthenticationToken)
|
||||
if (authentication == null || !(authentication instanceof PreAuthenticatedAuthenticationToken)
|
||||
|| !(authentication.getPrincipal() instanceof LocalUserDetails)) {
|
||||
throw new InsufficientAuthenticationException("login first!");
|
||||
}
|
||||
@ -75,14 +73,15 @@ public class FormSecondFactorAuthenticationFilter extends AbstractAuthentication
|
||||
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#unsuccessfulAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
|
||||
* @see org.springframework.security.web.authentication.
|
||||
* AbstractAuthenticationProcessingFilter#unsuccessfulAuthentication(javax.
|
||||
* servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
|
||||
* org.springframework.security.core.AuthenticationException)
|
||||
*/
|
||||
@Override
|
||||
protected void unsuccessfulAuthentication(HttpServletRequest request,
|
||||
HttpServletResponse response, AuthenticationException failed)
|
||||
throws IOException, ServletException {
|
||||
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
|
||||
AuthenticationException failed) throws IOException, ServletException {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Authentication request failed: " + failed.toString(), failed);
|
||||
logger.debug("Updated SecurityContextHolder to contain null Authentication");
|
||||
|
@ -32,22 +32,25 @@ public class LocalAnonymousAuthenticationFilter extends AnonymousAuthenticationF
|
||||
super(KEY);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.web.authentication.AnonymousAuthenticationFilter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
|
||||
* @see
|
||||
* org.springframework.security.web.authentication.AnonymousAuthenticationFilter
|
||||
* #doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
|
||||
* javax.servlet.FilterChain)
|
||||
*/
|
||||
@Override
|
||||
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
if (SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(createAuthentication((HttpServletRequest) req));
|
||||
SecurityContextHolder.getContext().setAuthentication(createAuthentication((HttpServletRequest) req));
|
||||
}
|
||||
chain.doFilter(req, res);
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.web.authentication.AnonymousAuthenticationFilter#createAuthentication(javax.servlet.http.HttpServletRequest)
|
||||
* @see
|
||||
* org.springframework.security.web.authentication.AnonymousAuthenticationFilter
|
||||
* #createAuthentication(javax.servlet.http.HttpServletRequest)
|
||||
*/
|
||||
@Override
|
||||
protected Authentication createAuthentication(HttpServletRequest request) {
|
||||
|
@ -44,16 +44,16 @@ public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFi
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
|
||||
* @see org.springframework.security.web.authentication.
|
||||
* AbstractAuthenticationProcessingFilter#attemptAuthentication(javax.servlet.
|
||||
* http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
|
||||
*/
|
||||
@Override
|
||||
public Authentication attemptAuthentication(HttpServletRequest request,
|
||||
HttpServletResponse response)
|
||||
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
|
||||
throws AuthenticationException, IOException, ServletException {
|
||||
|
||||
if (!request.getMethod().equals("POST")) {
|
||||
throw new AuthenticationServiceException(
|
||||
"Authentication method not supported: " + request.getMethod());
|
||||
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
|
||||
}
|
||||
|
||||
try {
|
||||
@ -77,8 +77,7 @@ public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFi
|
||||
}
|
||||
|
||||
Authentication authRequest = new UsernamePasswordAuthenticationToken(
|
||||
loginModel.get(usernameKey).getAsString(),
|
||||
loginModel.get(passwordKey).getAsString());
|
||||
loginModel.get(usernameKey).getAsString(), loginModel.get(passwordKey).getAsString());
|
||||
return this.getAuthenticationManager().authenticate(authRequest);
|
||||
} catch (JsonMappingException | JsonParseException exception) {
|
||||
throw new AuthenticationCredentialsNotFoundException("Bad request");
|
||||
|
@ -39,24 +39,22 @@ public class RestSecondFactorAuthenticationFilter extends FormSecondFactorAuthen
|
||||
super(defaultFilterProcessesUrl);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
|
||||
* @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter#
|
||||
* attemptAuthentication(javax.servlet.http.HttpServletRequest,
|
||||
* javax.servlet.http.HttpServletResponse)
|
||||
*/
|
||||
@Override
|
||||
public Authentication attemptAuthentication(HttpServletRequest request,
|
||||
HttpServletResponse response)
|
||||
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
|
||||
throws AuthenticationException, IOException, ServletException {
|
||||
|
||||
if (!request.getMethod().equals("POST")) {
|
||||
throw new AuthenticationServiceException(
|
||||
"Authentication method not supported: " + request.getMethod());
|
||||
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
|
||||
}
|
||||
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (authentication == null
|
||||
|| !(authentication instanceof PreAuthenticatedAuthenticationToken)
|
||||
if (authentication == null || !(authentication instanceof PreAuthenticatedAuthenticationToken)
|
||||
|| !(authentication.getPrincipal() instanceof LocalUserDetails)) {
|
||||
throw new InsufficientAuthenticationException("login first!");
|
||||
}
|
||||
@ -79,10 +77,8 @@ public class RestSecondFactorAuthenticationFilter extends FormSecondFactorAuthen
|
||||
String provider = model2FA.get(SPRING_SECURITY_FORM_2FA_PROVIDER_KEY).getAsString();
|
||||
String code = model2FA.get(SPRING_SECURITY_FORM_2FA_CODE_KEY).getAsString();
|
||||
|
||||
if (model2FA.has(SecurityConfig.KEEP_PARAM)
|
||||
&& model2FA.get(SecurityConfig.KEEP_PARAM).isJsonPrimitive()) {
|
||||
request.setAttribute(SecurityConfig.KEEP_PARAM,
|
||||
model2FA.get(SecurityConfig.KEEP_PARAM).getAsString());
|
||||
if (model2FA.has(SecurityConfig.KEEP_PARAM) && model2FA.get(SecurityConfig.KEEP_PARAM).isJsonPrimitive()) {
|
||||
request.setAttribute(SecurityConfig.KEEP_PARAM, model2FA.get(SecurityConfig.KEEP_PARAM).getAsString());
|
||||
}
|
||||
|
||||
LocalUserDetails details = (LocalUserDetails) authentication.getPrincipal();
|
||||
@ -93,14 +89,15 @@ public class RestSecondFactorAuthenticationFilter extends FormSecondFactorAuthen
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter#unsuccessfulAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
|
||||
* @see de.bstly.we.security.filter.FormSecondFactorAuthenticationFilter#
|
||||
* unsuccessfulAuthentication(javax.servlet.http.HttpServletRequest,
|
||||
* javax.servlet.http.HttpServletResponse,
|
||||
* org.springframework.security.core.AuthenticationException)
|
||||
*/
|
||||
@Override
|
||||
protected void unsuccessfulAuthentication(HttpServletRequest request,
|
||||
HttpServletResponse response, AuthenticationException failed)
|
||||
throws IOException, ServletException {
|
||||
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
|
||||
AuthenticationException failed) throws IOException, ServletException {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Authentication request failed: " + failed.toString(), failed);
|
||||
logger.debug("Updated SecurityContextHolder to contain null Authentication");
|
||||
|
@ -7,7 +7,6 @@ import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.authentication.RememberMeServices;
|
||||
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
|
||||
@ -24,13 +23,10 @@ import de.bstly.we.security.token.LocalSecondFactorAuthenticationToken;
|
||||
/**
|
||||
* The Class FormAuthenticationSuccessHandler.
|
||||
*/
|
||||
public class FormAuthenticationSuccessHandler
|
||||
extends SavedRequestAwareAuthenticationSuccessHandler {
|
||||
public class FormAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
|
||||
|
||||
@Autowired
|
||||
protected RememberMeServices rememberMeServices;
|
||||
@Autowired
|
||||
protected TokenSessionManager tokenSessionManager;
|
||||
protected final RememberMeServices rememberMeServices;
|
||||
protected final TokenSessionManager tokenSessionManager;
|
||||
|
||||
private String totpRedirectUrl;
|
||||
private String rememberMeParameter;
|
||||
@ -40,33 +36,44 @@ public class FormAuthenticationSuccessHandler
|
||||
/**
|
||||
* Instantiates a new form authentication success handler.
|
||||
*
|
||||
* @param rememberMeServices the remember me services
|
||||
* @param tokenSessionManager the token session manager
|
||||
* @param rememberMeParameter the remember me parameter
|
||||
*/
|
||||
public FormAuthenticationSuccessHandler(String rememberMeParameter) {
|
||||
public FormAuthenticationSuccessHandler(RememberMeServices rememberMeServices,
|
||||
TokenSessionManager tokenSessionManager, String rememberMeParameter) {
|
||||
this.rememberMeServices = rememberMeServices;
|
||||
this.tokenSessionManager = tokenSessionManager;
|
||||
this.rememberMeParameter = rememberMeParameter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new form authentication success handler.
|
||||
*
|
||||
* @param 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
|
||||
*/
|
||||
public FormAuthenticationSuccessHandler(String defaultTargetUrl, String rememberMeParameter) {
|
||||
public FormAuthenticationSuccessHandler(RememberMeServices rememberMeServices,
|
||||
TokenSessionManager tokenSessionManager, String defaultTargetUrl, String rememberMeParameter) {
|
||||
this.rememberMeServices = rememberMeServices;
|
||||
this.tokenSessionManager = tokenSessionManager;
|
||||
setDefaultTargetUrl(defaultTargetUrl);
|
||||
this.rememberMeParameter = rememberMeParameter;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
|
||||
* @see org.springframework.security.web.authentication.
|
||||
* SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax.
|
||||
* servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
|
||||
* org.springframework.security.core.Authentication)
|
||||
*/
|
||||
@Override
|
||||
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
|
||||
Authentication authentication) throws ServletException, IOException {
|
||||
|
||||
if (!authentication.isAuthenticated()
|
||||
&& authentication instanceof PreAuthenticatedAuthenticationToken) {
|
||||
|
||||
if (!authentication.isAuthenticated() && authentication instanceof PreAuthenticatedAuthenticationToken) {
|
||||
rememberMeServices.loginFail(request, response);
|
||||
boolean keep = false;
|
||||
String paramValue = request.getParameter(rememberMeParameter);
|
||||
@ -77,23 +84,20 @@ public class FormAuthenticationSuccessHandler
|
||||
}
|
||||
}
|
||||
|
||||
if (authentication.getAuthorities() != null && authentication.getAuthorities()
|
||||
.containsAll(LocalSecondFactorAuthenticationToken.AUTHORITIES)) {
|
||||
if (authentication.getAuthorities() != null
|
||||
&& authentication.getAuthorities().containsAll(LocalSecondFactorAuthenticationToken.AUTHORITIES)) {
|
||||
getRedirectStrategy().sendRedirect(request, response,
|
||||
totpRedirectUrl + "?error" + (keep ? "&keep" : ""));
|
||||
} else {
|
||||
getRedirectStrategy().sendRedirect(request, response,
|
||||
totpRedirectUrl + (keep ? "?keep" : ""));
|
||||
getRedirectStrategy().sendRedirect(request, response, totpRedirectUrl + (keep ? "?keep" : ""));
|
||||
}
|
||||
} else {
|
||||
rememberMeServices.loginSuccess(request, response, authentication);
|
||||
|
||||
for (RequestMatcher matcher : requestMatchers) {
|
||||
if (matcher.matches(request)) {
|
||||
getRedirectStrategy().sendRedirect(request, response,
|
||||
request.getRequestURI() + (request.getQueryString() != null
|
||||
? "?" + request.getQueryString()
|
||||
: ""));
|
||||
getRedirectStrategy().sendRedirect(request, response, request.getRequestURI()
|
||||
+ (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
@ -17,9 +17,12 @@ import org.springframework.stereotype.Component;
|
||||
@Component
|
||||
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {
|
||||
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
|
||||
* @see
|
||||
* org.springframework.security.web.authentication.AuthenticationFailureHandler#
|
||||
* onAuthenticationFailure(javax.servlet.http.HttpServletRequest,
|
||||
* javax.servlet.http.HttpServletResponse,
|
||||
* org.springframework.security.core.AuthenticationException)
|
||||
*/
|
||||
@Override
|
||||
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
|
||||
|
@ -8,30 +8,36 @@ import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.security.web.authentication.RememberMeServices;
|
||||
|
||||
import de.bstly.we.controller.support.TokenSessionManager;
|
||||
import de.bstly.we.security.SecurityConfig;
|
||||
|
||||
/**
|
||||
* The Class RestAuthenticationSuccessHandler.
|
||||
*/
|
||||
@Component
|
||||
public class RestAuthenticationSuccessHandler extends FormAuthenticationSuccessHandler {
|
||||
|
||||
/**
|
||||
* Instantiates a new rest authentication success handler.
|
||||
*
|
||||
* @param rememberMeServices the remember me services
|
||||
* @param tokenSessionManager the token session manager
|
||||
*/
|
||||
public RestAuthenticationSuccessHandler() {
|
||||
super(SecurityConfig.KEEP_PARAM);
|
||||
public RestAuthenticationSuccessHandler(RememberMeServices rememberMeServices,
|
||||
TokenSessionManager tokenSessionManager) {
|
||||
super(rememberMeServices, tokenSessionManager, SecurityConfig.KEEP_PARAM);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* @see de.bstly.we.security.handler.FormAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
|
||||
* @see de.bstly.we.security.handler.FormAuthenticationSuccessHandler#
|
||||
* onAuthenticationSuccess(javax.servlet.http.HttpServletRequest,
|
||||
* javax.servlet.http.HttpServletResponse,
|
||||
* org.springframework.security.core.Authentication)
|
||||
*/
|
||||
@Override
|
||||
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
|
||||
Authentication authentication) throws IOException, ServletException {
|
||||
Authentication authentication) throws IOException, ServletException {
|
||||
if (!authentication.isAuthenticated()) {
|
||||
rememberMeServices.loginFail(request, response);
|
||||
response.sendError(HttpStatus.PRECONDITION_REQUIRED.value(),
|
||||
|
@ -22,9 +22,9 @@ public class LocalUserDetails extends User {
|
||||
/**
|
||||
* Instantiates a new local user details.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @param username the username
|
||||
* @param password the password
|
||||
* @param userId the user id
|
||||
* @param username the username
|
||||
* @param password the password
|
||||
* @param authorities the authorities
|
||||
*/
|
||||
public LocalUserDetails(Long userId, String username, String password,
|
||||
|
@ -19,8 +19,7 @@ public class LocalAnonymousAuthenticationToken extends AnonymousAuthenticationTo
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
public static final String ANONYMOUS_USERNAME = "anonymous";
|
||||
public static final List<GrantedAuthority> AUTHORITIES = AuthorityUtils
|
||||
.createAuthorityList("ROLE_ANONYMOUS");
|
||||
public static final List<GrantedAuthority> AUTHORITIES = AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");
|
||||
|
||||
/**
|
||||
* Instantiates a new local anonymous authentication token.
|
||||
@ -34,7 +33,7 @@ public class LocalAnonymousAuthenticationToken extends AnonymousAuthenticationTo
|
||||
/**
|
||||
* Instantiates a new local anonymous authentication token.
|
||||
*
|
||||
* @param principal the principal
|
||||
* @param principal the principal
|
||||
* @param authorities the authorities
|
||||
*/
|
||||
public LocalAnonymousAuthenticationToken(Object principal, List<GrantedAuthority> authorities) {
|
||||
|
@ -21,8 +21,7 @@ public class LocalSecondFactorAuthenticationToken extends AbstractAuthentication
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
public static final String ROLE_REQUIRE_2FA = "ROLE_REQUIRE_2FA";
|
||||
public static final List<GrantedAuthority> AUTHORITIES = AuthorityUtils
|
||||
.createAuthorityList(ROLE_REQUIRE_2FA);
|
||||
public static final List<GrantedAuthority> AUTHORITIES = AuthorityUtils.createAuthorityList(ROLE_REQUIRE_2FA);
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@ -34,11 +33,10 @@ public class LocalSecondFactorAuthenticationToken extends AbstractAuthentication
|
||||
* Instantiates a new local second factor authentication token.
|
||||
*
|
||||
* @param principal the principal
|
||||
* @param provider the provider
|
||||
* @param code the code
|
||||
* @param provider the provider
|
||||
* @param code the code
|
||||
*/
|
||||
public LocalSecondFactorAuthenticationToken(LocalUserDetails principal, String provider,
|
||||
String code) {
|
||||
public LocalSecondFactorAuthenticationToken(LocalUserDetails principal, String provider, String code) {
|
||||
super(AUTHORITIES);
|
||||
this.principal = principal;
|
||||
this.provider = provider;
|
||||
|
@ -32,10 +32,10 @@ public class EmailManager {
|
||||
/**
|
||||
* Send text.
|
||||
*
|
||||
* @param to the to
|
||||
* @param from the from
|
||||
* @param to the to
|
||||
* @param from the from
|
||||
* @param subject the subject
|
||||
* @param text the text
|
||||
* @param text the text
|
||||
* @return the mail message
|
||||
*/
|
||||
public MailMessage sendText(String to, String from, String subject, String text) {
|
||||
@ -52,10 +52,10 @@ public class EmailManager {
|
||||
/**
|
||||
* Send bcc.
|
||||
*
|
||||
* @param bcc the bcc
|
||||
* @param from the from
|
||||
* @param bcc the bcc
|
||||
* @param from the from
|
||||
* @param subject the subject
|
||||
* @param text the text
|
||||
* @param text the text
|
||||
* @return the mail message
|
||||
*/
|
||||
public MailMessage sendBcc(String[] bcc, String from, String subject, String text) {
|
||||
@ -80,12 +80,10 @@ public class EmailManager {
|
||||
|
||||
UserProfileField primaryEmailUserProfileField = userProfileFieldManager.get(user.getId(),
|
||||
UserProfileFields.PROFILE_FIELD_EMAIL_PRIMARY);
|
||||
if (primaryEmailUserProfileField != null
|
||||
&& "true".equals(primaryEmailUserProfileField.getValue())) {
|
||||
if (primaryEmailUserProfileField != null && "true".equals(primaryEmailUserProfileField.getValue())) {
|
||||
UserProfileField emailUserProfileField = userProfileFieldManager.get(user.getId(),
|
||||
UserProfileFields.PROFILE_FIELD_EMAIL);
|
||||
if (emailUserProfileField != null
|
||||
&& StringUtils.hasText(emailUserProfileField.getValue())) {
|
||||
if (emailUserProfileField != null && StringUtils.hasText(emailUserProfileField.getValue())) {
|
||||
email = emailUserProfileField.getValue();
|
||||
}
|
||||
}
|
||||
|
@ -54,8 +54,7 @@ public class EmailController extends BaseController {
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/test")
|
||||
public MailMessage sendTest(@RequestBody String to) {
|
||||
return emailManager.sendText(to, "no-reply@we.bstly.de", "Test Email",
|
||||
"Test from we.bstly");
|
||||
return emailManager.sendText(to, "no-reply@we.bstly.de", "Test Email", "Test from we.bstly");
|
||||
}
|
||||
|
||||
/**
|
||||
@ -80,8 +79,7 @@ public class EmailController extends BaseController {
|
||||
|
||||
UserProfileField localeUserProfileField = userProfileFieldManager.get(user.getId(),
|
||||
UserProfileFields.PROFILE_FIELD_LOCALE);
|
||||
if (localeUserProfileField != null
|
||||
&& StringUtils.hasText(localeUserProfileField.getValue())) {
|
||||
if (localeUserProfileField != null && StringUtils.hasText(localeUserProfileField.getValue())) {
|
||||
userMailModel.setLocale(localeUserProfileField.getValue());
|
||||
}
|
||||
|
||||
@ -91,6 +89,4 @@ public class EmailController extends BaseController {
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
@ -16,7 +16,7 @@ public class UserMailModel {
|
||||
* Instantiates a new user mail model.
|
||||
*
|
||||
* @param username the username
|
||||
* @param email the email
|
||||
* @param email the email
|
||||
*/
|
||||
public UserMailModel(String username, String email) {
|
||||
super();
|
||||
|
@ -70,7 +70,7 @@ public class I18nManager {
|
||||
* Extend json object.
|
||||
*
|
||||
* @param dest the dest
|
||||
* @param src the src
|
||||
* @param src the src
|
||||
*/
|
||||
protected void extendJsonObject(JsonObject dest, JsonObject src) {
|
||||
for (Entry<String, JsonElement> srcEntry : src.entrySet()) {
|
||||
@ -92,7 +92,7 @@ public class I18nManager {
|
||||
/**
|
||||
* Adds the label.
|
||||
*
|
||||
* @param locale the locale
|
||||
* @param locale the locale
|
||||
* @param newLabel the new label
|
||||
* @return the i 18 n
|
||||
*/
|
||||
@ -116,7 +116,7 @@ public class I18nManager {
|
||||
* Sets the label.
|
||||
*
|
||||
* @param locale the locale
|
||||
* @param label the label
|
||||
* @param label the label
|
||||
* @return the i 18 n
|
||||
*/
|
||||
public I18n setLabel(String locale, JsonObject label) {
|
||||
|
@ -51,11 +51,11 @@ public class I18nController extends BaseController {
|
||||
/**
|
||||
* Gets the label.
|
||||
*
|
||||
* @param locale the locale
|
||||
* @param locale the locale
|
||||
* @param response the response
|
||||
* @return the label
|
||||
* @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}")
|
||||
public void getLabel(@PathVariable("locale") String locale, HttpServletResponse response)
|
||||
@ -71,7 +71,7 @@ public class I18nController extends BaseController {
|
||||
* Sets the label.
|
||||
*
|
||||
* @param locale the locale
|
||||
* @param label the label
|
||||
* @param label the label
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/{locale}")
|
||||
@ -87,7 +87,7 @@ public class I18nController extends BaseController {
|
||||
* Adds the label.
|
||||
*
|
||||
* @param locale the locale
|
||||
* @param label the label
|
||||
* @param label the label
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PutMapping("/{locale}")
|
||||
|
@ -13,7 +13,6 @@ import de.bstly.we.i18n.model.I18n;
|
||||
* The Interface I18nRepository.
|
||||
*/
|
||||
@Repository
|
||||
public interface I18nRepository
|
||||
extends JpaRepository<I18n, String>, QuerydslPredicateExecutor<I18n> {
|
||||
public interface I18nRepository extends JpaRepository<I18n, String>, QuerydslPredicateExecutor<I18n> {
|
||||
|
||||
}
|
||||
|
@ -63,15 +63,14 @@ public class InviteManager implements UserDataProvider {
|
||||
/**
|
||||
* Gets the.
|
||||
*
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param search the search
|
||||
* @return the page
|
||||
*/
|
||||
public Page<Invite> get(int page, int size, String search) {
|
||||
if (StringUtils.hasText(search)) {
|
||||
return inviteRepository.findAll(qInvite.note.containsIgnoreCase(search),
|
||||
PageRequest.of(page, size));
|
||||
return inviteRepository.findAll(qInvite.note.containsIgnoreCase(search), PageRequest.of(page, size));
|
||||
}
|
||||
return inviteRepository.findAll(PageRequest.of(page, size));
|
||||
}
|
||||
@ -89,18 +88,18 @@ public class InviteManager implements UserDataProvider {
|
||||
/**
|
||||
* Gets the by owner.
|
||||
*
|
||||
* @param owner the owner
|
||||
* @param quota the quota
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param owner the owner
|
||||
* @param quota the quota
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @param search the search
|
||||
* @param redeemed the redeemed
|
||||
* @param search the search
|
||||
* @param redeemed the redeemed
|
||||
* @return the by owner
|
||||
*/
|
||||
public Page<Invite> getByOwner(Long owner, String quota, int page, int size, String sortBy,
|
||||
boolean descending, String search, String redeemed) {
|
||||
public Page<Invite> getByOwner(Long owner, String quota, int page, int size, String sortBy, boolean descending,
|
||||
String search, String redeemed) {
|
||||
PageRequest pageRequest = PageRequest.of(page, size,
|
||||
descending ? Sort.by(sortBy).descending() : Sort.by(sortBy).ascending());
|
||||
|
||||
@ -129,16 +128,15 @@ public class InviteManager implements UserDataProvider {
|
||||
/**
|
||||
* Gets the others.
|
||||
*
|
||||
* @param owner the owner
|
||||
* @param quota the quota
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param search the search
|
||||
* @param owner the owner
|
||||
* @param quota the quota
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param search the search
|
||||
* @param redeemed the redeemed
|
||||
* @return the others
|
||||
*/
|
||||
public Page<Invite> getOthers(Long owner, String quota, int page, int size, String search,
|
||||
String redeemed) {
|
||||
public Page<Invite> getOthers(Long owner, String quota, int page, int size, String search, String redeemed) {
|
||||
|
||||
BooleanBuilder query = new BooleanBuilder();
|
||||
query.and(qInvite.owner.ne(owner));
|
||||
@ -173,8 +171,7 @@ public class InviteManager implements UserDataProvider {
|
||||
}
|
||||
}
|
||||
|
||||
InviteMapping inviteMapping = inviteMappingManager.getByItemAndQuota(invite.getItem(),
|
||||
invite.getQuota());
|
||||
InviteMapping inviteMapping = inviteMappingManager.getByItemAndQuota(invite.getItem(), invite.getQuota());
|
||||
Assert.notNull(inviteMapping, "No mapping for item!");
|
||||
if (StringUtils.hasLength(inviteMapping.getCodeLink())) {
|
||||
invite.setCodeLink(String.format(inviteMapping.getCodeLink(), invite.getCode()));
|
||||
|
@ -46,22 +46,21 @@ public class InviteMappingManager {
|
||||
/**
|
||||
* Gets the by item and quota.
|
||||
*
|
||||
* @param item the item
|
||||
* @param item the item
|
||||
* @param quota the quota
|
||||
* @return the by item and quota
|
||||
*/
|
||||
public InviteMapping getByItemAndQuota(int item, String quota) {
|
||||
return inviteMappingRepository
|
||||
.findOne(qInviteMapping.item.eq(item).and(qInviteMapping.quota.eq(quota)))
|
||||
return inviteMappingRepository.findOne(qInviteMapping.item.eq(item).and(qInviteMapping.quota.eq(quota)))
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the.
|
||||
*
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param sortBy the sort by
|
||||
* @param descending the descending
|
||||
* @return the page
|
||||
*/
|
||||
@ -73,9 +72,9 @@ public class InviteMappingManager {
|
||||
/**
|
||||
* Creates the.
|
||||
*
|
||||
* @param quota the quota
|
||||
* @param item the item
|
||||
* @param starts the starts
|
||||
* @param quota the quota
|
||||
* @param item the item
|
||||
* @param starts the starts
|
||||
* @param expires the expires
|
||||
* @return the invite mapping
|
||||
*/
|
||||
@ -98,8 +97,8 @@ public class InviteMappingManager {
|
||||
*/
|
||||
public InviteMapping save(InviteMapping inviteMapping) {
|
||||
|
||||
for (Invite invite : inviteRepository.findAll(qInvite.item.eq(inviteMapping.getItem())
|
||||
.and(qInvite.quota.eq(inviteMapping.getQuota())))) {
|
||||
for (Invite invite : inviteRepository
|
||||
.findAll(qInvite.item.eq(inviteMapping.getItem()).and(qInvite.quota.eq(inviteMapping.getQuota())))) {
|
||||
if (StringUtils.hasText(inviteMapping.getCodeLink())) {
|
||||
String codeLink = String.format(inviteMapping.getCodeLink(), invite.getCode());
|
||||
if (!codeLink.equals(invite.getCodeLink())) {
|
||||
@ -120,17 +119,17 @@ public class InviteMappingManager {
|
||||
invite.setUrl(null);
|
||||
inviteRepository.save(invite);
|
||||
}
|
||||
|
||||
|
||||
if (!invite.getStarts().equals(inviteMapping.getStarts())) {
|
||||
invite.setStarts(inviteMapping.getStarts());
|
||||
inviteRepository.save(invite);
|
||||
}
|
||||
|
||||
|
||||
if (!invite.getExpires().equals(inviteMapping.getExpires())) {
|
||||
invite.setExpires(inviteMapping.getExpires());
|
||||
inviteRepository.save(invite);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
return inviteMappingRepository.save(inviteMapping);
|
||||
|
@ -119,8 +119,8 @@ public class InviteController extends BaseController {
|
||||
throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE);
|
||||
}
|
||||
|
||||
return permissionManager.getForItem(null, invite.getItem(), new JsonArray(),
|
||||
invite.getStarts(), invite.getExpires());
|
||||
return permissionManager.getForItem(null, invite.getItem(), new JsonArray(), invite.getStarts(),
|
||||
invite.getExpires());
|
||||
}
|
||||
|
||||
/**
|
||||
@ -162,15 +162,14 @@ public class InviteController extends BaseController {
|
||||
throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE);
|
||||
}
|
||||
|
||||
if (invite.isRedeemed()
|
||||
|| invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) {
|
||||
if (invite.isRedeemed() || invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) {
|
||||
throw new EntityResponseStatusException(HttpStatus.GONE);
|
||||
}
|
||||
|
||||
boolean register = false;
|
||||
|
||||
for (Permission permission : permissionManager.getForItem(null, invite.getItem(),
|
||||
new JsonArray(), invite.getStarts(), invite.getExpires())) {
|
||||
for (Permission permission : permissionManager.getForItem(null, invite.getItem(), new JsonArray(),
|
||||
invite.getStarts(), invite.getExpires())) {
|
||||
if (permission.getExpires().isAfter(Instant.now()) && !permission.isAddon()) {
|
||||
register = true;
|
||||
break;
|
||||
@ -200,8 +199,7 @@ public class InviteController extends BaseController {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
User user = userManager.create(userModel.getUsername(), userModel.getPassword(),
|
||||
userModel.getStatus());
|
||||
User user = userManager.create(userModel.getUsername(), userModel.getPassword(), userModel.getStatus());
|
||||
|
||||
Long userId = user.getId();
|
||||
|
||||
@ -218,8 +216,7 @@ public class InviteController extends BaseController {
|
||||
userProfileField = userProfileFieldManager.save(userProfileField);
|
||||
}
|
||||
|
||||
permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(),
|
||||
invite.getExpires());
|
||||
permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(), invite.getExpires());
|
||||
quotaManager.applyItem(userId, invite.getItem());
|
||||
|
||||
invite.setRedeemed(true);
|
||||
@ -241,15 +238,13 @@ public class InviteController extends BaseController {
|
||||
throw new EntityResponseStatusException(HttpStatus.NOT_ACCEPTABLE);
|
||||
}
|
||||
|
||||
if (invite.isRedeemed()
|
||||
|| invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) {
|
||||
if (invite.isRedeemed() || invite.getExpires() != null && invite.getExpires().isBefore(Instant.now())) {
|
||||
throw new EntityResponseStatusException(HttpStatus.GONE);
|
||||
}
|
||||
|
||||
Long userId = getCurrentUserId();
|
||||
|
||||
permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(),
|
||||
invite.getExpires());
|
||||
permissionManager.applyItem(userId, invite.getItem(), new JsonArray(), invite.getStarts(), invite.getExpires());
|
||||
quotaManager.applyItem(userId, invite.getItem());
|
||||
|
||||
invite.setRedeemed(true);
|
||||
@ -260,12 +255,12 @@ public class InviteController extends BaseController {
|
||||
/**
|
||||
* Gets the invites.
|
||||
*
|
||||
* @param quotaParameter the quota parameter
|
||||
* @param pageParameter the page parameter
|
||||
* @param sizeParameter the size parameter
|
||||
* @param sortParamater the sort paramater
|
||||
* @param descParameter the desc parameter
|
||||
* @param searchParameter the search parameter
|
||||
* @param quotaParameter the quota parameter
|
||||
* @param pageParameter the page parameter
|
||||
* @param sizeParameter the size parameter
|
||||
* @param sortParamater the sort paramater
|
||||
* @param descParameter the desc parameter
|
||||
* @param searchParameter the search parameter
|
||||
* @param redeemedParameter the redeemed parameter
|
||||
* @return the invites
|
||||
*/
|
||||
@ -273,25 +268,23 @@ public class InviteController extends BaseController {
|
||||
@GetMapping
|
||||
public Page<Invite> getInvites(@RequestParam("quota") Optional<String> quotaParameter,
|
||||
@RequestParam("page") Optional<Integer> pageParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter,
|
||||
@RequestParam("sort") Optional<String> sortParamater,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("sort") Optional<String> sortParamater,
|
||||
@RequestParam("desc") Optional<Boolean> descParameter,
|
||||
@RequestParam("search") Optional<String> searchParameter,
|
||||
@RequestParam("redeemed") Optional<String> redeemedParameter) {
|
||||
|
||||
return inviteManager.getByOwner(getCurrentUserId(), quotaParameter.orElse(""),
|
||||
pageParameter.orElse(0), sizeParameter.orElse(10), sortParamater.orElse("id"),
|
||||
descParameter.orElse(false), searchParameter.orElse(null),
|
||||
redeemedParameter.orElse(null));
|
||||
return inviteManager.getByOwner(getCurrentUserId(), quotaParameter.orElse(""), pageParameter.orElse(0),
|
||||
sizeParameter.orElse(10), sortParamater.orElse("id"), descParameter.orElse(false),
|
||||
searchParameter.orElse(null), redeemedParameter.orElse(null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the other invites.
|
||||
*
|
||||
* @param quota the quota
|
||||
* @param pageParameter the page parameter
|
||||
* @param sizeParameter the size parameter
|
||||
* @param searchParameter the search parameter
|
||||
* @param quota the quota
|
||||
* @param pageParameter the page parameter
|
||||
* @param sizeParameter the size parameter
|
||||
* @param searchParameter the search parameter
|
||||
* @param redeemedParameter the redeemed parameter
|
||||
* @return the other invites
|
||||
*/
|
||||
@ -304,15 +297,13 @@ public class InviteController extends BaseController {
|
||||
@RequestParam("redeemed") Optional<String> redeemedParameter) {
|
||||
|
||||
InviteMapping inviteMapping = inviteMappingManager.get(quota);
|
||||
Quota inviteQuota = quotaManager.get(getCurrentUserId(),
|
||||
InviteMapping.QUOTA_PREFIX + quota);
|
||||
Quota inviteQuota = quotaManager.get(getCurrentUserId(), InviteMapping.QUOTA_PREFIX + quota);
|
||||
if (inviteMapping == null || inviteQuota == null || inviteQuota.getValue() < 1) {
|
||||
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
Page<Invite> page = inviteManager.getOthers(getCurrentUserId(), quota,
|
||||
pageParameter.orElse(0), sizeParameter.orElse(10), searchParameter.orElse(null),
|
||||
redeemedParameter.orElse(null));
|
||||
Page<Invite> page = inviteManager.getOthers(getCurrentUserId(), quota, pageParameter.orElse(0),
|
||||
sizeParameter.orElse(10), searchParameter.orElse(null), redeemedParameter.orElse(null));
|
||||
for (Invite invite : page.getContent()) {
|
||||
invite.setCode(null);
|
||||
invite.setCodeLink(null);
|
||||
@ -327,17 +318,15 @@ public class InviteController extends BaseController {
|
||||
/**
|
||||
* Creates the invite.
|
||||
*
|
||||
* @param quota the quota
|
||||
* @param quota the quota
|
||||
* @param inviteModel the invite model
|
||||
* @return the invite
|
||||
*/
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@PostMapping("/{quota}")
|
||||
public Invite createInvite(@PathVariable("quota") String quota,
|
||||
@RequestBody Invite inviteModel) {
|
||||
public Invite createInvite(@PathVariable("quota") String quota, @RequestBody Invite inviteModel) {
|
||||
InviteMapping inviteMapping = inviteMappingManager.get(quota);
|
||||
Quota inviteQuota = quotaManager.get(getCurrentUserId(),
|
||||
InviteMapping.QUOTA_PREFIX + quota);
|
||||
Quota inviteQuota = quotaManager.get(getCurrentUserId(), InviteMapping.QUOTA_PREFIX + quota);
|
||||
if (inviteMapping == null || inviteQuota == null || inviteQuota.getValue() < 1) {
|
||||
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
|
||||
}
|
||||
@ -348,10 +337,8 @@ public class InviteController extends BaseController {
|
||||
|
||||
Invite invite = new Invite();
|
||||
invite.setOwner(getCurrentUserId());
|
||||
invite.setStarts(inviteMapping.getStarts() != null ? inviteMapping.getStarts()
|
||||
: inviteModel.getStarts());
|
||||
invite.setExpires(inviteMapping.getExpires() != null ? inviteMapping.getExpires()
|
||||
: inviteModel.getExpires());
|
||||
invite.setStarts(inviteMapping.getStarts() != null ? inviteMapping.getStarts() : inviteModel.getStarts());
|
||||
invite.setExpires(inviteMapping.getExpires() != null ? inviteMapping.getExpires() : inviteModel.getExpires());
|
||||
invite.setItem(inviteMapping.getItem());
|
||||
invite.setQuota(inviteMapping.getQuota());
|
||||
|
||||
|
@ -44,16 +44,15 @@ public class InviteManagingController extends BaseController {
|
||||
/**
|
||||
* Gets the invites.
|
||||
*
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param page the page
|
||||
* @param size the size
|
||||
* @param search the search
|
||||
* @return the invites
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping
|
||||
public Page<Invite> getInvites(@RequestParam("page") Optional<Integer> page,
|
||||
@RequestParam("size") Optional<Integer> size,
|
||||
@RequestParam("search") Optional<String> search) {
|
||||
@RequestParam("size") Optional<Integer> size, @RequestParam("search") Optional<String> search) {
|
||||
return inviteManager.get(page.orElse(0), size.orElse(10), search.orElse(null));
|
||||
}
|
||||
|
||||
@ -66,8 +65,8 @@ public class InviteManagingController extends BaseController {
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping
|
||||
public Invite createOrUpdate(@RequestBody Invite invite) {
|
||||
if (invite.getItem() == null || inviteMappingManager.getByItemAndQuota(invite.getItem(),
|
||||
invite.getQuota()) == null) {
|
||||
if (invite.getItem() == null
|
||||
|| inviteMappingManager.getByItemAndQuota(invite.getItem(), invite.getQuota()) == null) {
|
||||
throw new EntityResponseStatusException(HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
|
@ -47,11 +47,9 @@ public class InviteMappingController extends BaseController {
|
||||
*/
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping
|
||||
public Page<InviteMapping> getInviteMappings(
|
||||
@RequestParam("page") Optional<Integer> pageParameter,
|
||||
public Page<InviteMapping> getInviteMappings(@RequestParam("page") Optional<Integer> pageParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter) {
|
||||
return inviteMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "quota",
|
||||
true);
|
||||
return inviteMappingManager.get(pageParameter.orElse(0), sizeParameter.orElse(10), "quota", true);
|
||||
}
|
||||
|
||||
/**
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user