TokenVerificationServiceImpl.java

/**
 * Copyright 2014 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.server.service.impl;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

import org.apache.commons.lang3.RandomStringUtils;
import org.genesys.server.model.impl.VerificationToken;
import org.genesys.server.persistence.VerificationTokenRepository;
import org.genesys.server.service.JPATokenStoreCleanup;
import org.genesys.server.service.TokenVerificationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class TokenVerificationServiceImpl implements TokenVerificationService, JPATokenStoreCleanup {

	private static final Logger LOG = LoggerFactory.getLogger(TokenVerificationServiceImpl.class);

	private static final int TOKEN_VALIDITY_HOURS = 24 * 12; // 12 days

	@Autowired
	private VerificationTokenRepository verificationTokenRepository;

	@Override
	@Transactional
	public VerificationToken generateToken(String tokenPurpose, String data) {

		var inst = Instant.now().plus(TOKEN_VALIDITY_HOURS, ChronoUnit.HOURS);

		final VerificationToken existingToken = verificationTokenRepository.findByPurposeAndData(tokenPurpose, data);
		if (existingToken != null) {
			// Extend validity of the token
			existingToken.setValidUntil(inst);
			return verificationTokenRepository.save(existingToken);

		} else {
			// Make a new token
			VerificationToken token = new VerificationToken();
			token.setPurpose(tokenPurpose);
			// Store data
			token.setData(data);
			token.setKey(RandomStringUtils.randomAlphanumeric(4).toUpperCase());
			token.setValidUntil(inst);
			token = verificationTokenRepository.save(token);
			return token;
		}
	}

	@Override
	@Transactional
	public void cancel(String tokenUuid) throws NoSuchVerificationTokenException {
		final VerificationToken verificationToken = verificationTokenRepository.findByUuid(tokenUuid);
		if (verificationToken == null) {
			LOG.warn("Canceling verification token failed. No such verification token {}", tokenUuid);
			throw new NoSuchVerificationTokenException();
		} else {
			LOG.warn("Canceling verification token {}", tokenUuid);
			verificationTokenRepository.delete(verificationToken);
		}
	}

	@Override
	public VerificationToken fetchToken(String purpose, String tokenUuid) throws NoSuchVerificationTokenException {
		final VerificationToken verificationToken = verificationTokenRepository.findByPurposeAndUuid(purpose, tokenUuid);

		if (verificationToken == null) {
			LOG.warn("No such verification token {}", tokenUuid);
			throw new NoSuchVerificationTokenException();
		}

		return verificationToken;
	}

	@Override
	@Transactional
	public VerificationToken consumeToken(String purpose, String tokenUuid, String key) throws NoSuchVerificationTokenException, TokenExpiredException {
		final VerificationToken verificationToken = verificationTokenRepository.findByPurposeAndUuid(purpose, tokenUuid);
		if (verificationToken == null) {
			LOG.warn("No such verification token {} key={}", tokenUuid, key);
			throw new NoSuchVerificationTokenException();
		}

		if (!verificationToken.getKey().equals(key)) {
			LOG.error("Verification key invalid for token={} providedKey={}", verificationToken.getUuid(), key);
			throw new NoSuchVerificationTokenException();
		}

		Instant inst = Instant.now();
		if (verificationToken.getValidUntil().compareTo(inst) < 0) {
			LOG.error("Verification token={} key={} has expired", verificationToken.getUuid(), key);
			throw new TokenExpiredException();
		}

		// Consume token
		verificationTokenRepository.delete(verificationToken);
		return verificationToken;
	}

	/**
	 * Cleanup executed every 10 minutes
	 */
	@Override
	@Transactional
	@Scheduled(fixedDelay = 600000)
	public void removeExpired() {
		var inst = Instant.now();
		if (LOG.isTraceEnabled()) {
			LOG.trace("Removing expired verification tokens");
		}

		int count = verificationTokenRepository.deleteOlderThan(inst);
		if (count > 0) {
			LOG.info("Removed expired verification tokens: {}", count);
		}
	}
}