Skip to content

Commit

Permalink
Merge pull request #504 from COS301-SE-2023/frontend/files2
Browse files Browse the repository at this point in the history
Frontend/files2
  • Loading branch information
ChrisMitt authored Oct 16, 2023
2 parents 749edc9 + 89a13cb commit 9fcd6be
Show file tree
Hide file tree
Showing 35 changed files with 690 additions and 222 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,14 @@ public static void main(String[] args) {
//Uncomment the below code if this is your first time use
//This will create an admin role in the system and create your first profile

// @Autowired
// private RoleRepository roleRepository;
@Autowired
private RoleRepository roleRepository;
//
// @Bean
// public CommandLineRunner cr (AuthenticationService service){
// return args -> {
// //Check if it exists
// Role admin = roleRepository.findByRole_name("ADMIN");
//
// //Create role if it doesn't exist
// if (admin == null){
// admin = new Role();
// admin.setRole_Name("ADMIN");
Expand All @@ -51,8 +49,11 @@ public static void main(String[] args) {
// @Bean
// public CommandLineRunner commandLineRunner(AuthenticationService service) {
// return args -> {
// Role adminRole = roleRepository.findByRole_name("ADMIN");
//
// var adminRole = roleRepository.findByRole_name("ADMIN");
// if (adminRole == null) {
// System.err.println("'ADMIN' role not found in the database.");
// return;
// }
// var admin = RegisterRequest.builder()
// .first_name("John")
// .last_name("Smith")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ public class AuthenticationResponse {

@JsonProperty("access_token")
private String accessToken;
@JsonProperty("refresh_token")
private String refreshToken;
private boolean error = false;

public void setError(){
Expand Down
Original file line number Diff line number Diff line change
@@ -1,101 +1,73 @@
package com.fragile.infosafe.primary.auth;

import com.fragile.infosafe.primary.model.Role;
import com.fragile.infosafe.primary.model.User;
import com.fragile.infosafe.primary.repository.RoleRepository;
import com.fragile.infosafe.primary.repository.UserRepository;
import com.fragile.infosafe.primary.requests.RegisterRequest;
import com.fragile.infosafe.primary.config.JwtService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fragile.infosafe.primary.service.EncryptionService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.security.core.AuthenticationException;
import javax.crypto.Cipher;
import org.springframework.security.crypto.codec.Hex;

import java.io.IOException;

@Service
@RequiredArgsConstructor
@Slf4j
public class AuthenticationService {
private final UserRepository repository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
private final AuthenticationManager authenticationManager;
private final RoleRepository roleRepository;
private final EncryptionService encryptionService;

public AuthenticationResponse register(RegisterRequest request) {
var user = User.builder()
.first_name(request.getFirst_name())
.last_name(request.getLast_name())
.email(request.getEmail())
.first_name(encryptionService.encryptString(request.getFirst_name()))
.last_name(encryptionService.encryptString(request.getLast_name()))
.email(encryptionService.encryptString(request.getEmail()))
.password(passwordEncoder.encode(request.getPassword()))
.role(roleRepository.findByRole_name(request.getRole().getRole_name()))
.build();

repository.save(user);
var jwtToken = jwtService.generateToken(user);
var refreshToken = jwtService.generateRefreshToken(user);
return AuthenticationResponse.builder()
.accessToken(jwtToken)
.refreshToken(refreshToken)
.build();
}




public AuthenticationResponse authenticate(AuthenticationRequest request) {
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
request.getEmail(),
encryptionService.encryptString(request.getEmail()),
request.getPassword()
)
);
var user = repository.findByEmail(request.getEmail())
var user = repository.findByEmail(encryptionService.encryptString(request.getEmail()))
.orElseThrow();
log.info(String.valueOf(user));
var jwtToken = jwtService.generateToken(user);
var refreshToken = jwtService.generateRefreshToken(user);

return AuthenticationResponse.builder()
.accessToken(jwtToken)
.refreshToken(refreshToken)
.build();
} catch (AuthenticationException e) {
AuthenticationResponse auth = new AuthenticationResponse();
auth.setError();
return auth;
}
}

public void refreshToken(
HttpServletRequest request,
HttpServletResponse response
) throws IOException {
final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
final String refreshToken;
final String userEmail;
if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
return;
}
refreshToken = authHeader.substring(7);
userEmail = jwtService.extractUsername(refreshToken);
if (userEmail != null) {
var user = this.repository.findByEmail(userEmail)
.orElseThrow();
if (jwtService.isTokenValid(refreshToken, user)) {
var accessToken = jwtService.generateToken(user);
var authResponse = AuthenticationResponse.builder()
.accessToken(accessToken)
.refreshToken(refreshToken)
.build();
new ObjectMapper().writeValue(response.getOutputStream(), authResponse);
}
}
}

}
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package com.fragile.infosafe.primary.config;

import com.fragile.infosafe.primary.repository.UserRepository;
import com.fragile.infosafe.primary.service.AWSSecretService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -12,13 +15,20 @@
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.security.Key;
import java.util.Base64;

@Configuration
@RequiredArgsConstructor
@EnableCaching
@Slf4j
public class ApplicationConfig {
private final UserRepository repository;

Expand Down Expand Up @@ -47,6 +57,10 @@ public PasswordEncoder passwordEncoder() {
}






}


Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.fragile.infosafe.primary.config;

import com.fragile.infosafe.primary.service.EncryptionService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
Expand All @@ -17,12 +18,15 @@
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.crypto.EncryptedPrivateKeyInfo;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

private final JwtService jwtService;
private final UserDetailsService userDetailsService;
private final EncryptionService encryptionService;

@Override
protected void doFilterInternal(
Expand All @@ -42,7 +46,7 @@ protected void doFilterInternal(
return;
}
jwt = authHeader.substring(7);
userEmail = jwtService.extractUsername(jwt);
userEmail = encryptionService.encryptString(jwtService.extractUsername(jwt));
if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
if (jwtService.isTokenValid(jwt, userDetails)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,33 +1,37 @@
package com.fragile.infosafe.primary.config;

import com.fragile.infosafe.primary.service.EncryptionService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.services.controltower.model.EnableControlRequest;

import javax.crypto.Cipher;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Service
@RequiredArgsConstructor
public class JwtService {

private final JwtAWSFetch fetch;
private String cachedSecretKey;

@Autowired
public JwtService(JwtAWSFetch fetch){
this.fetch = fetch;
}
private final int jwtExpiration = 86400000;
private final int refreshExpiration = 604800000;

private final EncryptionService encryptionService;

public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
Expand All @@ -45,26 +49,20 @@ public String generateToken(Map<String, Object> extractClaims, UserDetails userD
return buildToken(extractClaims, userDetails, jwtExpiration);
}

public String generateRefreshToken(
UserDetails userDetails
) {
return buildToken(new HashMap<>(), userDetails, refreshExpiration);
}

private String buildToken(Map<String, Object> extractClaims, UserDetails userDetails, long expiration) {
return Jwts
.builder()
.setClaims(extractClaims)
.setSubject(userDetails.getUsername())
.setSubject(encryptionService.decryptString(userDetails.getUsername()))
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 600 * 24))
.setExpiration(new Date(System.currentTimeMillis() + expiration))
.signWith(getSignInKey(), SignatureAlgorithm.HS256)
.compact();
}

public boolean isTokenValid(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername())) && !isTokenExpired(token);
return (username.equals(encryptionService.decryptString(userDetails.getUsername()))) && !isTokenExpired(token);
}

private boolean isTokenExpired(String token) {
Expand Down Expand Up @@ -92,4 +90,5 @@ public Key getSignInKey() {
byte[] keyBytes = Decoders.BASE64.decode(cachedSecretKey);
return Keys.hmacShaKeyFor(keyBytes);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,14 @@ public ResponseEntity<AuthenticationResponse> authenticate(
return ResponseEntity.ok(service.authenticate(request));
}

@PostMapping("/refresh-token")
public void refreshToken(
HttpServletRequest request,
HttpServletResponse response
) throws IOException {
service.refreshToken(request, response);
}
// @PostMapping("/refresh-token")
// public void refreshToken(
// HttpServletRequest request,
// HttpServletResponse response
// ) throws IOException {
// service.refreshToken(request, response);
// }

@PostMapping("/login")
public ResponseEntity<AuthenticationResponse> login(@RequestBody AuthenticationRequest request) {
AuthenticationResponse response = service.authenticate(request);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,14 @@ public ResponseEntity<List<DataScope>> getAllMyDatascopes(){
return ResponseEntity.badRequest().build();
}

@GetMapping("/getDC/{dataScopeId}")
public ResponseEntity<String> getDataCustodian(@PathVariable int dataScopeId){
return ResponseEntity.ok(service.getDataCustodian(dataScopeId));
}

@GetMapping("/getDSUsersEmails/{dataScopeId}")
public ResponseEntity<List<String>> getDSUsersEmails(@PathVariable int dataScopeId){
return ResponseEntity.ok(service.getAllUsersOfDatascope(dataScopeId));
}

}
Loading

0 comments on commit 9fcd6be

Please sign in to comment.