implements table hs_office_relationship to HsOfficeRelationshipController

This commit is contained in:
Michael Hoennig 2022-09-26 10:57:22 +02:00
parent 49ba141ca5
commit 956ee581c6
43 changed files with 2292 additions and 102 deletions

View File

@ -35,6 +35,9 @@ public abstract class Mapper {
}
public static <S, T> T map(final S source, final Class<T> targetClass, final BiConsumer<S, T> postMapper) {
if (source == null ) {
return null;
}
final var target = modelMapper.map(source, targetClass);
if (postMapper != null) {
postMapper.accept(source, target);

View File

@ -0,0 +1,63 @@
package net.hostsharing.hsadminng;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
// TODO.refa: use this instead of toDisplayName everywhere and add JavaDoc
public class Stringify<B> {
private final Class<B> clazz;
private final String name;
private final List<Property<B>> props = new ArrayList<>();
public static <B> Stringify<B> stringify(final Class<B> clazz, final String name) {
return new Stringify<B>(clazz, name);
}
public static <B> Stringify<B> stringify(final Class<B> clazz) {
return new Stringify<B>(clazz, null);
}
private Stringify(final Class<B> clazz, final String name) {
this.clazz = clazz;
this.name = name;
}
public Stringify<B> withProp(final String propName, final Function<B, ?> getter) {
props.add(new Property<B>(propName, getter));
return this;
}
public String apply(@NotNull B object) {
final var propValues = props.stream()
.map(prop -> PropertyValue.of(prop, prop.getter.apply(object)))
.filter(Objects::nonNull)
.map(propVal -> {
if (propVal.rawValue instanceof Stringifyable stringifyable) {
return new PropertyValue<>(propVal.prop, propVal.rawValue, stringifyable.toShortString());
}
return propVal;
})
.map(propVal -> propVal.prop.name + "=" + optionallyQuoted(propVal))
.collect(Collectors.joining(", "));
return (name != null ? name : object.getClass().getSimpleName()) + "(" + propValues + ")";
}
private String optionallyQuoted(final PropertyValue<B> propVal) {
return (propVal.rawValue instanceof Number) || (propVal.rawValue instanceof Boolean)
? propVal.value
: "'" + propVal.value + "'";
}
private record Property<B>(String name, Function<B, ?> getter) {}
private record PropertyValue<B>(Property<B> prop, Object rawValue, String value) {
static <B> PropertyValue<B> of(Property<B> prop, Object rawValue) {
return rawValue != null ? new PropertyValue<>(prop, rawValue, rawValue.toString()) : null;
}
}
}

View File

@ -0,0 +1,6 @@
package net.hostsharing.hsadminng;
public interface Stringifyable {
String toShortString();
}

View File

@ -1,6 +1,9 @@
package net.hostsharing.hsadminng.hs.office.contact;
import lombok.*;
import lombok.experimental.FieldNameConstants;
import net.hostsharing.hsadminng.Stringify;
import net.hostsharing.hsadminng.Stringifyable;
import javax.persistence.Column;
import javax.persistence.Entity;
@ -8,6 +11,8 @@ import javax.persistence.Id;
import javax.persistence.Table;
import java.util.UUID;
import static net.hostsharing.hsadminng.Stringify.stringify;
@Entity
@Table(name = "hs_office_contact_rv")
@Getter
@ -15,7 +20,12 @@ import java.util.UUID;
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class HsOfficeContactEntity {
@FieldNameConstants
public class HsOfficeContactEntity implements Stringifyable {
private static Stringify<HsOfficeContactEntity> toString = stringify(HsOfficeContactEntity.class, "contact")
.withProp(Fields.label, HsOfficeContactEntity::getLabel)
.withProp(Fields.emailAddresses, HsOfficeContactEntity::getEmailAddresses);
private @Id UUID uuid;
private String label;
@ -28,4 +38,14 @@ public class HsOfficeContactEntity {
@Column(name = "phonenumbers", columnDefinition = "json")
private String phoneNumbers;
@Override
public String toString() {
return toString.apply(this);
}
@Override
public String toShortString() {
return label;
}
}

View File

@ -2,6 +2,9 @@ package net.hostsharing.hsadminng.hs.office.person;
import com.vladmihalcea.hibernate.type.basic.PostgreSQLEnumType;
import lombok.*;
import lombok.experimental.FieldNameConstants;
import net.hostsharing.hsadminng.Stringify;
import net.hostsharing.hsadminng.Stringifyable;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
@ -9,6 +12,8 @@ import org.hibernate.annotations.TypeDef;
import javax.persistence.*;
import java.util.UUID;
import static net.hostsharing.hsadminng.Stringify.stringify;
@Entity
@Table(name = "hs_office_person_rv")
@TypeDef(
@ -20,7 +25,14 @@ import java.util.UUID;
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class HsOfficePersonEntity {
@FieldNameConstants
public class HsOfficePersonEntity implements Stringifyable {
private static Stringify<HsOfficePersonEntity> toString = stringify(HsOfficePersonEntity.class, "person")
.withProp(Fields.personType, HsOfficePersonEntity::getPersonType)
.withProp(Fields.tradeName, HsOfficePersonEntity::getTradeName)
.withProp(Fields.familyName, HsOfficePersonEntity::getFamilyName)
.withProp(Fields.givenName, HsOfficePersonEntity::getGivenName);
private @Id UUID uuid;
@ -32,13 +44,23 @@ public class HsOfficePersonEntity {
@Column(name = "tradename")
private String tradeName;
@Column(name = "givenname")
private String givenName;
@Column(name = "familyname")
private String familyName;
@Column(name = "givenname")
private String givenName;
public String getDisplayName() {
return toShortString();
}
@Override
public String toString() {
return toString.apply(this);
}
@Override
public String toShortString() {
return !StringUtils.isEmpty(tradeName) ? tradeName : (familyName + ", " + givenName);
}
}

View File

@ -0,0 +1,151 @@
package net.hostsharing.hsadminng.hs.office.relationship;
import net.hostsharing.hsadminng.Mapper;
import net.hostsharing.hsadminng.context.Context;
import net.hostsharing.hsadminng.hs.office.contact.HsOfficeContactRepository;
import net.hostsharing.hsadminng.hs.office.generated.api.v1.api.HsOfficeRelationshipsApi;
import net.hostsharing.hsadminng.hs.office.generated.api.v1.model.*;
import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.function.BiConsumer;
import static net.hostsharing.hsadminng.Mapper.map;
import static net.hostsharing.hsadminng.Mapper.mapList;
@RestController
public class HsOfficeRelationshipController implements HsOfficeRelationshipsApi {
@Autowired
private Context context;
@Autowired
private HsOfficeRelationshipRepository relationshipRepo;
@Autowired
private HsOfficePersonRepository relHolderRepo;
@Autowired
private HsOfficeContactRepository contactRepo;
@Autowired
private EntityManager em;
@Override
@Transactional(readOnly = true)
public ResponseEntity<List<HsOfficeRelationshipResource>> listRelationships(
final String currentUser,
final String assumedRoles,
final UUID personUuid,
final HsOfficeRelationshipTypeResource relationshipType) {
context.define(currentUser, assumedRoles);
final var entities = relationshipRepo.findRelationshipRelatedToPersonUuid(personUuid,
map(relationshipType, HsOfficeRelationshipType.class));
final var resources = mapList(entities, HsOfficeRelationshipResource.class,
RELATIONSHIP_ENTITY_TO_RESOURCE_POSTMAPPER);
return ResponseEntity.ok(resources);
}
@Override
@Transactional
public ResponseEntity<HsOfficeRelationshipResource> addRelationship(
final String currentUser,
final String assumedRoles,
final HsOfficeRelationshipInsertResource body) {
context.define(currentUser, assumedRoles);
final var entityToSave = new HsOfficeRelationshipEntity();
entityToSave.setRelType(HsOfficeRelationshipType.valueOf(body.getRelType()));
entityToSave.setUuid(UUID.randomUUID());
entityToSave.setRelAnchor(relHolderRepo.findByUuid(body.getRelAnchorUuid()).orElseThrow(
() -> new NoSuchElementException("cannot find relAnchorUuid " + body.getRelAnchorUuid())
));
entityToSave.setRelHolder(relHolderRepo.findByUuid(body.getRelHolderUuid()).orElseThrow(
() -> new NoSuchElementException("cannot find relHolderUuid " + body.getRelHolderUuid())
));
entityToSave.setContact(contactRepo.findByUuid(body.getContactUuid()).orElseThrow(
() -> new NoSuchElementException("cannot find contactUuid " + body.getContactUuid())
));
final var saved = relationshipRepo.save(entityToSave);
final var uri =
MvcUriComponentsBuilder.fromController(getClass())
.path("/api/hs/office/relationships/{id}")
.buildAndExpand(entityToSave.getUuid())
.toUri();
final var mapped = map(saved, HsOfficeRelationshipResource.class,
RELATIONSHIP_ENTITY_TO_RESOURCE_POSTMAPPER);
return ResponseEntity.created(uri).body(mapped);
}
@Override
@Transactional(readOnly = true)
public ResponseEntity<HsOfficeRelationshipResource> getRelationshipByUuid(
final String currentUser,
final String assumedRoles,
final UUID relationshipUuid) {
context.define(currentUser, assumedRoles);
final var result = relationshipRepo.findByUuid(relationshipUuid);
if (result.isEmpty()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(map(result.get(), HsOfficeRelationshipResource.class, RELATIONSHIP_ENTITY_TO_RESOURCE_POSTMAPPER));
}
@Override
@Transactional
public ResponseEntity<Void> deleteRelationshipByUuid(
final String currentUser,
final String assumedRoles,
final UUID relationshipUuid) {
context.define(currentUser, assumedRoles);
final var result = relationshipRepo.deleteByUuid(relationshipUuid);
if (result == 0) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.noContent().build();
}
@Override
@Transactional
public ResponseEntity<HsOfficeRelationshipResource> patchRelationship(
final String currentUser,
final String assumedRoles,
final UUID relationshipUuid,
final HsOfficeRelationshipPatchResource body) {
context.define(currentUser, assumedRoles);
final var current = relationshipRepo.findByUuid(relationshipUuid).orElseThrow();
new HsOfficeRelationshipEntityPatcher(em, current).apply(body);
final var saved = relationshipRepo.save(current);
final var mapped = map(saved, HsOfficeRelationshipResource.class);
return ResponseEntity.ok(mapped);
}
final BiConsumer<HsOfficeRelationshipEntity, HsOfficeRelationshipResource> RELATIONSHIP_ENTITY_TO_RESOURCE_POSTMAPPER = (entity, resource) -> {
resource.setRelAnchor(map(entity.getRelAnchor(), HsOfficePersonResource.class));
resource.setRelHolder(map(entity.getRelHolder(), HsOfficePersonResource.class));
resource.setContact(map(entity.getContact(), HsOfficeContactResource.class));
};
}

View File

@ -0,0 +1,60 @@
package net.hostsharing.hsadminng.hs.office.relationship;
import com.vladmihalcea.hibernate.type.basic.PostgreSQLEnumType;
import lombok.*;
import lombok.experimental.FieldNameConstants;
import net.hostsharing.hsadminng.Stringify;
import net.hostsharing.hsadminng.hs.office.contact.HsOfficeContactEntity;
import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonEntity;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import javax.persistence.*;
import java.util.UUID;
import static net.hostsharing.hsadminng.Stringify.stringify;
@Entity
@Table(name = "hs_office_relationship_rv")
@TypeDef(
name = "pgsql_enum",
typeClass = PostgreSQLEnumType.class
)
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@FieldNameConstants
public class HsOfficeRelationshipEntity {
private static Stringify<HsOfficeRelationshipEntity> toString = stringify(HsOfficeRelationshipEntity.class, "rel")
.withProp(Fields.relAnchor, HsOfficeRelationshipEntity::getRelAnchor)
.withProp(Fields.relType, HsOfficeRelationshipEntity::getRelType)
.withProp(Fields.relHolder, HsOfficeRelationshipEntity::getRelHolder)
.withProp(Fields.contact, HsOfficeRelationshipEntity::getContact);
private @Id UUID uuid;
@ManyToOne
@JoinColumn(name = "relanchoruuid")
private HsOfficePersonEntity relAnchor;
@ManyToOne
@JoinColumn(name = "relholderuuid")
private HsOfficePersonEntity relHolder;
@ManyToOne
@JoinColumn(name = "contactuuid")
private HsOfficeContactEntity contact;
@Column(name = "reltype")
@Enumerated(EnumType.STRING)
@Type( type = "pgsql_enum" )
private HsOfficeRelationshipType relType;
@Override
public String toString() {
return toString.apply(this);
}
}

View File

@ -0,0 +1,34 @@
package net.hostsharing.hsadminng.hs.office.relationship;
import net.hostsharing.hsadminng.EntityPatcher;
import net.hostsharing.hsadminng.OptionalFromJson;
import net.hostsharing.hsadminng.hs.office.contact.HsOfficeContactEntity;
import net.hostsharing.hsadminng.hs.office.generated.api.v1.model.HsOfficeRelationshipPatchResource;
import javax.persistence.EntityManager;
import java.util.UUID;
class HsOfficeRelationshipEntityPatcher implements EntityPatcher<HsOfficeRelationshipPatchResource> {
private final EntityManager em;
private final HsOfficeRelationshipEntity entity;
HsOfficeRelationshipEntityPatcher(final EntityManager em, final HsOfficeRelationshipEntity entity) {
this.em = em;
this.entity = entity;
}
@Override
public void apply(final HsOfficeRelationshipPatchResource resource) {
OptionalFromJson.of(resource.getContactUuid()).ifPresent(newValue -> {
verifyNotNull(newValue, "contact");
entity.setContact(em.getReference(HsOfficeContactEntity.class, newValue));
});
}
private void verifyNotNull(final UUID newValue, final String propertyName) {
if (newValue == null) {
throw new IllegalArgumentException("property '" + propertyName + "' must not be null");
}
}
}

View File

@ -0,0 +1,37 @@
package net.hostsharing.hsadminng.hs.office.relationship;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface HsOfficeRelationshipRepository extends Repository<HsOfficeRelationshipEntity, UUID> {
Optional<HsOfficeRelationshipEntity> findByUuid(UUID id);
default List<HsOfficeRelationshipEntity> findRelationshipRelatedToPersonUuid(@NotNull UUID personUuid, HsOfficeRelationshipType relationshipType) {
return findRelationshipRelatedToPersonUuid(personUuid, relationshipType.toString());
}
@Query(value = """
SELECT p.* FROM hs_office_relationship_rv AS p
WHERE p.relAnchorUuid = :personUuid OR p.relHolderUuid = :personUuid
""", nativeQuery = true)
List<HsOfficeRelationshipEntity> findRelationshipRelatedToPersonUuid(@NotNull UUID personUuid);
@Query(value = """
SELECT p.* FROM hs_office_relationship_rv AS p
WHERE (:relationshipType IS NULL OR p.relType = cast(:relationshipType AS HsOfficeRelationshipType))
AND ( p.relAnchorUuid = :personUuid OR p.relHolderUuid = :personUuid)
""", nativeQuery = true)
List<HsOfficeRelationshipEntity> findRelationshipRelatedToPersonUuid(@NotNull UUID personUuid, String relationshipType);
HsOfficeRelationshipEntity save(final HsOfficeRelationshipEntity entity);
long count();
int deleteByUuid(UUID uuid);
}

View File

@ -0,0 +1,8 @@
package net.hostsharing.hsadminng.hs.office.relationship;
public enum HsOfficeRelationshipType {
SOLE_AGENT,
JOINT_AGENT,
ACCOUNTING_CONTACT,
TECHNICAL_CONTACT
}

View File

@ -18,3 +18,5 @@ map:
null: org.openapitools.jackson.nullable.JsonNullable
/api/hs/office/persons/{personUUID}:
null: org.openapitools.jackson.nullable.JsonNullable
/api/hs/office/relationships/{relationshipUUID}:
null: org.openapitools.jackson.nullable.JsonNullable

View File

@ -3,12 +3,6 @@ components:
schemas:
HsOfficePersonTypeValues:
- NATURAL # a human
- LEGAL # e.g. Corp., Inc., AG, GmbH, eG
- SOLE_REPRESENTATION # e.g. OHG, GbR
- JOINT_REPRESENTATION # e.g. community of heirs
HsOfficePersonType:
type: string
enum:

View File

@ -0,0 +1,55 @@
components:
schemas:
HsOfficeRelationshipType:
type: string
enum:
- SOLE_AGENT # e.g. CEO
- JOINT_AGENT # e.g. heir
- ACCOUNTING_CONTACT
- TECHNICAL_CONTACT
HsOfficeRelationship:
type: object
properties:
uuid:
type: string
format: uuid
relAnchor:
$ref: './hs-office-person-schemas.yaml#/components/schemas/HsOfficePerson'
relHolder:
$ref: './hs-office-person-schemas.yaml#/components/schemas/HsOfficePerson'
relType:
type: string
contact:
$ref: './hs-office-contact-schemas.yaml#/components/schemas/HsOfficeContact'
HsOfficeRelationshipPatch:
type: object
properties:
contactUuid:
type: string
format: uuid
nullable: true
HsOfficeRelationshipInsert:
type: object
properties:
relAnchorUuid:
type: string
format: uuid
relHolderUuid:
type: string
format: uuid
relType:
type: string
nullable: true
contactUuid:
type: string
format: uuid
required:
- relAnchorUuid
- relHolderUuid
- relType

View File

@ -0,0 +1,83 @@
get:
tags:
- hs-office-relationships
description: 'Fetch a single person relationship by its uuid, if visible for the current subject.'
operationId: getRelationshipByUuid
parameters:
- $ref: './auth.yaml#/components/parameters/currentUser'
- $ref: './auth.yaml#/components/parameters/assumedRoles'
- name: relationshipUUID
in: path
required: true
schema:
type: string
format: uuid
description: UUID of the relationship to fetch.
responses:
"200":
description: OK
content:
'application/json':
schema:
$ref: './hs-office-relationship-schemas.yaml#/components/schemas/HsOfficeRelationship'
"401":
$ref: './error-responses.yaml#/components/responses/Unauthorized'
"403":
$ref: './error-responses.yaml#/components/responses/Forbidden'
patch:
tags:
- hs-office-relationships
description: 'Updates a single person relationship by its uuid, if permitted for the current subject.'
operationId: patchRelationship
parameters:
- $ref: './auth.yaml#/components/parameters/currentUser'
- $ref: './auth.yaml#/components/parameters/assumedRoles'
- name: relationshipUUID
in: path
required: true
schema:
type: string
format: uuid
requestBody:
content:
'application/json':
schema:
$ref: './hs-office-relationship-schemas.yaml#/components/schemas/HsOfficeRelationshipPatch'
responses:
"200":
description: OK
content:
'application/json':
schema:
$ref: './hs-office-relationship-schemas.yaml#/components/schemas/HsOfficeRelationship'
"401":
$ref: './error-responses.yaml#/components/responses/Unauthorized'
"403":
$ref: './error-responses.yaml#/components/responses/Forbidden'
delete:
tags:
- hs-office-relationships
description: 'Delete a single person relationship by its uuid, if permitted for the current subject.'
operationId: deleteRelationshipByUuid
parameters:
- $ref: './auth.yaml#/components/parameters/currentUser'
- $ref: './auth.yaml#/components/parameters/assumedRoles'
- name: relationshipUUID
in: path
required: true
schema:
type: string
format: uuid
description: UUID of the relationship to delete.
responses:
"204":
description: No Content
"401":
$ref: './error-responses.yaml#/components/responses/Unauthorized'
"403":
$ref: './error-responses.yaml#/components/responses/Forbidden'
"404":
$ref: './error-responses.yaml#/components/responses/NotFound'

View File

@ -0,0 +1,63 @@
get:
summary: Returns a list of (optionally filtered) person relationships for a given person.
description: Returns the list of (optionally filtered) person relationships of a given person and which are visible to the current user or any of it's assumed roles.
tags:
- hs-office-relationships
operationId: listRelationships
parameters:
- $ref: './auth.yaml#/components/parameters/currentUser'
- $ref: './auth.yaml#/components/parameters/assumedRoles'
- name: personUuid
in: query
required: true
schema:
type: string
format: uuid
description: Prefix of name properties from relHolder or contact to filter the results.
- name: relationshipType
in: query
required: false
schema:
$ref: './hs-office-relationship-schemas.yaml#/components/schemas/HsOfficeRelationshipType'
description: Prefix of name properties from relHolder or contact to filter the results.
responses:
"200":
description: OK
content:
'application/json':
schema:
type: array
items:
$ref: './hs-office-relationship-schemas.yaml#/components/schemas/HsOfficeRelationship'
"401":
$ref: './error-responses.yaml#/components/responses/Unauthorized'
"403":
$ref: './error-responses.yaml#/components/responses/Forbidden'
post:
summary: Adds a new person relationship.
tags:
- hs-office-relationships
operationId: addRelationship
parameters:
- $ref: './auth.yaml#/components/parameters/currentUser'
- $ref: './auth.yaml#/components/parameters/assumedRoles'
requestBody:
content:
'application/json':
schema:
$ref: './hs-office-relationship-schemas.yaml#/components/schemas/HsOfficeRelationshipInsert'
required: true
responses:
"201":
description: Created
content:
'application/json':
schema:
$ref: './hs-office-relationship-schemas.yaml#/components/schemas/HsOfficeRelationship'
"401":
$ref: './error-responses.yaml#/components/responses/Unauthorized'
"403":
$ref: './error-responses.yaml#/components/responses/Forbidden'
"409":
$ref: './error-responses.yaml#/components/responses/Conflict'

View File

@ -34,3 +34,13 @@ paths:
/api/hs/office/persons/{personUUID}:
$ref: "./hs-office-persons-with-uuid.yaml"
# Relationships
/api/hs/office/relationships:
$ref: "./hs-office-relationships.yaml"
/api/hs/office/relationships/{relationshipUUID}:
$ref: "./hs-office-relationships-with-uuid.yaml"

View File

@ -20,6 +20,10 @@ create or replace function assertReferenceType(argument varchar, referenceId uui
declare
actualType ReferenceType;
begin
if referenceId is null then
raise exception '% must be a % and not null', argument, expectedType;
end if;
actualType = (select type from RbacReference where uuid = referenceId);
if (actualType <> expectedType) then
raise exception '% must reference a %, but got a %', argument, expectedType, actualType;
@ -608,21 +612,29 @@ begin
into RbacGrants (ascendantuuid, descendantUuid, assumed)
values (superRoleId, subRoleId, doAssume)
on conflict do nothing; -- allow granting multiple times
delete from RbacGrants where ascendantUuid = superRoleId and descendantUuid = subRoleId;
insert
into RbacGrants (ascendantuuid, descendantUuid, assumed)
values (superRoleId, subRoleId, doAssume); -- allow granting multiple times
end; $$;
create or replace procedure revokeRoleFromRole(subRoleId uuid, superRoleId uuid)
create or replace procedure grantRoleToRoleIfNotNull(subRole RbacRoleDescriptor, superRole RbacRoleDescriptor, doAssume bool = true)
language plpgsql as $$
declare
superRoleId uuid;
subRoleId uuid;
begin
superRoleId := findRoleId(superRole);
if ( subRoleId is null ) then return; end if;
subRoleId := findRoleId(subRole);
perform assertReferenceType('superRoleId (ascendant)', superRoleId, 'RbacRole');
perform assertReferenceType('subRoleId (descendant)', subRoleId, 'RbacRole');
if (isGranted(superRoleId, subRoleId)) then
delete from RbacGrants where ascendantUuid = superRoleId and descendantUuid = subRoleId;
if isGranted(subRoleId, superRoleId) then
raise exception '[400] Cyclic role grant detected between % and %', subRoleId, superRoleId;
end if;
insert
into RbacGrants (ascendantuuid, descendantUuid, assumed)
values (superRoleId, subRoleId, doAssume)
on conflict do nothing; -- allow granting multiple times
end; $$;
create or replace procedure revokeRoleFromRole(subRole RbacRoleDescriptor, superRole RbacRoleDescriptor)

View File

@ -61,7 +61,7 @@ create or replace view rbacgrants_ev as
x.descendingIdName as descendantIdName,
x.grantedByRoleUuid,
x.ascendantUuid as ascendantUuid,
x.descendantUuid as descenantUuid,
x.descendantUuid as descendantUuid,
x.assumed
from (
select g.uuid as grantUuid,

View File

@ -51,7 +51,9 @@ declare
begin
foreach superRoleDescriptor in array roleDescriptors
loop
superRoleUuids := superRoleUuids || getRoleId(superRoleDescriptor, 'fail');
if superRoleDescriptor is not null then
superRoleUuids := superRoleUuids || getRoleId(superRoleDescriptor, 'fail');
end if;
end loop;
return row (superRoleUuids)::RbacSuperRoles;
@ -96,7 +98,6 @@ create type RbacSubRoles as
roleUuids uuid[]
);
-- drop FUNCTION beingItselfA(roleUuid uuid)
create or replace function beingItselfA(roleUuid uuid)
returns RbacSubRoles
language plpgsql
@ -105,7 +106,6 @@ begin
return row (array [roleUuid]::uuid[])::RbacSubRoles;
end; $$;
-- drop FUNCTION beingItselfA(roleDescriptor RbacRoleDescriptor)
create or replace function beingItselfA(roleDescriptor RbacRoleDescriptor)
returns RbacSubRoles
language plpgsql
@ -124,7 +124,9 @@ declare
begin
foreach subRoleDescriptor in array roleDescriptors
loop
subRoleUuids := subRoleUuids || getRoleId(subRoleDescriptor, 'fail');
if subRoleDescriptor is not null then
subRoleUuids := subRoleUuids || getRoleId(subRoleDescriptor, 'fail');
end if;
end loop;
return row (subRoleUuids)::RbacSubRoles;

View File

@ -127,6 +127,7 @@ begin
/*
Creates a restricted view based on the 'view' permission of the current subject.
*/
-- TODO.refa: hoist `select queryAccessibleObjectUuidsOfSubjectIds(...)` into WITH CTE for performance
sql := format($sql$
set session session authorization default;
create view %1$s_rv as

View File

@ -17,7 +17,7 @@ begin
currentTask = 'creating RBAC test contact ' || contLabel;
execute format('set local hsadminng.currentTask to %L', currentTask);
emailAddr = 'customer-admin@' || cleanIdentifier(contLabel) || '.example.com';
emailAddr = 'contact-admin@' || cleanIdentifier(contLabel) || '.example.com';
call defineContext(currentTask);
perform createRbacUser(emailAddr);
call defineContext(currentTask, null, emailAddr);
@ -64,6 +64,7 @@ do language plpgsql $$
call createHsOfficeContactTestData('forth contact');
call createHsOfficeContactTestData('fifth contact');
call createHsOfficeContactTestData('sixth contact');
call createHsOfficeContactTestData('seventh contact');
call createHsOfficeContactTestData('eighth contact');
call createHsOfficeContactTestData('ninth contact');
call createHsOfficeContactTestData('tenth contact');

View File

@ -60,10 +60,12 @@ end; $$;
do language plpgsql $$
begin
call createHsOfficePersonTestData('LEGAL', 'First Impressions GmbH');
call createHsOfficePersonTestData('NATURAL', null, 'Peter', 'Smith');
call createHsOfficePersonTestData('NATURAL', null, 'Smith', 'Peter');
call createHsOfficePersonTestData('LEGAL', 'Rockshop e.K.', 'Sandra', 'Miller');
call createHsOfficePersonTestData('SOLE_REPRESENTATION', 'Ostfriesische Kuhhandel OHG');
call createHsOfficePersonTestData('JOINT_REPRESENTATION', 'Erben Bessler', 'Mel', 'Bessler');
call createHsOfficePersonTestData('NATURAL', null, 'Bessler', 'Anita');
call createHsOfficePersonTestData('NATURAL', null, 'Winkler', 'Paul');
end;
$$;
--//

View File

@ -0,0 +1,19 @@
--liquibase formatted sql
-- ============================================================================
--changeset hs-office-relationship-MAIN-TABLE:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
CREATE TYPE HsOfficeRelationshipType AS ENUM ('SOLE_AGENT', 'JOINT_AGENT', 'CO_OWNER', 'ACCOUNTING_CONTACT', 'TECHNICAL_CONTACT');
CREATE CAST (character varying as HsOfficeRelationshipType) WITH INOUT AS IMPLICIT;
create table if not exists hs_office_relationship
(
uuid uuid unique references RbacObject (uuid) initially deferred, -- on delete cascade
relAnchorUuid uuid not null references hs_office_person(uuid),
relHolderUuid uuid not null references hs_office_person(uuid),
contactUuid uuid references hs_office_contact(uuid),
relType HsOfficeRelationshipType not null
);
--//

View File

@ -0,0 +1,192 @@
--liquibase formatted sql
-- ============================================================================
--changeset hs-office-relationship-rbac-OBJECT:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
call generateRelatedRbacObject('hs_office_relationship');
--//
-- ============================================================================
--changeset hs-office-relationship-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
call generateRbacRoleDescriptors('hsOfficeRelationship', 'hs_office_relationship');
--//
-- ============================================================================
--changeset hs-office-relationship-rbac-ROLES-CREATION:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
/*
Creates and updates the roles and their assignments for relationship entities.
*/
create or replace function hsOfficeRelationshipRbacRolesTrigger()
returns trigger
language plpgsql
strict as $$
declare
hsOfficeRelationshipTenant RbacRoleDescriptor;
ownerRole uuid;
adminRole uuid;
newRelAnchor hs_office_person;
newRelHolder hs_office_person;
oldContact hs_office_contact;
newContact hs_office_contact;
begin
hsOfficeRelationshipTenant := hsOfficeRelationshipTenant(NEW);
select * from hs_office_person as p where p.uuid = NEW.relAnchorUuid into newRelAnchor;
select * from hs_office_person as p where p.uuid = NEW.relHolderUuid into newRelHolder;
select * from hs_office_contact as c where c.uuid = NEW.contactUuid into newContact;
if TG_OP = 'INSERT' then
-- the owner role with full access for admins of the relAnchor global admins
ownerRole = createRole(
hsOfficeRelationshipOwner(NEW),
grantingPermissions(forObjectUuid => NEW.uuid, permitOps => array ['*']),
beneathRoles(array[
globalAdmin(),
hsOfficePersonAdmin(newRelAnchor)])
);
-- the admin role with full access for the owner
adminRole = createRole(
hsOfficeRelationshipAdmin(NEW),
grantingPermissions(forObjectUuid => NEW.uuid, permitOps => array ['edit']),
beneathRole(ownerRole)
);
-- the tenant role for those related users who can view the data
perform createRole(
hsOfficeRelationshipTenant,
grantingPermissions(forObjectUuid => NEW.uuid, permitOps => array ['view']),
beneathRoles(array[
hsOfficePersonAdmin(newRelAnchor),
hsOfficePersonAdmin(newRelHolder),
hsOfficeContactAdmin(newContact)]),
withSubRoles(array[
hsOfficePersonTenant(newRelAnchor),
hsOfficePersonTenant(newRelHolder),
hsOfficeContactTenant(newContact)])
);
-- anchor and holder admin roles need each others tenant role
-- to be able to see the joined relationship
call grantRoleToRole(hsOfficePersonTenant(newRelAnchor), hsOfficePersonAdmin(newRelHolder));
call grantRoleToRole(hsOfficePersonTenant(newRelHolder), hsOfficePersonAdmin(newRelAnchor));
call grantRoleToRoleIfNotNull(hsOfficePersonTenant(newRelHolder), hsOfficeContactAdmin(newContact));
elsif TG_OP = 'UPDATE' then
if OLD.contactUuid <> NEW.contactUuid then
-- nothing but the contact can be updated,
-- in other cases, a new relationship needs to be created and the old updated
select * from hs_office_contact as c where c.uuid = OLD.contactUuid into oldContact;
call revokeRoleFromRole( hsOfficeRelationshipTenant, hsOfficeContactAdmin(oldContact) );
call grantRoleToRole( hsOfficeRelationshipTenant, hsOfficeContactAdmin(newContact) );
call revokeRoleFromRole( hsOfficeContactTenant(oldContact), hsOfficeRelationshipTenant );
call grantRoleToRole( hsOfficeContactTenant(newContact), hsOfficeRelationshipTenant );
end if;
else
raise exception 'invalid usage of TRIGGER';
end if;
return NEW;
end; $$;
/*
An AFTER INSERT TRIGGER which creates the role structure for a new customer.
*/
create trigger createRbacRolesForHsOfficeRelationship_Trigger
after insert
on hs_office_relationship
for each row
execute procedure hsOfficeRelationshipRbacRolesTrigger();
/*
An AFTER UPDATE TRIGGER which updates the role structure of a customer.
*/
create trigger updateRbacRolesForHsOfficeRelationship_Trigger
after update
on hs_office_relationship
for each row
execute procedure hsOfficeRelationshipRbacRolesTrigger();
--//
-- ============================================================================
--changeset hs-office-relationship-rbac-IDENTITY-VIEW:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
call generateRbacIdentityView('hs_office_relationship', $idName$
(select idName from hs_office_person_iv p where p.uuid = target.relAnchorUuid)
|| '-with-' || target.relType || '-' ||
(select idName from hs_office_person_iv p where p.uuid = target.relHolderUuid)
$idName$);
--//
-- ============================================================================
--changeset hs-office-relationship-rbac-RESTRICTED-VIEW:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
call generateRbacRestrictedView('hs_office_relationship',
'(select idName from hs_office_person_iv p where p.uuid = target.relHolderUuid)',
$updates$
contactUuid = new.contactUuid
$updates$);
--//
-- TODO: exception if one tries to amend any other column
-- ============================================================================
--changeset hs-office-relationship-rbac-NEW-RELATHIONSHIP:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
/*
Creates a global permission for new-relationship and assigns it to the hostsharing admins role.
*/
do language plpgsql $$
declare
addCustomerPermissions uuid[];
globalObjectUuid uuid;
globalAdminRoleUuid uuid ;
begin
call defineContext('granting global new-relationship permission to global admin role', null, null, null);
globalAdminRoleUuid := findRoleId(globalAdmin());
globalObjectUuid := (select uuid from global);
addCustomerPermissions := createPermissions(globalObjectUuid, array ['new-relationship']);
call grantPermissionsToRole(globalAdminRoleUuid, addCustomerPermissions);
end;
$$;
/**
Used by the trigger to prevent the add-customer to current user respectively assumed roles.
*/
create or replace function addHsOfficeRelationshipNotAllowedForCurrentSubjects()
returns trigger
language PLPGSQL
as $$
begin
raise exception '[403] new-relationship not permitted for %',
array_to_string(currentSubjects(), ';', 'null');
end; $$;
/**
Checks if the user or assumed roles are allowed to create a new customer.
*/
create trigger hs_office_relationship_insert_trigger
before insert
on hs_office_relationship
for each row
-- TODO.spec: who is allowed to create new relationships
when ( not hasAssumedRole() )
execute procedure addHsOfficeRelationshipNotAllowedForCurrentSubjects();
--//

View File

@ -0,0 +1,81 @@
--liquibase formatted sql
-- ============================================================================
--changeset hs-office-relationship-TEST-DATA-GENERATOR:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
/*
Creates a single relationship test record.
*/
create or replace procedure createHsOfficeRelationshipTestData(
anchorPersonTradeName varchar,
holderPersonFamilyName varchar,
relationshipType HsOfficeRelationshipType,
contactLabel varchar)
language plpgsql as $$
declare
currentTask varchar;
idName varchar;
anchorPerson hs_office_person;
holderPerson hs_office_person;
contact hs_office_contact;
begin
idName := cleanIdentifier( anchorPersonTradeName|| '-' || holderPersonFamilyName);
currentTask := 'creating RBAC test relationship ' || idName;
call defineContext(currentTask, null, 'superuser-alex@hostsharing.net', 'global#global.admin');
execute format('set local hsadminng.currentTask to %L', currentTask);
select p.* from hs_office_person p where p.tradeName = anchorPersonTradeName into anchorPerson;
select p.* from hs_office_person p where p.familyName = holderPersonFamilyName into holderPerson;
select c.* from hs_office_contact c where c.label = contactLabel into contact;
raise notice 'creating test relationship: %', idName;
raise notice '- using anchor person (%): %', anchorPerson.uuid, anchorPerson;
raise notice '- using holder person (%): %', holderPerson.uuid, holderPerson;
raise notice '- using contact (%): %', contact.uuid, contact;
insert
into hs_office_relationship (uuid, relanchoruuid, relholderuuid, reltype, contactUuid)
values (uuid_generate_v4(), anchorPerson.uuid, holderPerson.uuid, relationshipType, contact.uuid);
end; $$;
--//
/*
Creates a range of test relationship for mass data generation.
*/
create or replace procedure createHsOfficeRelationshipTestData(
startCount integer, -- count of auto generated rows before the run
endCount integer -- count of auto generated rows after the run
)
language plpgsql as $$
declare
person hs_office_person;
contact hs_office_contact;
begin
for t in startCount..endCount
loop
select p.* from hs_office_person p where tradeName = intToVarChar(t, 4) into person;
select c.* from hs_office_contact c where c.label = intToVarChar(t, 4) || '#' || t into contact;
call createHsOfficeRelationshipTestData(person.uuid, contact.uuid, 'SOLE_AGENT');
commit;
end loop;
end; $$;
--//
-- ============================================================================
--changeset hs-office-relationship-TEST-DATA-GENERATION:1 context=dev,tc endDelimiter:--//
-- ----------------------------------------------------------------------------
do language plpgsql $$
begin
call createHsOfficeRelationshipTestData('First Impressions GmbH', 'Smith', 'SOLE_AGENT', 'first contact');
call createHsOfficeRelationshipTestData('Rockshop e.K.', 'Smith', 'SOLE_AGENT', 'second contact');
call createHsOfficeRelationshipTestData('Ostfriesische Kuhhandel OHG', 'Smith', 'SOLE_AGENT', 'third contact');
end;
$$;
--//

View File

@ -65,3 +65,9 @@ databaseChangeLog:
file: db/changelog/223-hs-office-partner-rbac.sql
- include:
file: db/changelog/228-hs-office-partner-test-data.sql
- include:
file: db/changelog/230-hs-office-relationship.sql
- include:
file: db/changelog/233-hs-office-relationship-rbac.sql
- include:
file: db/changelog/238-hs-office-relationship-test-data.sql

View File

@ -0,0 +1,57 @@
package net.hostsharing.hsadminng;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
class MapperUnitTest {
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public static class SourceBean {
private String a;
private String b;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public static class TargetBean {
private String a;
private String b;
private String c;
}
@Test
void mapsNullBeanToNull() {
final SourceBean givenSource = null;
final var result = Mapper.map(givenSource, TargetBean.class, (s, t) -> { fail("should not have been called"); });
assertThat(result).isNull();
}
@Test
void mapsBean() {
final SourceBean givenSource = new SourceBean("1234", "Text");
final var result = Mapper.map(givenSource, TargetBean.class, null);
assertThat(result).usingRecursiveComparison().isEqualTo(
new TargetBean("1234", "Text", null)
);
}
@Test
void mapsBeanWithPostmapper() {
final SourceBean givenSource = new SourceBean("1234", "Text");
final var result = Mapper.map(givenSource, TargetBean.class, (s, t) -> { t.setC("Extra"); });
assertThat(result).usingRecursiveComparison().isEqualTo(
new TargetBean("1234", "Text", "Extra")
);
}
}

View File

@ -0,0 +1,99 @@