ApiTokenApiServiceImpl.java

/*
 * Copyright 2025 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.api.v2.facade.impl;

import org.genesys.blocks.oauth.model.OAuthClient;
import org.genesys.blocks.oauth.persistence.OAuthClientRepository;
import org.genesys.blocks.security.SecurityContextUtil;
import org.genesys.blocks.tokenauth.model.ApiToken;
import org.genesys.blocks.tokenauth.service.ApiTokenService;
import org.genesys.server.api.v2.facade.ApiTokenApiService;
import org.genesys.server.api.v2.mapper.MapstructMapper;
import org.genesys.server.api.v2.model.impl.ApiTokenDTO;
import org.genesys.server.api.v2.model.impl.ApiTokenInfo;
import org.genesys.server.exception.NotFoundElement;
import org.genesys.server.model.impl.User;
import org.genesys.server.persistence.UserRepository;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.time.Period;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true)
public class ApiTokenApiServiceImpl implements ApiTokenApiService, InitializingBean {

	@Autowired
	private ApiTokenService apiTokenService;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private OAuthClientRepository clientRepository;

	@Autowired
	private MapstructMapper mapper;

	@Value("${apitoken.validity:1Y}")
	private String tokenDurationStr;

	private Period defaultTokenDuration;

	@Override
	public void afterPropertiesSet() throws Exception {
		defaultTokenDuration = Period.parse("P".concat(tokenDurationStr));
	}

	@Override
	@Transactional
	public ApiTokenDTO generateUserToken(String label) {
		User currentUser = SecurityContextUtil.getMe();
		User user = userRepository.findById(currentUser.getId()).orElseThrow(() -> new EntityNotFoundException("User not found."));
		return mapper.map(apiTokenService.createToken(user, label, ZonedDateTime.now().plus(defaultTokenDuration).toInstant()));
	}

	@Override
	@Transactional
	public ApiTokenDTO generateTokenForUser(Long userId, String label) {
		User user = userRepository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found."));
		return mapper.map(apiTokenService.createToken(user, label, ZonedDateTime.now().plus(defaultTokenDuration).toInstant()));
	}

	@Override
	@Transactional
	public ApiTokenDTO generateTokenForClient(String clientId, String label) {
		OAuthClient client = clientRepository.findByClientId(clientId);
		if (client == null) {
			throw new EntityNotFoundException("Client not found.");
		}

		return mapper.map(apiTokenService.createToken(client, label, ZonedDateTime.now().plus(defaultTokenDuration).toInstant()));
	}

	@Override
	public Page<ApiTokenInfo> getAllTokens(Pageable page) {
		return mapper.map(apiTokenService.listTokens(page), mapper::mapInfo);
	}

	@Override
	public List<ApiTokenInfo> getMyTokens() {
		User currentUser = SecurityContextUtil.getMe();
		User user = userRepository.findById(currentUser.getId()).orElseThrow(() -> new EntityNotFoundException("User not found."));

		var myTokens = apiTokenService.listTokensForSid(user);
		return myTokens.stream().filter(ApiToken::isCredentialsNonExpired).map(mapper::mapInfo).collect(Collectors.toList());
	}

	@Override
	@Transactional
	public ApiTokenInfo update(ApiTokenInfo apiToken) {
		var toUpdate = apiTokenService.loadById(apiToken.getId());
		if (toUpdate == null) {
			throw new NotFoundElement("API Token not found");
		}
		toUpdate.apply(mapper.mapInfo(apiToken));
		return mapper.mapInfo(apiTokenService.update(toUpdate));
	}

	@Override
	@Transactional
	public ApiTokenInfo removeToken(Long id) {
		var token = apiTokenService.loadById(id);
		if (token == null) {
			throw new NotFoundElement("API Token not found by id: " + id);
		}
		return mapper.mapInfo(apiTokenService.remove(token));
	}
}