Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
18 changes: 18 additions & 0 deletions src/main/java/org/commons/login/UserId.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.commons.login;

import lombok.NonNull;

public class UserId {
private String userId;

public UserId(@NonNull final String userId) {
if (userId.isEmpty()) throw new IllegalArgumentException("userId is empty");

this.userId = userId;
}

@Override
public String toString() {
return this.userId;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
if (authorization != null && authorization.startsWith("Bearer ")) {
String token = authorization.substring(7);
try {
String login = this.jwtService.extractLogin(token);
if (login != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(login);
String userId = this.jwtService.extractUserId(token);
if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userId);

if (this.jwtService.validateToken(token)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package pl.milosnicyit.codewarehousebackend.jwt;

import lombok.NonNull;
import org.commons.login.Username;
import org.commons.login.UserId;
import pl.milosnicyit.codewarehousebackend.jwt.secret.JWTSecretService;

class AppJwtService implements JWTService {
Expand All @@ -12,13 +12,13 @@ public AppJwtService(@NonNull final JWTSecretService jwtSecretService) {
}

@Override
public String generateToken(@NonNull String username) {
return this.jwtBasicService.generateToken(new Username(username));
public String generateToken(@NonNull String userId) {
return this.jwtBasicService.generateToken(new UserId(userId));
}

@Override
public String extractLogin(@NonNull String token) {
return this.jwtBasicService.extractLogin(token).toString();
public String extractUserId(@NonNull String token) {
return this.jwtBasicService.extractUserId(token).toString();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import lombok.NonNull;

public interface JWTService {
String generateToken(@NonNull final String username);
String generateToken(@NonNull final String userId);

String extractLogin(@NonNull final String token);
String extractUserId(@NonNull final String token);

boolean validateToken(@NonNull final String jwtToken);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.NonNull;
import org.commons.login.UserId;
import org.commons.login.Username;
import pl.milosnicyit.codewarehousebackend.jwt.secret.JWTSecretService;

Expand All @@ -18,24 +19,24 @@ public JwtBasicService(JWTSecretService jwtSecretService) {
this.jwtSecretService = jwtSecretService;
}

public String generateToken(@NonNull final Username username) {
public String generateToken(@NonNull final UserId userId) {
return Jwts.builder()
.subject(username.toString())
.subject(userId.toString())
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + 86400000)) // 1 day
.signWith(getSigningKey())
.compact();
}

public Username extractLogin(@NonNull final String token) {
public UserId extractUserId(@NonNull final String token) {
final String subject = Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload()
.getSubject();

return new Username(subject);
return new UserId(subject);
}

public boolean validateToken(@NonNull final String jwtToken) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ public String registerUser(@NonNull final String username, @NonNull final String
userDTO.setPassword(this.passwordEncoderService.encode(password));

if (this.userRepositoryWrapper.save(userDTO)) {
return this.jwtService.generateToken(username);
UserDTO newUserDTO = this.userRepositoryWrapper.findByUsername(username);

if (newUserDTO != null) {
return this.jwtService.generateToken(newUserDTO.getId());
}
}
return null;
}
Expand All @@ -44,6 +48,6 @@ public String loginUser(@NonNull final String username, @NonNull final String ra
throw new BadCredentialsException("Bad credentials");
}

return this.jwtService.generateToken(userDTO.getUsername());
return this.jwtService.generateToken(userDTO.getId());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
@Table(name = "users")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private long id;
@GeneratedValue(strategy = GenerationType.UUID)
@Column(name = "user_id", unique = true, nullable = false)
private String id;

@Column(name = "username", nullable = false, unique = true)
private String username;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
@AllArgsConstructor
@NoArgsConstructor
public class UserDTO {
private long id;
private String id;
private String username;
private String password;
}
38 changes: 38 additions & 0 deletions src/test/java/org/commons/login/UserIdTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package org.commons.login;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class UserIdTest {

@Test
@DisplayName("Should create UserId when valid string is provided")
void shouldCreateUserId() {
String expectedValue = "user-123";

UserId userId = new UserId(expectedValue);

assertThat(userId.toString()).isEqualTo(expectedValue);
}

@Test
@DisplayName("Should throw NullPointerException when userId is null")
void shouldThrowExceptionWhenNull() {
assertThatThrownBy(() -> new UserId(null))
.isInstanceOf(NullPointerException.class);
}

@ParameterizedTest
@ValueSource(strings = {"", " ", " "})
@DisplayName("Should throw IllegalArgumentException when userId is empty or blank")
void shouldThrowExceptionWhenEmpty(String emptyValue) {
assertThatThrownBy(() -> new UserId(emptyValue.trim()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("userId is empty");
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package pl.milosnicyit.codewarehousebackend.jwt;

import org.commons.login.UserId;
import org.commons.login.Username;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand All @@ -25,7 +26,7 @@ class AppJwtServiceTest {
void shouldDelegateGenerateToken() {
try (MockedConstruction<JwtBasicService> mockedConstruction = Mockito.mockConstruction(JwtBasicService.class,
(mock, context) -> {
when(mock.generateToken(any(Username.class))).thenReturn("mocked_token");
when(mock.generateToken(any(UserId.class))).thenReturn("mocked_token");
})) {

AppJwtService appJwtService = new AppJwtService(jwtSecretService);
Expand All @@ -45,12 +46,12 @@ void shouldDelegateExtractLogin() {
// given
try (MockedConstruction<JwtBasicService> mockedConstruction = Mockito.mockConstruction(JwtBasicService.class,
(mock, context) -> {
when(mock.extractLogin("some_token")).thenReturn(new Username("extractedUser"));
when(mock.extractUserId("some_token")).thenReturn(new UserId("extractedUser"));
})) {

AppJwtService appJwtService = new AppJwtService(jwtSecretService);

String result = appJwtService.extractLogin("some_token");
String result = appJwtService.extractUserId("some_token");

assertEquals("extractedUser", result);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package pl.milosnicyit.codewarehousebackend.jwt;

import org.commons.login.UserId;
import org.commons.login.Username;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -30,10 +31,10 @@ void setUp() {

@Test
void shouldGenerateValidToken() {
Username username = mock(Username.class);
when(username.toString()).thenReturn(TEST_USERNAME);
UserId userId = mock(UserId.class);
when(userId.toString()).thenReturn(TEST_USERNAME);

String token = jwtBasicService.generateToken(username);
String token = jwtBasicService.generateToken(userId);

assertNotNull(token);
assertFalse(token.isEmpty());
Expand All @@ -42,22 +43,22 @@ void shouldGenerateValidToken() {

@Test
void shouldExtractLoginFromToken() {
Username mockUsername = mock(Username.class);
when(mockUsername.toString()).thenReturn(TEST_USERNAME);
UserId userId = mock(UserId.class);
when(userId.toString()).thenReturn(TEST_USERNAME);

String generatedToken = jwtBasicService.generateToken(mockUsername);
String generatedToken = jwtBasicService.generateToken(userId);

Username extractedUsername = jwtBasicService.extractLogin(generatedToken);
UserId extractedUserId = jwtBasicService.extractUserId(generatedToken);

assertNotNull(extractedUsername);
assertEquals(TEST_USERNAME, extractedUsername.toString());
assertNotNull(extractedUserId);
assertEquals(TEST_USERNAME, extractedUserId.toString());
}

@Test
void shouldReturnTrueWhenTokenIsValid() {
Username mockUsername = mock(Username.class);
when(mockUsername.toString()).thenReturn(TEST_USERNAME);
String generatedToken = jwtBasicService.generateToken(mockUsername);
UserId userId = mock(UserId.class);
when(userId.toString()).thenReturn(TEST_USERNAME);
String generatedToken = jwtBasicService.generateToken(userId);

boolean isValid = jwtBasicService.validateToken(generatedToken);

Expand All @@ -66,10 +67,9 @@ void shouldReturnTrueWhenTokenIsValid() {

@Test
void shouldReturnFalseWhenTokenIsTampered() {
// given
Username mockUsername = mock(Username.class);
when(mockUsername.toString()).thenReturn(TEST_USERNAME);
String generatedToken = jwtBasicService.generateToken(mockUsername);
UserId userId = mock(UserId.class);
when(userId.toString()).thenReturn(TEST_USERNAME);
String generatedToken = jwtBasicService.generateToken(userId);

String tamperedToken = generatedToken.substring(0, generatedToken.length() - 3) + "BAD";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,14 @@ void shouldRegisterUserAndReturnTokenWhenDataIsCorrect() {
String rawPassword = "secretPasswodddddddddddddddddddddddd";
String encodedPassword = "encodedPassword123";
String expectedToken = "jwt.token.here";
String userId = "aaa";

when(userRepositoryWrapper.existsByUsername(username)).thenReturn(false);
when(passwordEncoderService.encode(any(Password.class))).thenReturn(encodedPassword);
when(userRepositoryWrapper.save(any(UserDTO.class))).thenReturn(true);
when(jwtService.generateToken(username)).thenReturn(expectedToken);
when(userRepositoryWrapper.findByUsername(any(String.class))).thenReturn(new UserDTO(userId, username,
encodedPassword));
when(jwtService.generateToken(userId)).thenReturn(expectedToken);

String result = userAppService.registerUser(username, rawPassword);

Expand Down Expand Up @@ -92,24 +95,26 @@ void shouldReturnNullWhenDatabaseSaveFails() {

@Test
void shouldLoginUserAndReturnTokenWhenCredentialsAreCorrect() {
String userId = "ddddddd";
String username = "existingUser";
String rawPassword = "correctPassword123";
String encodedPasswordInDb = "encodedHash";
String expectedToken = "valid.jwt.token";

UserDTO userDTO = new UserDTO();
userDTO.setId(userId);
userDTO.setUsername(username);
userDTO.setPassword(encodedPasswordInDb);

when(userRepositoryWrapper.findByUsername(username)).thenReturn(userDTO);
when(passwordEncoderService.matches(any(Password.class), eq(encodedPasswordInDb))).thenReturn(true);
when(jwtService.generateToken(username)).thenReturn(expectedToken);
when(jwtService.generateToken(userId)).thenReturn(expectedToken);

String result = userAppService.loginUser(username, rawPassword);

assertEquals(expectedToken, result);
verify(passwordEncoderService).matches(any(Password.class), eq(encodedPasswordInDb));
verify(jwtService).generateToken(username);
verify(jwtService).generateToken(userId);
}

@Test
Expand Down
Loading