SysUserManagementController.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 java.util.Set;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.genesys.blocks.security.NoUserFoundException;
import org.genesys.blocks.security.UserException;
import org.genesys.blocks.security.service.PasswordPolicy;
import org.gringlobal.api.v1.ApiBaseController;
import org.gringlobal.api.v1.FilteredPage;
import org.gringlobal.api.v1.Pagination;
import org.gringlobal.model.SysUser;
import org.gringlobal.service.CooperatorService;
import org.gringlobal.service.ShortFilterService;
import org.gringlobal.service.SysGroupService;
import org.gringlobal.service.UserService;
import org.gringlobal.service.filter.SysUserFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
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;


@RestController("userManagementApi1")
@RequestMapping(SysUserManagementController.API_URL)
@PreAuthorize("hasAuthority('GROUP_ADMINS')")
@Tag(name = "UserAdmin")
public class SysUserManagementController extends ApiBaseController {

	/** The Constant API_URL. */
	public static final String API_URL = ApiBaseController.APIv1_ADMIN_BASE + "/user";

	/** The short filter service. */
	@Autowired
	private ShortFilterService shortFilterService;

	/** The user service. */
	@Autowired
	private UserService userService;

	@Autowired
	private CooperatorService cooperatorService;

	@Autowired
	private SysGroupService sysGroupService;

	/**
	 * Gets lazy loaded sys user.
	 *
	 * @param id the id
	 * @return the sys user
	 * @throws NoUserFoundException the no user found exception
	 */
	@GetMapping(value = "/{id}")
	public SysUser getUser(@PathVariable("id") final Long id) throws NoUserFoundException {
		return userService.loadSysUser(id);
	}

	/**
	 * Create a new user.
	 *
	 * @param username the username
	 * @param pass the password
	 * @param cooperatorId the cooperator ID
	 * @return the user
	 */
	@PostMapping(value = "")
	public SysUser create(@RequestParam(name = "username") final String username, @RequestParam(name = "pass") final String pass,
			@RequestParam(name = "cooperatorId") final Long cooperatorId) throws PasswordPolicy.PasswordPolicyException {

		SysUser source = new SysUser();
		source.setUsername(username);
		source.setPassword(pass);
		source.setCooperator(cooperatorService.get(cooperatorId));
		return userService.create(source);
	}

	/**
	 * Update the user.
	 *
	 * @param source the source
	 * @return the user
	 */
	@PutMapping(value = "")
	public SysUser update(@RequestBody SysUser source) throws UserException {
		return getUser(userService.update(source, userService.loadSysUser(source.getId())).getId());
	}

	/**
	 * Assign new sys groups to the user
	 *
	 * @param id the id of user
	 * @param sysGroupIds the group ids
	 * @return updated user
	 * @throws NoUserFoundException
	 */
	@PostMapping(value = "/{id}/assign-groups")
	public SysUser assignNewSysGroups(@PathVariable("id") final Long id, @RequestBody final Set<Long> sysGroupIds) throws NoUserFoundException {
		return userService.setSysGroups(getUser(id), sysGroupService.listAllByIds(sysGroupIds));
	}

	/**
	 * Set new password.
	 *
	 * @param id the id of user
	 * @param pass new password
	 * @return true if OK
	 * @throws UserException
	 */
	@PostMapping(value = "/{id}/password")
	public boolean setPassword(@PathVariable("id") final Long id, @RequestParam(name = "pass") final String pass) throws UserException {
		userService.setPassword(userService.loadSysUser(id), pass);
		return true;
	}

	/**
	 * Enable account.
	 *
	 * @param id the id
	 * @return the user
	 * @throws NoUserFoundException the no user found exception
	 */
	@PostMapping(value = "/{id}/enable")
	public SysUser enableAccount(@PathVariable("id") final Long id) throws UserException {
		userService.setAccountActive(id, true);
		return userService.loadSysUser(id);
	}

	/**
	 * Disable account.
	 *
	 * @param id the id
	 * @return the user
	 * @throws NoUserFoundException the no user found exception
	 */
	@PostMapping(value = "/{id}/disable")
	public SysUser disableAccount(@PathVariable("id") final Long id) throws UserException {
		userService.setAccountActive(id, false);
		return userService.loadSysUser(id);
	}

	/**
	 * Remove user.
	 *
	 * @param user the user
	 * @return the user
	 */
	@DeleteMapping(value = "")
	public SysUser removeUser(@RequestBody SysUser user) throws UserException {
		var userForRemove = userService.loadSysUser(user.getId());
		return userService.loadSysUser(userService.remove(userForRemove).getId());
	}
	
	/**
	 * Filter sys users.
	 *
	 * @param filterCode the filter code
	 * @param page the page
	 * @param filter the filter
	 * @return the filtered page
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	@PostMapping(value = "/filter")
	public FilteredPage<SysUser, SysUserFilter> filterSysUsers(@RequestParam(name = "f", required = false) String filterCode, final Pagination page,
			@RequestBody(required = false) SysUserFilter filter) throws IOException {

		if (filterCode != null) {
			filter = shortFilterService.filterByCode(filterCode, SysUserFilter.class);
		} else {
			filterCode = shortFilterService.getCode(filter);
		}

		ShortFilterService.FilterInfo<SysUserFilter> filterInfo = shortFilterService.processFilter(filterCode, filter, SysUserFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, userService.list(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.ASC, "username")));
	}

}