Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Auth Security #25

Merged
merged 23 commits into from
Apr 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
65 changes: 46 additions & 19 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,39 +17,39 @@ ext {
}


/*implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
implementation 'org.springframework.boot:spring-boot-starter-webflux'
implementation 'org.springframework.session:spring-session-jdbc'

//runtime "com.h2database:h2"
runtime "org.grails.plugins:asset-pipeline"
runtime "mysql:mysql-connector-java:5.1.37"
runtimeOnly 'mysql:mysql-connector-java'

testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'
testImplementation 'org.testcontainers:junit-jupiter'
/*

compile group: 'javax.persistence', name: 'persistence-api', version: '1.0'
compile "org.springframework.boot:spring-boot-starter-data-jpa"
compile "org.springframework.boot:spring-boot-starter-web"
compile "mysql:mysql-connector-java"

// implementation "org.springframework.security.oauth:spring-security-oauth2"
// implementation 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure'
// implementation "org.springframework.security:spring-security-jwt"

testCompile "org.springframework.boot:spring-boot-starter-test"*/

*/

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.apache.httpcomponents:httpclient'
// Actuator (Mapping and Health)
implementation 'org.springframework.boot:spring-boot-starter-actuator'

runtimeOnly 'mysql:mysql-connector-java'
//test
testImplementation 'org.springframework.boot:spring-boot-starter-test'
//testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'org.apache.httpcomponents:httpclient'
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'junit:junit'

compile "com.google.guava:guava:28.1-jre"

//security
implementation "org.springframework.boot:spring-boot-starter-oauth2-client"
implementation "org.springframework.boot:spring-boot-starter-security"
// jwt
compile "io.jsonwebtoken:jjwt:0.9.0"

}

dependencyManagement {
Expand All @@ -61,3 +61,30 @@ dependencyManagement {
test {
useJUnitPlatform()
}


/*
// BACKUP

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-web'
// Actuator (Mapping and Health)
implementation 'org.springframework.boot:spring-boot-starter-actuator'

runtimeOnly 'mysql:mysql-connector-java'
//test
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.apache.httpcomponents:httpclient'
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'junit:junit'

compile "com.google.guava:guava:28.1-jre"

//security
implementation "org.springframework.boot:spring-boot-starter-oauth2-client"
implementation "org.springframework.boot:spring-boot-starter-security"
// jwt
compile "io.jsonwebtoken:jjwt:0.9.0"

*/
31 changes: 0 additions & 31 deletions src/main/java/com/partycipate/Partycipate/config/CorsFilter.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.partycipate.Partycipate.config;

import com.partycipate.Partycipate.security.jwt.JwtAuthEntryPoint;
import com.partycipate.Partycipate.security.jwt.JwtAuthTokenFilter;
import com.partycipate.Partycipate.security.services.UserDetailsServiceImpl;
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.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired private UserDetailsServiceImpl userDetailsService;
@Autowired private JwtAuthEntryPoint unauthorizedHandler;

@Bean
public JwtAuthTokenFilter authenticationJwtTokenFilter(){
return new JwtAuthTokenFilter();
}

@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception{
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());

}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception{
return super.authenticationManagerBean();
}

@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}

@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package com.partycipate.Partycipate.controller;

import com.partycipate.Partycipate.model.Role;
import com.partycipate.Partycipate.model.RoleName;
import com.partycipate.Partycipate.model.User;
import com.partycipate.Partycipate.repository.RoleRepository;
import com.partycipate.Partycipate.repository.UserRepository;
import com.partycipate.Partycipate.security.jwt.JwtProvider;
import com.partycipate.Partycipate.security.message.request.LoginForm;
import com.partycipate.Partycipate.security.message.request.SignUpForm;
import com.partycipate.Partycipate.security.message.response.JwtResponse;
import com.partycipate.Partycipate.security.message.response.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.Set;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController {

@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtProvider jwtProvider;

@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@RequestBody LoginForm loginRequest){
//ToDo Check password and username, email with RegEx
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
);
SecurityContextHolder.getContext().setAuthentication(authentication);

String jwt = jwtProvider.generateJwtToken(authentication);
UserDetails userDetails = (UserDetails) authentication.getPrincipal();

//ToDo (optional) extend authenication or principal to SetName into response
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getUsername(), userDetails.getAuthorities()));
}

@PutMapping("/signup")
public ResponseEntity<?> registerUser(@RequestBody SignUpForm signUpRequest){
if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))){
return new ResponseEntity<>(new ResponseMessage("Fail -> Email is aleady in use!"), HttpStatus.BAD_REQUEST);
}

//creating user account
User user = new User.Builder().username(signUpRequest.getUsername()).email(signUpRequest.getEmail()).password(encoder.encode(signUpRequest.getPassword())).build();
Set<String> strRoles = signUpRequest.getRole();
Set<Role> roles = new HashSet<>();

strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Fail -> Cause : Admin User Role not found."));
roles.add(adminRole);
break;
case "pm":
Role pmRole = roleRepository.findByName(RoleName.ROLE_PM)
.orElseThrow(() -> new RuntimeException("Fail -> PM User Role not found"));
roles.add(pmRole);
break;
default:
Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Fail -> User Role not found"));
roles.add(userRole);
}
});
user.setRoles(roles);
userRepository.save(user);

return new ResponseEntity<>(new ResponseMessage("User Registered successfully!"), HttpStatus.OK);
}

}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,12 @@
import com.partycipate.Partycipate.service.SurveyElementService;
import com.partycipate.Partycipate.service.SurveyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;


@RestController
@RequestMapping("/api/survey")
@CrossOrigin(origins = "*")
public class SurveyController {

@Autowired
Expand All @@ -28,43 +25,38 @@ public SurveyController(SurveyService surveyService, SurveyElementService survey
this.surveyElementService = surveyElementService;
}


// addSurvey
@PostMapping("")
public int addSurvey(@RequestBody SendSurvey survey){
int id = surveyService.addSurvey(survey).getId();
System.out.println("id: " + id);
return id;
}


//getAll
// getAll
@GetMapping("")
public @ResponseBody Iterable<Survey> getAllSurveys(){
return surveyService.getAllSurveys();
}

//getById
// getById
@GetMapping("/{id}")
@CrossOrigin(origins = "*")
public Survey getSurvey(@PathVariable("id") int id){
return surveyService.getSurvey(id);
}



//deleteById
// deleteById
@DeleteMapping("/{id}")
public int deleteSurveybyId(@PathVariable("id") int id){

surveyService.deleteSurveybyId(id);
return id;
}

//addSurveyElement
// addSurveyElement
@PostMapping("/element")
public int addSurveyElement(@RequestBody SendElement sendElement){
return 0;
}

return 0;
}

}
Loading