WebUserController.java

/*
 * Copyright 2020 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.gringlobal.api.v2.impl;

import com.querydsl.core.types.OrderSpecifier;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.validator.routines.EmailValidator;
import org.genesys.blocks.security.UserException;
import org.gringlobal.api.ApiBaseController;
import org.gringlobal.api.FilteredPage;
import org.gringlobal.api.Pagination;
import org.gringlobal.api.exception.InvalidApiUsageException;
import org.gringlobal.api.model.WebCooperatorDTO;
import org.gringlobal.api.model.WebUserDTO;
import org.gringlobal.api.v2.facade.WebUserApiService;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.model.QWebUser;
import org.gringlobal.model.WebUser;
import org.gringlobal.service.EMailVerificationService;
import org.gringlobal.service.ShortFilterService;
import org.gringlobal.service.TokenVerificationService;
import org.gringlobal.service.filter.WebUserFilter;
import org.gringlobal.util.ReCaptchaUtil;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
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.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 javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController("webUserApi2")
@RequestMapping(WebUserController.API_URL)
@PreAuthorize("isAuthenticated()")
@Tag(name = "WebUser")
@Slf4j
public class WebUserController extends ApiBaseController {

	/** The Constant API_URL. */
	public static final String API_URL = ApiBaseController.APIv2_BASE + "/webuser";

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

	private final EmailValidator emailValidator = EmailValidator.getInstance();

	@Autowired
	private ShortFilterService shortFilterService;

	@Autowired
	private WebUserApiService service;

	@Autowired
	private EMailVerificationService emailVerificationService;

	protected Class<WebUserFilter> filterType() {
		return WebUserFilter.class;
	}

	protected OrderSpecifier<?>[] defaultSort() {
		return new OrderSpecifier[] { QWebUser.webUser.id.asc() };
	}

	/**
	 * Create a new user.
	 *
	 * @param username the username
	 * @param pass the password
	 * @param webCooperatorId the web cooperator ID
	 * @return the web user
	 */
	@PreAuthorize("hasAuthority('GROUP_ADMINS')")
	@PostMapping(value = "")
	@Operation(operationId = "createWebUser", description = "Create a WebUser", summary = "Add")
	public WebUserDTO create(@RequestParam(name = "username") final String username, @RequestParam(name = "pass") final String pass,
		@RequestParam(name = "webCooperatorId", required = false) final Long webCooperatorId) {

		return service.create(username, pass, webCooperatorId);
	}

	/**
	 * Update a WebCooperator of the WebUser.
	 * Or create a new one and attach it to the WebUser.
	 *
	 * @param webUserId the id of the web user
	 * @param webCooperator a WebCooperator to be updated or created
	 * @return updated web user
	 */
	@PostMapping(value = "/{id}/upsert-webcooperator")
	@Operation(operationId = "upsertWebCooperator", description = "Update or insert WebCooperator data to WebUser", summary = "Upsert WebCooperator")
	public WebUserDTO upsertWebCooperator(@PathVariable("id") final Long webUserId, @RequestBody final WebCooperatorDTO webCooperator) {
		return service.upsertWebCooperator(webUserId, webCooperator);
	}

	/**
	 * Update the entity.
	 *
	 * @param entity entity with updates
	 * @return the updated record
	 */
	@PutMapping(value = "", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "update", description = "Update an existing record", summary = "Update")
	public WebUserDTO update(@RequestBody final WebUserDTO entity) {
		return service.update(entity);
	}

	@PreAuthorize("hasAuthority('GROUP_ADMINS')")
	@PostMapping(value = "/list", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(description = "Retrieve list of records matching the filter", summary = "List by filter")
	public FilteredPage<WebUserDTO, WebUserFilter> list(@ParameterObject final Pagination page, @RequestBody WebUserFilter filter) throws SearchException, IOException {
		WebUserFilter normalizedFilter = shortFilterService.normalizeFilter(filter, filterType());
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(normalizedFilter, service.list(pageable, filter));
	}

	/**
	 * Get entity by id
	 *
	 * @param id the id
	 * @return the loaded record
	 */
	@PreAuthorize("hasAuthority('GROUP_ADMINS')")
	@GetMapping(value = "/{id}", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(description = "Get record by ID", summary = "Get")
	public WebUserDTO get(@PathVariable("id") final long id) {
		return service.load(id);
	}

	/**
	 * Remove the entity.
	 *
	 * @param id the id
	 * @return the removed record
	 */
	@DeleteMapping(value = "/{id}", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(description = "Delete existing record by ID", summary = "Delete")
	public WebUserDTO remove(@PathVariable("id") final long id) {
		return service.remove(id);
	}

	/**
	 * Set new password.
	 *
	 * @param id the id of user
	 * @param pass new password
	 * @return true if OK
	 */
	@PostMapping(value = "/{id}/password")
	@Operation(operationId = "setPassword", description = "Set new password", summary = "New password")
	public boolean setPassword(@PathVariable("id") final Long id, @RequestParam(name = "pass") final String pass) {
		service.setPassword(id, pass);
		return true;
	}

	/**
	 * Enable account.
	 *
	 * @param id the id
	 * @return the user
	 */
	@PreAuthorize("hasAuthority('GROUP_ADMINS')")
	@PostMapping(value = "/{id}/enable")
	@Operation(operationId = "enable", description = "Enable a WebUser", summary = "Enable")
	public WebUserDTO enable(@PathVariable("id") final Long id) {
		return service.enable(id);
	}

	/**
	 * Disable account.
	 *
	 * @param id the id
	 * @return the user
	 */
	@PreAuthorize("hasAuthority('GROUP_ADMINS')")
	@PostMapping(value = "/{id}/disable")
	@Operation(operationId = "disable", description = "Disable a WebUser", summary = "Disable")
	public WebUserDTO disable(@PathVariable("id") final Long id) {
		return service.disable(id);
	}

	@PreAuthorize("isAuthenticated() && hasRole('WEBUSER')")
	@GetMapping(value = "/me")
	public WebUserDTO getMe() {
		final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication instanceof AbstractOAuth2TokenAuthenticationToken<?>) {
			var oauthAuth = (AbstractOAuth2TokenAuthenticationToken<?>) authentication;
			if (oauthAuth != null) {
				final WebUser currentUser = (WebUser) oauthAuth.getPrincipal();
				return service.loadUserByUsername(currentUser.getUsername());
			}
		}
		throw new InvalidApiUsageException("Not using user authentication");
	}

	/**
	 * Register new web user
	 *
	 * @param captchaResponse the captchaResponse
	 * @param email the email
	 * @param password the password
	 * @return the web user
	 */
	@PostMapping(value = "/register")
	public WebUserDTO registerUser(@RequestParam(value = "g-recaptcha-response", required = true) final String captchaResponse,
		@RequestParam(name = "email", required = true) final String email, @RequestParam(name = "pass", required = true) final String password,
		final HttpServletRequest request) throws Exception {

		// Validate the reCAPTCHA
		if (!ReCaptchaUtil.isValid(captchaResponse, request.getRemoteAddr(), captchaPrivateKey)) {
			log.warn("Invalid captcha.");
			throw new InvalidApiUsageException("Captcha check failed.");
		}

		if (!emailValidator.isValid(email)) {
			log.warn("Invalid email provided: {}", email);
			throw new InvalidApiUsageException("Invalid email provided: " + email);
		}

		try {
			if (service.loadUserByUsername(email) != null)
				throw new InvalidApiUsageException("E-mail already taken.");
		} catch (UsernameNotFoundException e) {
			// it's fine
		}

		return service.registerUser(email, password);
	}

	@PostMapping(value = "/{tokenUuid:.+}/validate")
	public boolean validateEMail(@PathVariable("tokenUuid") String tokenUuid, @RequestParam(value = "key", required = true) String key) throws Exception {
		try {
			emailVerificationService.validateEMail(tokenUuid, key);
			return true;
		} catch (final TokenVerificationService.NoSuchVerificationTokenException e) {
			throw new Exception("Verification token is not valid");
		} catch (final TokenVerificationService.TokenExpiredException e) {
			throw new Exception("Verification token has expired");
		}
	}

	@PostMapping(value = "/{tokenUuid:.+}/cancel")
	public boolean cancelValidation(@PathVariable("tokenUuid") String tokenUuid, @RequestParam(value = "g-recaptcha-response") String response,
		HttpServletRequest request) throws Exception {

		// Validate the reCAPTCHA
		if (!ReCaptchaUtil.isValid(response, request.getRemoteAddr(), captchaPrivateKey)) {
			log.warn("Invalid captcha.");
			throw new UserException("Captcha check failed.");
		}

		emailVerificationService.cancelValidation(tokenUuid);
		return true;
	}
}