UserProfileController.java

/**
 * Copyright 2014 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.mvc;

import java.io.IOException;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.security.NotUniqueUserException;
import org.genesys.blocks.security.UserException;
import org.genesys.blocks.security.model.BasicUser.AccountType;
import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException;
import org.genesys.server.exception.NotFoundElement;
import org.genesys.server.model.UserRole;
import org.genesys.server.model.impl.User;
import org.genesys.server.service.ContentService;
import org.genesys.server.service.EMailVerificationService;
import org.genesys.server.service.TokenVerificationService.NoSuchVerificationTokenException;
import org.genesys.server.service.TokenVerificationService.TokenExpiredException;
import org.genesys.server.service.UserService;
import org.genesys.util.CaptchaUtil;
import org.genesys.util.RandomPasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/profile")
public class UserProfileController extends BaseController {

	@Autowired
	private UserService userService;

	@Autowired
	private EMailVerificationService emailVerificationService;

	@Autowired
	private ContentService contentService;

	@Value("${captcha.siteKey}")
	private String captchaSiteKey;

	@Value("${captcha.privateKey}")
	private String captchaPrivateKey;

	@RequestMapping
	@PreAuthorize("isAuthenticated()")
	public String welcome(ModelMap model) {
		final User user = userService.getMe();
		return "redirect:/profile/" + user.getUuid();
	}

	@RequestMapping("/list")
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	public String list(ModelMap model, @RequestParam(value = "page", defaultValue = "1") int page) {
		model.addAttribute("pagedData", userService.listUsers(PageRequest.of(page - 1, 50, Sort.by("fullName"))));
		return "/user/index";
	}

	@RequestMapping("/{uuid:.+}/vetted-user")
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	public String addRoleVettedUser(@PathVariable("uuid") UUID uuid) {
		userService.addVettedUserRole(uuid);
		return "redirect:/profile/" + uuid;
	}

	@RequestMapping(value = "/{uuid:.+}/generate-ftp-password", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@PreAuthorize("hasAnyRole('ADMINISTRATOR', 'VETTEDUSER')")
	@ResponseBody
	public ResponseEntity<?> generateFtpPassword(@PathVariable("uuid") UUID uuid) {
		String generatedPassword = RandomPasswordUtil.generatePassword(new Random(), 15);
		final User user = userService.getUser(uuid);
		if (user == null) {
			return new ResponseEntity<>(HttpStatus.NOT_FOUND);
		}

		final Object result = new Object() {
			@SuppressWarnings("unused")
			public String password = generatedPassword;
		};

		try {
			userService.setFtpPassword(user, generatedPassword);
			return new ResponseEntity<>(result, HttpStatus.OK);
		} catch (PasswordPolicyException e) {
			return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("/{uuid:.+}")
	@PreAuthorize("isAuthenticated()")
	public String someProfile(ModelMap model, @PathVariable("uuid") UUID uuid) {
		final User user = userService.getUser(uuid);
		if (user == null) {
			throw new NotFoundElement();
		}

		model.addAttribute("user", user);

		return "/user/profile";
	}

	@RequestMapping("/{uuid:.+}/edit")
	@PreAuthorize("hasRole('ADMINISTRATOR') || principal.uuid == #uuid")
	public String edit(ModelMap model, @PathVariable("uuid") UUID uuid) {
		someProfile(model, uuid);
		model.addAttribute("availableRoles", userService.listAvailableRoles());
		return "/user/edit";
	}

	@RequestMapping(value = "/{uuid}/send", method = RequestMethod.GET)
	@PreAuthorize("hasRole('ADMINISTRATOR') || principal.uuid == #uuid")
	public String sendEmail(ModelMap model, @PathVariable("uuid") UUID uuid) {

		final User user = userService.getUser(uuid);
		emailVerificationService.sendVerificationEmail(user);

		return "redirect:/profile/" + user.getUuid();
	}

	@RequestMapping(value = "/{tokenUuid:.+}/cancel", method = RequestMethod.GET)
	public String cancelValidation(ModelMap model, @PathVariable("tokenUuid") String tokenUuid) throws Exception {
		emailVerificationService.cancelValidation(tokenUuid);
		return "redirect:/content/user-registration-canceled";
	}

	@RequestMapping(value = "/{tokenUuid:.+}/cancel", method = RequestMethod.GET, params = { "type=pass" })
	public String cancelPasswordReset(ModelMap model, @PathVariable("tokenUuid") String tokenUuid) throws NoSuchVerificationTokenException {
		emailVerificationService.cancelPasswordReset(tokenUuid);
		return "redirect:/content/user-password-reset-canceled";
	}
	@RequestMapping(value = "/{tokenUuid:.+}/validate", method = RequestMethod.GET)
	public String validateEmail(ModelMap model, @PathVariable("tokenUuid") String tokenUuid) {
		model.addAttribute("tokenUuid", tokenUuid);
		return "/user/validateemail";
	}

	@RequestMapping(value = "/{tokenUuid:.+}/validate", method = RequestMethod.POST)
	public String validateEmail2(ModelMap model, @PathVariable("tokenUuid") String tokenUuid, @RequestParam(value = "key", required = true) String key) {
		try {
			emailVerificationService.validateEMail(tokenUuid, key);
			return "redirect:/content/account-email-validated";
		} catch (final NoSuchVerificationTokenException | TokenExpiredException e) {
			// Not valid
			model.addAttribute("tokenUuid", tokenUuid);
			model.addAttribute("error", "error");
			return "/user/validateemail";
		}
	}

	@RequestMapping(value = "/forgot-password")
	public String forgotPassword(ModelMap model) {
		var blurb = contentService.getGlobalArticle(ContentService.USER_RESET_PASSWORD_INSTRUCTIONS, getLocale());
		model.addAttribute("captchaSiteKey", captchaSiteKey);
		model.addAttribute("blurb", blurb);
		return "/user/email";
	}

	@RequestMapping(value = "/password/reset", method = RequestMethod.POST)
	public String resetPassword(ModelMap model, HttpServletRequest req, @RequestParam(value = "g-recaptcha-response", required = false) String response, @RequestParam("email") String email,
			RedirectAttributes redirectAttributes) throws IOException {

		// Validate the reCAPTCHA
		if (!CaptchaUtil.isValid(response, req.getRemoteAddr(), captchaPrivateKey)) {
			LOG.warn("Invalid captcha.");
			redirectAttributes.addFlashAttribute("error", "errors.badCaptcha");
			return "redirect:/profile/forgot-password";
		}

		try {
			final User user = userService.getUserByEmail(email);

			if (user != null && user.getAccountType() == AccountType.GOOGLE) {
				LOG.warn("Password for users with login type GOOGLE can't be reset!");
				redirectAttributes.addFlashAttribute("error", "errors.reset-password.invalid-login-type");
				return "redirect:/profile/forgot-password";
			}

			if (user != null && user.isAccountLocked()) {
				LOG.warn("Password for locked user accounts can't be reset!");
				redirectAttributes.addFlashAttribute("error", "errors.reset-password.account-is-locked");
				return "redirect:/profile/forgot-password";
			}

			if (user != null && ! user.isEnabled()) {
				LOG.warn("Password for disabled user accounts can't be reset!");
				redirectAttributes.addFlashAttribute("error", "errors.reset-password.account-is-disabled");
				return "redirect:/profile/forgot-password";
			}

			if (user != null) {
				emailVerificationService.sendPasswordResetEmail(user);
			}

			return "redirect:/content/" + ContentService.USER_PASSWORD_RESET_EMAIL_SENT;
		} catch (UsernameNotFoundException e) {
			redirectAttributes.addFlashAttribute("error", "errors.no-such-user");
			return "redirect:/profile/forgot-password";
		}
	}

	@RequestMapping(value = "/{tokenUuid:.+}/pwdreset", method = RequestMethod.GET)
	public String passwordReset(ModelMap model, @PathVariable("tokenUuid") String tokenUuid) {
		model.addAttribute("captchaSiteKey", captchaSiteKey);
		model.addAttribute("tokenUuid", tokenUuid);
		return "/user/password";
	}

	@RequestMapping(value = "/{tokenUuid:.+}/pwdreset", method = RequestMethod.POST)
	public String updatePassword(ModelMap model, @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, RedirectAttributes redirectAttributes) throws IOException {

		// Validate the reCAPTCHA
		if (!CaptchaUtil.isValid(response, req.getRemoteAddr(), captchaPrivateKey)) {
			model.addAttribute("key", key);
			model.addAttribute("error", "errors.badCaptcha");
			return passwordReset(model, tokenUuid);
		}

		try {
			emailVerificationService.changePassword(tokenUuid, key, password);
			return "redirect:/content/" + ContentService.USER_PASSWORD_RESET;
		} catch (final NoSuchVerificationTokenException e) {
			model.addAttribute("key", key);
			model.addAttribute("error", "verification.invalid-key");
			return passwordReset(model, tokenUuid);
		} catch (PasswordPolicyException e) {
			model.addAttribute("key", key);
			model.addAttribute("error", e.getMessage());
			return passwordReset(model, tokenUuid);
		} catch (TokenExpiredException e) {
			model.addAttribute("error", e.getMessage());
			return passwordReset(model, tokenUuid);
		}
	}

	@RequestMapping(value = "/{uuid:.+}/update", method = { RequestMethod.POST })
	@PreAuthorize("hasRole('ADMINISTRATOR') || principal.uuid == #uuid")
	public String update(ModelMap model, @PathVariable("uuid") UUID uuid, @RequestParam("fullName") String fullName,
				@RequestParam("email") String email, @RequestParam(value = "currentPwd", required = false) String currentPwd,
				@RequestParam(value = "pwd1", required = false) String pwd1, @RequestParam(value = "pwd2", required = false) String pwd2,
				RedirectAttributes redirectAttributes) {
		User user = userService.getUser(uuid);
		if (user == null) {
			throw new NotFoundElement();
		}

		try {
			user = userService.updateUser(user, email, fullName);
		} catch (NotUniqueUserException e) {
			redirectAttributes.addFlashAttribute("emailError", "User with e-mail address " + e.getEmail() + " already exists");
			return "redirect:/profile/" + user.getUuid() + "/edit";
		} catch (UserException e) {
			redirectAttributes.addFlashAttribute("emailError", e.getMessage());
			return "redirect:/profile/" + user.getUuid() + "/edit";
		}

		if (StringUtils.isNotBlank(pwd1) || StringUtils.isNotBlank(pwd2)) {

			if (user.getAccountType() == AccountType.GOOGLE) {
				redirectAttributes.addFlashAttribute("emailError", "Password for users with login type GOOGLE can't be set!");
				return "redirect:/profile/" + user.getUuid() + "/edit";
			}

			if (StringUtils.isBlank(currentPwd) || !userService.checkPasswordsMatch(currentPwd, user.getPassword())) {
				redirectAttributes.addFlashAttribute("emailError", "Current password is incorrect");
				return "redirect:/profile/" + user.getUuid() + "/edit";
			}

			if (pwd1.equals(pwd2)) {
				try {
					LOG.info("Updating password for {}", user);
					userService.changePassword(user, pwd1);
					LOG.warn("Password updated for {}", user);
				} catch (PasswordPolicyException e) {
					redirectAttributes.addFlashAttribute("emailError", e.getMessage());
					LOG.error(e.getMessage());
					return "redirect:/profile/" + user.getUuid() + "/edit";
				}
			} else {
				LOG.warn("Passwords didn't match for {}", user);
				redirectAttributes.addFlashAttribute("emailError", "Passwords didn't match for " + user);
				return "redirect:/profile/" + user.getUuid() + "/edit";
			}
		}

		return "redirect:/profile/" + user.getUuid();
	}

	@GetMapping("/me/delete")
	@PreAuthorize("isFullyAuthenticated()")
	public String startDelete(ModelMap model, Locale locale) {
		var info = contentService.getGlobalArticle(ContentService.DELETE_ACCOUNT, locale);
		model.addAttribute("info", info);
		return "/user/delete";
	}

	@PostMapping("/me/delete")
	@PreAuthorize("isFullyAuthenticated()")
	public String requestDelete(ModelMap model) {
		final User user = userService.getMe();
		if (user == null) {
			throw new NotFoundElement();
		}

		emailVerificationService.requestDeleteAccount(user);

		return "redirect:/content/" + ContentService.DELETE_ACCOUNT_SENT;
	}
	
	@RequestMapping(value = "/me/delete/{tokenUuid:.+}", method = RequestMethod.GET)
	@PreAuthorize("isFullyAuthenticated()")
	public String confirmDelete(ModelMap model, HttpServletRequest servletRequest, @PathVariable("tokenUuid") String tokenUuid, @RequestParam(value = "key", required = true) String key) throws NoSuchVerificationTokenException, TokenExpiredException, ServletException, UserException {

		emailVerificationService.confirmDeleteAccount(tokenUuid, key);

		servletRequest.logout();

		return "redirect:/content/" + ContentService.DELETE_ACCOUNT_CONFIRMED;
	}


	@RequestMapping(value = "/{uuid:.+}/update-roles", method = { RequestMethod.POST })
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	public String updateRoles(ModelMap model, @PathVariable("uuid") UUID uuid, @RequestParam("role") Set<UserRole> selectedRoles) {
		final User user = userService.getUser(uuid);
		if (user == null) {
			throw new NotFoundElement();
		}

		userService.setRoles(user, selectedRoles);
		return "redirect:/profile/" + user.getUuid();
	}

}