Rafael Bantu 8 months ago
parent
commit
0145807d22
  1. 2
      .idea/vcs.xml
  2. 161
      src/main/java/org/waterproofingdata/wpdauth/controller/UsersController.java
  3. 31
      src/main/java/org/waterproofingdata/wpdauth/model/EduCemadenOrganizations.java
  4. 2
      src/main/java/org/waterproofingdata/wpdauth/model/Users.java
  5. 8
      src/main/java/org/waterproofingdata/wpdauth/repository/UsersRepository.java
  6. 106
      src/main/java/org/waterproofingdata/wpdauth/service/UsersService.java
  7. 28
      src/main/resources/application.properties

2
.idea/vcs.xml

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
<mapping directory="" vcs="Git" />
</component>
</project>

161
src/main/java/org/waterproofingdata/wpdauth/controller/UsersController.java

@ -2,10 +2,14 @@ package org.waterproofingdata.wpdauth.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.waterproofingdata.wpdauth.dto.CustomMapper;
import org.waterproofingdata.wpdauth.dto.UsersRequestDTO;
import org.waterproofingdata.wpdauth.dto.UsersResponseDTO;
import org.waterproofingdata.wpdauth.exception.CustomException;
import org.waterproofingdata.wpdauth.model.EduCemadenOrganizations;
import org.waterproofingdata.wpdauth.model.Users;
import org.waterproofingdata.wpdauth.model.UsersEducemadenOrganizations;
import org.waterproofingdata.wpdauth.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
@ -26,6 +30,10 @@ import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@RestController
@RequestMapping("/users")
@Api(tags = "users")
@ -33,6 +41,115 @@ public class UsersController {
@Autowired
private UsersService userService;
private final UsersService usersService;
private final UsersService.UsersEducemadenOrganizationsService usersEducemadenOrganizationsService;
@Autowired
public UsersController(UsersService usersService, UsersService.UsersEducemadenOrganizationsService usersEducemadenOrganizationsService) {
this.usersService = usersService;
this.usersEducemadenOrganizationsService = usersEducemadenOrganizationsService;
}
// Endpoint para associar um usuário a uma instituição
@PostMapping("/associate")
public ResponseEntity<UsersEducemadenOrganizations> associateUserWithOrganization(
@RequestBody UsersEducemadenOrganizations userOrganizationMapping) {
UsersEducemadenOrganizations savedMapping = usersEducemadenOrganizationsService.saveUserOrganizationMapping(userOrganizationMapping);
return new ResponseEntity<>(savedMapping, HttpStatus.CREATED);
}
// Endpoint para encontrar um mapeamento de usuário por ID do usuário
@GetMapping("/organization/{userId}")
public ResponseEntity<UsersEducemadenOrganizations> findUserOrganizationMappingByUserId(
@PathVariable Integer userId) {
UsersEducemadenOrganizations mapping = usersEducemadenOrganizationsService.findByUserId(userId);
return mapping != null
? new ResponseEntity<>(mapping, HttpStatus.OK)
: new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
// Endpoint para encontrar um mapeamento de usuário por chave de ativação
@GetMapping("/organization/activation/{activationKey}")
public ResponseEntity<UsersEducemadenOrganizations> findUserOrganizationMappingByActivationKey(
@PathVariable UUID activationKey) {
UsersEducemadenOrganizations mapping = usersEducemadenOrganizationsService.findByActivationKey(activationKey);
return mapping != null
? new ResponseEntity<>(mapping, HttpStatus.OK)
: new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@RestController
@RequestMapping("/organizations")
public class EduCemadenOrganizationsController {
// Inject the service
private final UsersService.EduCemadenOrganizationsService organizationsService;
@Autowired
public EduCemadenOrganizationsController(UsersService.EduCemadenOrganizationsService organizationsService) {
this.organizationsService = organizationsService;
}
// Endpoint to get all organizations
@GetMapping("/all")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public ResponseEntity<List<EduCemadenOrganizations>> getAllOrganizations() {
List<EduCemadenOrganizations> organizations = organizationsService.getAllOrganizations();
return new ResponseEntity<>(organizations, HttpStatus.OK);
}
// Endpoint to get an organization by ID
@GetMapping("/{id}")
@PreAuthorize("hasRole('ROLE_INSTITUTION')")
public ResponseEntity<EduCemadenOrganizations> getOrganizationById(@PathVariable Integer id) {
Optional<EduCemadenOrganizations> organization = organizationsService.getOrganizationById(id);
return organization.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
// Endpoint para atualizar uma instituição por ID
@PutMapping("/update/{id}")
@PreAuthorize("hasRole('ROLE_INSTITUTION')")
public ResponseEntity<EduCemadenOrganizations> updateOrganization(
@PathVariable Integer id,
@RequestBody EduCemadenOrganizations updatedOrganization) {
Optional<EduCemadenOrganizations> updatedOrg = organizationsService.updateOrganization(id, updatedOrganization);
return updatedOrg.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
}
@PostMapping("/createInstitution")
@ApiOperation(
value = "${UserController.createInstitution}",
notes = "This is the createInstitution method to create new institutions."
)
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Something went wrong"),
@ApiResponse(code = 422, message = "Required parameters should be provided")
}
)
public ResponseEntity<UUID> createInstitution(
@ApiParam(
name = "institution",
value = "Institution details",
required = true
)
@RequestBody EduCemadenOrganizations institution
) {
try {
// Adiciona lógica para criar instituição no serviço e retorna UUID
UUID activationKey = userService.createInstitution(institution);
return ResponseEntity.ok(activationKey);
} catch (CustomException ce) {
return ResponseEntity.status(ce.getHttpStatus()).body(null);
}
}
@PutMapping("/update")
public ResponseEntity<Users> editUser(@RequestBody Users updatedUser) {
Users editedUser = userService.editUser(updatedUser);
@ -95,27 +212,27 @@ public class UsersController {
return userService.existsByUsername(username);
}
@PostMapping("/existsByNickname")
@ApiOperation(
value = "${UserController.existsByNickname}",
notes = "From a nickname, this method returns if there is a nickname in db or not."
)
@ApiResponses(value = {//
@ApiResponse(code = 400, message = "Something went wrong")
}
)
public boolean existsByNickname(//
@ApiParam(
name = "nickname",
type = "String",
value = "nickname of the user",
example = "This is an unique field, and consumers should be aware of it.",
required = true
)
@RequestParam String nickname
) {
return userService.existsByNickname(nickname);
}
// @PostMapping("/existsByNickname")
// @ApiOperation(
// value = "${UserController.existsByNickname}",
// notes = "From a nickname, this method returns if there is a nickname in db or not."
// )
// @ApiResponses(value = {//
// @ApiResponse(code = 400, message = "Something went wrong")
// }
// )
// public boolean existsByNickname(//
// @ApiParam(
// name = "nickname",
// type = "String",
// value = "nickname of the user",
// example = "This is an unique field, and consumers should be aware of it.",
// required = true
// )
// @RequestParam String nickname
// ) {
// return userService.existsByNickname(nickname);
// }
@PostMapping("/login")
@ApiOperation(
@ -168,7 +285,7 @@ public class UsersController {
) {
return userService.signup(CustomMapper.map(user, Users.class));
}
@PostMapping("/activate")
@PreAuthorize("hasRole('ROLE_INSTITUTION') or hasRole('ROLE_CLIENT')")
@ApiOperation(

31
src/main/java/org/waterproofingdata/wpdauth/model/EduCemadenOrganizations.java

@ -2,22 +2,19 @@ package org.waterproofingdata.wpdauth.model;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity(name = "educemaden_organizations")
@Table(name = "educemaden_organizations")
@Getter
@Setter
@NoArgsConstructor
public class EduCemadenOrganizations {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = true)
@ -47,6 +44,30 @@ public class EduCemadenOrganizations {
@Column(nullable = true)
private String address;
@Column(nullable = true)
private String rua;
@Column(nullable = true)
private String numero;
@Column(nullable = true)
private String bairro;
@Column(nullable = true)
private String cep;
@Column(nullable = true)
private String cidade;
@Column(nullable = true)
private String uf;
@Column(nullable = true)
private String lat;
@Column(nullable = true)
private String lng;
@Column(nullable = true)
private String responsible;

2
src/main/java/org/waterproofingdata/wpdauth/model/Users.java

@ -33,7 +33,7 @@ public class Users {
private String username;
@Size(min = 4, max = 255, message = "Minimum name length: 4 characters")
@Column(unique = true, nullable = false)
@Column(nullable = false)
private String nickname;
@Size(min = 8, message = "Minimum password length: 8 characters")

8
src/main/java/org/waterproofingdata/wpdauth/repository/UsersRepository.java

@ -16,10 +16,10 @@ public interface UsersRepository extends JpaRepository<Users, Integer> {
Users findByUsername(String username);
boolean existsByNickname(String nickname);
@Query(value = "SELECT nickname || rank() OVER (PARTITION BY nickname) nickname_unique FROM auth.users WHERE nickname = ?1", nativeQuery = true)
String findSuggestedNickname(String nickname);
// boolean existsByNickname(String nickname);
// @Query(value = "SELECT nickname || rank() OVER (PARTITION BY nickname) nickname_unique FROM auth.users WHERE nickname = ?1", nativeQuery = true)
// String findSuggestedNickname(String nickname);
@Modifying(clearAutomatically = true)
@Query(value = "UPDATE auth.users SET active = ?2 WHERE username = ?1", nativeQuery = true)

106
src/main/java/org/waterproofingdata/wpdauth/service/UsersService.java

@ -1,5 +1,8 @@
package org.waterproofingdata.wpdauth.service;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
@ -7,6 +10,7 @@ import javax.servlet.http.HttpServletRequest;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
@ -47,6 +51,92 @@ public class UsersService {
@Autowired
private AuthenticationManager authenticationManager;
@Service
public class UsersEducemadenOrganizationsService {
private final UsersEducemadenOrganizationsRepository usersRepository;
@Autowired
public UsersEducemadenOrganizationsService(UsersEducemadenOrganizationsRepository usersRepository) {
this.usersRepository = usersRepository;
}
// ... outros métodos
public UsersEducemadenOrganizations saveUserOrganizationMapping(UsersEducemadenOrganizations userOrganizationMapping) {
return usersRepository.save(userOrganizationMapping);
}
public UsersEducemadenOrganizations findByUserId(Integer userId) {
return usersRepository.findByUsersid(userId);
}
public UsersEducemadenOrganizations findByActivationKey(UUID activationKey) {
return usersRepository.findByActivationkey(activationKey);
}
}
@Service
public class EduCemadenOrganizationsService {
// Inject the repository
private final EduCemadenOrganizationsRepository organizationsRepository;
@Autowired
public EduCemadenOrganizationsService(EduCemadenOrganizationsRepository organizationsRepository) {
this.organizationsRepository = organizationsRepository;
}
// Method to get all organizations
public List<EduCemadenOrganizations> getAllOrganizations() {
return organizationsRepository.findAll();
}
// Method to get an organization by ID
public Optional<EduCemadenOrganizations> getOrganizationById(Integer id) {
return organizationsRepository.findById(id);
}
public Optional<EduCemadenOrganizations> updateOrganization(Integer id, EduCemadenOrganizations updatedOrganization) {
return organizationsRepository.findById(id)
.map(existingOrganization -> {
// Atualizar os campos necessários
existingOrganization.setName(updatedOrganization.getName());
existingOrganization.setInep_code(updatedOrganization.getInep_code());
existingOrganization.setPhone(updatedOrganization.getPhone());
existingOrganization.setType(updatedOrganization.getType());
existingOrganization.setWebsite(updatedOrganization.getWebsite());
existingOrganization.setLogin(updatedOrganization.getLogin());
existingOrganization.setAddress(updatedOrganization.getAddress());
existingOrganization.setRua(updatedOrganization.getRua());
existingOrganization.setNumero(updatedOrganization.getNumero());
existingOrganization.setBairro(updatedOrganization.getBairro());
existingOrganization.setCep(updatedOrganization.getCep());
existingOrganization.setCidade(updatedOrganization.getCidade());
existingOrganization.setUf(updatedOrganization.getUf());
existingOrganization.setLat(updatedOrganization.getLat());
existingOrganization.setLng(updatedOrganization.getLng());
existingOrganization.setResponsible(updatedOrganization.getResponsible());
// Salvar a instituição atualizada
return organizationsRepository.save(existingOrganization);
});
}
}
// public String createInstitution(EduCemadenOrganizations institution) {
// institution.setActivationkey(UUID.randomUUID());
//
// EduCemadenOrganizations savedInstitution = eduCemadenOrganizationsRepository.save(institution);
// return jwtTokenProvider.createToken(savedInstitution.getName(), Arrays.asList(Roles.ROLE_INSTITUTION));
// }
public UUID createInstitution(EduCemadenOrganizations institution) {
institution.setActivationkey(UUID.randomUUID());
EduCemadenOrganizations savedInstitution = eduCemadenOrganizationsRepository.save(institution);
return savedInstitution.getActivationkey();
}
public Users editUser(@NotNull Users updatedUser) {
Users existingUser = usersRepository.findById(updatedUser.getId()).orElse(null);
if (existingUser != null) {
@ -91,10 +181,10 @@ public class UsersService {
public boolean existsByUsername(String username) {
return usersRepository.existsByUsername(username);
}
public boolean existsByNickname(String nickname) {
return usersRepository.existsByNickname(nickname);
}
// public boolean existsByNickname(String nickname) {
// return usersRepository.existsByNickname(nickname);
// }
public Users search(String username) {
Users user = usersRepository.findByUsername(username);
@ -130,10 +220,10 @@ public class UsersService {
if (user.getNickname().length() == 0) {
throw new CustomException("Nickname must be provided", HttpStatus.UNPROCESSABLE_ENTITY);
}
else if (existsByNickname(user.getNickname())) {
String nickname_unique = usersRepository.findSuggestedNickname(user.getNickname());
throw new CustomException(String.format("Nickname already exists. Would you like to use '%s'?", nickname_unique), HttpStatus.UNPROCESSABLE_ENTITY);
}
// else if (existsByNickname(user.getNickname())) {
// String nickname_unique = usersRepository.findSuggestedNickname(user.getNickname());
// throw new CustomException(String.format("Nickname already exists. Would you like to use '%s'?", nickname_unique), HttpStatus.UNPROCESSABLE_ENTITY);
// }
if (user.getPassword().length() == 0) {
throw new CustomException("Password must be provided", HttpStatus.UNPROCESSABLE_ENTITY);
}

28
src/main/resources/application.properties

@ -5,9 +5,10 @@ spring.datasource.hikari.maximumPoolSize=5
## PostgreSQL
spring.datasource.url=jdbc:postgresql://localhost:5432/wpdauth
spring.datasource.username=uwpdauth
spring.datasource.password=root
spring.datasource.password=pwd123
spring.jpa.properties.hibernate.default_schema=auth
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.default_schema=auth
server.port=8080
@ -15,10 +16,10 @@ security.jwt.token.secret-key=<secret-key>
##5 minutes duration by default: 5 minutes * 60 seconds * 1000 miliseconds
security.jwt.token.expire-length=300000
spring.mail.host=<host>
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<username>
spring.mail.password=<password>
spring.mail.username=danieldrb@gmail.com
spring.mail.password=1234
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
@ -27,20 +28,3 @@ UsersController.signup=Creates user and returns its JWT token.
UsersController.delete=Deletes specific user by username.
UsersController.search=Returns specific user by username.
UsersController.me=Returns current user's data.
# actuator
management.endpoint.health.show-details=always
#indica que health deve mostrar detalhes sempre
management.endpoints.web.exposure.include=*
#alem do health e do info ele sempre vai export todos endpoints disponiveis
info.app.name=@project.name@
info.app.description=@project.description@
info.app.version=@project.version@
info.app.encoding=@project.build.sourceEncoding@
info.app.java.version=@java.version@
# puxa informacoes do projeto do pom.xml
spring.boot.admin.client.url=http://localhost:8080
# configurando o Spring Boot Admin Server
Loading…
Cancel
Save