UserRegistrationController.java

/*
 * Copyright 2016 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.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.security.model.BasicUser.AccountType;
import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException;
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.UserService;
import org.genesys.util.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ResolvableType;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
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 to handle user registration
 */
@Controller
public class UserRegistrationController extends BaseController {

	@Autowired
	private UserService userService;

	@Autowired
	private Validator validator;

	@Autowired
	private EMailVerificationService emailVerificationService;

	@Autowired
	private ContentService contentService;

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

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

	private static String authorizationRequestBaseUri = "oauth2/authorization";

	@Autowired
	private ClientRegistrationRepository clientRegistrationRepository;

	@RequestMapping(value = "/registration", method = RequestMethod.GET)
	public String registration(ModelMap model) {
		var blurb = contentService.getGlobalArticle(ContentService.REGISTRATION, getLocale());
		model.addAttribute("captchaSiteKey", captchaSiteKey);
		model.addAttribute("blurb", blurb);
		model.addAttribute("user", new User());

		Map<String, String> oauth2AuthenticationUrls = new HashMap<>();

		Iterable<ClientRegistration> clientRegistrations = null;
		ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository).as(Iterable.class);
		if (type != ResolvableType.NONE &&
			ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
			clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository;
			clientRegistrations.forEach(registration -> {
				// Add all but self!
				if (! registration.getRegistrationId().equals("local")) {
					oauth2AuthenticationUrls.put(
						registration.getClientName(),
						authorizationRequestBaseUri + "/" + registration.getRegistrationId()
					);
				}
			});
		}

		model.addAttribute("urls", oauth2AuthenticationUrls);
		return "/registration";
	}

	@RequestMapping(value = "/registration", method = RequestMethod.POST)
	public String addUser(@ModelAttribute("user") User user, BindingResult bindingResult, HttpServletRequest req,
			@RequestParam(value = "g-recaptcha-response", required = false) String response, RedirectAttributes redirectAttributes, ModelMap model) throws IOException {

		user.getRoles().add(UserRole.USER);
		validator.validate(user, bindingResult);

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

		try {
			String confirmPassword = req.getParameter("confirm_password");

			if (!bindingResult.hasErrors() && user.getPassword().equals(confirmPassword) && !StringUtils.isBlank(confirmPassword)) {
				if (!userService.exists(user.getEmail())) {
					final User newUser = userService.createUser(user.getEmail(), user.getFullName(), user.getPassword(), AccountType.LOCAL);

					emailVerificationService.sendVerificationEmail(newUser);

					return "redirect:/content/account-created";
				} else {
					model.addAttribute("error", "registration.user-exists");
				}
			} else {
				int errorCount = bindingResult.getErrorCount();

				if (!user.getPassword().equals(confirmPassword)) {
					model.addAttribute("passwordRepeatError", "errors.second-password-doesnt-match");
					errorCount++;
				}

				if (StringUtils.isBlank(confirmPassword)) {
					model.addAttribute("passwordRepeatError", "sample.error.not.empty");
					errorCount++;
				}

				LOG.warn("New account form has errors: {}", errorCount);
			}
		} catch (final PasswordPolicyException e) {
			model.addAttribute("passwordError", e.getMessage());
		} catch (final Exception e) {
			LOG.error(e.getMessage(), e);
			model.addAttribute("error", e.getMessage());
		}

		var blurb = contentService.getGlobalArticle(ContentService.REGISTRATION, getLocale());
		model.addAttribute("user", user);
		model.addAttribute("captchaSiteKey", captchaSiteKey);
		model.addAttribute("blurb", blurb);

		return "/registration";
	}
}