Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GAP-2510: Fixing errors caused by setting last updated fields on grant adverts #254

Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -70,19 +70,21 @@ public GrantAdvert save(GrantAdvert advert) {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Optional.ofNullable(auth)
.ifPresentOrElse(authentication -> {
final AdminSession adminSession = (AdminSession) authentication.getPrincipal();
final GrantAdmin admin = grantAdminRepository.findByGapUserUserSub(adminSession.getUserSub())
.orElseThrow(() -> new UserNotFoundException("Could not find an admin with sub " + adminSession.getUserSub()));
if (!HelperUtils.isAnonymousSession()) {
final AdminSession adminSession = (AdminSession) authentication.getPrincipal();
final GrantAdmin admin = grantAdminRepository.findByGapUserUserSub(adminSession.getUserSub())
.orElseThrow(() -> new UserNotFoundException("Could not find an admin with sub " + adminSession.getUserSub()));

if (advert.getScheme().getGrantAdmins().contains(admin)) {
final Instant updatedAt = Instant.now(clock);
advert.setLastUpdated(updatedAt);
advert.setLastUpdatedBy(admin);
if (advert.getScheme().getGrantAdmins().contains(admin)) {
final Instant updatedAt = Instant.now(clock);
advert.setLastUpdated(updatedAt);
advert.setLastUpdatedBy(admin);

advert.getScheme().setLastUpdated(updatedAt);
advert.getScheme().setLastUpdatedBy(adminSession.getGrantAdminId());
advert.getScheme().setLastUpdated(updatedAt);
advert.getScheme().setLastUpdatedBy(adminSession.getGrantAdminId());

advert.setValidLastUpdated(true);
advert.setValidLastUpdated(true);
}
}
}, () -> log.warn("Admin session was null. Update must have been performed by a lambda."));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,22 @@
import com.fasterxml.jackson.databind.json.JsonMapper;
import gov.cabinetoffice.gap.adminbackend.exceptions.UnauthorizedException;
import gov.cabinetoffice.gap.adminbackend.models.AdminSession;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;

public class HelperUtils {

public static final String ROLE_ANONYMOUS = "ROLE_ANONYMOUS";

/**
* Used to generate a safely encoded URL, incl. any query params This method will
* auto-remove any query params where the value is null, to prevent empty request
Expand Down Expand Up @@ -88,4 +93,21 @@ public static String getJwtFromCookies(final HttpServletRequest request, final S
return userServiceToken.getValue();
}


/**
* Verifies whether a session is anonymous in spring security or not.
*
* Useful method to have because some of our lambdas use encrypted headers to bypass spring security.
* @return
*/
public static boolean isAnonymousSession() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(authentication -> authentication.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.toList())
.orElse(Collections.emptyList())
.stream()
.anyMatch(auth -> auth.equals(ROLE_ANONYMOUS));
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,38 @@
package gov.cabinetoffice.gap.adminbackend.utils;

import gov.cabinetoffice.gap.adminbackend.models.AdminSession;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import static gov.cabinetoffice.gap.adminbackend.testdata.SchemeTestData.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

class HelperUtilsTest {

@Mock
private Authentication auth;

@Mock
private SecurityContext context;

@Test
void buildUrlWithNoParamsTest() {
String builtUrl = HelperUtils.buildUrl("testHost", "testPath", null);
Expand Down Expand Up @@ -43,4 +66,46 @@ void parseJsonExpectedHappyTest() {
+ "\",\"contactEmail\":\"" + SAMPLE_SCHEME_CONTACT + "\",\"lastUpdatedByADeletedUser\":false}");
}

@Test
void isAnonymousSession_ReturnsTrueIfAnonymousSession() {

Authentication auth = Mockito.mock(Authentication.class);
SecurityContext context = mock(SecurityContext.class);

try (MockedStatic<SecurityContextHolder> securityContextHolder = Mockito.mockStatic(SecurityContextHolder.class)) {
securityContextHolder.when(SecurityContextHolder::getContext).thenReturn(context);

final GrantedAuthority role = new SimpleGrantedAuthority("ROLE_ANONYMOUS");

when(context.getAuthentication())
.thenReturn(auth);

when(auth.getAuthorities())
.thenReturn((Collection) List.of(role));

assertThat(HelperUtils.isAnonymousSession()).isTrue();
}
}

@Test
void isAnonymousSession_ReturnsFalseIfIdNotAnonymousSession() {

Authentication auth = Mockito.mock(Authentication.class);
SecurityContext context = mock(SecurityContext.class);

try (MockedStatic<SecurityContextHolder> securityContextHolder = Mockito.mockStatic(SecurityContextHolder.class)) {
securityContextHolder.when(SecurityContextHolder::getContext).thenReturn(context);

final GrantedAuthority role = new SimpleGrantedAuthority("ROLE_ADMIN");

when(context.getAuthentication())
.thenReturn(auth);

when(auth.getAuthorities())
.thenReturn((Collection) List.of(role));

assertThat(HelperUtils.isAnonymousSession()).isFalse();
}
}

}
Loading