TokenVerificationServiceImpl.java

/*
 * Copyright 2020 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.gringlobal.service.impl;

import java.util.Calendar;
import java.util.Date;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.gringlobal.model.VerificationToken;
import org.gringlobal.persistence.VerificationTokenRepository;
import org.gringlobal.service.TokenVerificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;


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

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

	@Autowired
	private VerificationTokenRepository verificationTokenRepository;

	@Override
	@Transactional
	public VerificationToken generateToken(String tokenPurpose, String data) {
		VerificationToken token = new VerificationToken();
		token.setPurpose(tokenPurpose);
		// Store data
		token.setData(data);
		token.setKey(RandomStringUtils.randomAlphanumeric(4).toUpperCase());

		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR_OF_DAY, TOKEN_VALIDITY_HOURS);
		Date validUntil = calendar.getTime();

		token.setValidUntil(validUntil);
		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();
		}

		Date now = Calendar.getInstance().getTime();
		if (verificationToken.getValidUntil().before(now)) {
			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(initialDelayString = "PT5M", fixedDelayString = "PT10M")
	@SchedulerLock(name = "org.gringlobal.service.impl.TokenVerificationServiceImpl")
	public void removeExpired() {
		final Date now = Calendar.getInstance().getTime();
		if (log.isTraceEnabled()) {
			log.trace("Removing expired verification tokens");
		}

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