Skip to content

Commit

Permalink
Synchronize users by account name (#248)
Browse files Browse the repository at this point in the history
  • Loading branch information
boavenn authored Oct 22, 2024
1 parent 28aff99 commit 211df5b
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ protected void doFilterInternal(HttpServletRequest request,
private Authentication getAuthenticationForUser(User user,
HttpServletResponse response) {
try{
var principal = user.getPrincipalName();
var accountName = user.getAccountName();
var authorities = userAuthoritiesProvider.getAuthoritiesFromUser(user);
return new UsernamePasswordAuthenticationToken(principal, null, authorities);
return new UsernamePasswordAuthenticationToken(accountName, null, authorities);
}catch (InvalidTokenException | NoSuchUserException exception){
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
@RequiredArgsConstructor
@ConditionalOnProperty(name = "ad.configuration.enabled", havingValue = "true", matchIfMissing = true)
public class JwtFilter extends OncePerRequestFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(OncePerRequestFilter.class);
private static final Logger LOGGER = LoggerFactory.getLogger(JwtFilter.class);

private final JwtTokenValidator jwtTokenValidator;

@Override
Expand All @@ -36,20 +37,20 @@ protected void doFilterInternal(HttpServletRequest request,
return;
}
var authResult = getAuthenticationByToken(header, response);
if (authResult != null){
if (authResult != null) {
SecurityContextHolder.getContext().setAuthentication(authResult);
chain.doFilter(request, response);
}
}
private Authentication getAuthenticationByToken(String header,
HttpServletResponse response) {
try{

private Authentication getAuthenticationByToken(String header, HttpServletResponse response) {
try {
var accessToken = jwtTokenValidator.validateAuthorizationHeader(header);
var accountName = accessToken.getAccountName();
var authorities = accessToken.getAuthorities();
return new UsernamePasswordAuthenticationToken(accountName, null, authorities);
}catch (InvalidTokenException | NoSuchUserException exception){
LOGGER.warn("Invalid authentication token", exception);
} catch (InvalidTokenException | NoSuchUserException exception) {
LOGGER.warn("Error when authenticating user", exception);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ public static JsonObject decodeTokenPayloadToJsonObject(DecodedJWT decodedJWT) {
public static String getAccountNameFromDecodedToken(DecodedJWT decodedToken) {
var payloadAsJson = decodeTokenPayloadToJsonObject(decodedToken);
var principal = payloadAsJson.getAsJsonPrimitive(PRINCIPAL_KEY).getAsString();
return principal.substring(0, principal.indexOf("@"));
return principal.contains("@") ? principal.substring(0, principal.indexOf("@")) : principal;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
@RequiredArgsConstructor
@ConditionalOnProperty(name = "ad.configuration.enabled", havingValue = "true", matchIfMissing = true)
public class ActiveDirectoryUserSynchronizer {

private static final Logger LOGGER = LoggerFactory.getLogger(ActiveDirectoryUserSynchronizer.class);

private final UserRepository userRepository;
Expand All @@ -32,11 +31,10 @@ public class ActiveDirectoryUserSynchronizer {
private final ActiveDirectoryUserMapperWrapper userMapper;
private final AutomaticVacationDayService automaticVacationDayService;


public void addNewUsers() {
var dbUsers = userRepository.findAllPrincipalNames();
var dbUsers = userRepository.findAllAccountNames();
pickUsersFromActiveDirectory().stream()
.filter(user -> !dbUsers.contains(ActiveDirectoryUtils.pickAttribute(user, Attribute.PRINCIPAL_NAME)))
.filter(user -> !dbUsers.contains(ActiveDirectoryUtils.pickAttribute(user, Attribute.ACCOUNT_NAME)))
.map(userMapper::mapNewUser)
.forEach(this::saveNewUser);
LOGGER.info("Synchronisation succeed: find new users");
Expand All @@ -52,23 +50,23 @@ private void saveNewUser(User user) {
}

public void deactivateDeletedUsers() {
var adUsers = pickUsersFromActiveDirectory().stream()
.map(user -> ActiveDirectoryUtils.pickAttribute(user, Attribute.PRINCIPAL_NAME))
var existingAccountNames = pickUsersFromActiveDirectory().stream()
.map(user -> ActiveDirectoryUtils.pickAttribute(user, Attribute.ACCOUNT_NAME))
.toList();

userRepository.findAll().stream()
.filter(user -> !adUsers.contains(user.getPrincipalName()))
.filter(user -> !existingAccountNames.contains(user.getAccountName()))
.forEach(this::deactivateUser);
LOGGER.info("Synchronisation succeed: deactivate deleted users");
}

public void deactivateDisabledUsers() {
var disabledUsers = pickDisabledUsersFromActiveDirectory().stream()
.map(user -> ActiveDirectoryUtils.pickAttribute(user, Attribute.PRINCIPAL_NAME))
var disabledAccountNames = pickDisabledUsersFromActiveDirectory().stream()
.map(user -> ActiveDirectoryUtils.pickAttribute(user, Attribute.ACCOUNT_NAME))
.toList();

userRepository.findAll().stream()
.filter(user -> disabledUsers.contains(user.getPrincipalName()))
.filter(user -> disabledAccountNames.contains(user.getAccountName()))
.forEach(this::deactivateUser);
LOGGER.info("Synchronisation succeed: deactivate disabled users");
}
Expand All @@ -91,9 +89,9 @@ public void synchronizeFull() {

private void synchronize(Stream<SearchResult> adUsers) {
adUsers.forEach(adUser -> {
var principalName = ActiveDirectoryUtils.pickAttribute(adUser, Attribute.PRINCIPAL_NAME);
var accountName = ActiveDirectoryUtils.pickAttribute(adUser, Attribute.ACCOUNT_NAME);
userRepository
.findFirstByPrincipalName(principalName)
.findFirstByAccountName(accountName)
.map(user -> userMapper.updateUser(adUser, user))
.ifPresent(userRepository::save);
});
Expand Down
6 changes: 2 additions & 4 deletions src/main/java/info/fingo/urlopia/user/UserRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@ public interface UserRepository extends BaseRepository<User>, JpaRepository<User

Optional<User> findFirstByAdName(String adName);

Optional<User> findFirstByFirstNameAndLastName(String firstName, String lastName);

@Query("SELECT u.principalName FROM User u")
List<String> findAllPrincipalNames();
@Query("SELECT u.accountName FROM User u")
List<String> findAllAccountNames();

@Query("SELECT u FROM User u WHERE u.admin = true")
List<User> findAdmins();
Expand Down

0 comments on commit 211df5b

Please sign in to comment.