Skip to content
This repository was archived by the owner on Apr 5, 2024. It is now read-only.

Commit bfb66bc

Browse files
authored
Find User Api (#19)
* Wrote Steps. * Fixed advises, added basic exception and advise * Changed response messages, fixed feature files * Implemented logic for finding users. Fixed some exceptions. * Wrote Unit tests, added comment. * Added missed Unit Test
1 parent 9e645be commit bfb66bc

20 files changed

+264
-98
lines changed

src/main/java/de/filefighter/rest/configuration/PrepareDataBase.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ CommandLineRunner initUserDataBaseProd(UserRepository repository) {
7272
.builder()
7373
.userId(0L)
7474
.username("admin")
75+
.lowercaseUsername("admin")
7576
.password("admin")
7677
.refreshToken("refreshToken1234")
7778
.groupIds(new long[]{0, 1})
@@ -90,6 +91,7 @@ CommandLineRunner initUserDataBaseDev(UserRepository repository) {
9091
.builder()
9192
.userId(0)
9293
.username("user")
94+
.lowercaseUsername("user")
9395
.password("1234")
9496
.refreshToken("rft1234")
9597
.groupIds(new long[]{0})
@@ -98,6 +100,7 @@ CommandLineRunner initUserDataBaseDev(UserRepository repository) {
98100
.builder()
99101
.userId(1)
100102
.username("user1")
103+
.lowercaseUsername("user1")
101104
.password("12345")
102105
.refreshToken("rft")
103106
.groupIds(new long[]{-1})

src/main/java/de/filefighter/rest/domain/token/business/AccessTokenBusinessService.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import de.filefighter.rest.domain.token.exceptions.AccessTokenNotFoundException;
77
import de.filefighter.rest.domain.user.data.dto.User;
88
import de.filefighter.rest.domain.user.exceptions.UserNotAuthenticatedException;
9+
import de.filefighter.rest.rest.exceptions.RequestDidntMeetFormalRequirementsException;
910
import org.springframework.stereotype.Service;
1011

1112
import java.time.Instant;
@@ -59,7 +60,7 @@ public AccessToken getValidAccessTokenForUser(User user) {
5960

6061
public AccessToken findAccessTokenByValueAndUserId(String accessTokenValue, long userId) {
6162
if (!stringIsValid(accessTokenValue))
62-
throw new IllegalArgumentException("Value of AccessToken was not valid.");
63+
throw new RequestDidntMeetFormalRequirementsException("Value of AccessToken was not valid.");
6364

6465
AccessTokenEntity accessTokenEntity = accessTokenRepository.findByUserIdAndValue(userId, accessTokenValue);
6566
if (null == accessTokenEntity)
@@ -68,13 +69,24 @@ public AccessToken findAccessTokenByValueAndUserId(String accessTokenValue, long
6869
return accessTokenDtoService.createDto(accessTokenEntity);
6970
}
7071

72+
public AccessToken findAccessTokenByValue(String accessTokenValue) {
73+
if (!stringIsValid(accessTokenValue))
74+
throw new RequestDidntMeetFormalRequirementsException("Value of AccessToken was not valid.");
75+
76+
AccessTokenEntity accessTokenEntity = accessTokenRepository.findByValue(accessTokenValue);
77+
if (null == accessTokenEntity)
78+
throw new UserNotAuthenticatedException("AccessToken not found.");
79+
80+
return accessTokenDtoService.createDto(accessTokenEntity);
81+
}
82+
7183
public String generateRandomTokenValue() {
7284
return UUID.randomUUID().toString();
7385
}
7486

7587
public String checkBearerHeader(String accessTokenValue) {
7688
if (!accessTokenValue.matches("^" + AUTHORIZATION_BEARER_PREFIX + "[^\\s](.*)$"))
77-
throw new UserNotAuthenticatedException("Header does not contain '" + AUTHORIZATION_BEARER_PREFIX + "', or format is invalid.");
89+
throw new RequestDidntMeetFormalRequirementsException("Header does not contain '" + AUTHORIZATION_BEARER_PREFIX + "', or format is invalid.");
7890
return accessTokenValue.split(AUTHORIZATION_BEARER_PREFIX)[1];
7991
}
8092
}

src/main/java/de/filefighter/rest/domain/token/exceptions/AccessTokenNotFoundAdvise.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public class AccessTokenNotFoundAdvise {
1717
@ResponseStatus(HttpStatus.BAD_REQUEST)
1818

1919
ResponseEntity<ServerResponse> tokenNotFoundAdvise(AccessTokenNotFoundException ex) {
20-
LoggerFactory.getLogger(UserAlreadyExistsAdvise.class).warn(ex.getMessage());
20+
LoggerFactory.getLogger(AccessTokenNotFoundException.class).warn(ex.getMessage());
2121
return new ResponseEntity<>(new ServerResponse("denied", ex.getMessage()), HttpStatus.BAD_REQUEST);
2222
}
2323
}

src/main/java/de/filefighter/rest/domain/user/business/UserBusinessService.java

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import de.filefighter.rest.domain.user.data.persistance.UserRepository;
88
import de.filefighter.rest.domain.user.exceptions.UserNotAuthenticatedException;
99
import de.filefighter.rest.domain.user.exceptions.UserNotFoundException;
10+
import de.filefighter.rest.rest.exceptions.RequestDidntMeetFormalRequirementsException;
1011
import org.slf4j.Logger;
1112
import org.slf4j.LoggerFactory;
1213
import org.springframework.stereotype.Service;
@@ -39,11 +40,11 @@ public long getUserCount() {
3940

4041
public User getUserByUsernameAndPassword(String base64encodedUserAndPasswordWithHeaderPrefix) {
4142
if (!stringIsValid(base64encodedUserAndPasswordWithHeaderPrefix))
42-
throw new UserNotAuthenticatedException("Header was empty.");
43+
throw new RequestDidntMeetFormalRequirementsException("Header was empty.");
4344

4445
//TODO: maybe filter unsupported characters?
4546
if (!base64encodedUserAndPasswordWithHeaderPrefix.matches("^" + AUTHORIZATION_BASIC_PREFIX + "[^\\s](.*)$"))
46-
throw new UserNotAuthenticatedException("Header does not contain '" + AUTHORIZATION_BASIC_PREFIX + "', or format is invalid.");
47+
throw new RequestDidntMeetFormalRequirementsException("Header does not contain '" + AUTHORIZATION_BASIC_PREFIX + "', or format is invalid.");
4748

4849
String[] split = base64encodedUserAndPasswordWithHeaderPrefix.split(AUTHORIZATION_BASIC_PREFIX);
4950

@@ -60,22 +61,22 @@ public User getUserByUsernameAndPassword(String base64encodedUserAndPasswordWith
6061
split = decodedUsernameUndPassword.strip().split(":");
6162

6263
if (split.length != 2)
63-
throw new UserNotAuthenticatedException("Credentials didnt meet formal requirements.");
64+
throw new RequestDidntMeetFormalRequirementsException("Credentials didnt meet formal requirements.");
6465

6566
String username = split[0];
6667
String password = split[1];
6768

6869
UserEntity userEntity = userRepository.findByUsernameAndPassword(username, password);
6970
if (null == userEntity)
70-
throw new UserNotFoundException("No User found with this username and password.");
71+
throw new UserNotAuthenticatedException("No User found with this username and password.");
7172

7273
return userDtoService.createDto(userEntity);
7374
}
7475

7576
public RefreshToken getRefreshTokenForUser(User user) {
7677
UserEntity userEntity = userRepository.findByUserIdAndUsername(user.getId(), user.getUsername());
7778
if (null == userEntity)
78-
throw new UserNotFoundException();
79+
throw new UserNotAuthenticatedException(user.getId());
7980

8081
String refreshTokenValue = userEntity.getRefreshToken();
8182

@@ -91,11 +92,11 @@ public RefreshToken getRefreshTokenForUser(User user) {
9192

9293
public User getUserByRefreshTokenAndUserId(String refreshToken, long userId) {
9394
if (!stringIsValid(refreshToken))
94-
throw new UserNotAuthenticatedException("RefreshToken was not valid.");
95+
throw new RequestDidntMeetFormalRequirementsException("RefreshToken was not valid.");
9596

9697
UserEntity userEntity = userRepository.findByRefreshTokenAndUserId(refreshToken, userId);
9798
if (null == userEntity)
98-
throw new UserNotFoundException(userId);
99+
throw new UserNotAuthenticatedException(userId);
99100

100101
return userDtoService.createDto(userEntity);
101102
}
@@ -110,4 +111,17 @@ public User getUserByAccessTokenAndUserId(AccessToken accessToken, long userId)
110111

111112
return userDtoService.createDto(userEntity);
112113
}
114+
115+
public User findUserByUsername(String username) {
116+
if (!stringIsValid(username))
117+
throw new RequestDidntMeetFormalRequirementsException("Username was not valid.");
118+
119+
String lowercaseUsername = username.toLowerCase().replace(" ","");
120+
121+
UserEntity entity = userRepository.findByLowercaseUsername(lowercaseUsername);
122+
if (null == entity)
123+
throw new UserNotFoundException("User with username '" + username + "' not found.");
124+
125+
return userDtoService.createDto(entity);
126+
}
113127
}
Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,24 @@
11
package de.filefighter.rest.domain.user.data.persistance;
22

33
import lombok.Builder;
4-
import lombok.Data;
4+
import lombok.Getter;
5+
import lombok.ToString;
56
import org.springframework.data.mongodb.core.mapping.Document;
67
import org.springframework.data.mongodb.core.mapping.MongoId;
78

89
@Document(collection = "user")
9-
@Data
10+
@Getter
11+
@ToString
1012
@Builder
1113
public class UserEntity {
1214

1315
@MongoId
14-
private String _id;
15-
private long userId;
16-
private String username;
17-
private String password;
18-
private String refreshToken; //TODO: add valid_until for refreshToken
19-
private long[] groupIds;
16+
private final String _id;
17+
private final long userId;
18+
private final String username;
19+
private final String lowercaseUsername; // Redundancy for performance tradeoff.
20+
private final String password;
21+
private final String refreshToken; //TODO: add valid_until for refreshToken
22+
private final long[] groupIds;
2023

2124
}

src/main/java/de/filefighter/rest/domain/user/data/persistance/UserRepository.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@ public interface UserRepository extends MongoRepository<UserEntity, String> {
99
UserEntity findByUsernameAndPassword(String username, String password);
1010
UserEntity findByRefreshTokenAndUserId(String refreshToken, long userId);
1111
UserEntity findByUserId(long userId);
12+
UserEntity findByLowercaseUsername(String lowercaseUsername);
1213
}

src/main/java/de/filefighter/rest/domain/user/exceptions/UserAlreadyExistsAdvise.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public class UserAlreadyExistsAdvise {
1616
@ResponseStatus(HttpStatus.BAD_REQUEST)
1717

1818
ResponseEntity<ServerResponse> userAlreadyExistsAdvise(UserAlreadyExistsException ex) {
19-
LoggerFactory.getLogger(UserAlreadyExistsAdvise.class).warn(ex.getMessage());
19+
LoggerFactory.getLogger(UserAlreadyExistsException.class).warn(ex.getMessage());
2020
return new ResponseEntity<>(new ServerResponse("denied", ex.getMessage()), HttpStatus.BAD_REQUEST);
2121
}
2222
}

src/main/java/de/filefighter/rest/domain/user/exceptions/UserNotAuthenticatedAdvise.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public class UserNotAuthenticatedAdvise {
1616
@ExceptionHandler(UserNotAuthenticatedException.class)
1717
@ResponseStatus(HttpStatus.UNAUTHORIZED)
1818
ResponseEntity<ServerResponse> userNotAuthenticatedHandler(UserNotAuthenticatedException ex) {
19-
LoggerFactory.getLogger(UserAlreadyExistsAdvise.class).warn(ex.getMessage());
19+
LoggerFactory.getLogger(UserNotAuthenticatedException.class).warn(ex.getMessage());
2020
return new ResponseEntity<>(new ServerResponse("denied", ex.getMessage()), HttpStatus.UNAUTHORIZED);
2121
}
2222
}

src/main/java/de/filefighter/rest/domain/user/exceptions/UserNotAuthenticatedException.java

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,6 @@ public UserNotAuthenticatedException(String reason){
55
super("User could not be authenticated. "+reason);
66
}
77

8-
// public UserNotAuthenticatedException() {
9-
// super("User could not be authenticated.");
10-
// }
11-
128
public UserNotAuthenticatedException(long id){
139
super("User with the id "+id+" could not be authenticated.");
1410
}

src/main/java/de/filefighter/rest/domain/user/exceptions/UserNotFoundAdvice.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class UserNotFoundAdvice {
1616
@ExceptionHandler(UserNotFoundException.class)
1717
@ResponseStatus(HttpStatus.NOT_FOUND)
1818
ResponseEntity<ServerResponse> userNotFoundHandler(UserNotFoundException ex) {
19-
LoggerFactory.getLogger(UserAlreadyExistsAdvise.class).warn(ex.getMessage());
20-
return new ResponseEntity<>(new ServerResponse("denied", ex.getMessage()), HttpStatus.NOT_FOUND);
19+
LoggerFactory.getLogger(UserNotFoundException.class).warn(ex.getMessage());
20+
return new ResponseEntity<>(new ServerResponse("not found", ex.getMessage()), HttpStatus.NOT_FOUND);
2121
}
2222
}

0 commit comments

Comments
 (0)