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.v1.impl;

import java.io.IOException;

import org.apache.commons.lang3.ArrayUtils;
import org.gringlobal.api.PageableAsQueryParam;
import org.gringlobal.api.exception.InvalidApiUsageException;
import org.gringlobal.api.v1.ApiBaseController;
import org.gringlobal.api.v1.FilteredPage;
import org.gringlobal.api.v1.Pagination;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.model.QWebUser;
import org.gringlobal.model.WebCooperator;
import org.gringlobal.model.WebUser;
import org.gringlobal.service.LanguageService;
import org.gringlobal.service.ShortFilterService;
import org.gringlobal.service.WebCooperatorService;
import org.gringlobal.service.WebUserService;
import org.gringlobal.service.filter.WebUserFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
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.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 com.querydsl.core.types.OrderSpecifier;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

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

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

	@Autowired
	private LanguageService languageService;

	@Autowired
	private ShortFilterService shortFilterService;

	@Autowired
	private WebUserService crudService;

	@Autowired
	private WebCooperatorService webCooperatorService;

	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 WebUser create(@RequestParam(name = "username") final String username, @RequestParam(name = "pass") final String pass,
			@RequestParam(name = "webCooperatorId", required = false) final Long webCooperatorId) {

		WebUser source = new WebUser();
		source.setIsEnabled("N");
		source.setUsername(username);
		source.setPassword(pass);
		source.setSysLang(languageService.getLanguage(LocaleContextHolder.getLocale()));
		if (webCooperatorId != null) {
			source.setWebCooperator(webCooperatorService.get(webCooperatorId));
		}

		return crudService.create(source);
	}

	/**
	 * 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 WebUser upsertWebCooperator(@PathVariable("id") final Long webUserId, @RequestBody final WebCooperator webCooperator) {
		return crudService.upsertWebCooperator(crudService.get(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 WebUser update(@RequestBody final WebUser entity) {
		return crudService.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")
	@PageableAsQueryParam
	public FilteredPage<WebUser, WebUserFilter> list(@Parameter(hidden = true) 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, crudService.list(filter, pageable));
	}

	/**
	 * 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 WebUser get(@PathVariable("id") final long id) {
		return crudService.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 WebUser remove(@PathVariable("id") final long id) {
		return crudService.remove(crudService.load(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) {
		crudService.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 WebUser enable(@PathVariable("id") final Long id) {
		crudService.setAccountActive(id, true);
		return crudService.load(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 WebUser disable(@PathVariable("id") final Long id) {
		crudService.setAccountActive(id, false);
		return crudService.load(id);
	}

	@PreAuthorize("isAuthenticated() && hasRole('WEBUSER')")
	@GetMapping(value = "/me")
	public WebUser 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 (WebUser) crudService.loadUserByUsername(currentUser.getUsername());
			}
		}
		throw new InvalidApiUsageException("Not using user authentication");
	}

}