UserApiServiceImpl.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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.security.NoUserFoundException;
import org.genesys.blocks.security.SecurityContextUtil;
import org.genesys.blocks.security.UserException;
import org.genesys.blocks.security.lockout.AccountLockoutManager;
import org.genesys.blocks.security.model.BasicUser;
import org.genesys.blocks.security.service.PasswordPolicy;
import org.genesys.server.api.v2.facade.UserApiService;
import org.genesys.server.api.v2.mapper.MapstructMapper;
import org.genesys.server.api.v2.model.impl.UserDTO;
import org.genesys.server.exception.InvalidApiUsageException;
import org.genesys.server.exception.NotFoundElement;
import org.genesys.server.model.UserRole;
import org.genesys.server.model.impl.QUser;
import org.genesys.server.model.impl.User;
import org.genesys.server.persistence.UserRepository;
import org.genesys.server.service.EMailVerificationService;
import org.genesys.server.service.UserService;
import org.genesys.server.service.filter.UserFilter;
import org.genesys.util.RandomPasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true)
@Slf4j
public class UserApiServiceImpl implements UserApiService {

	@Autowired
	private UserService userService;

	@Autowired
	private EMailVerificationService emailVerificationService;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private MapstructMapper mapper;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private AccountLockoutManager lockoutManager;

	@Override
	public UserDTO getUser(UUID uuid) {
		return mapper.map(userService.getUser(uuid));
	}

	@Override
	@Transactional
	public UserDTO unlockAccount(UUID uuid) throws NoUserFoundException {
		User user = userService.getUser(uuid);
		userService.setAccountLock(user.getId(), false);
		return mapper.map(userService.getUser(uuid));
	}

	@Override
	@Transactional
	public UserDTO lockAccount(UUID uuid) throws NoUserFoundException {
		User user = userService.getUser(uuid);
		userService.setAccountLock(user.getId(), true);
		return mapper.map(userService.getUser(uuid));
	}

	@Override
	@Transactional
	public UserDTO extendAccount(UUID uuid) {
		User user = userService.getUser(uuid);
		if (user == null) {
			throw new NotFoundElement("No such user");
		}
		return mapper.map(userService.extendAccount(user));
	}

	@Override
	@Transactional
	public UserDTO enableAccount(UUID uuid) throws UserException {
		userService.setAccountActive(uuid, true);
		return mapper.map(userService.getUser(uuid));
	}

	@Override
	@Transactional
	public UserDTO disableAccount(UUID uuid) throws UserException {
		userService.setAccountActive(uuid, false);
		return mapper.map(userService.getUser(uuid));
	}

	@Override
	public UserDTO archiveAccount(UUID uuid) throws UserException {
		User user = userService.getUser(uuid);
		user = userService.archiveUser(user);
		log.info("Archived user " + user.getEmail());
		return mapper.map(user);
	}

	@Override
	@Transactional
	public List<UserDTO> archiveAccounts(Set<UUID> uuids) {
		var userUuids = uuids.stream().map(UUID::toString).collect(Collectors.toSet());
		var users = userRepository.findAll(QUser.user.uuid.in(userUuids));

		List<User> archived = new ArrayList<>();
		for (User user : users) {
			try {
				archived.add(userService.archiveUser(user));
			} catch (UserException e) {
				log.warn("User archiving exception", e);
			}
		}
		return mapper.map(archived, mapper::map);
	}

	@Override
	@Transactional
	public String generateFtpPassword(UUID uuid) throws PasswordPolicy.PasswordPolicyException {
		User user = userService.getUser(uuid);
		String generatedPassword = RandomPasswordUtil.generatePassword(new Random(), 15);
		userService.setFtpPassword(user, generatedPassword);
		log.info("Generated new FTP password for user " + user.getEmail());
		return generatedPassword;
	}

	@Override
	public void sendEmail(UUID uuid) {
		final User user = userService.getUser(uuid);
		emailVerificationService.sendVerificationEmail(user);
	}

	@Override
	@Transactional
	public UserDTO updateUser(UserDTO dto) throws UserException {
		var user = mapper.map(dto);
		User updated = userService.updateUser(user, user.getEmail(), user.getFullName());
		if (CollectionUtils.isNotEmpty(user.getRoles())) {
			updated = userService.setRoles(updated, user.getRoles());
		}
		return mapper.map(updated);
	}

	@Override
	public Page<UserDTO> list(UserFilter filter, Pageable email) {
		return mapper.map(userService.list(filter, email), mapper::map);
	}

	@Override
	@Transactional
	public UserDTO registerUser(String email, String password, String fullName) throws UserException {
		final User newUser = userService.createUser(email, fullName, password, BasicUser.AccountType.LOCAL);
		emailVerificationService.sendVerificationEmail(newUser);
		return mapper.map(newUser);
	}

	@Override
	public Page<UserDTO> listUsers(Pageable page) {
		return mapper.map(userService.listUsers(page), mapper::map);
	}

	@Override
	@Transactional
	public void addVettedUserRole(UUID uuid) {
		userService.addVettedUserRole(uuid);
	}

	@Override
	public List<UserRole> listAvailableRoles() {
		return userService.listAvailableRoles();
	}

	@Override
	@Transactional
	public void adminResetPassword(String email) {
		final User user = userService.getUserByEmail(email);
		if (user != null) {
			emailVerificationService.sendPasswordResetEmail(user);
		}
	}

	@Override
	@Transactional
	public void update(UUID uuid, UserDTO updatedUser, String pwd1) throws UserException {
		final User user = userService.getUser(UUID.fromString(updatedUser.getUuid()));
		if (user == null) {
			throw new NotFoundElement();
		}

		userService.updateUser(user, updatedUser.getEmail(), updatedUser.getFullName());

		if (StringUtils.isNotBlank(pwd1)) {
			log.info("Updating password for {}", user);
			userService.changePassword(user, pwd1);
			log.warn("Password updated for {}", user);
		}
	}

	@Override
	@Transactional
	public void delete(UUID uuid) throws UserException {
		final User user = userService.getUser(uuid);

		if (user == null) {
			throw new NotFoundElement();
		}

		if (!user.isAccountNonExpired()) {
			throw new InvalidApiUsageException("User is already expired");
		}

		log.warn("Archiving user account {}", user.getEmail());
		userService.archiveUser(user);
	}

	@Override
	@Transactional
	public void updateRoles(UUID uuid, Set<UserRole> selectedRoles) {
		final User user = userService.getUser(uuid);
		if (user == null) {
			throw new NotFoundElement();
		}

		userService.setRoles(user, selectedRoles);
	}

	@Override
	public UserDTO getProfile() {
		final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication instanceof AbstractOAuth2TokenAuthenticationToken<?>) {
			var oauthAuth = (AbstractOAuth2TokenAuthenticationToken<?>) authentication;
			final User currentUser = (User) oauthAuth.getPrincipal();
			return mapper.map((User) userService.loadUserByUsername(currentUser.getUsername()));
		}
		// This is added for unit test support
		if (authentication instanceof UsernamePasswordAuthenticationToken) {
			final User currentUser = (User) authentication.getPrincipal();
			return mapper.map((User) userService.loadUserByUsername(currentUser.getUsername()));
		}
		throw new NotFoundElement("Not using user authentication");
	}

	@Override
	@Transactional
	public String changePassword(String oldPassword, String newPassword) throws UserException {
		final User currentUser = userService.getUser(UUID.fromString(SecurityContextUtil.getMe().getUuid()));

		if (currentUser.isAccountLocked()) {
			throw new LockedException("Too many failed login attempts.");
		}

		if (passwordEncoder.matches(oldPassword, currentUser.getPassword())) {
			lockoutManager.handleSuccessfulLogin(currentUser.getUsername());
			// need to reload the record (different versions)
			userService.changePassword(userService.getUser(UUID.fromString(currentUser.getUuid())), newPassword);
			return "OK";
		} else {
			lockoutManager.handleFailedLogin(currentUser.getUsername());
			throw new UserException("Your old password was entered incorrectly. Please enter it again.");
		}
	}

	@Override
	@Transactional
	public boolean resetPassword(String email) throws UserException {
		try {
			final User user = userService.getUserByEmail(email);

			if (user != null && user.getAccountType() == BasicUser.AccountType.GOOGLE) {
				log.warn("Password for users with login type GOOGLE can't be reset!");
				throw new UserException("Password for users with login type GOOGLE can't be reset!");
			}

			if (user != null && user.isAccountLocked()) {
				log.warn("Password for locked user accounts can't be reset!");
				throw new UserException("Password for locked user accounts can't be reset!");
			}

			if (user != null && !user.isEnabled()) {
				log.warn("Password for disabled user accounts can't be reset!");
				throw new UserException("Password for disabled user accounts can't be reset!");
			}

			if (user != null) {
				emailVerificationService.sendPasswordResetEmail(user);
				return true;
			}
			throw new NotFoundElement("User not found");
		} catch (UsernameNotFoundException e) {
			throw new UserException("No such user!");
		}
	}

	@Override
	@Transactional
	public boolean deleteAccountRequest() throws UserException {
		var user = userService.getMe();
		if (user == null) {
			throw new NoUserFoundException();
		}
		if (user.hasRole(UserRole.ADMINISTRATOR.getName())) {
			throw new UserException("Refusing to disable active administrator account");
		}
		emailVerificationService.sendDeleteAccountEmail(user);
		return true;
	}

	@Override
	@Transactional
	public UserDTO updateUserPreferences(UserService.UserPreferences preferences) throws UserException {
		return mapper.map(userService.updateUserPreferences(preferences));
	}

	@Override
	@Transactional
	public UserDTO updateUserPreference(String setting, boolean value) throws UserException {
		return mapper.map(userService.updateUserPreference(setting, value));
	}
}