ApiTokenController.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.server.api.v1;

import com.fasterxml.jackson.annotation.JsonView;
import io.swagger.annotations.Api;

import java.time.Period;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityNotFoundException;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.ArrayUtils;
import org.genesys.blocks.model.JsonViews;
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.ApiBaseController;
import org.genesys.server.api.Pagination;
import org.genesys.server.exception.NotFoundElement;
import org.genesys.server.model.impl.User;
import org.genesys.server.persistence.UserRepository;
import org.springdoc.api.annotations.ParameterObject;
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.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController("apiTokenApi1")
@RequestMapping(ApiTokenController.API_URL)
@Api(tags = { "apiToken" })
@PreAuthorize("isFullyAuthenticated()")
public class ApiTokenController extends ApiBaseController implements InitializingBean {

	public static final String API_URL = APIv1_BASE + "/api-token";

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

	private Period defaultTokenDuration;

	@Autowired
	private ApiTokenService apiTokenService;
	
	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private OAuthClientRepository clientRepository;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		defaultTokenDuration = Period.parse("P".concat(tokenDurationStr));
	}

	@PostMapping(value = "/user/generate", produces = MediaType.APPLICATION_JSON_VALUE)
	@JsonView({ JsonViews.Internal.class })
	@PreAuthorize("hasRole('ADMINISTRATOR') || hasRole('VETTEDUSER')")
	public ApiToken generateUserToken(@RequestParam(required = false) String label) {
		User currentUser = SecurityContextUtil.getMe();

		User user = userRepository.findById(currentUser.getId()).orElseThrow(() -> new EntityNotFoundException("User not found."));
	
		return apiTokenService.createToken(user, label, ZonedDateTime.now().plus(defaultTokenDuration).toInstant());
	}

	@PostMapping(value = "/user/{userId}/generate", produces = MediaType.APPLICATION_JSON_VALUE)
	@JsonView({ JsonViews.Internal.class })
	@PreAuthorize("hasRole('ADMINISTRATOR') || (hasRole('VETTEDUSER') && #userId == principal.id)")
	public ApiToken generateTokenForUser(@PathVariable Long userId, @RequestParam(required = false) String label) {

		User user = userRepository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found."));

		return apiTokenService.createToken(user, label, ZonedDateTime.now().plus(defaultTokenDuration).toInstant());
	}

	@PostMapping(value = "/client/{clientId}/generate", produces = MediaType.APPLICATION_JSON_VALUE)
	@JsonView({ JsonViews.Internal.class })
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	public ApiToken generateTokenForClient(@PathVariable String clientId, @RequestParam(required = false) String label) {

		OAuthClient client = clientRepository.findByClientId(clientId);
		if (client == null) {
			throw new EntityNotFoundException("Client not found.");
		}

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

	@GetMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
	@JsonView({ JsonViews.Public.class })
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	public Page<ApiToken> getAllTokens(@ParameterObject final Pagination page) {
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.ASC) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		
		return apiTokenService.listTokens(pageable);
	}

	@GetMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
	@JsonView({ JsonViews.Public.class })
	public List<ApiToken> 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).collect(Collectors.toList());
	}

	@PutMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
	@PreAuthorize("hasRole('ADMINISTRATOR') || hasRole('VETTEDUSER')")
	@JsonView({ JsonViews.Public.class })
	public ApiToken update(@RequestBody @NotNull final ApiToken apiToken) {

		var toUpdate = apiTokenService.loadById(apiToken.getId());
		if (toUpdate == null) {
			throw new NotFoundElement("API Token not found");
		}
		
		toUpdate.apply(apiToken);
		return apiTokenService.update(toUpdate);
	}

	@DeleteMapping(value = "/{id}")
	@PreAuthorize("hasRole('ADMINISTRATOR') || hasRole('VETTEDUSER')")
	@JsonView({ JsonViews.Public.class })
	public ApiToken removeToken(@PathVariable Long id) {
		var token = apiTokenService.loadById(id);
		if (token == null) {
			throw new NotFoundElement("API Token not found by id: " + id);
		}
		return apiTokenService.remove(token);
	}

}