diff --git a/src/main/java/com/devsuperior/bds04/config/AppConfig.java b/src/main/java/com/devsuperior/bds04/config/AppConfig.java new file mode 100644 index 00000000..806b9d68 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/config/AppConfig.java @@ -0,0 +1,32 @@ +package com.devsuperior.bds04.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; +import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; + +@Configuration +public class AppConfig { + + @Value("${jwt.secret}") + private String jwtSecret; + + @Bean + public BCryptPasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public JwtAccessTokenConverter accessTokenConverter() { + JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter(); + tokenConverter.setSigningKey(jwtSecret); + return tokenConverter; + } + + @Bean + public JwtTokenStore tokenStore() { + return new JwtTokenStore(accessTokenConverter()); + } +} diff --git a/src/main/java/com/devsuperior/bds04/config/AuthorizationServerConfig.java b/src/main/java/com/devsuperior/bds04/config/AuthorizationServerConfig.java new file mode 100644 index 00000000..94d5d11e --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/config/AuthorizationServerConfig.java @@ -0,0 +1,63 @@ +package com.devsuperior.bds04.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; +import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; + +@Configuration +@EnableAuthorizationServer +public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { + + @Value("${security.oauth2.client.client-id}") + private String clientId; + + @Value("${security.oauth2.client.client-secret}") + private String clientSecret; + + @Value("${jwt.duration}") + private Integer jwtDuration; + + @Autowired + private BCryptPasswordEncoder passwordEncoder; + + @Autowired + private JwtAccessTokenConverter accessTokenConverter; + + @Autowired + private JwtTokenStore tokenStore; + + @Autowired + private AuthenticationManager authenticationManager; + + @Override + public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { + security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); + } + + @Override + public void configure(ClientDetailsServiceConfigurer clients) throws Exception { + clients.inMemory() + .withClient(clientId) + .secret(passwordEncoder.encode(clientSecret)) + .scopes("read", "write") + .authorizedGrantTypes("password") + .accessTokenValiditySeconds(jwtDuration); + } + + @Override + public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { + + endpoints.authenticationManager(authenticationManager) + .tokenStore(tokenStore) + .accessTokenConverter(accessTokenConverter); + } +} diff --git a/src/main/java/com/devsuperior/bds04/config/ResourceServerConfig.java b/src/main/java/com/devsuperior/bds04/config/ResourceServerConfig.java new file mode 100644 index 00000000..c95692c5 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/config/ResourceServerConfig.java @@ -0,0 +1,52 @@ +package com.devsuperior.bds04.config; + +import java.util.Arrays; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; + +@Configuration +@EnableResourceServer +public class ResourceServerConfig extends ResourceServerConfigurerAdapter { + + @Autowired + private Environment env; + + @Autowired + private JwtTokenStore tokenStore; + + private static final String[] PUBLIC = { "/oauth/token", "/h2-console/**" }; + + private static final String[] PUBLIC_GET = { "/cities/**", "/events/**" }; + + private static final String[] CLIENT = { "/events/**" }; + + private static final String[] ADMIN = { "/cities/**", "/events/**", "/users/**" }; + + @Override + public void configure(ResourceServerSecurityConfigurer resources) throws Exception { + resources.tokenStore(tokenStore); + } + + @Override + public void configure(HttpSecurity http) throws Exception { + + // H2 + if (Arrays.asList(env.getActiveProfiles()).contains("test")) { + http.headers().frameOptions().disable(); + } + + http.authorizeRequests() + .antMatchers(PUBLIC).permitAll() + .antMatchers(HttpMethod.GET, PUBLIC_GET).permitAll() + .antMatchers(HttpMethod.POST, CLIENT).hasAnyRole("CLIENT") + .anyRequest().hasAnyRole("ADMIN"); + } +} diff --git a/src/main/java/com/devsuperior/bds04/config/WebSecurityConfig.java b/src/main/java/com/devsuperior/bds04/config/WebSecurityConfig.java new file mode 100644 index 00000000..31dad645 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/config/WebSecurityConfig.java @@ -0,0 +1,39 @@ +package com.devsuperior.bds04.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +@Configuration +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private BCryptPasswordEncoder passwordEncoder; + + @Autowired + private UserDetailsService userDetailsService; + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder); + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/actuator/**"); + } + + @Override + @Bean + protected AuthenticationManager authenticationManager() throws Exception { + return super.authenticationManager(); + } +} diff --git a/src/main/java/com/devsuperior/bds04/controllers/CityController.java b/src/main/java/com/devsuperior/bds04/controllers/CityController.java new file mode 100644 index 00000000..9fccf470 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/controllers/CityController.java @@ -0,0 +1,40 @@ +package com.devsuperior.bds04.controllers; + +import java.net.URI; +import java.util.List; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.devsuperior.bds04.dto.CityDTO; +import com.devsuperior.bds04.services.CityService; + +@RestController +@RequestMapping(value = "/cities") +public class CityController { + + @Autowired + private CityService service; + + @GetMapping + public ResponseEntity> findAll() { + List list = service.findAll(); + return ResponseEntity.ok().body(list); + } + + @PostMapping + public ResponseEntity insert(@Valid @RequestBody CityDTO dto) { + dto = service.insert(dto); + URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}") + .buildAndExpand(dto.getId()).toUri(); + return ResponseEntity.created(uri).body(dto); + } +} \ No newline at end of file diff --git a/src/main/java/com/devsuperior/bds04/controllers/EventController.java b/src/main/java/com/devsuperior/bds04/controllers/EventController.java new file mode 100644 index 00000000..9818ea6a --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/controllers/EventController.java @@ -0,0 +1,41 @@ +package com.devsuperior.bds04.controllers; + +import java.net.URI; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.devsuperior.bds04.dto.EventDTO; +import com.devsuperior.bds04.services.EventService; + +@RestController +@RequestMapping(value = "/events") +public class EventController { + + @Autowired + private EventService service; + + @GetMapping + public ResponseEntity> findAll(Pageable pageable) { + Page page = service.findAllPaged(pageable); + return ResponseEntity.ok().body(page); + } + + @PostMapping + public ResponseEntity insert(@Valid @RequestBody EventDTO dto) { + dto = service.insert(dto); + URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}") + .buildAndExpand(dto.getId()).toUri(); + return ResponseEntity.created(uri).body(dto); + } +} \ No newline at end of file diff --git a/src/main/java/com/devsuperior/bds04/controllers/exceptions/FieldMessage.java b/src/main/java/com/devsuperior/bds04/controllers/exceptions/FieldMessage.java new file mode 100644 index 00000000..095db169 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/controllers/exceptions/FieldMessage.java @@ -0,0 +1,35 @@ +package com.devsuperior.bds04.controllers.exceptions; + +import java.io.Serializable; + +public class FieldMessage implements Serializable { + private static final long serialVersionUID = 1L; + + private String fieldName; + private String message; + + public FieldMessage() { + } + + public FieldMessage(String fieldName, String message) { + super(); + this.fieldName = fieldName; + this.message = message; + } + + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/src/main/java/com/devsuperior/bds04/controllers/exceptions/ResourceExceptionHandler.java b/src/main/java/com/devsuperior/bds04/controllers/exceptions/ResourceExceptionHandler.java new file mode 100644 index 00000000..f908b163 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/controllers/exceptions/ResourceExceptionHandler.java @@ -0,0 +1,33 @@ +package com.devsuperior.bds04.controllers.exceptions; + +import java.time.Instant; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@ControllerAdvice +public class ResourceExceptionHandler { + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity validation(MethodArgumentNotValidException e, HttpServletRequest request) { + HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY; + ValidationError err = new ValidationError(); + err.setTimestamp(Instant.now()); + err.setStatus(status.value()); + err.setError("Validation exception"); + err.setMessage(e.getMessage()); + err.setPath(request.getRequestURI()); + + for (FieldError f : e.getBindingResult().getFieldErrors()) { + err.addError(f.getField(), f.getDefaultMessage()); + } + + return ResponseEntity.status(status).body(err); + } +} diff --git a/src/main/java/com/devsuperior/bds04/controllers/exceptions/StandardError.java b/src/main/java/com/devsuperior/bds04/controllers/exceptions/StandardError.java new file mode 100644 index 00000000..7ecd0019 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/controllers/exceptions/StandardError.java @@ -0,0 +1,57 @@ +package com.devsuperior.bds04.controllers.exceptions; + +import java.io.Serializable; +import java.time.Instant; + +public class StandardError implements Serializable { + private static final long serialVersionUID = 1L; + + private Instant timestamp; + private Integer status; + private String error; + private String message; + private String path; + + public StandardError() { + } + + public Instant getTimestamp() { + return timestamp; + } + + public void setTimestamp(Instant timestamp) { + this.timestamp = timestamp; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } +} diff --git a/src/main/java/com/devsuperior/bds04/controllers/exceptions/ValidationError.java b/src/main/java/com/devsuperior/bds04/controllers/exceptions/ValidationError.java new file mode 100644 index 00000000..fb82297c --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/controllers/exceptions/ValidationError.java @@ -0,0 +1,18 @@ +package com.devsuperior.bds04.controllers.exceptions; + +import java.util.ArrayList; +import java.util.List; + +public class ValidationError extends StandardError { + private static final long serialVersionUID = 1L; + + private List errors = new ArrayList<>(); + + public List getErrors() { + return errors; + } + + public void addError(String fieldName, String message) { + errors.add(new FieldMessage(fieldName, message)); + } +} diff --git a/src/main/java/com/devsuperior/bds04/dto/CityDTO.java b/src/main/java/com/devsuperior/bds04/dto/CityDTO.java index d7cf8420..1b38845b 100644 --- a/src/main/java/com/devsuperior/bds04/dto/CityDTO.java +++ b/src/main/java/com/devsuperior/bds04/dto/CityDTO.java @@ -2,12 +2,16 @@ import java.io.Serializable; +import javax.validation.constraints.NotBlank; + import com.devsuperior.bds04.entities.City; public class CityDTO implements Serializable { private static final long serialVersionUID = 1L; private Long id; + + @NotBlank(message = "Campo requerido") private String name; public CityDTO() { diff --git a/src/main/java/com/devsuperior/bds04/dto/EventDTO.java b/src/main/java/com/devsuperior/bds04/dto/EventDTO.java index 0a3024d3..b0b2956e 100644 --- a/src/main/java/com/devsuperior/bds04/dto/EventDTO.java +++ b/src/main/java/com/devsuperior/bds04/dto/EventDTO.java @@ -3,15 +3,25 @@ import java.io.Serializable; import java.time.LocalDate; +import javax.validation.constraints.FutureOrPresent; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + import com.devsuperior.bds04.entities.Event; public class EventDTO implements Serializable { private static final long serialVersionUID = 1L; private Long id; + + @NotBlank(message = "Campo requerido") private String name; + + @FutureOrPresent(message = "A data do evento não pode ser passada") private LocalDate date; private String url; + + @NotNull(message = "Campo requerido") private Long cityId; public EventDTO() { diff --git a/src/main/java/com/devsuperior/bds04/entities/Role.java b/src/main/java/com/devsuperior/bds04/entities/Role.java new file mode 100644 index 00000000..af96141b --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/entities/Role.java @@ -0,0 +1,70 @@ +package com.devsuperior.bds04.entities; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "tb_role") +public class Role implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String authority; + + public Role() { + } + + public Role(Long id, String authority) { + super(); + this.id = id; + this.authority = authority; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getAuthority() { + return authority; + } + + public void setAuthority(String authority) { + this.authority = authority; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Role other = (Role) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } +} diff --git a/src/main/java/com/devsuperior/bds04/entities/User.java b/src/main/java/com/devsuperior/bds04/entities/User.java new file mode 100644 index 00000000..7c65d5bc --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/entities/User.java @@ -0,0 +1,136 @@ +package com.devsuperior.bds04.entities; + +import java.io.Serializable; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +@Entity +@Table(name = "tb_user") +public class User implements UserDetails, Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(unique = true) + private String email; + private String password; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "tb_user_role", + joinColumns = @JoinColumn(name = "user_id"), + inverseJoinColumns = @JoinColumn(name = "role_id")) + private Set roles = new HashSet<>(); + + public User() { + } + + public User(Long id, String email, String password) { + super(); + this.id = id; + this.email = email; + this.password = password; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Set getRoles() { + return roles; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + User other = (User) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + + @Override + public Collection getAuthorities() { + return roles.stream().map(role -> new SimpleGrantedAuthority(role.getAuthority())) + .collect(Collectors.toList()); + } + + @Override + public String getUsername() { + return email; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } +} diff --git a/src/main/java/com/devsuperior/bds04/repositories/CityRepository.java b/src/main/java/com/devsuperior/bds04/repositories/CityRepository.java new file mode 100644 index 00000000..9404faf6 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/repositories/CityRepository.java @@ -0,0 +1,9 @@ +package com.devsuperior.bds04.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.devsuperior.bds04.entities.City; + +public interface CityRepository extends JpaRepository { + +} diff --git a/src/main/java/com/devsuperior/bds04/repositories/EventRepository.java b/src/main/java/com/devsuperior/bds04/repositories/EventRepository.java new file mode 100644 index 00000000..0cabfa8c --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/repositories/EventRepository.java @@ -0,0 +1,9 @@ +package com.devsuperior.bds04.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.devsuperior.bds04.entities.Event; + +public interface EventRepository extends JpaRepository { + +} diff --git a/src/main/java/com/devsuperior/bds04/repositories/UserRepository.java b/src/main/java/com/devsuperior/bds04/repositories/UserRepository.java new file mode 100644 index 00000000..14bfba92 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/repositories/UserRepository.java @@ -0,0 +1,10 @@ +package com.devsuperior.bds04.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.devsuperior.bds04.entities.User; + +public interface UserRepository extends JpaRepository { + + User findByEmail(String email); +} diff --git a/src/main/java/com/devsuperior/bds04/services/CityService.java b/src/main/java/com/devsuperior/bds04/services/CityService.java new file mode 100644 index 00000000..c82f5334 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/services/CityService.java @@ -0,0 +1,34 @@ +package com.devsuperior.bds04.services; + +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.devsuperior.bds04.dto.CityDTO; +import com.devsuperior.bds04.entities.City; +import com.devsuperior.bds04.repositories.CityRepository; + +@Service +public class CityService { + + @Autowired + private CityRepository repository; + + @Transactional(readOnly = true) + public List findAll() { + List list = repository.findAll(Sort.by("name")); + return list.stream().map(x -> new CityDTO(x)).collect(Collectors.toList()); + } + + @Transactional + public CityDTO insert(CityDTO dto) { + City entity = new City(); + entity.setName(dto.getName()); + entity = repository.save(entity); + return new CityDTO(entity); + } +} \ No newline at end of file diff --git a/src/main/java/com/devsuperior/bds04/services/EventService.java b/src/main/java/com/devsuperior/bds04/services/EventService.java new file mode 100644 index 00000000..08189f01 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/services/EventService.java @@ -0,0 +1,36 @@ +package com.devsuperior.bds04.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.devsuperior.bds04.dto.EventDTO; +import com.devsuperior.bds04.entities.City; +import com.devsuperior.bds04.entities.Event; +import com.devsuperior.bds04.repositories.EventRepository; + +@Service +public class EventService { + + @Autowired + private EventRepository repository; + + @Transactional(readOnly = true) + public Page findAllPaged(Pageable pageable) { + Page page = repository.findAll(pageable); + return page.map(x -> new EventDTO(x)); + } + + @Transactional + public EventDTO insert(EventDTO dto) { + Event entity = new Event(); + entity.setName(dto.getName()); + entity.setDate(dto.getDate()); + entity.setUrl(dto.getUrl()); + entity.setCity(new City(dto.getCityId(), null)); + entity = repository.save(entity); + return new EventDTO(entity); + } +} \ No newline at end of file diff --git a/src/main/java/com/devsuperior/bds04/services/UserService.java b/src/main/java/com/devsuperior/bds04/services/UserService.java new file mode 100644 index 00000000..56123ba5 --- /dev/null +++ b/src/main/java/com/devsuperior/bds04/services/UserService.java @@ -0,0 +1,34 @@ +package com.devsuperior.bds04.services; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import com.devsuperior.bds04.entities.User; +import com.devsuperior.bds04.repositories.UserRepository; + +@Service +public class UserService implements UserDetailsService { + + private static Logger logger = LoggerFactory.getLogger(UserService.class); + + @Autowired + private UserRepository repository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + + User user = repository.findByEmail(username); + if (user == null) { + logger.error("User not found: " + username); + throw new UsernameNotFoundException("Email not found"); + } + logger.info("User found: " + username); + return user; + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index a7dcd8af..de5668d0 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,3 +1,9 @@ -spring.profiles.active=test +spring.profiles.active=${APP_PROFILE:test} spring.jpa.open-in-view=false + +security.oauth2.client.client-id=${CLIENT_ID:myclientid} +security.oauth2.client.client-secret=${CLIENT_SECRET:myclientsecret} + +jwt.secret=${JWT_SECRET:MY-JWT-SECRET} +jwt.duration=${JWT_DURATION:86400} \ No newline at end of file diff --git a/src/main/resources/data.sql b/src/main/resources/data.sql index 0b897e20..108d3a89 100644 --- a/src/main/resources/data.sql +++ b/src/main/resources/data.sql @@ -1,3 +1,13 @@ +INSERT INTO tb_user (email, password) VALUES ('ana@gmail.com', '$2a$10$eACCYoNOHEqXve8aIWT8Nu3PkMXWBaOxJ9aORUYzfMQCbVBIhZ8tG'); +INSERT INTO tb_user (email, password) VALUES ('bob@gmail.com', '$2a$10$eACCYoNOHEqXve8aIWT8Nu3PkMXWBaOxJ9aORUYzfMQCbVBIhZ8tG'); + +INSERT INTO tb_role (authority) VALUES ('ROLE_CLIENT'); +INSERT INTO tb_role (authority) VALUES ('ROLE_ADMIN'); + +INSERT INTO tb_user_role (user_id, role_id) VALUES (1, 1); +INSERT INTO tb_user_role (user_id, role_id) VALUES (2, 1); +INSERT INTO tb_user_role (user_id, role_id) VALUES (2, 2); + INSERT INTO tb_city(name) VALUES ('São Paulo'); INSERT INTO tb_city(name) VALUES ('Brasília'); INSERT INTO tb_city(name) VALUES ('Fortaleza');