MeController.java

/*
 * Copyright 2019 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.UUID;

import javax.servlet.http.HttpServletRequest;

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.AclSid;
import org.genesys.blocks.security.model.BasicUser;
import org.genesys.blocks.security.service.PasswordPolicy;
import org.genesys.server.api.ApiBaseController;
import org.genesys.server.exception.NotFoundElement;
import org.genesys.server.model.UserRole;
import org.genesys.server.model.impl.User;
import org.genesys.server.service.EMailVerificationService;
import org.genesys.server.service.ShortFilterService;
import org.genesys.server.service.TokenVerificationService;
import org.genesys.server.service.UserService;
import org.genesys.spring.CaptchaChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
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.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.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;

/**
 * Me API v1
 */
@RestController("meApi1")
@RequestMapping(MeController.CONTROLLER_URL)
@PreAuthorize("isAuthenticated() && (hasRole('USER') || hasRole('ADMINISTRATOR'))") // Don't allow OAuth clients here
@Api(tags = { "me" })
public class MeController extends ApiBaseController {

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

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private AccountLockoutManager lockoutManager;

	@Autowired
	private UserService userService;

	/** The short filter service. */
	@Autowired
	protected ShortFilterService shortFilterService;

	@Autowired
	private EMailVerificationService emailVerificationService;

	@Autowired
	private CaptchaChecker captchaChecker;

	/**
	 * Gets the profile.
	 *
	 * @return the profile
	 */
	@PreAuthorize("isAuthenticated()") // Available for OAuth clients
	@GetMapping(value = "/profile")
	public AclSid getProfile() {
		final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication instanceof AbstractOAuth2TokenAuthenticationToken<?>) {
			var oauthAuth = (AbstractOAuth2TokenAuthenticationToken<?>) authentication;
			final User currentUser = (User) oauthAuth.getPrincipal();
			return (AclSid) userService.loadUserByUsername(currentUser.getUsername());
		}
		// This is added for unit test support
		if (authentication instanceof UsernamePasswordAuthenticationToken) {
			final User currentUser = (User) authentication.getPrincipal();
			return (AclSid) userService.loadUserByUsername(currentUser.getUsername());
		}
		throw new NotFoundElement("Not using user authentication");
	}

	/**
	 * Change password.
	 *
	 * @param oldPassword the old password
	 * @param newPassword the new password
	 * @return the string
	 * @throws UserException the user exception
	 */
	@PostMapping(value = "/password")
	public String changePassword(@RequestParam(name = "old", required = true) final String oldPassword, @RequestParam(name = "new", required = true) final 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.");
		}
	}

	@PreAuthorize("isAuthenticated()")
	@PostMapping(value = "/password/reset")
	public boolean resetPassword(HttpServletRequest req, @RequestParam(value = "g-recaptcha-response", required = false) String response, @RequestParam("email") String email) throws IOException, UserException {

		// Validate the reCAPTCHA
		captchaChecker.assureValidResponseForClient(response, req.getRemoteAddr());

		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!");
		}
	}

	@PreAuthorize("isAuthenticated()")
	@PostMapping(value = "/{tokenUuid:.+}/pwdreset")
	public boolean updatePassword(@PathVariable("tokenUuid") String tokenUuid, HttpServletRequest req, @RequestParam(value = "g-recaptcha-response", required = false) String response,
			@RequestParam(value = "key", required = true) String key, @RequestParam("password") String password) throws IOException, UserException {

		// Validate the reCAPTCHA
		captchaChecker.assureValidResponseForClient(response, req.getRemoteAddr());

		try {
			emailVerificationService.changePassword(tokenUuid, key, password);
			return true;
		} catch (final TokenVerificationService.NoSuchVerificationTokenException e) {
			throw new UserException("No such verification token!");
		} catch (PasswordPolicy.PasswordPolicyException e) {
			throw new UserException("Password for disabled user accounts can't be reset!");
		} catch (TokenVerificationService.TokenExpiredException e) {
			throw new UserException("Your token expired!");
		}
	}

	@PreAuthorize("isAuthenticated()")
	@PostMapping(value = "/{tokenUuid:.+}/cancel")
	public boolean cancelValidation(@PathVariable("tokenUuid") String tokenUuid, HttpServletRequest req, @RequestParam(value = "g-recaptcha-response", required = false) String response) throws IOException, UserException, TokenVerificationService.NoSuchVerificationTokenException {

		// Validate the reCAPTCHA
		captchaChecker.assureValidResponseForClient(response, req.getRemoteAddr());

		emailVerificationService.cancelPasswordReset(tokenUuid);
		return true;
	}

	@PreAuthorize("isAuthenticated()")
	@PostMapping(value = "/delete/request")
	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;
	}

	@PreAuthorize("isAuthenticated()")
	@DeleteMapping(value = "/{tokenUuid:.+}")
	public boolean deleteAccount(@PathVariable("tokenUuid") String tokenUuid, HttpServletRequest req, @RequestParam(value = "g-recaptcha-response", required = false) String response,
		@RequestParam(value = "key", required = true) String key) throws UserException {

		// Validate the reCAPTCHA
		captchaChecker.assureValidResponseForClient(response, req.getRemoteAddr());

		try {
			emailVerificationService.archiveUserByToken(tokenUuid, key);
//			logout(); TODO
			return true;
		} catch (final TokenVerificationService.NoSuchVerificationTokenException e) {
			throw new UserException("No such verification token!");
		} catch (TokenVerificationService.TokenExpiredException e) {
			throw new UserException("Your token expired!");
		}
	}

	@PreAuthorize("isAuthenticated()")
	@PostMapping(value = "/settings")
	public User updateUserPreferences(@RequestBody UserService.UserPreferences preferences) throws UserException {
		return userService.updateUserPreferences(preferences);
	}

	@PreAuthorize("isAuthenticated()")
	@PostMapping(value = "/settings/{setting}")
	public User updateUserPreferences(@PathVariable String setting, @RequestBody boolean value) throws UserException {
		return userService.updateUserPreference(setting, value);
	}
}