Skip to content

Commit

Permalink
feat: jwt after login (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
izaiasmachado authored Mar 1, 2024
1 parent 08cd60e commit 90909c2
Show file tree
Hide file tree
Showing 13 changed files with 234 additions and 34 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ MANDACARU_POSTGRES_PASSWORD=mandacaru
# Change value to "never" for production environment
MANDACARU_SQL_INIT_MODE=always
MANDACARU_API_PORT=8080
MANDACARU_JWT_SECRET=mandacaru-jwt-secret

# Integration test environment
MANDACARU_TEST_POSTGRES_HOST=127.0.0.1
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ jobs:
MANDACARU_POSTGRES_USER: "time_dez"
MANDACARU_POSTGRES_PASSWORD: "mandacaru"
MANDACARU_POSTGRES_PORT: 5432
MANDACARU_JWT_SECRET: mandacaru-jwt-secret
MANDACARU_TEST_POSTGRES_DB: "mandacaru_broker_test"
MANDACARU_TEST_POSTGRES_USER: "time_dez_test"
MANDACARU_TEST_POSTGRES_PASSWORD: "mandacaru"
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ jobs:
MANDACARU_POSTGRES_USER: "time_dez"
MANDACARU_POSTGRES_PASSWORD: "mandacaru"
MANDACARU_POSTGRES_PORT: 5432
MANDACARU_JWT_SECRET: mandacaru-jwt-secret
MANDACARU_TEST_POSTGRES_DB: "mandacaru_broker_test"
MANDACARU_TEST_POSTGRES_USER: "time_dez_test"
MANDACARU_TEST_POSTGRES_PASSWORD: "mandacaru"
Expand Down
7 changes: 6 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<java.version>17</java.version>
<sonar.organization>mandacaru-broker</sonar.organization>
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
<powermock.version>2.0.2</powermock.version>
</properties>
<dependencies>
<dependency>
Expand Down Expand Up @@ -70,6 +71,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
Expand All @@ -88,7 +94,6 @@
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
Expand Down
10 changes: 5 additions & 5 deletions src/main/java/com/mandacarubroker/controller/AuthController.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.mandacarubroker.controller;

import com.mandacarubroker.domain.auth.RequestAuthUserDTO;
import com.mandacarubroker.domain.user.User;
import com.mandacarubroker.domain.auth.ResponseAuthUserDTO;
import com.mandacarubroker.service.AuthService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
Expand All @@ -23,13 +23,13 @@ public AuthController(final AuthService receivedAuthService) {
}

@PostMapping("/login")
public ResponseEntity<String> login(@Valid @RequestBody final RequestAuthUserDTO requestAuthUserDTO) {
Optional<User> user = authService.login(requestAuthUserDTO);
public ResponseEntity<ResponseAuthUserDTO> login(@Valid @RequestBody final RequestAuthUserDTO requestAuthUserDTO) {
Optional<ResponseAuthUserDTO> responseAuthUserDTO = authService.login(requestAuthUserDTO);

if (user.isEmpty()) {
if (responseAuthUserDTO.isEmpty()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}

return ResponseEntity.ok("User logged in successfully");
return ResponseEntity.ok(responseAuthUserDTO.orElseThrow());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.mandacarubroker.domain.auth;

public record ResponseAuthUserDTO(
String token,
int expiresIn,
String tokenType
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.mandacarubroker.security;

public class MissingSecuritySecretException extends RuntimeException {
public MissingSecuritySecretException(final String message) {
super("Missing security secret: " + message);
}
}
16 changes: 16 additions & 0 deletions src/main/java/com/mandacarubroker/security/SecuritySecrets.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.mandacarubroker.security;

public final class SecuritySecrets {
private SecuritySecrets() {
}

public static String getJWTSecret() {
final String secret = System.getenv("MANDACARU_JWT_SECRET");

if (secret == null) {
throw new MissingSecuritySecretException("JWT secret not found");
}

return secret;
}
}
25 changes: 21 additions & 4 deletions src/main/java/com/mandacarubroker/service/AuthService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.mandacarubroker.service;

import com.mandacarubroker.domain.auth.RequestAuthUserDTO;
import com.mandacarubroker.domain.auth.ResponseAuthUserDTO;
import com.mandacarubroker.domain.user.User;
import com.mandacarubroker.domain.user.UserRepository;
import org.springframework.stereotype.Service;
Expand All @@ -12,13 +13,29 @@
@Service
public class AuthService {
private final UserRepository userRepository;
private final PasswordHashingService passwordHashingService = new PasswordHashingService();

public AuthService(final UserRepository receivedUserRepository) {
this.userRepository = receivedUserRepository;
private final PasswordHashingService passwordHashingService;
private final TokenService tokenService;

public AuthService(final UserRepository receivedUserRepostory, final PasswordHashingService receivedPasswordHashingService, final TokenService receivedTokenService) {
this.userRepository = receivedUserRepostory;
this.passwordHashingService = receivedPasswordHashingService;
this.tokenService = receivedTokenService;
}

public Optional<ResponseAuthUserDTO> login(final RequestAuthUserDTO requestAuthUserDTO) {
Optional<User> user = getUserGivenCredentials(requestAuthUserDTO);

if (user.isEmpty()) {
return Optional.empty();
}

String userId = user.get().getId();
ResponseAuthUserDTO responseAuthUserDTO = tokenService.encodeToken(userId);
return Optional.of(responseAuthUserDTO);
}

public Optional<User> login(final RequestAuthUserDTO requestAuthUserDTO) {
public Optional<User> getUserGivenCredentials(final RequestAuthUserDTO requestAuthUserDTO) {
validateRequestDTO(requestAuthUserDTO);

User user = userRepository.findByUsername(requestAuthUserDTO.username());
Expand Down
63 changes: 63 additions & 0 deletions src/main/java/com/mandacarubroker/service/TokenService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.mandacarubroker.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.mandacarubroker.domain.auth.ResponseAuthUserDTO;
import com.mandacarubroker.security.SecuritySecrets;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TokenService {
private static final String TOKEN_ISSUER = "mandacaru-broker";
private static final int EXPIRATION_TIME = 864 * 1000 * 1000;
private static final int EXPIRATION_TIME_IN_SECONDS = EXPIRATION_TIME / 1000;
private static final String TOKEN_TYPE = "Bearer";
private final Algorithm algorithm;

public TokenService() {
String secret = SecuritySecrets.getJWTSecret();
algorithm = Algorithm.HMAC512(secret.getBytes());
}

public ResponseAuthUserDTO encodeToken(final String subject) {
try {
return tryToEncodeToken(subject);
} catch (JWTCreationException exception) {
return null;
}
}

private ResponseAuthUserDTO tryToEncodeToken(final String subject) {
Date expirationDate = new Date(System.currentTimeMillis() + EXPIRATION_TIME);

String generatedToken = JWT.create()
.withSubject(subject)
.withIssuer(TOKEN_ISSUER)
.withExpiresAt(expirationDate)
.sign(algorithm);

String tokenWithPrefix = TOKEN_TYPE + " " + generatedToken;
return new ResponseAuthUserDTO(tokenWithPrefix, EXPIRATION_TIME_IN_SECONDS, TOKEN_TYPE);
}

public String getTokenSubject(final String token) {
DecodedJWT decodedToken = decodeUserToken(token);
return decodedToken.getSubject();
}

public DecodedJWT decodeUserToken(final String token) {
try {
return tryToDecodeUserToken(token);
} catch (Exception exception) {
return null;
}
}

private DecodedJWT tryToDecodeUserToken(final String token) {
return JWT.require(algorithm).build().verify(token);
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package com.mandacarubroker.controller;

import com.mandacarubroker.domain.auth.RequestAuthUserDTO;
import com.mandacarubroker.domain.auth.ResponseAuthUserDTO;
import com.mandacarubroker.domain.user.RequestUserDTO;
import com.mandacarubroker.domain.user.User;
import com.mandacarubroker.security.SecuritySecretsMock;
import com.mandacarubroker.service.AuthService;
import com.mandacarubroker.service.PasswordHashingService;
import org.junit.jupiter.api.BeforeEach;
Expand All @@ -22,6 +23,8 @@ class AuthControllerTest {
private AuthService authService;
private AuthController authController;

private static final String TOKEN_TYPE = "Bearer";

private final PasswordHashingService passwordHashingService = new PasswordHashingService();

private final String validEmail = "[email protected]";
Expand Down Expand Up @@ -50,21 +53,31 @@ class AuthControllerTest {
validPassword
);

private final ResponseAuthUserDTO validResponseAuthUserDTO = new ResponseAuthUserDTO(
"Bearer token",
86400,
"Bearer"
);

@BeforeEach
void setUp() {
SecuritySecretsMock.mockStatic();

authService = Mockito.mock(AuthService.class);
User validUser = new User(validRequestUserDTO);
Optional<User> optionalValidUser = Optional.of(validUser);
Mockito.when(authService.login(validRequestAuthUserDTO)).thenReturn(optionalValidUser);
Mockito.when(authService.login(validRequestAuthUserDTO)).thenReturn(Optional.of(validResponseAuthUserDTO));
Mockito.when(authService.login(new RequestAuthUserDTO(invalidUsername, validPassword))).thenReturn(Optional.empty());
Mockito.when(authService.login(new RequestAuthUserDTO(validUsername, invalidPassword))).thenReturn(Optional.empty());
authController = new AuthController(authService);
}

@Test
void itShouldBeAbleToLoginWithValidUser() {
ResponseEntity<String> response = authController.login(validRequestAuthUserDTO);
assertEquals(ResponseEntity.ok("User logged in successfully"), response);
ResponseEntity<ResponseAuthUserDTO> response = authController.login(validRequestAuthUserDTO);
ResponseAuthUserDTO responseAuthUserDTO = response.getBody();

assertEquals(ResponseEntity.ok().build().getStatusCode(), response.getStatusCode());
assertEquals(ResponseAuthUserDTO.class, responseAuthUserDTO.getClass());
assertEquals(TOKEN_TYPE, responseAuthUserDTO.tokenType());
}

@Test
Expand All @@ -74,7 +87,7 @@ void itShouldNotBeAbleToLoginWithInvalidUser() {
validPassword
);

ResponseEntity<String> response = authController.login(invalidRequestAuthUserDTO);
ResponseEntity<ResponseAuthUserDTO> response = authController.login(invalidRequestAuthUserDTO);
assertEquals(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(), response);
}

Expand All @@ -85,7 +98,7 @@ void itShouldNotBeAbleToLoginWithInvalidPassword() {
invalidPassword
);

ResponseEntity<String> response = authController.login(invalidRequestAuthUserDTO);
ResponseEntity<ResponseAuthUserDTO> response = authController.login(invalidRequestAuthUserDTO);
assertEquals(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(), response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.mandacarubroker.security;

import org.mockito.MockedStatic;
import org.mockito.Mockito;

public final class SecuritySecretsMock {
private static MockedStatic<SecuritySecrets> securitySecretsMockedStatic = null;

private SecuritySecretsMock() {
}

public static void mockStatic() {
if (securitySecretsMockedStatic != null) {
return;
}

securitySecretsMockedStatic = Mockito.mockStatic(SecuritySecrets.class);
securitySecretsMockedStatic.when(SecuritySecrets::getJWTSecret).thenReturn("secret");
}
}
Loading

0 comments on commit 90909c2

Please sign in to comment.