Skip to content

Commit

Permalink
PO-827: Add authorisation to draft account POST endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
RustyHMCTS committed Oct 16, 2024
1 parent 1a73278 commit 4047007
Show file tree
Hide file tree
Showing 16 changed files with 249 additions and 157 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public void postDraftAccountWithInvalidToken() throws JSONException {
JSONObject postBody = new JSONObject();

postBody.put("business_unit_id", "77");
postBody.put("account", "{\"accountCreateRequest\":{\"Defendant\":{},\"Account\":{}}}");
postBody.put("account", "{\"account_create_request\":{\"defendant\":{},\"account\":{}}}");
postBody.put("account_type", "Fine");
postBody.put("account_status", "");
postBody.put("submitted_by", "BUUID");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"accountCreateRequest": {
"Defendant": {},
"Account": {}
"account_create_request": {
"defendant": {},
"account": {}
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"accountCreateRequest": {
"Defendant": {
"Surname": "LNAME",
"Forenames": "FNAME",
"DOB": "01/01/2000"
"account_create_request": {
"defendant": {
"surname": "LNAME",
"forenames": "FNAME",
"dob": "01/01/2000"
},
"Account": {
"AccountType": "Fine"
"account": {
"account_type": "Fine"
}
}
}

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import uk.gov.hmcts.opal.authorisation.model.UserState;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
Expand All @@ -16,9 +17,14 @@ public static final UserState noPermissionsUser() {
return UserState.builder()
.userId(999L)
.userName("no-permissions@users.com")
.businessUnitUser(Collections.emptySet())
.build();
}

public static final UserState allPermissionsUser() {
return new UserState.DeveloperUserState();
}

public static final UserState permissionUser(Short buid, Permissions... permissions) {
return UserState.builder()
.userId(1L)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class PermissionNotAllowedException extends RuntimeException {
private final BusinessUnitUser businessUnitUser;

public PermissionNotAllowedException(Permissions... value) {
super(Arrays.toString(value) + " permission(s) are not allowed for the user");
super(Arrays.toString(value) + " permission(s) are not allowed for the user.");
this.permission = value;
this.businessUnitUser = null;
}
Expand All @@ -27,7 +27,7 @@ public PermissionNotAllowedException(Collection<Short> buIds, Permissions... val

public PermissionNotAllowedException(Permissions permission,
BusinessUnitUser businessUnitUser) {
super(permission + " permission is not allowed for the business unit user "
super(permission + " permission is not allowed for the business unit user: "
+ businessUnitUser.getBusinessUnitUserId());
this.permission = new Permissions[] {permission};
this.businessUnitUser = businessUnitUser;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,18 +142,19 @@ public ResponseEntity<List<DraftAccountResponseDto>> postDraftAccountsSearch(
@CheckAcceptHeader
public ResponseEntity<DraftAccountResponseDto> postDraftAccount(@RequestBody AddDraftAccountRequestDto dto,
@RequestHeader(value = "Authorization", required = false) String authHeaderValue) {
log.info(":POST:postDraftAccount: creating a new draft account entity.");
log.info(":POST:postDraftAccount: creating a new draft account entity: \n{}", dto.toPrettyJson());

userStateService.checkForAuthorisedUser(authHeaderValue);




jsonSchemaValidationService.validateOrError(dto.toJson(), ADD_DRAFT_ACCOUNT_REQUEST_JSON);
UserState userState = userStateService.checkForAuthorisedUser(authHeaderValue);

DraftAccountEntity response = draftAccountService.submitDraftAccount(dto);
if (userState.hasBusinessUnitUserWithPermission(dto.getBusinessUnitId(),
Permissions.CREATE_MANAGE_DRAFT_ACCOUNTS)) {
jsonSchemaValidationService.validateOrError(dto.toJson(), ADD_DRAFT_ACCOUNT_REQUEST_JSON);

return buildCreatedResponse(toGetResponseDto(response));
DraftAccountEntity response = draftAccountService.submitDraftAccount(dto);
return buildCreatedResponse(toGetResponseDto(response));
} else {
throw new PermissionNotAllowedException(Permissions.CREATE_MANAGE_DRAFT_ACCOUNTS);
}
}

@Hidden
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ public ResponseEntity<String> handlePermissionNotAllowedException(Exception ex,
HttpServletRequest request) {
String authorization = request.getHeader(AUTH_HEADER);
String preferredName = extractPreferredUsername(authorization, tokenService);
String message = String.format("{\"error\": \"Forbidden\", \"message\" : \"For user %s, %s \"}", preferredName,
String message = String.format("{\"error\": \"Forbidden\", \"message\" : \"For user %s, %s\"}", preferredName,
ex.getMessage());
log.error(message);
log.error(":handlePermissionNotAllowedException: {}", message);
return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON).body(message);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import uk.gov.hmcts.opal.util.KeepAsJsonDeserializer;

import java.time.OffsetDateTime;
Expand All @@ -29,6 +30,7 @@ public class AddDraftAccountRequestDto implements ToJsonString, DraftAccountRequ
private OffsetDateTime validatedDate;

@JsonProperty(value = "business_unit_id", required = true)
@NonNull
private Short businessUnitId;

@JsonProperty("validated_by")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ public interface DraftAccountRequestDto {

String getAccount();

Short getBusinessUnitId();

String getSubmittedBy();

String getAccountType();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import uk.gov.hmcts.opal.util.KeepAsJsonDeserializer;

@Data
Expand All @@ -18,6 +19,7 @@
public class ReplaceDraftAccountRequestDto implements ToJsonString, DraftAccountRequestDto {

@JsonProperty(value = "business_unit_id", required = true)
@NonNull
private Short businessUnitId;

@JsonProperty(value = "submitted_by", required = true)
Expand Down
8 changes: 8 additions & 0 deletions src/main/java/uk/gov/hmcts/opal/dto/ToJsonString.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,12 @@ static JsonNode toJsonNode(String json) throws JsonProcessingException {
static ObjectMapper getObjectMapper() {
return OBJECT_MAPPER;
}

static <T> T toClassInstance(String json, Class<T> clss) {
try {
return OBJECT_MAPPER.readValue(json, clss);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@
@Qualifier("draftAccountService")
public class DraftAccountService {

private static final String A_C_R_JSON_PATH = "$.accountCreateRequest";
private static final String DEFENDANT_JSON_PATH = A_C_R_JSON_PATH + ".Defendant";
private static final String ACCOUNT_JSON_PATH = A_C_R_JSON_PATH + ".Account";
private static final String A_C_R_JSON_PATH = "$.account_create_request";
private static final String DEFENDANT_JSON_PATH = A_C_R_JSON_PATH + ".defendant";
private static final String ACCOUNT_JSON_PATH = A_C_R_JSON_PATH + ".account";

private static final EnumSet<DraftAccountStatus> VALID_UPDATE_STATUSES =
EnumSet.of(DraftAccountStatus.PENDING, DraftAccountStatus.REJECTED, DraftAccountStatus.DELETED);
Expand Down Expand Up @@ -90,8 +90,6 @@ public List<DraftAccountEntity> searchDraftAccounts(DraftAccountSearchDto criter
return page.getContent();
}



public DraftAccountEntity submitDraftAccount(AddDraftAccountRequestDto dto) {
LocalDateTime created = LocalDateTime.now();
BusinessUnitEntity businessUnit = businessUnitRepository.findById(dto.getBusinessUnitId()).orElse(null);
Expand Down Expand Up @@ -197,19 +195,19 @@ private DraftAccountSnapshots.Snapshot buildInitialSnapshot(String document, L

JsonPathUtil.DocContext docContext = createDocContext(document);

String companyName = docContext.read(DEFENDANT_JSON_PATH + ".CompanyName");
String companyName = docContext.read(DEFENDANT_JSON_PATH + ".company_name");

final boolean notCompany = companyName == null || companyName.isBlank();

String defendantName = notCompany
? docContext.read(DEFENDANT_JSON_PATH + ".Surname") + ", "
+ docContext.read(DEFENDANT_JSON_PATH + ".Forenames")
? docContext.read(DEFENDANT_JSON_PATH + ".surname") + ", "
+ docContext.read(DEFENDANT_JSON_PATH + ".forenames")
: companyName;

String dob = notCompany
? docContext.read(DEFENDANT_JSON_PATH + ".DOB")
? docContext.read(DEFENDANT_JSON_PATH + ".dob")
: null;
String accType = docContext.read(ACCOUNT_JSON_PATH + ".AccountType");
String accType = docContext.read(ACCOUNT_JSON_PATH + ".account_type");

return DraftAccountSnapshots.Snapshot.builder()
.defendantName(defendantName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
"submitted_by",
"account",
"account_type",
"account_status",
"timeline_data"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ void constructor_ShouldSetMessage() {
Permissions permission = Permissions.ACCOUNT_ENQUIRY_NOTES;
PermissionNotAllowedException exception = new PermissionNotAllowedException(permission);

assertEquals("[" + permission + "]" + " permission(s) are not allowed for the user",
assertEquals("[" + permission + "]" + " permission(s) are not allowed for the user.",
exception.getMessage());
}

Expand All @@ -31,7 +31,7 @@ void constructor2_ShouldSetMessage() {
PermissionNotAllowedException exception = new PermissionNotAllowedException(
permission, BusinessUnitUser.builder().businessUnitUserId("A001").build());

assertEquals(permission + " permission is not allowed for the business unit user A001",
assertEquals(permission + " permission is not allowed for the business unit user: A001",
exception.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ void testSubmitDraftAccounts_success() {
// Arrange
DraftAccountEntity draftAccountEntity = DraftAccountEntity.builder().build();
AddDraftAccountRequestDto addDraftAccountDto = AddDraftAccountRequestDto.builder()
.businessUnitId((short)1)
.account(createAccountString())
.build();
BusinessUnitEntity businessUnit = BusinessUnitEntity.builder()
Expand All @@ -132,6 +133,7 @@ void testSubmitDraftAccounts_success() {
void testSubmitDraftAccounts_fail() {
// Arrange
AddDraftAccountRequestDto addDraftAccountDto = AddDraftAccountRequestDto.builder()
.businessUnitId((short)1)
.account("{}")
.build();
BusinessUnitEntity businessUnit = BusinessUnitEntity.builder()
Expand All @@ -145,7 +147,7 @@ void testSubmitDraftAccounts_fail() {
draftAccountService.submitDraftAccount(addDraftAccountDto));

// Assert
assertEquals("Missing property in path $['accountCreateRequest']", re.getMessage());
assertEquals("Missing property in path $['account_create_request']", re.getMessage());
}

@Test
Expand Down Expand Up @@ -245,7 +247,9 @@ void testReplaceDraftAccount_success() {
void testReplaceDraftAccount_draftAccountNotFound() {
// Arrange
Long draftAccountId = 1L;
ReplaceDraftAccountRequestDto replaceDto = ReplaceDraftAccountRequestDto.builder().build();
ReplaceDraftAccountRequestDto replaceDto = ReplaceDraftAccountRequestDto.builder()
.businessUnitId((short)1)
.build();

when(draftAccountRepository.findById(draftAccountId)).thenReturn(Optional.empty());

Expand Down Expand Up @@ -397,14 +401,14 @@ void testUpdateDraftAccount_invalidStatus() {
private String createAccountString() {
return """
{
"accountCreateRequest": {
"Defendant": {
"Surname": "Windsor",
"Forenames": "Charles",
"DOB": "August 1958"
"account_create_request": {
"defendant": {
"surname": "Windsor",
"forenames": "Charles",
"dob": "August 1958"
},
"Account": {
"AccountType": "Fine"
"account": {
"account_type": "Fine"
}
}
}
Expand Down

0 comments on commit 4047007

Please sign in to comment.