Skip to content

Commit

Permalink
carregando urls e roles dinamicamente
Browse files Browse the repository at this point in the history
  • Loading branch information
asouza committed Jul 13, 2015
1 parent 330ccdf commit 3d89caa
Show file tree
Hide file tree
Showing 7 changed files with 210 additions and 8 deletions.
6 changes: 3 additions & 3 deletions .project
Expand Up @@ -21,17 +21,17 @@
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
Expand Down
@@ -0,0 +1,77 @@
package br.com.casadocodigo.loja.conf;

import java.util.Collection;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import br.com.casadocodigo.loja.daos.SystemURLDAO;
import br.com.casadocodigo.loja.models.Role;
import br.com.casadocodigo.loja.models.SystemURL;

@Component
public class DynamicSecurityMetadataSource implements
FilterInvocationSecurityMetadataSource {

@Autowired
private SystemURLDAO systemUrls;;

@Override
public Collection<ConfigAttribute> getAttributes(Object object)
throws IllegalArgumentException {
final HttpServletRequest request = ((FilterInvocation) object)
.getRequest();

String urlWithoutContextPath = request.getRequestURI().substring(
request.getContextPath().length());

Optional<SystemURL> foundUrl = systemUrls
.findByURL(urlWithoutContextPath);

if (foundUrl.isPresent()) {
System.out.println("achou a url");
return foundUrl.get().getRolesAllowed().stream()
.map(this::configAttribute).collect(Collectors.toList());
}

return null;
}

private ConfigAttribute configAttribute(Role role) {
return new ConfigAttribute() {

/**
*
*/
private static final long serialVersionUID = -474661209383691172L;

@Override
public String getAttribute() {
return role.getAuthority();
}
};
}

@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}

@Override
public boolean supports(Class<?> clazz) {
return FilterInvocation.class.isAssignableFrom(clazz);
}

public static void main(String[] args) {
String test = "/casadocodigo-blog/produtos/form";
System.out.println(test.substring("/casadocodigo-blog".length()));
}

}
@@ -1,37 +1,56 @@
package br.com.casadocodigo.loja.conf;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.expression.WebExpressionVoter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()

AffirmativeBased affirmativeBased = new AffirmativeBased(Arrays.asList(new RoleVoter(),new WebExpressionVoter()));
http.authorizeRequests().accessDecisionManager(affirmativeBased)
.antMatchers("/produtos/form").hasRole("ADMIN")
.antMatchers("/shopping/**").permitAll()
.antMatchers(HttpMethod.POST,"/produtos").hasRole("ADMIN")
.antMatchers("/produtos/**").permitAll()
.antMatchers(HttpMethod.GET, "/admin/users").permitAll()
.anyRequest().authenticated()
.anyRequest().authenticated()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
public <O extends FilterSecurityInterceptor> O postProcess(
O fsi) {
fsi.setSecurityMetadataSource(dynamicSecurityMetadataSource);
return fsi;
}
})
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}



@Autowired
private UserDetailsService users;
@Autowired
private DynamicSecurityMetadataSource dynamicSecurityMetadataSource;

@Override
protected void configure(AuthenticationManagerBuilder auth)
Expand Down
Expand Up @@ -98,7 +98,7 @@ public SseEmitter enableQuickPromoNotifier(){
@RequestMapping("habilita/promocao/{id}")
@ResponseStatus(value=HttpStatus.OK)
public void enableQuickPromoForProduct(@PathVariable("id") Integer id) throws IOException{
Product product = products.findOne(id);
Product product = products.findOne(id);
notifier.send(new QuickPromoData(product,messageSource));
}

Expand Down
@@ -0,0 +1,37 @@
package br.com.casadocodigo.loja.controllers;

import java.util.Arrays;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import br.com.casadocodigo.loja.models.Role;
import br.com.casadocodigo.loja.models.SystemURL;

/**
* Apenas para a ajudar a criar algumas urls associadas a roles
* @author alberto
*
*/
@Controller
public class SystemURLsController {

@PersistenceContext
private EntityManager em;

@RequestMapping("/url")
@ResponseBody
@Transactional
public String create(String url,String roleName) {
SystemURL systemURL = new SystemURL();
systemURL.setValue(url);
systemURL.setRolesAllowed(Arrays.asList(new Role(roleName)));
em.persist(systemURL);
return "urls criadas";
}
}
30 changes: 30 additions & 0 deletions src/main/java/br/com/casadocodigo/loja/daos/SystemURLDAO.java
@@ -0,0 +1,30 @@
package br.com.casadocodigo.loja.daos;

import java.util.List;
import java.util.Optional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Component;

import br.com.casadocodigo.loja.models.SystemURL;

@Component
public class SystemURLDAO {

@PersistenceContext
private EntityManager entityManager;

public Optional<SystemURL> findByURL(String url) {
TypedQuery<SystemURL> query = entityManager
.createQuery("select su from SystemURL su join fetch su.rolesAllowed where su.value = :url",SystemURL.class);
query.setParameter("url", url);
List<SystemURL> urls = query.getResultList();
if(urls.isEmpty()){
return Optional.empty();
}
return Optional.of(urls.get(0));
}
}
39 changes: 39 additions & 0 deletions src/main/java/br/com/casadocodigo/loja/models/SystemURL.java
@@ -0,0 +1,39 @@
package br.com.casadocodigo.loja.models;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class SystemURL {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(unique=true)
private String value;
@ManyToMany
private List<Role> rolesAllowed;

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

public List<Role> getRolesAllowed() {
return rolesAllowed;
}

public void setRolesAllowed(List<Role> rolesAllowed) {
this.rolesAllowed = rolesAllowed;
}

}

0 comments on commit 3d89caa

Please sign in to comment.