Skip to content

Commit 3dec2ad

Browse files
committed
Remove unused UUID utility and clean up entity naming
1 parent 2aa02d2 commit 3dec2ad

19 files changed

+134
-134
lines changed

src/docs/subscriptions.adoc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ POST /api/v1/users
1818
[[actions-subscriptions-create]]
1919
=== Create subscriptions
2020

21-
When a user adds a subscriptionEntity to the system, a corresponding `subscriptionEntity` object is fetched or created depending on whether a matching subscriptionEntity is present. A link is then created between the user and the subscriptionEntity.
21+
When a user adds a subscription to the system, a corresponding `subscriptionEntity` object is fetched or created depending on whether a matching subscriptionEntity is present. A link is then created between the user and the subscriptionEntity.
2222

2323
operation::subscriptions-bulk-create-mixed[snippets='request-fields,curl-request,response-fields,http-response']
2424

src/main/java/org/openpodcastapi/opa/auth/ApiAuthController.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import lombok.extern.log4j.Log4j2;
77
import org.openpodcastapi.opa.config.JwtService;
88
import org.openpodcastapi.opa.security.TokenService;
9-
import org.openpodcastapi.opa.user.User;
9+
import org.openpodcastapi.opa.user.UserEntity;
1010
import org.openpodcastapi.opa.user.UserRepository;
1111
import org.springframework.http.ResponseEntity;
1212
import org.springframework.security.authentication.AuthenticationManager;
@@ -38,11 +38,11 @@ public ResponseEntity<AuthDTO.LoginSuccessResponse> login(@RequestBody @NotNull
3838
SecurityContextHolder.getContext().setAuthentication(authentication);
3939

4040
// Fetch the user record from the database
41-
User user = userRepository.findByUsername(loginRequest.username()).orElseThrow(() -> new EntityNotFoundException("No user with username " + loginRequest.username() + " found"));
41+
UserEntity userEntity = userRepository.findByUsername(loginRequest.username()).orElseThrow(() -> new EntityNotFoundException("No userEntity with username " + loginRequest.username() + " found"));
4242

4343
// Generate the access and refresh tokens for the user
44-
String accessToken = tokenService.generateAccessToken(user);
45-
String refreshToken = tokenService.generateRefreshToken(user);
44+
String accessToken = tokenService.generateAccessToken(userEntity);
45+
String refreshToken = tokenService.generateRefreshToken(userEntity);
4646

4747
// Format the tokens and expiration time into a DTO
4848
AuthDTO.LoginSuccessResponse response = new AuthDTO.LoginSuccessResponse(accessToken, refreshToken, String.valueOf(jwtService.getExpirationTime()));
@@ -52,13 +52,13 @@ public ResponseEntity<AuthDTO.LoginSuccessResponse> login(@RequestBody @NotNull
5252

5353
@PostMapping("/api/auth/refresh")
5454
public ResponseEntity<AuthDTO.RefreshTokenResponse> getRefreshToken(@RequestBody @NotNull AuthDTO.RefreshTokenRequest refreshTokenRequest) {
55-
User targetUser = userRepository.findByUsername(refreshTokenRequest.username()).orElseThrow(() -> new EntityNotFoundException("No user with username " + refreshTokenRequest.username() + " found"));
55+
UserEntity targetUserEntity = userRepository.findByUsername(refreshTokenRequest.username()).orElseThrow(() -> new EntityNotFoundException("No user with username " + refreshTokenRequest.username() + " found"));
5656

5757
// Validate the existing refresh token
58-
User user = tokenService.validateRefreshToken(refreshTokenRequest.refreshToken(), targetUser);
58+
UserEntity userEntity = tokenService.validateRefreshToken(refreshTokenRequest.refreshToken(), targetUserEntity);
5959

6060
// Generate new access token
61-
String newAccessToken = tokenService.generateAccessToken(user);
61+
String newAccessToken = tokenService.generateAccessToken(userEntity);
6262

6363
// Format the token and expiration time into a DTO
6464
AuthDTO.RefreshTokenResponse response = new AuthDTO.RefreshTokenResponse(newAccessToken, String.valueOf(jwtService.getExpirationTime()));

src/main/java/org/openpodcastapi/opa/config/JwtAuthenticationFilter.java

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import lombok.RequiredArgsConstructor;
1313
import lombok.extern.log4j.Log4j2;
1414
import org.openpodcastapi.opa.service.CustomUserDetails;
15-
import org.openpodcastapi.opa.user.User;
15+
import org.openpodcastapi.opa.user.UserEntity;
1616
import org.openpodcastapi.opa.user.UserRepository;
1717
import org.springframework.beans.factory.annotation.Value;
1818
import org.springframework.http.HttpHeaders;
@@ -37,17 +37,17 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
3737

3838
/// Returns an authentication token for a user
3939
///
40-
/// @param user the [User] to fetch a token for
40+
/// @param userEntity the [UserEntity] to fetch a token for
4141
/// @return a generated token
4242
/// @throws EntityNotFoundException if no matching user is found
43-
private static UsernamePasswordAuthenticationToken getUsernamePasswordAuthenticationToken(User user) throws EntityNotFoundException {
43+
private static UsernamePasswordAuthenticationToken getUsernamePasswordAuthenticationToken(UserEntity userEntity) throws EntityNotFoundException {
4444
// Create a new CustomUserDetails entity with the fetched user
4545
CustomUserDetails userDetails =
46-
new CustomUserDetails(user.getId(),
47-
user.getUuid(),
48-
user.getUsername(),
49-
user.getPassword(),
50-
user.getUserRoles());
46+
new CustomUserDetails(userEntity.getId(),
47+
userEntity.getUuid(),
48+
userEntity.getUsername(),
49+
userEntity.getPassword(),
50+
userEntity.getUserRoles());
5151

5252
// Return a token for the user
5353
return new UsernamePasswordAuthenticationToken(
@@ -99,10 +99,10 @@ protected void doFilterInternal(HttpServletRequest req, @Nonnull HttpServletResp
9999
UUID parsedUuid = UUID.fromString(userUuid);
100100

101101
// Fetch the matching user
102-
User user = repository.getUserByUuid(parsedUuid).orElseThrow(() -> new EntityNotFoundException("No matching user found"));
102+
UserEntity userEntity = repository.getUserByUuid(parsedUuid).orElseThrow(() -> new EntityNotFoundException("No matching user found"));
103103

104104
// Create a user
105-
UsernamePasswordAuthenticationToken authentication = getUsernamePasswordAuthenticationToken(user);
105+
UsernamePasswordAuthenticationToken authentication = getUsernamePasswordAuthenticationToken(userEntity);
106106

107107
SecurityContextHolder.getContext().setAuthentication(authentication);
108108
} catch (Exception e) {

src/main/java/org/openpodcastapi/opa/security/RefreshToken.java renamed to src/main/java/org/openpodcastapi/opa/security/RefreshTokenEntity.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import jakarta.persistence.*;
44
import lombok.*;
5-
import org.openpodcastapi.opa.user.User;
5+
import org.openpodcastapi.opa.user.UserEntity;
66

77
import java.time.Instant;
88

@@ -12,7 +12,7 @@
1212
@NoArgsConstructor
1313
@AllArgsConstructor
1414
@Builder
15-
public class RefreshToken {
15+
public class RefreshTokenEntity {
1616
@Id
1717
@Generated
1818
@GeneratedValue(strategy = GenerationType.IDENTITY)
@@ -22,7 +22,7 @@ public class RefreshToken {
2222
private String tokenHash;
2323

2424
@ManyToOne(optional = false, fetch = FetchType.LAZY)
25-
private User user;
25+
private UserEntity user;
2626

2727
@Column(nullable = false)
2828
private Instant expiresAt;
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
package org.openpodcastapi.opa.security;
22

3-
import org.openpodcastapi.opa.user.User;
3+
import org.openpodcastapi.opa.user.UserEntity;
44
import org.springframework.data.jpa.repository.JpaRepository;
55
import org.springframework.stereotype.Repository;
66

77
import java.util.List;
88

99
@Repository
10-
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
11-
List<RefreshToken> findAllByUser(User user);
10+
public interface RefreshTokenRepository extends JpaRepository<RefreshTokenEntity, Long> {
11+
List<RefreshTokenEntity> findAllByUser(UserEntity userEntity);
1212
}

src/main/java/org/openpodcastapi/opa/security/TokenService.java

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import io.jsonwebtoken.Jwts;
44
import io.jsonwebtoken.security.Keys;
55
import lombok.RequiredArgsConstructor;
6-
import org.openpodcastapi.opa.user.User;
6+
import org.openpodcastapi.opa.user.UserEntity;
77
import org.springframework.beans.factory.annotation.Value;
88
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
99
import org.springframework.stereotype.Service;
@@ -38,32 +38,32 @@ private SecretKey key() {
3838
return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
3939
}
4040

41-
/// Generates an access token for a given user
41+
/// Generates an access token for a given userEntity
4242
///
43-
/// @param user the [User] to generate a token for
43+
/// @param userEntity the [UserEntity] to generate a token for
4444
/// @return the generated token
45-
public String generateAccessToken(User user) {
45+
public String generateAccessToken(UserEntity userEntity) {
4646
Instant now = Instant.now();
4747
return Jwts.builder()
48-
.subject(user.getUuid().toString())
49-
.claim("username", user.getUsername())
48+
.subject(userEntity.getUuid().toString())
49+
.claim("username", userEntity.getUsername())
5050
.issuedAt(Date.from(now))
5151
.expiration(Date.from(now.plusSeconds(accessTokenMinutes * 60)))
5252
.signWith(key())
5353
.compact();
5454
}
5555

56-
/// Generates a refresh token for a given user
56+
/// Generates a refresh token for a given userEntity
5757
///
58-
/// @param user the [User] to generate a refresh token for
58+
/// @param userEntity the [UserEntity] to generate a refresh token for
5959
/// @return the generated refresh token
60-
public String generateRefreshToken(User user) {
60+
public String generateRefreshToken(UserEntity userEntity) {
6161
String raw = UUID.randomUUID().toString() + UUID.randomUUID();
6262
String hash = passwordEncoder.encode(raw);
6363

64-
RefreshToken token = RefreshToken.builder()
64+
RefreshTokenEntity token = RefreshTokenEntity.builder()
6565
.tokenHash(hash)
66-
.user(user)
66+
.user(userEntity)
6767
.createdAt(Instant.now())
6868
.expiresAt(Instant.now().plusSeconds(refreshTokenDays * 24 * 3600))
6969
.build();
@@ -72,22 +72,22 @@ public String generateRefreshToken(User user) {
7272
return raw;
7373
}
7474

75-
/// Validates the refresh token for a user and updates its expiry time
75+
/// Validates the refresh token for a userEntity and updates its expiry time
7676
///
7777
/// @param rawToken the raw token to validate
78-
/// @param user the [User] to validate the token for
79-
/// @return the validated [User]
80-
public User validateRefreshToken(String rawToken, User user) {
81-
// Only fetch refresh tokens for the requesting user
82-
for (RefreshToken token : repository.findAllByUser(user)) {
78+
/// @param userEntity the [UserEntity] to validate the token for
79+
/// @return the validated [UserEntity]
80+
public UserEntity validateRefreshToken(String rawToken, UserEntity userEntity) {
81+
// Only fetch refresh tokens for the requesting userEntity
82+
for (RefreshTokenEntity token : repository.findAllByUser(userEntity)) {
8383
// Check that the raw token and the token hash match and the token is not expired
8484
if (passwordEncoder.matches(rawToken, token.getTokenHash()) &&
8585
token.getExpiresAt().isAfter(Instant.now())) {
8686
// Update the expiry date on the refresh token
8787
token.setExpiresAt(Instant.now().plusSeconds(refreshTokenDays * 24 * 3600));
88-
RefreshToken updatedToken = repository.save(token);
88+
RefreshTokenEntity updatedToken = repository.save(token);
8989

90-
// Return the user to confirm the token is valid
90+
// Return the userEntity to confirm the token is valid
9191
return updatedToken.getUser();
9292
}
9393
}

src/main/java/org/openpodcastapi/opa/service/CustomUserDetailsService.java

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package org.openpodcastapi.opa.service;
22

33
import lombok.RequiredArgsConstructor;
4-
import org.openpodcastapi.opa.user.User;
4+
import org.openpodcastapi.opa.user.UserEntity;
55
import org.openpodcastapi.opa.user.UserRepository;
66
import org.springframework.security.core.userdetails.UserDetails;
77
import org.springframework.security.core.userdetails.UserDetailsService;
@@ -22,19 +22,19 @@ public class CustomUserDetailsService implements UserDetailsService {
2222
public UserDetails loadUserByUsername(String username) {
2323
return userRepository.getUserByUsername(username)
2424
.map(this::mapToUserDetails)
25-
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
25+
.orElseThrow(() -> new UsernameNotFoundException("UserEntity not found"));
2626
}
2727

2828
/// Maps a user to a custom user details model
2929
///
30-
/// @param user the user model to map
31-
private CustomUserDetails mapToUserDetails(User user) {
30+
/// @param userEntity the [UserEntity] model to map
31+
private CustomUserDetails mapToUserDetails(UserEntity userEntity) {
3232
return new CustomUserDetails(
33-
user.getId(),
34-
user.getUuid(),
35-
user.getUsername(),
36-
user.getPassword(),
37-
user.getUserRoles()
33+
userEntity.getId(),
34+
userEntity.getUuid(),
35+
userEntity.getUsername(),
36+
userEntity.getPassword(),
37+
userEntity.getUserRoles()
3838
);
3939
}
4040

src/main/java/org/openpodcastapi/opa/subscription/SubscriptionRestController.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@
2222
public class SubscriptionRestController {
2323
private final SubscriptionService service;
2424

25-
/// Returns all subscriptions for a given user
25+
/// Returns all subscriptions for a given userEntity
2626
///
27-
/// @param user the [CustomUserDetails] of the authenticated user
27+
/// @param user the [CustomUserDetails] of the authenticated userEntity
2828
/// @param pageable the [Pageable] pagination object
2929
/// @param includeUnsubscribed whether to include unsubscribed feeds in the response
3030
/// @return a paginated list of subscriptions
@@ -67,7 +67,7 @@ public ResponseEntity<SubscriptionDTO.UserSubscriptionDTO> getSubscriptionByUuid
6767
return new ResponseEntity<>(dto, HttpStatus.OK);
6868
}
6969

70-
/// Updates the subscriptionEntity status of a subscriptionEntity for a given user
70+
/// Updates the subscriptionEntity status of a subscriptionEntity for a given userEntity
7171
///
7272
/// @param uuid the UUID of the subscriptionEntity to update
7373
/// @return the updated subscriptionEntity entity
@@ -86,7 +86,7 @@ public ResponseEntity<SubscriptionDTO.UserSubscriptionDTO> unsubscribeUserFromFe
8686
return new ResponseEntity<>(dto, HttpStatus.OK);
8787
}
8888

89-
/// Bulk creates UserSubscriptions for a user. Creates new SubscriptionEntity objects if not already present
89+
/// Bulk creates UserSubscriptions for a userEntity. Creates new SubscriptionEntity objects if not already present
9090
///
9191
/// @param request a list of [SubscriptionDTO.SubscriptionCreateDTO] objects
9292
/// @return a [SubscriptionDTO.BulkSubscriptionResponseDTO] object

0 commit comments

Comments
 (0)