SessionService.java

/**
 * TFG 75.678 - TFG Desarrollo web 2020 e-Learning for Schools
 * Copyright (C) 2020  Eduardo Rodriguez Carro
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.uoc.tfg.sel.service;

import java.util.Optional;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.uoc.tfg.sel.repository.UserSessionRepository;
import org.uoc.tfg.sel.repository.model.UserSession;

/**
 * Servicio de Mantenimiento de session.
 *
 * @author Eduardo Rodriguez Carro
 */
@Service
@CacheConfig(cacheNames = {"sessionCache"})
public class SessionService {
	
	/** The session time. */
	@Value("${security.session.lifetime:86400000}")
	private Long sessionTime;
	
	/** The user session repository. */
	@Autowired
	private UserSessionRepository userSessionRepository;
	
	/**
	 * Generate session.
	 *
	 * @return the string
	 */
	@Transactional(readOnly = false)
	public String generateSession() {
		UserSession session = new UserSession();
		session.setCreated(System.currentTimeMillis());
		session.setUpdated(System.currentTimeMillis());
		session.setId(UUID.randomUUID().toString());
		userSessionRepository.save(session);
		return session.getId();
	}
	
	/**
	 * Cleaup.
	 */
	@CacheEvict(allEntries = true)
	@Scheduled(cron = "${security.session.cron:0 0/15 * * * *}")
	@Transactional(readOnly = false)
	public void cleaup() {
		userSessionRepository.deleteOld(System.currentTimeMillis() - sessionTime);
	}
	
	/**
	 * Logout.
	 *
	 * @param uuid the uuid
	 */
	@CacheEvict(key="#uuid")
	@Transactional(readOnly = false)
	public void logout (String uuid) {
		userSessionRepository.deleteById(uuid);
	}
	
	/**
	 * Checks for session.
	 *
	 * @param uuid the uuid
	 * @return true, if successful
	 */
	@Cacheable(key="#uuid")
	@Transactional(readOnly = false)
	public boolean hasSession(String uuid) {
		Optional<UserSession> sessionOptional = userSessionRepository.findById(uuid);
		
		// Si existe antes de retornar el OK actualizamos la fecha del ultimo uso para que no sea borrado
		if(sessionOptional.isPresent()) {
			UserSession session = sessionOptional.get();
			session.setUpdated(System.currentTimeMillis());
			userSessionRepository.save(session);
			return true;
		}
		return false;
	}
}