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.admin;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.security.NotUniqueUserException;
import org.genesys.blocks.security.UserException;
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.mvc.BaseController;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
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.servlet.mvc.support.RedirectAttributes;
@Controller("adminUsersController")
@RequestMapping(UserProfileController.URLBASE)
@PreAuthorize("hasRole('ADMINISTRATOR')")
public class UserProfileController extends BaseController {
	public static final String URLBASE = "/admin/users/";
	public static final String VIEWBASE = "/admin/users/";
	@Autowired
	private UserService userService;
	@Autowired
	private EMailVerificationService emailVerificationService;
	@RequestMapping("/")
	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 VIEWBASE + "index";
	}
	@RequestMapping("/{uuid:.+}/vetted-user")
	public String addRoleVettedUser(@PathVariable("uuid") UUID uuid) {
		userService.addVettedUserRole(uuid);
		return "redirect:" + URLBASE + uuid;
	}
	@RequestMapping("/{uuid:.+}")
	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 VIEWBASE + "profile";
	}
	@RequestMapping("/{uuid:.+}/edit")
	public String edit(ModelMap model, @PathVariable("uuid") UUID uuid) {
		someProfile(model, uuid);
		model.addAttribute("availableRoles", userService.listAvailableRoles());
		return VIEWBASE + "edit";
	}
	@RequestMapping(value = "/{uuid}/send", method = RequestMethod.GET)
	public String sendEmail(ModelMap model, @PathVariable("uuid") UUID uuid) {
		final User user = userService.getUser(uuid);
		emailVerificationService.sendVerificationEmail(user);
		return "redirect:" + URLBASE + 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:" + URLBASE;
	}
	@RequestMapping(value = "/{tokenUuid:.+}/validate", method = RequestMethod.GET)
	public String validateEmail(ModelMap model, @PathVariable("tokenUuid") String tokenUuid) {
		model.addAttribute("tokenUuid", tokenUuid);
		return VIEWBASE + "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:/profile";
		} catch (final NoSuchVerificationTokenException | TokenExpiredException e) {
			// Not valid
			model.addAttribute("tokenUuid", tokenUuid);
			model.addAttribute("error", "error");
			return VIEWBASE + "validateemail";
		}
	}
	@RequestMapping(value = "/password/reset", method = RequestMethod.POST)
	public String resetPassword(ModelMap model, @RequestParam("email") String email) {
		final User user = userService.getUserByEmail(email);
		if (user != null) {
			emailVerificationService.sendPasswordResetEmail(user);
		}
		return "redirect:/content/" + ContentService.USER_PASSWORD_RESET_EMAIL_SENT;
	}
	@RequestMapping(value = "/{tokenUuid:.+}/pwdreset", method = RequestMethod.GET)
	public String passwordReset(ModelMap model, @PathVariable("tokenUuid") String tokenUuid) {
		model.addAttribute("tokenUuid", tokenUuid);
		return VIEWBASE + "password";
	}
	@RequestMapping(value = "/{tokenUuid:.+}/pwdreset", method = RequestMethod.POST)
	public String updatePassword(ModelMap model, @PathVariable("tokenUuid") String tokenUuid, @RequestParam(value = "key", required = true) String key, @RequestParam("password") String password,
			RedirectAttributes redirectAttributes) throws UserException {
		try {
			emailVerificationService.changePassword(tokenUuid, key, password);
			return "redirect:/content/" + ContentService.USER_PASSWORD_RESET;
		} catch (final NoSuchVerificationTokenException | TokenExpiredException e) {
			// Not valid
			model.addAttribute("tokenUuid", tokenUuid);
			redirectAttributes.addFlashAttribute("error", e.getMessage());
		} catch (PasswordPolicyException e) {
			redirectAttributes.addFlashAttribute("error", e.getMessage());
		}
		return VIEWBASE + "password";
	}
	@RequestMapping(value = "/{uuid:.+}/update", method = { RequestMethod.POST })
	public String update(ModelMap model, @PathVariable("uuid") UUID uuid, @RequestParam("name") String name, @RequestParam("email") String email, @RequestParam("pwd1") String pwd1,
			@RequestParam("pwd2") String pwd2, RedirectAttributes redirectAttributes) {
		final User user = userService.getUser(uuid);
		if (user == null) {
			throw new NotFoundElement();
		}
		try {
			userService.updateUser(user, email, name);
		} catch (NotUniqueUserException e) {
			redirectAttributes.addFlashAttribute("emailError", "User with e-mail address " + e.getEmail() + " already exists");
			return "redirect:" + URLBASE + user.getUuid() + "/edit";
		} catch (UserException e) {
			redirectAttributes.addFlashAttribute("emailError", e.getMessage());
			return "redirect:" + URLBASE + user.getUuid() + "/edit";
		}
		if (StringUtils.isNotBlank(pwd1)) {
			if (pwd1.equals(pwd2)) {
				try {
					LOG.info("Updating password for {}", user);
					userService.changePassword(user, pwd1);
					LOG.warn("Password updated for {}", user);
				} catch (PasswordPolicyException e) {
					LOG.error(e.getMessage());
					redirectAttributes.addFlashAttribute("error", e.getMessage());
					return "redirect:" + URLBASE + user.getUuid() + "/edit";
				}
			} else {
				LOG.warn("Passwords didn't match for {}", user);
			}
		}
		return "redirect:" + URLBASE + user.getUuid();
	}
	@RequestMapping(value = "/{uuid:.+}/delete", method = RequestMethod.POST)
	public String delete(ModelMap model, @PathVariable("uuid") UUID uuid) throws UserException {
		final User user = userService.getUser(uuid);
		if (user==null) {
			throw new NotFoundElement();
		}
		// if (user.getAccountType() == AccountType.DELETED) {
		// LOG.warn("Account already archived.");
		// return "redirect:" + VIEWBASE;
		// }
		if (! user.isAccountNonExpired()) {
			LOG.warn("Account already expired.");
			return "redirect:" + VIEWBASE;
		}
		LOG.warn("Archiving user account {}", user.getEmail());
		userService.archiveUser(user);
		return "redirect:" + VIEWBASE;
	}
	@RequestMapping(value = "/{uuid:.+}/update-roles", method = { RequestMethod.POST })
	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:" + URLBASE + user.getUuid();
	}
}