Skip to content

Instantly share code, notes, and snippets.

@Deviad
Created September 10, 2017 05:44
Show Gist options
  • Save Deviad/52b20d5087b9331ff1e59c890f303c33 to your computer and use it in GitHub Desktop.
Save Deviad/52b20d5087b9331ff1e59c890f303c33 to your computer and use it in GitHub Desktop.
AOP - Aspect not working
package com.davidepugliese.springfood.security;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface Acl{
String value();
}
package com.davidepugliese.springfood.security;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class AclAspect {
@Pointcut(value = "@annotation(Acl)" + "&& args(getAcl)")
public void accessControl(Acl getAcl) {
}
@Around(value = "accessControl(getAcl)", argNames = "joinPoint,getAcl")
public void value(ProceedingJoinPoint joinPoint, Acl getAcl) throws Throwable {
System.out.println(">>>>>>>>\n" +"aweeeeee\n" + ">>>>>>>>\n");
// Object[] originalArguments = joinPoint.getArgs();
//
// Object[] newArguments = new Object[1];
// System.out.println(newArguments[0]);
// newArguments[0] = ((String)originalArguments[0]).toUpperCase();
//
// joinPoint.proceed(newArguments);
}
}
package com.davidepugliese.springfood.security;
public class AuthenticationException extends RuntimeException {
public AuthenticationException(String message) {
super(message);
}
}
package com.davidepugliese.springfood.controllers;
import com.davidepugliese.springfood.domain.UserDAO;
import com.davidepugliese.springfood.models.User;
import com.davidepugliese.springfood.security.Acl;
import com.davidepugliese.springfood.services.EncryptionUtilities;
import com.davidepugliese.springfood.adt.IEmail;
import com.sun.javaws.exceptions.InvalidArgumentException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/user/")
public class UserController {
@Value("${jwt.secret}")
private String secretKey;
private UserDAO userService;
@Autowired
public UserController(UserDAO userService) {
this.userService = userService;
}
@RequestMapping(value="/{id}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
@Acl("asdasdas")
public @ResponseBody
User getUser(@PathVariable Integer id) {
return userService.getUser(id);
}
@RequestMapping(value="/username/{username:.+}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public
ResponseEntity getUserByUsername(@PathVariable String username) throws InvalidArgumentException {
Object data = userService.getUserByUsername(IEmail.create(username));
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", data);
return ResponseEntity.ok(response);
}
@RequestMapping(value="/add", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus( HttpStatus.CREATED )
public
ResponseEntity addUser(@RequestBody User data, Model model) {
try {
User user = new User();
user.setUsername(data.getUsername());
user.setPassword(EncryptionUtilities.encryptPassword(data.getPassword()));
this.userService.saveUser(user);
Map<String, String> response = new HashMap<>();
response.put("status", "success");
response.put("message", "User created successfully");
return ResponseEntity.ok(response);
} catch (DataIntegrityViolationException e) {
Map<String, String> response = new HashMap<>();
response.put("status", "fail");
response.put("reason", "Username exists already");
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response);
}
}
@RequestMapping(value="/login", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus( HttpStatus.OK )
public
ResponseEntity login(@RequestBody User login, Model model) {
String jwtToken;
if (login.getUsername() == null || login.getPassword() == null) {
Map<String, String> response = new HashMap<>();
response.put("status", "fail");
response.put("reason", "Insert username and password");
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response);
}
String email = login.getUsername();
String password = login.getPassword();
User user = userService.getUserByUsername(email);
if (user == null) {
Map<String, String> response = new HashMap<>();
response.put("status", "fail");
response.put("reason", "Username not found");
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response);
}
String pwd = user.getPassword();
if (!EncryptionUtilities.matches(password, pwd)) {
Map<String, String> response = new HashMap<>();
response.put("status", "fail");
response.put("reason", "Wrong password");
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response);
}
jwtToken = Jwts.builder().setSubject(email).claim("roles", "user").setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, secretKey).compact();
Map<String, Object> response = new HashMap<>();
response.put("status", "success");
response.put("data", jwtToken);
return ResponseEntity.ok(response);
}
}
package com.davidepugliese.springfood;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.persistence.EntityManagerFactory;
@Configuration
@EnableAspectJAutoProxy
@EnableScheduling
// @ComponentScan("com.luv2code.springdemo")
public class WebConfig {
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public SessionFactory getSessionFactory() {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PATCH", "PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(0);
}
};
}
@Bean
public FilterRegistrationBean jwtFilter() {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new JwtFilter());
registrationBean.addUrlPatterns("/secure/*");
return registrationBean;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment