ExpiredAuthorizationEntityCleaner.java
/*
* Copyright 2023 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.oauth.component;
import com.querydsl.core.types.ExpressionUtils;
import lombok.extern.slf4j.Slf4j;
import org.genesys.blocks.oauth.model.QAuthorization;
import org.genesys.blocks.oauth.persistence.AuthorizationRepository;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
@Slf4j
public class ExpiredAuthorizationEntityCleaner {
private final AuthorizationRepository authorizationRepository;
private final int expiredEntitiesDelay;
public ExpiredAuthorizationEntityCleaner(AuthorizationRepository authorizationRepository, int expiredEntitiesDelay) {
this.authorizationRepository = authorizationRepository;
this.expiredEntitiesDelay = expiredEntitiesDelay;
}
@Scheduled(initialDelay = 30 * 1000, fixedDelay = 60 * 60 * 1000) // In milliseconds
@Transactional
public void processExpired() {
Instant expiredInstant = Instant.now().minus(Math.max(expiredEntitiesDelay, 0), ChronoUnit.DAYS);
log.trace("Searching for the authorization entities expired before: {}", expiredInstant);
var authorization = QAuthorization.authorization;
var entitiesForDelete = authorizationRepository.findAll(ExpressionUtils.anyOf(
// remove unused authorization code entries
authorization.authorizationCodeExpiresAt.before(expiredInstant).and(authorization.accessTokenExpiresAt.isNull()).and(authorization.refreshTokenExpiresAt.isNull()),
// remove expired access tokens with no refresh token
authorization.accessTokenExpiresAt.before(expiredInstant).and(authorization.refreshTokenExpiresAt.isNull()),
// remove expired refresh tokens
authorization.refreshTokenExpiresAt.before(expiredInstant)
));
authorizationRepository.deleteAll(entitiesForDelete);
}
}