瀏覽代碼

Add-api-user-all

new-feature
Viet.LeQ2 1 年之前
父節點
當前提交
f352c4b06c
共有 5 個文件被更改,包括 62 次插入38 次删除
  1. 二進制
      build/libs/smart-farm-0.0.1-SNAPSHOT.war
  2. +2
    -0
      src/main/java/vn/azteam/tpf/repository/UserRepository.java
  3. +1
    -0
      src/main/java/vn/azteam/tpf/security/authz/AuthzFilter.java
  4. +6
    -0
      src/main/java/vn/azteam/tpf/service/UserService.java
  5. +53
    -38
      src/main/java/vn/azteam/tpf/web/rest/UserResource.java

二進制
build/libs/smart-farm-0.0.1-SNAPSHOT.war 查看文件


+ 2
- 0
src/main/java/vn/azteam/tpf/repository/UserRepository.java 查看文件

Optional<User> findOneWithAuthoritiesByEmail(String email); Optional<User> findOneWithAuthoritiesByEmail(String email);


Page<User> findAllByLoginNot(Pageable pageable, String login); Page<User> findAllByLoginNot(Pageable pageable, String login);

List<User> findAllByLoginNot( String login);
} }

+ 1
- 0
src/main/java/vn/azteam/tpf/security/authz/AuthzFilter.java 查看文件

List<String> whiteListWithGetMethod = new ArrayList<>( List<String> whiteListWithGetMethod = new ArrayList<>(
Arrays.asList( Arrays.asList(
"/api/users", "/api/users",
"/api/users/all",
"/api/tb-functions", "/api/tb-functions",
"/api/_search/tb-crops", "/api/_search/tb-crops",
"/api/_search/tb-guidelines", "/api/_search/tb-guidelines",

+ 6
- 0
src/main/java/vn/azteam/tpf/service/UserService.java 查看文件

return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new); return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new);
} }


@Transactional(readOnly = true)
public List<UserDTO> getAllManagedUsers() {
return userRepository.findAllByLoginNot(Constants.ANONYMOUS_USER)
.stream().map(UserDTO::new).collect(Collectors.toList());
}



@Transactional(readOnly = true) @Transactional(readOnly = true)
public Optional<User> getUserWithAuthoritiesByLogin(String login) { public Optional<User> getUserWithAuthoritiesByLogin(String login) {

+ 53
- 38
src/main/java/vn/azteam/tpf/web/rest/UserResource.java 查看文件

package vn.azteam.tpf.web.rest; package vn.azteam.tpf.web.rest;


import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import vn.azteam.tpf.config.Constants; import vn.azteam.tpf.config.Constants;
import vn.azteam.tpf.domain.TBDetailUser; import vn.azteam.tpf.domain.TBDetailUser;
import vn.azteam.tpf.repository.search.UserSearchRepository; import vn.azteam.tpf.repository.search.UserSearchRepository;
import vn.azteam.tpf.security.AuthoritiesConstants; import vn.azteam.tpf.security.AuthoritiesConstants;
import vn.azteam.tpf.service.*; import vn.azteam.tpf.service.*;
import vn.azteam.tpf.service.dto.TBRoleDTO;
import vn.azteam.tpf.service.dto.UserDTO; import vn.azteam.tpf.service.dto.UserDTO;
import vn.azteam.tpf.service.mapper.UserMapper; import vn.azteam.tpf.service.mapper.UserMapper;
import vn.azteam.tpf.service.util.UserRoleUtil; import vn.azteam.tpf.service.util.UserRoleUtil;
import vn.azteam.tpf.web.rest.errors.*; import vn.azteam.tpf.web.rest.errors.*;
import vn.azteam.tpf.web.rest.util.HeaderUtil; import vn.azteam.tpf.web.rest.util.HeaderUtil;
import vn.azteam.tpf.web.rest.util.PaginationUtil; import vn.azteam.tpf.web.rest.util.PaginationUtil;
import com.codahale.metrics.annotation.Timed;
import io.github.jhipster.web.util.ResponseUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid; import javax.validation.Valid;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.*;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;


/** /**
* *
* @param userDTO the user to create * @param userDTO the user to create
* @return the ResponseEntity with status 201 (Created) and with body the new user, or with status 400 (Bad Request) if the login or email is already in use * @return the ResponseEntity with status 201 (Created) and with body the new user, or with status 400 (Bad Request) if the login or email is already in use
* @throws URISyntaxException if the Location URI syntax is incorrect
* @throws URISyntaxException if the Location URI syntax is incorrect
* @throws BadRequestAlertException 400 (Bad Request) if the login or email is already in use * @throws BadRequestAlertException 400 (Bad Request) if the login or email is already in use
*/ */
@PostMapping("/users") @PostMapping("/users")
throw new LoginAlreadyUsedException(); throw new LoginAlreadyUsedException();
} else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) { } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) {
throw new EmailAlreadyUsedException(); throw new EmailAlreadyUsedException();
} else if(tbDetailUserQueryService.findOneByPhone(userDTO.getPhone()).isPresent()) {
} else if (tbDetailUserQueryService.findOneByPhone(userDTO.getPhone()).isPresent()) {
throw new PhoneAlreadyUsedException(); throw new PhoneAlreadyUsedException();
} else { } else {
User newUser = userService.createUser(userDTO); User newUser = userService.createUser(userDTO);
mailService.sendCreationEmail(newUser); mailService.sendCreationEmail(newUser);
return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin())) return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin()))
.headers(HeaderUtil.createAlert( "userManagement.created", newUser.getLogin()))
.headers(HeaderUtil.createAlert("userManagement.created", newUser.getLogin()))
.body(newUser); .body(newUser);
} }
} }
throw new LoginAlreadyUsedException(); throw new LoginAlreadyUsedException();
} }
Optional<TBDetailUser> existingTBDetailUser = tbDetailUserQueryService.findOneByPhone(userDTO.getPhone()); Optional<TBDetailUser> existingTBDetailUser = tbDetailUserQueryService.findOneByPhone(userDTO.getPhone());
if(existingTBDetailUser.isPresent() && (!existingTBDetailUser.get().getUser().getId().equals(userDTO.getId()))){
if (existingTBDetailUser.isPresent() && (!existingTBDetailUser.get().getUser().getId().equals(userDTO.getId()))) {
throw new PhoneAlreadyUsedException(); throw new PhoneAlreadyUsedException();
} }
Optional<UserDTO> updatedUser = userService.updateUser(userDTO); Optional<UserDTO> updatedUser = userService.updateUser(userDTO);
throw new LoginAlreadyUsedException(); throw new LoginAlreadyUsedException();
} }
Optional<TBDetailUser> existingTBDetailUser = tbDetailUserQueryService.findOneByPhone(userDTO.getPhone()); Optional<TBDetailUser> existingTBDetailUser = tbDetailUserQueryService.findOneByPhone(userDTO.getPhone());
if(existingTBDetailUser.isPresent() && (!existingTBDetailUser.get().getUser().getId().equals(userDTO.getId()))){
if (existingTBDetailUser.isPresent() && (!existingTBDetailUser.get().getUser().getId().equals(userDTO.getId()))) {
throw new PhoneAlreadyUsedException(); throw new PhoneAlreadyUsedException();
} }
Optional<UserDTO> updatedUser = userService.updateUser(userDTO); Optional<UserDTO> updatedUser = userService.updateUser(userDTO);
* @throws EmailAlreadyUsedException 400 (Bad Request) if the email is already in use * @throws EmailAlreadyUsedException 400 (Bad Request) if the email is already in use
* @throws LoginAlreadyUsedException 400 (Bad Request) if the login is already in use * @throws LoginAlreadyUsedException 400 (Bad Request) if the login is already in use
*/ */
@PutMapping("/update-my-profile")
@PutMapping("/update-my-profile")
@Timed @Timed
public ResponseEntity<UserDTO> updateMyProfile(@Valid @RequestBody UserDTO userDTO) { public ResponseEntity<UserDTO> updateMyProfile(@Valid @RequestBody UserDTO userDTO) {
return updateUser(userDTO); return updateUser(userDTO);
} }


/**F
/**
* F
* GET /users : get all users. * GET /users : get all users.
* *
* @param pageable the pagination information * @param pageable the pagination information
*/ */
@GetMapping("/users") @GetMapping("/users")
@Timed @Timed
public ResponseEntity<List<UserDTO>> getAllUsers(Pageable pageable) {
public ResponseEntity<List<UserDTO>> getAllUsersPagination(Pageable pageable) {
UserDTO currentUser = userService.getCurrentUserDTO().get(); UserDTO currentUser = userService.getCurrentUserDTO().get();
Page<UserDTO> page = userService.getAllManagedUsers(pageable); Page<UserDTO> page = userService.getAllManagedUsers(pageable);
List<UserDTO> result = page.getContent(); List<UserDTO> result = page.getContent();
if(currentUser.getCustomerId() != null){
if (currentUser.getCustomerId() != null) {
result = result.stream() result = result.stream()
.filter(item -> item.getCustomerId() != null .filter(item -> item.getCustomerId() != null
&& item.getCustomerId().equals(currentUser.getCustomerId())) && item.getCustomerId().equals(currentUser.getCustomerId()))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
page = changeUserDTOToPageFromList(result,pageable);
page = changeUserDTOToPageFromList(result, pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users"); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
return new ResponseEntity<>(result, headers, HttpStatus.OK); return new ResponseEntity<>(result, headers, HttpStatus.OK);
} }


private Page<UserDTO> changeUserDTOToPageFromList(List<UserDTO> userDTOS, Pageable pageable){
@GetMapping("/users/all")
@Timed
public ResponseEntity<List<UserDTO>> getAllUsers() {
UserDTO currentUser = userService.getCurrentUserDTO().get();
List<UserDTO> result = userService.getAllManagedUsers();
if (currentUser.getCustomerId() != null) {
result = result.stream()
.filter(item -> item.getCustomerId() != null
&& item.getCustomerId().equals(currentUser.getCustomerId()))
.collect(Collectors.toList());
}
return ResponseEntity.ok().body(result);
}

private Page<UserDTO> changeUserDTOToPageFromList(List<UserDTO> userDTOS, Pageable pageable) {
int start = Math.toIntExact(pageable.getOffset()); int start = Math.toIntExact(pageable.getOffset());
int end = Math.toIntExact((start + pageable.getPageSize()) > userDTOS.size() ? userDTOS.size() : (start + pageable.getPageSize())); int end = Math.toIntExact((start + pageable.getPageSize()) > userDTOS.size() ? userDTOS.size() : (start + pageable.getPageSize()));
if(userDTOS.size() > start) {
if (userDTOS.size() > start) {
return new PageImpl<>(userDTOS.subList(start, end), pageable, userDTOS.size()); return new PageImpl<>(userDTOS.subList(start, end), pageable, userDTOS.size());
} }
return new PageImpl<>(Lists.newArrayList(), pageable, userDTOS.size()); return new PageImpl<>(Lists.newArrayList(), pageable, userDTOS.size());
log.debug("REST request to get User : {}", id); log.debug("REST request to get User : {}", id);
UserDTO currentUser = userService.getCurrentUserDTO().get(); UserDTO currentUser = userService.getCurrentUserDTO().get();
Optional<UserDTO> userSelected = userService.getUserWithAuthorities(id).map(UserDTO::new); Optional<UserDTO> userSelected = userService.getUserWithAuthorities(id).map(UserDTO::new);
if(currentUser.getCustomerId() != null && !currentUser.getCustomerId().equals(userSelected.get().getCustomerId())) {
if (currentUser.getCustomerId() != null && !currentUser.getCustomerId().equals(userSelected.get().getCustomerId())) {
userSelected = Optional.empty(); userSelected = Optional.empty();
} }
return ResponseUtil.wrapOrNotFound(userSelected); return ResponseUtil.wrapOrNotFound(userSelected);
log.debug("REST request to delete User: {}", login); log.debug("REST request to delete User: {}", login);
UserDTO currentUser = userService.getCurrentUserDTO().get(); UserDTO currentUser = userService.getCurrentUserDTO().get();
UserDTO deleteUser = userService.getUserWithAuthoritiesByLogin(login).map(UserDTO::new).get(); UserDTO deleteUser = userService.getUserWithAuthoritiesByLogin(login).map(UserDTO::new).get();
if(currentUser.getCustomerId() != null && !currentUser.getCustomerId().equals(deleteUser.getCustomerId())) {
if (currentUser.getCustomerId() != null && !currentUser.getCustomerId().equals(deleteUser.getCustomerId())) {
throw new BadRequestAlertException("1019", ENTITY_NAME, "1019"); throw new BadRequestAlertException("1019", ENTITY_NAME, "1019");
} }
userService.deleteUser(login); userService.deleteUser(login);
return ResponseEntity.ok().headers(HeaderUtil.createAlert( "userManagement.deleted", login)).build();
return ResponseEntity.ok().headers(HeaderUtil.createAlert("userManagement.deleted", login)).build();
} }


/** /**
* SEARCH /_search/users/:query : search for the User corresponding * SEARCH /_search/users/:query : search for the User corresponding
* to the query. * to the query.
* *
* @param query the query to search
* @param query the query to search
* @param pageable * @param pageable
* @return the result of the search * @return the result of the search
*/ */
UserDTO currentUser = userService.getCurrentUserDTO().get(); UserDTO currentUser = userService.getCurrentUserDTO().get();
log.debug("REST request to search for a page of Users for query {}", query); log.debug("REST request to search for a page of Users for query {}", query);
Page<UserDTO> page; Page<UserDTO> page;
if(query != null && !query.isEmpty()) {
if (query != null && !query.isEmpty()) {
page = userService.searchUser(query, pageable); page = userService.searchUser(query, pageable);
} else { } else {
page = userService.getAllManagedUsers(pageable); page = userService.getAllManagedUsers(pageable);
} }
List<UserDTO> result = page.getContent(); List<UserDTO> result = page.getContent();
if(currentUser.getCustomerId() != null){
if (currentUser.getCustomerId() != null) {
result = result.stream() result = result.stream()
.filter(item -> item.getCustomerId() != null && item.getCustomerId() == currentUser.getCustomerId()) .filter(item -> item.getCustomerId() != null && item.getCustomerId() == currentUser.getCustomerId())
.collect(Collectors.toList()); .collect(Collectors.toList());
page = changeUserDTOToPageFromList(result,pageable);
page = changeUserDTOToPageFromList(result, pageable);
} }
HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/users"); HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/users");
return ResponseEntity.ok().headers(headers).body(page.getContent()); return ResponseEntity.ok().headers(headers).body(page.getContent());


/** /**
* Upload images * Upload images
*
* @param userId * @param userId
* @param images * @param images
* @return * @return
@PostMapping("/users/upload-avatar/{userId}") @PostMapping("/users/upload-avatar/{userId}")
@Timed @Timed
public ResponseEntity<String> uploadAvatar(@PathVariable Long userId, public ResponseEntity<String> uploadAvatar(@PathVariable Long userId,
@RequestParam(value="images") final MultipartFile[] images)
@RequestParam(value = "images") final MultipartFile[] images)
throws URISyntaxException { throws URISyntaxException {
log.debug("REST request to upload avatar user : {}", userId); log.debug("REST request to upload avatar user : {}", userId);


UserDTO currentUserDTO = userService.getUserWithAuthorities() UserDTO currentUserDTO = userService.getUserWithAuthorities()
.map(UserDTO::new) .map(UserDTO::new)
.orElseThrow(() -> new InternalServerErrorException("1006")); .orElseThrow(() -> new InternalServerErrorException("1006"));
if(currentUserDTO.getFcmToken() == null || currentUserDTO.getFcmToken() == "") {
if (currentUserDTO.getFcmToken() == null || currentUserDTO.getFcmToken() == "") {
currentUserDTO.setFcmToken(fcmToken); currentUserDTO.setFcmToken(fcmToken);
} else if (currentUserDTO.getFcmToken().contains(fcmToken)) { } else if (currentUserDTO.getFcmToken().contains(fcmToken)) {
currentUserDTO.setFcmToken(currentUserDTO.getFcmToken()); currentUserDTO.setFcmToken(currentUserDTO.getFcmToken());
UserDTO currentUserDTO = userService.getUserWithAuthorities() UserDTO currentUserDTO = userService.getUserWithAuthorities()
.map(UserDTO::new) .map(UserDTO::new)
.orElseThrow(() -> new InternalServerErrorException("1006")); .orElseThrow(() -> new InternalServerErrorException("1006"));
if(currentUserDTO.getFcmToken() != null && !currentUserDTO.getFcmToken().isEmpty()
if (currentUserDTO.getFcmToken() != null && !currentUserDTO.getFcmToken().isEmpty()
&& currentUserDTO.getFcmToken().contains(fcmToken)) { && currentUserDTO.getFcmToken().contains(fcmToken)) {
if(currentUserDTO.getFcmToken().contains(vn.azteam.tpf.Constants.Constants.COMMA_DOT)) {
String remainingFcmToken = currentUserDTO.getFcmToken().replace(vn.azteam.tpf.Constants.Constants.COMMA_DOT + fcmToken,vn.azteam.tpf.Constants.Constants.EMPTY);
if (currentUserDTO.getFcmToken().contains(vn.azteam.tpf.Constants.Constants.COMMA_DOT)) {
String remainingFcmToken = currentUserDTO.getFcmToken().replace(vn.azteam.tpf.Constants.Constants.COMMA_DOT + fcmToken, vn.azteam.tpf.Constants.Constants.EMPTY);
currentUserDTO.setFcmToken(remainingFcmToken); currentUserDTO.setFcmToken(remainingFcmToken);
} else { } else {
currentUserDTO.setFcmToken(null); currentUserDTO.setFcmToken(null);

Loading…
取消
儲存