Created
September 10, 2017 16:00
-
-
Save Deviad/bd11571b79e535723b1443a4f0142233 to your computer and use it in GitHub Desktop.
Still not working
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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{ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | |
@Around("within(com.davidepugliese.springfood) && @annotation(com.davidepugliese.springfood.security.Acl)") | |
public Object value(ProceedingJoinPoint joinPoint) throws Throwable { | |
// Object[] originalArguments = joinPoint.getArgs(); | |
// | |
// Object[] newArguments = new Object[1]; | |
// System.out.println(newArguments[0]); | |
// newArguments[0] = ((String)originalArguments[0]).toUpperCase(); | |
// joinPoint.proceed(newArguments); | |
System.out.println("Hello world!"); | |
return joinPoint.proceed(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.davidepugliese.springfood.security; | |
public class AuthenticationException extends RuntimeException { | |
public AuthenticationException(String message) { | |
super(message); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
buildscript { | |
ext { | |
springBootVersion = '1.5.6.RELEASE' | |
} | |
repositories { | |
mavenCentral() | |
jcenter() | |
maven { | |
url 'https://maven.atlassian.com/repository/public' | |
} | |
} | |
dependencies { | |
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") | |
} | |
} | |
//buildscript { | |
// repositories { | |
// maven { | |
// url "https://maven.eveoh.nl/content/repositories/releases" | |
// } | |
// } | |
// | |
// dependencies { | |
// classpath "nl.eveoh:gradle-aspectj:2.0" | |
// } | |
//} | |
// | |
//repositories { | |
// mavenCentral() | |
//} | |
// | |
//project.ext { | |
// aspectjVersion = '1.8.4' | |
//} | |
// | |
//apply plugin: 'aspectj' | |
apply plugin: 'idea' | |
apply plugin: 'eclipse' | |
apply plugin: 'org.springframework.boot' | |
apply plugin: 'application' | |
tasks.withType(JavaCompile) { | |
//enable compilation in a separate daemon process | |
options.fork = true | |
options.forkOptions.executable = 'javac' | |
options.compilerArgs << "-XDignore.symbol.file=true" | |
//enable incremental compilation | |
options.incremental = true | |
options.encoding = 'UTF-8' | |
} | |
version = '0.0.1-SNAPSHOT' | |
sourceCompatibility = 1.8 | |
repositories { | |
mavenCentral() | |
} | |
configurations { | |
providedRuntime | |
} | |
dependencies { | |
compile fileTree(dir: 'lib', include: '*.jar') | |
compile('org.springframework.boot:spring-boot-starter-actuator') | |
compile('org.springframework.boot:spring-boot-actuator-docs') | |
compile('org.springframework.boot:spring-boot-starter-cache') | |
compile('org.springframework.boot:spring-boot-starter-data-jpa') | |
compile('org.springframework.boot:spring-boot-starter-data-rest') | |
compile('org.springframework.boot:spring-boot-starter-security') | |
compile('org.springframework.boot:spring-boot-starter-social-facebook') | |
compile('org.springframework.boot:spring-boot-starter-validation') | |
compile('org.springframework.boot:spring-boot-starter-web') | |
compile('org.springframework.boot:spring-boot-starter-aop') | |
compile('org.springframework:spring-context') | |
compile('org.springframework:spring-aspects') | |
compile('org.springframework:spring-instrument-tomcat') | |
compile('org.aspectj:aspectjweaver:1.8.10') | |
compile('org.aspectj:aspectjrt:1.8.10') | |
compile('org.springframework:spring-instrument') | |
compile('io.jsonwebtoken:jjwt:0.7.0') | |
runtime('org.springframework.boot:spring-boot-devtools') | |
runtime('mysql:mysql-connector-java') | |
compileOnly('org.projectlombok:lombok') | |
providedRuntime('org.springframework.boot:spring-boot-starter-tomcat') | |
testCompile('org.springframework.boot:spring-boot-starter-test') | |
testCompile('org.springframework.restdocs:spring-restdocs-mockmvc') | |
testCompile('org.springframework.security:spring-security-test') | |
} | |
bootRun { | |
// jvmArgs = [ | |
// '-javaagent:' + projectDir + '/aspectj-1.8.10/lib/aspectjweaver.jar', | |
// '-javaagent:' + projectDir + '/aspectj-1.8.10/lib/aspectjrt.jar', | |
// '-javaagent:' + projectDir + '/lib/spring-instrument.jar' | |
// ] | |
addResources = true | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
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); | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.davidepugliese.springfood; | |
import com.davidepugliese.springfood.security.Acl; | |
import org.aspectj.lang.Aspects; | |
import org.hibernate.SessionFactory; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; | |
import org.springframework.boot.web.servlet.FilterRegistrationBean; | |
import org.springframework.context.annotation.*; | |
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver; | |
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 | |
@EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.ENABLED) | |
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; | |
} | |
@Bean | |
public InstrumentationLoadTimeWeaver loadTimeWeaver() throws Throwable { | |
InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver(); | |
return loadTimeWeaver; | |
} | |
// @Bean | |
// public Acl AclAspect() { | |
// Acl aspect = Aspects.aspectOf(Acl.class); | |
// return aspect; | |
// } | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment