Skip to content

Commit

Permalink
Modified logs
Browse files Browse the repository at this point in the history
  • Loading branch information
yasasghari committed Mar 1, 2024
1 parent 7834264 commit f54b4eb
Show file tree
Hide file tree
Showing 9 changed files with 85 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,23 +77,20 @@ public ResponseEntity<Object> handleApplicationStatus(@RequestHeader("Authorizat
//IP address of the machine requesting to set/update application status.
String IP = request.getRemoteAddr();

String jwtToken = header.replace("Bearer ", "");
System.out.println("token" + jwtToken);
//Error messages in case of an invalid person_id or an invalid status or an invalid JWT token.
String jwtTokenErrorMessage = jwtAuthService.jwtAuth(header);
String personIdErrorMessage = applicationStatusService.isPersonIdValid(applicationStatusDTO.getPerson_id());
String statusErrorMessage = applicationStatusService.isStatusValid(applicationStatusDTO.getStatus());

//Validation process to make sure person_id and status received is correct.
if ("UNAUTHORIZED".equals(jwtTokenErrorMessage)) {
System.out.println("token invalid");
logger.error("The person with IP address: {} has unauthorized access with the provided JWT token ", IP);
logger.warn("The person with IP address: {} has unauthorized access with the provided JWT token ", IP);
return new ResponseEntity<>(new ErrorDTO(jwtTokenErrorMessage), HttpStatus.BAD_REQUEST);
} else if ("INVALID_DATA".equals(personIdErrorMessage)) {
logger.error("The person with IP address: {} submitted an invalid person Id: {} ", IP, applicationStatusDTO.getPerson_id());
logger.warn("The person with IP address: {} submitted an invalid person Id: {} ", IP, applicationStatusDTO.getPerson_id());
return new ResponseEntity<>(new ErrorDTO(personIdErrorMessage), HttpStatus.BAD_REQUEST);
} else if ("INVALID_DATA".equals(statusErrorMessage)) {
logger.error("The person with IP address: {} submitted an invalid status: {} ", IP, applicationStatusDTO.getStatus());
logger.warn("The person with IP address: {} submitted an invalid status: {} ", IP, applicationStatusDTO.getStatus());
return new ResponseEntity<>(new ErrorDTO(statusErrorMessage), HttpStatus.BAD_REQUEST);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.example.applicationstatusservice.exception;

import com.example.applicationstatusservice.model.dto.ErrorDTO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
Expand All @@ -9,22 +11,25 @@
/**
* This is an exception handler class with the annotation
* {@code @ControllerAdvice} that can handle various types of
* exceptions, returning specific ErrorDTO's and HTTP responses.
* exceptions, returning specific ErrorDTO and HTTP status response.
*/

@ControllerAdvice
public class ExceptionHandler {

/**
* Logger to log errors caught by the Exception handler.
*/
private static final Logger logger = LogManager.getLogger(ExceptionHandler.class);


/**
* Method for handling exception.
*
* @return a response entity with the appropriate ErrorDTO and HTTP status
* @return a response entity with the appropriate ErrorDTO and HTTP status.
*/

@org.springframework.web.bind.annotation.ExceptionHandler({Exception.class})
public ResponseEntity<Object> handleExceptions() {
public ResponseEntity<Object> handleExceptions(Exception e) {
logger.error("Log Exception caught: {}", e.getMessage());
return new ResponseEntity<>(new ErrorDTO("UNKNOWN"), HttpStatus.BAD_REQUEST);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,11 @@ public void updateApplicationStatus(ApplicationStatusDTO applicationStatusDTO) {
if (checkApplicationStatus != null) {
checkApplicationStatus.setStatus(status);
applicationStatusRepository.save(checkApplicationStatus);
logger.info("The status of the application for person Id: {} has been updated to status: {} ", applicationStatusDTO.getPerson_id(), applicationStatusDTO.getStatus());
logger.debug("The status of the application for person Id: {} has been updated to status: {} ", applicationStatusDTO.getPerson_id(), applicationStatusDTO.getStatus());
} else if (person != null) {
ApplicationStatus applicationStatus = ApplicationStatus.builder().person(person).status(applicationStatusDTO.getStatus()).build();
applicationStatusRepository.save(applicationStatus);
logger.info("A new application status for person Id: {} has been set to status: {} ", applicationStatusDTO.getPerson_id(), applicationStatusDTO.getStatus());
logger.debug("A new application status for person Id: {} has been set to status: {} ", applicationStatusDTO.getPerson_id(), applicationStatusDTO.getStatus());
}
}

Expand All @@ -85,10 +85,10 @@ public String isPersonIdValid(Long personId) {
boolean isPersonIdValid = personRepository.existsById(personId);
logger.debug("Check if person Id: {} exists: {} ", personId, isPersonIdValid);
if (isPersonIdValid) {
logger.info("Person Id: {} exists ", personId);
logger.debug("Person Id: {} exists ", personId);
return "VALID_DATA";
}
logger.error("Person Id: {} does not exists ", personId);
logger.debug("Person Id: {} does not exists ", personId);
return "INVALID_DATA";
}

Expand All @@ -100,7 +100,7 @@ public String isPersonIdValid(Long personId) {
* @return a response string indicating either a valid or an invalid status.
*/
public String isStatusValid(String status) {
logger.info("Check to see if status: {} is valid", status);
logger.debug("Check to see if status: {} is valid", status);
return switch (status) {
case "Accept", "Reject", "Pending" -> "VALID_DATA";
default -> "INVALID_DATA";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,27 +48,34 @@ public String jwtAuth(String header) {
Claims claims = parseJwtClaims.getBody();
Integer roleValue = claims.get("role", Integer.class);
if (roleValue != null && roleValue.equals(1)) {
System.out.println("role 1");
logger.info("Authorized user");
logger.debug("Authorized user");
return "AUTHORIZED";
} else {
logger.info("Unauthorized user");
System.out.println("role isnt 1");
logger.debug("Unauthorized user");
return "UNAUTHORIZED";
}
} catch (Exception e) {
System.out.println("deep shit");
return "UNAUTHORIZED";
}
}

/**
* Creates JWT tokens to use during integration testing.
* Creates JWT tokens to use during integration testing with recruiter role.
*
* @return JWT tokens encoded using HS256 algorithm.
*/
public String jwtCreateTestTokens() {
public String jwtCreateTestTokensRecruiter() {
SecretKeySpec keyTest = new SecretKeySpec(JWT_SECRET.getBytes(), SignatureAlgorithm.HS256.getJcaName());
return Jwts.builder().claim("usage", "login").claim("id", 5).claim("username", "MaxwellBailey").claim("role", 1).signWith(keyTest).compact();
}

/**
* Creates JWT tokens to use during integration testing with applicant role.
*
* @return JWT tokens encoded using HS256 algorithm.
*/
public String jwtCreateTestTokensApplicant() {
SecretKeySpec keyTest = new SecretKeySpec(JWT_SECRET.getBytes(), SignatureAlgorithm.HS256.getJcaName());
return Jwts.builder().claim("usage", "login").claim("id", 5).claim("username", "MaxwellBailey").claim("role", 2).signWith(keyTest).compact();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@ public PersonService(PersonRepository personRepository) {
public void saveApplicant(PersonDTO personDTO) {
Person person = Person.builder().name(personDTO.getName()).surname(personDTO.getSurname()).pnr(personDTO.getPnr()).email(personDTO.getEmail()).password(personDTO.getPassword()).role_id(2).username(personDTO.getUsername()).build();
personRepository.save(person);
logger.info("A new person has registered with username: {}", personDTO.getUsername());
logger.debug("A new person has registered with username: {}", personDTO.getUsername());
}
}
8 changes: 6 additions & 2 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@ spring.datasource.password=Qwerty123456!
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.show-sql=true
spring.sql.init.mode=always
logging.level.org.hibernate.SQL=DEBUG
spring.jpa.hibernate.ddl-auto=update
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
logging.level.org.springframework.security=DEBUG
server.error.include-message=always
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.max-active=3
logging.level.root=INFO
logging.level.org.springframework.security=WARN
logging.level.org.hibernate.SQL=WARN






7 changes: 7 additions & 0 deletions src/main/resources/log4j.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
log4j.rootLogger=INFO, stdout

# Log messages show in console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,9 @@ void saveAPerson() {
void personIdValid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");
String testToken = jwtAuthService.jwtCreateTestTokens();
String testToken = jwtAuthService.jwtCreateTestTokensRecruiter();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(5L, "Pending");
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(6L, "Pending");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
}
Expand All @@ -129,7 +129,7 @@ void personIdValid() throws Exception {
void personIdInvalid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");
String testToken = jwtAuthService.jwtCreateTestTokens();
String testToken = jwtAuthService.jwtCreateTestTokensRecruiter();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(4000L, "Pending");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
Expand All @@ -143,9 +143,9 @@ void personIdInvalid() throws Exception {
void statusPendingValid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");
String testToken = jwtAuthService.jwtCreateTestTokens();
String testToken = jwtAuthService.jwtCreateTestTokensRecruiter();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(9L, "Pending");
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(10L, "Pending");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
}
Expand All @@ -157,7 +157,7 @@ void statusPendingValid() throws Exception {
void statusAcceptValid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");
String testToken = jwtAuthService.jwtCreateTestTokens();
String testToken = jwtAuthService.jwtCreateTestTokensRecruiter();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(1L, "Accept");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
Expand All @@ -171,7 +171,7 @@ void statusAcceptValid() throws Exception {
void statusRejectValid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");
String testToken = jwtAuthService.jwtCreateTestTokens();
String testToken = jwtAuthService.jwtCreateTestTokensRecruiter();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(3L, "Reject");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
Expand All @@ -185,7 +185,7 @@ void statusRejectValid() throws Exception {
void statusInvalid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");
String testToken = jwtAuthService.jwtCreateTestTokens();
String testToken = jwtAuthService.jwtCreateTestTokensRecruiter();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(4L, "random");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
Expand All @@ -199,14 +199,29 @@ void statusInvalid() throws Exception {
void jwtTokenValid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");
String testToken = jwtAuthService.jwtCreateTestTokens();
String testToken = jwtAuthService.jwtCreateTestTokensRecruiter();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(6L, "Pending");
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(7L, "Pending");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.OK, resp.getStatusCode());

}

/**
* JUnit test to check if an invalid JWT token containing wrong role id returns the correct HTTP Status response.
*/
@Test
void jwtTokenInvalidRole() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");
String testToken = jwtAuthService.jwtCreateTestTokensApplicant();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(6L, "Pending");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.BAD_REQUEST, resp.getStatusCode());

}

/**
* JUnit test to check if an invalid JWT token returns the correct HTTP Status response.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ void saveAPerson() {
*/
@Test
void personIdValid() throws Exception {
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(5L, "Pending");
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(6L, "Pending");
assertEquals("VALID_DATA", applicationStatusService.isPersonIdValid(applicationStatusDTO.getPerson_id()));

}
Expand Down Expand Up @@ -172,11 +172,21 @@ void statusInvalid() throws Exception {
*/
@Test
void jwtTokenValid() throws Exception {
String testToken = jwtAuthService.jwtCreateTestTokens();
String testToken = jwtAuthService.jwtCreateTestTokensRecruiter();
String testHeader = "Bearer " + testToken;
assertEquals("AUTHORIZED", jwtAuthService.jwtAuth(testHeader));
}

/**
* JUnit test to check if a valid JWT token returns the correct response message from the service-layer.
*/
@Test
void jwtTokenInvalidRole() throws Exception {
String testToken = jwtAuthService.jwtCreateTestTokensApplicant();
String testHeader = "Bearer " + testToken;
assertEquals("UNAUTHORIZED", jwtAuthService.jwtAuth(testHeader));
}

/**
* JUnit test to check if an invalid JWT token returns the correct response message from the service-layer.
*/
Expand Down

0 comments on commit f54b4eb

Please sign in to comment.