UserManagementController.java

/*
 * Copyright 2018 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 java.io.IOException;
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;

import org.apache.commons.collections4.CollectionUtils;
import org.genesys.blocks.security.NoUserFoundException;
import org.genesys.blocks.security.NotUniqueUserException;
import org.genesys.blocks.security.UserException;
import org.genesys.server.api.ApiBaseController;
import org.genesys.server.api.FilteredPage;
import org.genesys.server.api.Pagination;
import org.genesys.server.exception.NotFoundElement;
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.ShortFilterService.FilterInfo;
import org.genesys.server.service.filter.UserFilter;
import org.genesys.server.service.worker.ShortFilterProcessor;
import org.genesys.util.RandomPasswordUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
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;

import io.swagger.annotations.Api;

/**
 * User API v1
 *
 * @author Matija Obreza
 */
@RestController("userApi1")
@RequestMapping(UserManagementController.CONTROLLER_URL)
@PreAuthorize("isAuthenticated()")
@Api(tags = { "user" })
public class UserManagementController extends ApiBaseController {

	/** The Constant CONTROLLER_URL. */
	public static final String CONTROLLER_URL = ApiBaseController.APIv1_BASE + "/user";

	/** The Constant LOG. */
	private static final Logger LOG = LoggerFactory.getLogger(UserManagementController.class);

	/** The short filter service. */
	@Autowired
	protected ShortFilterProcessor shortFilterProcessor;

	/** The repository service. */
	@Autowired
	protected UserService userService;

	@Autowired
	private EMailVerificationService emailVerificationService;
	
	@Autowired
	private UserRepository userRepository;

	/**
	 * Gets the user.
	 *
	 * @param uuid the uuid
	 * @return the user
	 */
	@GetMapping(value = "/u/{uuid}")
	public User getUser(@PathVariable("uuid") final UUID uuid) {
		User user = userService.getUser(uuid);
		if (user == null) {
			throw new NotFoundElement("No such user");
		}
		return user;
	}
	
	/**
	 * Unlock account.
	 *
	 * @param uuid the uuid
	 * @return the user
	 * @throws NoUserFoundException the no user found exception
	 */
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	@PostMapping(value = "/u/{uuid}/unlock")
	public User unlockAccount(@PathVariable("uuid") final UUID uuid) throws NoUserFoundException {
		User user = userService.getUser(uuid);
		userService.setAccountLock(user.getId(), false);
		return userService.getUser(uuid);
	}
	
	/**
	 * Lock account.
	 *
	 * @param uuid the uuid
	 * @return the user
	 * @throws NoUserFoundException the no user found exception
	 */
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	@PostMapping(value = "/u/{uuid}/lock")
	public User lockAccount(@PathVariable("uuid") final UUID uuid) throws NoUserFoundException {
		User user = userService.getUser(uuid);
		userService.setAccountLock(user.getId(), true);
		return userService.getUser(uuid);
	}

	/**
	 * Extend account.
	 *
	 * @param uuid the uuid
	 * @return the user
	 */
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	@PostMapping(value = "/u/{uuid}/extend")
	public User extendAccount(@PathVariable("uuid") final UUID uuid) {
		User user = userService.getUser(uuid);
		if (user == null) {
			throw new NotFoundElement("No such user");
		}
		return userService.extendAccount(user);
	}

	/**
	 * Enable account.
	 *
	 * @param uuid the uuid
	 * @return the user
	 * @throws NoUserFoundException the no user found exception
	 */
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	@PostMapping(value = "/u/{uuid}/enable")
	public User enableAccount(@PathVariable("uuid") final UUID uuid) throws UserException {
		userService.setAccountActive(uuid, true);
		return userService.getUser(uuid);
	}
	
	/**
	 * Disable account.
	 *
	 * @param uuid the uuid
	 * @return the user
	 * @throws NoUserFoundException the no user found exception
	 */
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	@PostMapping(value = "/u/{uuid}/disable")
	public User disableAccount(@PathVariable("uuid") final UUID uuid) throws UserException {
		userService.setAccountActive(uuid, false);
		return userService.getUser(uuid);
	}

	/**
	 * Archive account.
	 *
	 * @param uuid the uuid
	 * @return the user
	 * @throws UserException the user exception
	 */
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	@PostMapping(value = "/u/{uuid}/archive")
	public User archiveAccount(@PathVariable("uuid") final UUID uuid) throws UserException {
		User user = userService.getUser(uuid);
		user = userService.archiveUser(user);
		LOG.info("Archived user " + user.getEmail());
		return user;
	}

	/**
	 * Archive accounts.
	 *
	 * @param uuids the set of uuids
	 * @return the list of archived users
	 */
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	@PostMapping(value = "/u/archive")
	public List<User> archiveAccounts(@RequestBody final 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 archived;
	}

	/**
	 * Generate ftp password.
	 *
	 * @param uuid the uuid
	 * @return the user
	 * @throws UserException the user exception
	 */
	@PostMapping(value = "/u/{uuid}/ftp-password")
	public String generateFtpPassword(@PathVariable("uuid") final UUID uuid) throws UserException {
		User user = 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;
	}


	/**
	 * Send verification email.
	 *
	 * @param uuid the uuid
	 */
	@PostMapping(value = "/u/{uuid}/email-verification")
	public boolean sendEmail(@PathVariable("uuid") UUID uuid) {
		final User user = getUser(uuid);
		emailVerificationService.sendVerificationEmail(user);
		return true;
	}

	/**
	 * Update user.
	 *
	 * @param user the user
	 * @return the user
	 * @throws NotUniqueUserException the not unique user exception
	 * @throws UserException the user exception
	 */
	@PutMapping(value = "/user")
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	public User updateUser(@RequestBody User user) throws NotUniqueUserException, UserException {
		User updated = userService.updateUser(user, user.getEmail(), user.getFullName());
		if (CollectionUtils.isNotEmpty(user.getRoles())) {
			return userService.setRoles(updated, user.getRoles());
		} else {
			return updated;
		}
	}

	/**
	 * List users.
	 *
	 * @param filterCode the filter code
	 * @param page the page
	 * @param filter the filter
	 * @return the filtered page
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	@PostMapping(value = "/list")
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	public FilteredPage<User, UserFilter> listUsers(@RequestParam(name = "f", required = false) String filterCode, @ParameterObject final Pagination page,
			@RequestBody(required = false) UserFilter filter) throws IOException {

		FilterInfo<UserFilter> filterInfo = shortFilterProcessor.processFilter(filterCode, filter, UserFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, userService.list(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.ASC, "email")));
	}

}