Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<h1> Domínio e ORM, autorizações -Development Challenge- Chapter 4 </h1>
<h2>Competências</h2>
<h4>Domínio e ORM</h4><br>
. Implementação de um modelo de domínio complexo (projeto DSLearn)<br>
. Instanciação (seed) de um modelo de domínio com SQL<br>
<h4>Autorizações</h4><br>
. Autorização customizada em nível de serviço<br>
. Conteúdo customizado para o usuário logado<br>
. Refresh token<br>
. Pré-autorização de métodos<br>

<br>
Implementado as funcionalidades necessárias para que os testes do projeto passem: https://github.com/evrasouza/bds05
<br>
<br>
O que devo foi feito para resolver o desafio!<br>
-> Implementado o modelo conceitual, com seed do banco de dados.<br>
-> Incluído a infraestrutura de exceções, validação e segurança ao projeto.<br>
-> Implementar o endpoint GET /users/profile, para Obter o perfil do usuário logado<br>
<br>
<h4>Projeto finalizado na branch: https://github.com/evrasouza/bds05/tree/entregaTarefaMovieFlixDominioAutorizacao</h4>

<br><br>
<h1> Consultas ao banco de dados -Development Challenge- Chapter 5 </h1>
<h2>Competências</h2>
<h4>SQL e JPQL</h4><br>
. Estudos de caso SQL e JPQL<br>
. Projeção, restrição, escalares<br>
. Joins<br>
. Group by<br>
. UNION<br>
<h4>Spring Data JPA</h4><br>
. Query methods<br>
. Estudo de caso: busca detalhada com parâmetros opcionais e paginação<br>
. Problema N+1 consultas<br>
. Refresh token<br>
. Pré-autorização de métodos<br>
<br>
<h4>Projeto finalizado na branch: https://github.com/evrasouza/bds05/tree/entregaTarefaCapitulo5</h4>
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,4 @@ public class MovieflixApplication {
public static void main(String[] args) {
SpringApplication.run(MovieflixApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.devsuperior.movieflix.components;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import com.devsuperior.movieflix.entities.User;
import com.devsuperior.movieflix.repositories.UserRepository;

@Component
public class JwtTokenEnhancer implements TokenEnhancer{

@Autowired
private UserRepository userRepository;

@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

User user = userRepository.findByEmail(authentication.getName());

Map<String, Object> map = new HashMap<>();
map.put("userName", user.getName());
map.put("userId", user.getId());

DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
token.setAdditionalInformation(map);

return token;
}

}
35 changes: 35 additions & 0 deletions src/main/java/com/devsuperior/movieflix/config/AppConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.devsuperior.movieflix.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());
}



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.devsuperior.movieflix.config;

import java.util.Arrays;

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.core.userdetails.UserDetailsService;
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.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import com.devsuperior.movieflix.components.JwtTokenEnhancer;

@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 TokenStore tokenStore;

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private JwtTokenEnhancer tokenEnhancer;

@Autowired
private UserDetailsService userDetailsService;

@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 {

TokenEnhancerChain chain = new TokenEnhancerChain();
chain.setTokenEnhancers(Arrays.asList(accessTokenConverter, tokenEnhancer));

endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore)
.accessTokenConverter(accessTokenConverter)
.tokenEnhancer(chain)
.userDetailsService(userDetailsService);
}



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.devsuperior.movieflix.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.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/**" };

@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()
.anyRequest().authenticated();

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.devsuperior.movieflix.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.method.configuration.EnableGlobalMethodSecurity;
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
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private BCryptPasswordEncoder passwordEncoder;

@Autowired
private UserDetailsService userDetailService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder);
super.configure(auth);
}

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/actuator/**");
}

@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.devsuperior.movieflix.controllers;

import java.util.List;

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.devsuperior.movieflix.dto.GenreDTO;
import com.devsuperior.movieflix.services.GenreService;

@RestController
@RequestMapping(value = "/genres")
public class GenreController {

@Autowired
private GenreService service;

@GetMapping
public ResponseEntity<List<GenreDTO>> findAll(){
List<GenreDTO> list = service.findAll();
return ResponseEntity.ok().body(list);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.devsuperior.movieflix.controllers;

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.devsuperior.movieflix.dto.UserDTO;
import com.devsuperior.movieflix.services.UserService;

@RestController
@RequestMapping(value = "/users")
public class UserController {

@Autowired
private UserService service;

@GetMapping(value = "/profile")
public ResponseEntity<UserDTO> findCurrentUser(){
UserDTO dto = service.findCurrentUser();
return ResponseEntity.ok().body(dto);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.devsuperior.movieflix.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) {
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;
}

}
Loading