initial commit

This commit is contained in:
Muhammad Ali
2022-07-13 07:51:24 +04:00
commit 3d2cb078de
83 changed files with 4777 additions and 0 deletions

56
README.md Normal file
View File

@@ -0,0 +1,56 @@
# Getting Started
This is a demo project to demonstrate the concept of DDD (Domain Driven Development)
within a monolithic web application.
## DDD in a nutshell
<blockquote><p>You cannot create a banking software system unless you have a good understanding about the domain of banking.</p>
<p>Domain Driven Design - by Eric Evans.</p>
</blockquote>
Our Application usually consists of three layers:
1. **Domain layer** includes all the information about the business case and the business rules.
2. **Infrastructure layer** supports communication between the domain and other layers.
Infrastructure layer is an expression/implementation for the domain layer - a way of conducting/executing business information described on domain layer.
Yes, Domain layer is like a java interface, and infrastructure layer is its implementation.
We express business information through services.
Services are built using contracts - a way of abstracting business information.
So that for each service, theres a contract and one or more implementations.
Contracts like [Adapters - a well-known design pattern] are placed within the domain layer,
while their implementations are placed within the infrastructure layer.
Most importantly, the domain layer is in the center of the business application.
This means that it should be separated from the rest of the layers.
It shouldnt depend on the other layers or their frameworks.
Contracts (adapters) implementations should NOT contain any business logic.
All operations with Domain objects should be initiated and encapsulated only in domain module.
So, you can utilize Utils/Tools/Handlers built within domain layer.
3. **Application layer** a point of control that manages a combination of both previous layers.
On this project you'll find it encapsulating spring boot configuration properties.
In general for dependencies in a DDD Service, the Application layer depends on Domain and Infrastructure,
and Infrastructure depends on Domain, but Domain doesn't depend on any layer / The other way around is not permitted.
Think about it this way - What is more likely to be replaced at some point? Infrastructure or domain?
Infrastructure will change over time (different providers, different servers, …),
Your domain on the other hand will always be there.
## Useful Concepts
### Aggregates
* For each business feature delivered, it can be wrapped within whats called a **BoundedContext**.
* To use Aggregates please read this article offered by [Bealdung](https://baeldung-cn.com/java-modules-ddd-bounded-contexts).
* Aggregate Root is the mothership entity inside the aggregate.
* It identifies a transaction boundary so that an aggregate root and all related boundaries
should be modified following strong consistency principle (oppose to domain events
and eventual consistency for cross aggregation root changes).
## Deployment notes
Environment Variables:
* host
* keycloak.credentials.secret
## Authors
[![Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white&label=Muhammad%20Ali)](https://linkedin.com/in/zatribune)

View File

@@ -0,0 +1,10 @@
# Getting Started
### Reference Documentation
For further reference, please consider the following sections:
* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html)
* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.6.7/maven-plugin/reference/html/)
* [Create an OCI image](https://docs.spring.io/spring-boot/docs/2.6.7/maven-plugin/reference/html/#build-image)

View File

@@ -0,0 +1,101 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.tribune</groupId>
<artifactId>backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>backend-api-definition</artifactId>
<properties>
<swagger-annotations-version>1.6.6</swagger-annotations-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<springfox-version>2.9.2</springfox-version>
<spring-boot-starter-test-version>2.6.7</spring-boot-starter-test-version>
<spring-boot-starter-web-version>2.6.7</spring-boot-starter-web-version>
<jackson-databind-nullable>0.2.2</jackson-databind-nullable>
</properties>
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot-starter-web-version}</version>
</dependency>
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>4.3.1</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>
${project.basedir}/src/main/resources/tribune/reporting-service.yml
</inputSpec>
<generatorName>spring</generatorName>
<apiPackage>com.tribune.backend.infrastructure.api</apiPackage>
<!-- We should output to the general one -->
<!-- <modelPackage>com.example.cas.restapi.model</modelPackage>-->
<modelPackage>com.tribune.backend.infrastructure.model</modelPackage>
<supportingFilesToGenerate>
ApiUtil.java
</supportingFilesToGenerate>
<configOptions>
<delegatePattern>true</delegatePattern>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<proc>none</proc>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,22 @@
openapi: "3.0.3"
info:
title: "reporting API"
description: "reporting API"
version: "1.0.0"
servers:
- url: "https://reporting"
paths:
/reporting/generate/{type}:
post:
summary: "POST reporting/generate/{type}"
operationId: "generate"
parameters:
- name: "type"
in: "path"
required: true
schema:
type: string
example: "PDF"
responses:
"200":
description: "OK"

View File

@@ -0,0 +1,9 @@
# Getting Started
### Reference Documentation
For further reference, please consider the following sections:
* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html)
* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.6.7/maven-plugin/reference/html/)
* [Create an OCI image](https://docs.spring.io/spring-boot/docs/2.6.7/maven-plugin/reference/html/#build-image)

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.tribune</groupId>
<artifactId>backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>backend-application</artifactId>
<dependencies>
<!-- infrastructure operated-->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-infrastructure</artifactId>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--tests to be made-->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-domain</artifactId>
<type>test-jar</type>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-infrastructure</artifactId>
<type>test-jar</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,19 @@
## Notes regarding keycloak deployment
### Database
* Keycloak is integrated with the main postgres instance of our backend, but connected to a different database.
* Keycloak can access this database via a dedicated user.
* Both Keycloak's user and database are initialized within this script file [create_keycloak_db](create_keycloak_db.sh) and mounted on start.
* Scripts in `/docker-entrypoint-initdb.d` are only run if you start
the container with a data directory that is empty; any pre-existing database
will be left untouched on container startup.
* One common problem is that if one of your `/docker-entrypoint-initdb.d`
scripts fails (which will cause the entrypoint script to exit) and your orchestrator restarts the container with the already initialized data directory, it will not continue on with your scripts.
* Any `*.sql` files will be executed by `POSTGRES_USER`, which defaults to the postgres **superuser**. So it is recommended that any `psql` commands that are run inside a `*.sh` script be executed
as `POSTGRES_USER` by using the `--username "$POSTGRES_USER"` flag.
* This newly created user is supposed to be able to connect without a password due to the presence of
trust authentication for Unix socket connections made inside the container (**tested and failed -> needs a password on user creation**).
### Initial Configuration
* This file [realm-export.json](keycloak-init/realm-export.json) is used as a backup for realm configuration. It can be loaded from the admin console.

View File

@@ -0,0 +1,9 @@
#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
CREATE USER keycloak WITH ENCRYPTED PASSWORD 'keycloak';
CREATE DATABASE keycloak_db;
GRANT ALL PRIVILEGES ON DATABASE keycloak_db TO keycloak;
EOSQL

View File

@@ -0,0 +1,72 @@
version: '3.8'
networks:
tribune-network:
name: tribune-network
services:
app:
image: 'tribune-backend:latest'
build:
context: ../../../../..
dockerfile: ./infrastructure/docker/dev/Dockerfile
container_name: app
depends_on:
- db
ports:
- '8880:8880'
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/tribune_db_docker
- SPRING_DATASOURCE_USERNAME=tribune_db_user
- SPRING_DATASOURCE_PASSWORD=password
labels:
collect_logs_with_filebeat: 'true'
decode_log_event_to_json_object: 'true'
networks:
- tribune-network
db:
image: 'postgres:13.1-alpine'
restart: unless-stopped
container_name: db
environment:
#default superuser
POSTGRES_USER: tribune_db_user
##default superuser password
POSTGRES_PASSWORD: password
##default database
POSTGRES_DB: tribune_db_docker
ports:
- '5432:5432'
volumes:
- ./db:/var/lib/postgresql/data
- ./create_keycloak_db.sh:/docker-entrypoint-initdb.d/create_keycloak_db.sh
labels:
collect_logs_with_filebeat: 'true'
decode_log_event_to_json_object: 'true'
networks:
- tribune-network
keycloak:
image: bitnami/keycloak:18
container_name: keycloak
environment:
DB_VENDOR: POSTGRES
#by service name
DB_ADDR: db
#database name
DB_DATABASE: keycloak_db
DB_USER: keycloak
DB_PASSWORD: keycloak
KEYCLOAK_USER: admin
KEYCLOAK_PASSWORD: Pass@1234
# Uncomment the line below if you want to specify JDBC parameters. The parameter below is just an example, and it shouldn't be used in production without knowledge. It is highly recommended that you read the PostgreSQL JDBC driver documentation in order to use it.
#JDBC_PARAMS: "ssl=true"
ports:
- "8080:8080"
depends_on:
- db
networks:
- tribune-network

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
package com.tribune.backend;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
@ConfigurationPropertiesScan("com.tribune.backend.infrastructure.config.security")
@SpringBootApplication
public class BackendApplication {
public static void main(String[] args) {
SpringApplication.run(BackendApplication.class, args);
}
}

View File

@@ -0,0 +1,22 @@
## Spring embedded webserver
server:
port: 9090
error:
whitelabel:
enabled: false
spring:
## Spring datasource config
datasource:
url: jdbc:h2:mem:testdb
username: admin
password:
# H2 specific
h2:
console:
enabled: true
jpa:
hibernate:
ddl-auto: create-drop
open-in-view: false

View File

@@ -0,0 +1,46 @@
spring:
application:
name: tribune
mvc:
throw-exception-if-no-handler-found: true
management:
endpoints:
web:
exposure:
include: *
#keycloak user client properties
keycloak:
auth-server-url: http://${host}:8080/auth/
realm: tribune
resource: tribune-user
credentials:
secret: ${keycloak.credentials.secret}
ssl-required: external
principal-attribute: preferred_username
use-resource-role-mappings: true
bearer-only: true
#keycloak.policy-enforcer-config.enforcement-mode=ENFORCING
#keycloak admin client properties
tribune:
keycloak:
client:
user-management:
resource: tribune-user-management
client-secret: oT9cm9JhbJH5owI444FxS4DPKLdIpKel
username: users.admin@paywithtribune.com
password: 1234
#app.cors.allowed-origins=https://localhost:8880
#if needed for any reason by frontend
#app.cors.allowed-origins: http://localhost:port
logging:
level:
org:
keycloak: DEBUG
springframework:
security: DEBUG
#spring.jackson.serialization.fail-on-empty-beans=false

View File

@@ -0,0 +1,8 @@
${AnsiColor.198}${AnsiBackground.255}
${AnsiColor.198}${AnsiBackground.255} ████████████ ████████ ██████ ███████ ██ ██ ██ ██ ████████
${AnsiColor.198}${AnsiBackground.255} ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ███
${AnsiColor.198}${AnsiBackground.255} ██ ██ ███ ██ █████ ██ ██ ██ ██ ██ ████████
${AnsiColor.198}${AnsiBackground.255} ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ███
${AnsiColor.198}${AnsiBackground.255} ██ ██ ██ ██████ ███████ ████ ██ ██ ████████
${AnsiColor.198}${AnsiBackground.255}
${AnsiBackground.DEFAULT}

View File

@@ -0,0 +1,13 @@
package com.tribune.application;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ApplicationTests {
@Test
void contextLoads() {
}
}

22
backend-domain/README.md Normal file
View File

@@ -0,0 +1,22 @@
# domain module
Contains all the business information that must be consistent and generic all time.
### Notes
- Contracts (adapters) implementations should NOT contain any business logic.
- All operations with Domain objects should be initiated and encapsulated only in domain module.
- When using Aggregates:
- **Aggregate Root** is the mothership entity inside the aggregate.
- It identifies a transaction boundaries so that an aggregate root and all related boundaries
should be modified following strong consistency principle (oppose to domain events
and eventual consistency for cross aggregation root changes).
- In general, your infrastructure can depend on your domain.
The other way around is not ok.
Think about it this way:
what is more likely to be replaced at some point?
Infrastructure or domain?
Infrastructure will change over time (different providers, different servers, ...)
- , Your domain on the other hand will always be there.

58
backend-domain/pom.xml Normal file
View File

@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.tribune</groupId>
<artifactId>backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>backend-domain</artifactId>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!--todo: starter-web needs to be removed-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,15 @@
package com.tribune.backend.domain;
import lombok.experimental.SuperBuilder;
/**
* Aggregate Root is the mothership entity inside the aggregate. It identifies
* a use case boundaries so that an aggregate root and all related boundaries
* should be modified following strong consistency principle (oppose to domain events
* and eventual consistency for cross aggregation root changes).
*
* @param <ID> - type of identifier (use wrapper on top of primitive types)
*/
@SuperBuilder
public abstract class AggregateRoot<ID> extends Entity<ID> {
}

View File

@@ -0,0 +1,8 @@
package com.tribune.backend.domain;
/**
* Indicates any movable object that somehow relates to the domain model.
* Top-level marker interface for all domain objects.
*/
public interface DomainObject {
}

View File

@@ -0,0 +1,59 @@
package com.tribune.backend.domain;
import com.tribune.backend.domain.error.DomainException;
import lombok.experimental.SuperBuilder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* Abstract representation of Domain Entities
* @param <ID> - type of identifier (use wrapper on top of primitive types)
*/
@SuperBuilder
public abstract class Entity<ID> implements IdentifiableDomainObject<ID> {
private final List<Object> domainEvents = new ArrayList<>();
private ID id;
@Override
public ID getId() {
return id;
}
public void setId(ID id) {
this.id = id;
}
protected <T> T registerEvent(T event) {
if (event==null){
//todo:
throw new DomainException("Domain event must not be null!");
}
this.domainEvents.add(event);
return event;
}
public void clearDomainEvents() {
this.domainEvents.clear();
}
public List<Object> domainEvents() {
return Collections.unmodifiableList(this.domainEvents);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Entity<?> entity = (Entity<?>) o;
return Objects.equals(id, entity.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}

View File

@@ -0,0 +1,9 @@
package com.tribune.backend.domain;
/**
* Interface for all domain objects that can be uniquely identified in some context
* @param <ID> - type of identifier (use wrapper on top of primitive types)
*/
public interface IdentifiableDomainObject<ID> extends DomainObject {
ID getId();
}

View File

@@ -0,0 +1,11 @@
package com.tribune.backend.domain;
import lombok.experimental.SuperBuilder;
/**
* Marker superclass for all local Entities
* @param <ID> - type of identifier (use wrapper on top of primitive types)
*/
@SuperBuilder
public abstract class LocalEntity<ID> extends Entity<ID> {
}

View File

@@ -0,0 +1,9 @@
package com.tribune.backend.domain;
/**
* Marker interface for all value objects.
* Implementations of this interface are required to be immutable and
* implement equals() and hashCode().
*/
public interface ValueObject extends DomainObject {
}

View File

@@ -0,0 +1,20 @@
package com.tribune.backend.domain.context;
import com.tribune.backend.domain.AggregateRoot;
import com.tribune.backend.domain.dto.customer.Customer;
import com.tribune.backend.domain.dto.order.Order;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.SuperBuilder;
import java.util.UUID;
@Data
@SuperBuilder
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
public class CustomerOrder extends AggregateRoot<UUID> {
private Customer customer;
private Order order;
}

View File

@@ -0,0 +1,5 @@
/**
* Bounded Contexts
*
*/
package com.tribune.backend.domain.context;

View File

@@ -0,0 +1,23 @@
package com.tribune.backend.domain.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class GenericResponse<T> {
private int code;
private String message;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Object reason;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private T data;
}

View File

@@ -0,0 +1,12 @@
package com.tribune.backend.domain.dto;
import lombok.*;
import java.util.List;
@Data
@Builder
public class OrdersResponse {
private List<SingleOrderResponse> blogs;
}

View File

@@ -0,0 +1,26 @@
package com.tribune.backend.domain.dto;
import lombok.*;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class PlaceOrderRequest {
@NotNull(message = "Content is missing.")
@Min(value = 20)
private String content;
@NotNull
@NotEmpty
@NotBlank
private String user;
}

View File

@@ -0,0 +1,27 @@
package com.tribune.backend.domain.dto;
import com.tribune.backend.domain.enums.BlogStatus;
import lombok.Builder;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@Builder
public class SingleOrderResponse {
private String id;
private String title;
private String content;
private BlogStatus status;
private String appUser;
private LocalDateTime creationTimestamp;
private LocalDateTime updateTimestamp;
}

View File

@@ -0,0 +1,26 @@
package com.tribune.backend.domain.dto;
import lombok.*;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class UpdateOrderRequest {
@NotNull(message = "Content is missing.")
@Min(value = 20)
private String content;
@NotNull
@NotEmpty
@NotBlank
private String user;
}

View File

@@ -0,0 +1,38 @@
package com.tribune.backend.domain.dto.customer;
import com.tribune.backend.domain.Entity;
import com.tribune.backend.domain.dto.customer.address.Address;
import com.tribune.backend.domain.dto.customer.payment.Payment;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import java.util.List;
import java.util.UUID;
@Getter
@Setter
@SuperBuilder
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
public class Customer extends Entity<UUID> {
private UUID id;
private String displayName;
private String firstName;
private String lastName;
private CustomerState state;
private CustomerType type;
//todo: like Address
private List<Payment> paymentList;
private List<Address> addressList;
}

View File

@@ -0,0 +1,12 @@
package com.tribune.backend.domain.dto.customer;
public enum CustomerState {
CREATED,
REGISTERED,
IDENTIFIED,
ACTIVE,
REJECTED,
DISABLED,
TERMINATED,
DELETED
}

View File

@@ -0,0 +1,6 @@
package com.tribune.backend.domain.dto.customer;
public enum CustomerType {
TRADITIONAL,
PREMIUM
}

View File

@@ -0,0 +1,22 @@
package com.tribune.backend.domain.dto.customer.address;
import com.tribune.backend.domain.ValueObject;
import com.tribune.backend.domain.dto.customer.common.Country;
import lombok.Builder;
import lombok.NonNull;
import lombok.Value;
@Value
@Builder
public class Address implements ValueObject{
@NonNull Country country;
@NonNull String city;
@NonNull Street street;
String flatNumber;
String additionalInformation;
}

View File

@@ -0,0 +1,15 @@
package com.tribune.backend.domain.dto.customer.address;
import lombok.NonNull;
import lombok.Value;
@Value
public class PostalCode {
@NonNull String value;
@Override
public String toString() {
return value;
}
}

View File

@@ -0,0 +1,10 @@
package com.tribune.backend.domain.dto.customer.address;
import lombok.NonNull;
import lombok.Value;
@Value
public class Street {
@NonNull String name;
String streetNumber;
}

View File

@@ -0,0 +1,19 @@
package com.tribune.backend.domain.dto.customer.common;
import com.tribune.backend.domain.ValueObject;
import lombok.NonNull;
import lombok.Value;
@Value
public class Country implements ValueObject {
@NonNull String code;
public Country(@NonNull String code) {
this.code = code;
}
@Override
public String toString() {
return code;
}
}

View File

@@ -0,0 +1,46 @@
package com.tribune.backend.domain.dto.customer.common;
public enum Profession {
EMPLOYEE("profession_employee", 1),
WORKER("profession_worker", 2),
TRAINEE("profession_trainee", 3),
OFFICIAL("profession_official", 4),
FREELANCER("profession_freelancer", 5),
MANAGING_PARTNER("profession_managing_partner", 6),
HOUSEWIFE("profession_housewife", 7),
HOUSEMAN("profession_houseman", 8),
EXECUTIVE("profession_executive", 9),
UNEMPLOYED("profession_unemployed", 10),
PENSIONER("profession_pensioner", 11),
RETIREE("profession_retiree", 12),
PUPIL("profession_pupil", 13),
SELF_EMPLOYED("profession_self_employed", 14),
STUDENT("profession_student", 15),
OTHER("profession_other", 16),
MANAGER("profession_manager", 17),
LIBERAL_PROFESSION("profession_liberal_profession", 18),
HOUSEPARENT("profession_houseparent", 19),
LIVING_OFF_INVESTMENTS("profession_living_off_investments", 20),
COMPANY_DIRECTOR("profession_company_director", 21);;
/**
* String code representation of the academic title used by the legacy API for registration purposes.
*/
private final String name;
private final Integer code;
Profession(final String name, final Integer code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public Integer getCode() {
return code;
}
}

View File

@@ -0,0 +1,19 @@
package com.tribune.backend.domain.dto.customer.invoice;
import com.tribune.backend.domain.dto.customer.Customer;
import lombok.*;
import java.util.UUID;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Invoice {
private UUID id;
private Customer customer;
}

View File

@@ -0,0 +1,20 @@
package com.tribune.backend.domain.dto.customer.payment;
import com.tribune.backend.domain.LocalEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.SuperBuilder;
import java.util.UUID;
@Data
@SuperBuilder
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
public class Payment extends LocalEntity<UUID>{
private String note;
private UUID customerId;
}

View File

@@ -0,0 +1,26 @@
package com.tribune.backend.domain.dto.order;
import com.tribune.backend.domain.Entity;
import com.tribune.backend.domain.dto.order.lineitem.LineItem;
import com.tribune.backend.domain.enums.OrderStatus;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import java.util.List;
import java.util.UUID;
@Setter
@Getter
@SuperBuilder
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
public class Order extends Entity<UUID> {
private UUID id;
private OrderStatus status;
private List<LineItem> lineItemEntities;
}

View File

@@ -0,0 +1,22 @@
package com.tribune.backend.domain.dto.order.lineitem;
import com.tribune.backend.domain.dto.order.Order;
import com.tribune.backend.domain.dto.order.lineitem.product.Product;
import lombok.*;
import java.util.UUID;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class LineItem {
private UUID id;
private Order order;
private Product product;
}

View File

@@ -0,0 +1,16 @@
package com.tribune.backend.domain.dto.order.lineitem.product;
import lombok.*;
import java.util.UUID;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Product {
private UUID id;
}

View File

@@ -0,0 +1,5 @@
package com.tribune.backend.domain.enums;
public enum BlogStatus {
CREATED,APPROVED,DECLINED,SETTLED;
}

View File

@@ -0,0 +1,6 @@
package com.tribune.backend.domain.enums;
public enum OrderStatus {
INITIALIZED,PROCESSING,SUBMITTED,CANCELLED
}

View File

@@ -0,0 +1,5 @@
package com.tribune.backend.domain.enums;
public enum UserStatus {
ACTIVE, DISABLED;
}

View File

@@ -0,0 +1,8 @@
package com.tribune.backend.domain.error;
public class DomainException extends RuntimeException{
public DomainException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,32 @@
package com.tribune.backend.domain.service;
import com.tribune.backend.domain.dto.customer.Customer;
import java.util.List;
import java.util.UUID;
/**
* Please note that adapter implementation should NOT contain any business logic.
* All operations with Domain objects should be initiated and encapsulated only in domain module
*/
public interface CustomerRepositoryAdapter {
/**
* Use Pagination to return a subset of the Customer collection
* @param pageNumber - zero-based page index, must not be negative
* @param pageSize - the size of the page to be returned, must be greater than 0
* @return a subset of the Customer collection, otherwise an empty list
*/
List<Customer> findAll(final int pageNumber, final int pageSize);
Customer findByCustomerId(final UUID customerId);
/**
* Saves a customer in the persistence repository.
*
* @param customer the customer to save
* @return the saved {@link Customer}
*/
Customer save(Customer customer);
}

View File

@@ -0,0 +1,12 @@
package com.tribune.backend.domain.validation;
import lombok.Value;
@Value
public class ValidationError {
String path;
String fieldName;
Object expectedValue;
Object actualValue;
String reason;
}

View File

@@ -0,0 +1,2 @@
# infrastructure module

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.tribune</groupId>
<artifactId>backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>backend-infrastructure</artifactId>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-domain</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-api-definition</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Security dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-admin-client</artifactId>
</dependency>
<!-- Miscellaneous -->
<!-- Test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.security</groupId>-->
<!-- <artifactId>spring-security-test</artifactId>-->
<!-- <scope>test</scope>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.h2database</groupId>-->
<!-- <artifactId>h2</artifactId>-->
<!-- <version>2.1.212</version>-->
<!-- <scope>test</scope>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.testcontainers</groupId>-->
<!-- <artifactId>postgresql</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-domain</artifactId>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,80 @@
package com.tribune.backend.infrastructure.config;
import com.tribune.backend.domain.dto.GenericResponse;
import com.tribune.backend.infrastructure.config.security.SecurityConfig;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL;
/**
* top tier config file : a config for configs
* can log responses as following:
*
* ObjectMapper mapper=new ObjectMapper();
* mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
*
* ... mapper.writeValueAsString(value)
**/
@Configuration
public class AppConfig {
/**
* Fix cycle dependency formed by {@link org.keycloak.adapters.KeycloakConfigResolver}
* if specified within {@link SecurityConfig}
**/
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> {
JsonSerializer<Response> jsonSerializer = new JsonSerializer<>() {
@Override
public void serialize(Response value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
String message = value.getStatusInfo().getFamily().equals(SUCCESSFUL) ? "Success" : "Error";
List<String> reason = new ArrayList<>();
Object data = null;
switch (value.getStatusInfo().getStatusCode()) {
case 409:
reason.add("Email/username already exists!");
break;
case 201:
//returns as a result of newly generated resources
//returns a URL that ends with the newly created resource id
//"http://localhost:8080/auth/admin/realms/tribune/users/b61adfce-ffe6-4d68-9169-0c476ae11179"
data = value.getLocation();
break;
}
reason.add(value.getStatusInfo().getReasonPhrase());
GenericResponse<?> response = GenericResponse.builder()
.data(data)
.code(value.getStatus())
.message(message)
.reason(reason)
.build();
gen.writePOJO(response);
}
};
builder.serializerByType(Response.class, jsonSerializer);
};
}
}

View File

@@ -0,0 +1,30 @@
package com.tribune.backend.infrastructure.config.security;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Collections;
import java.util.List;
@Configuration
public class CorsConfig {
// @Value("${app.cors.allowed-origins}")
// private List<String> allowedOrigins;
//
// @Bean
// CorsFilter corsFilter() {
// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// CorsConfiguration config = new CorsConfiguration();
// config.setAllowCredentials(true);
// config.setAllowedOrigins(allowedOrigins);
// config.setAllowedMethods(Collections.singletonList("*"));
// config.setAllowedHeaders(Collections.singletonList("*"));
// source.registerCorsConfiguration("/**", config);
// return new CorsFilter(source);
// }
}

View File

@@ -0,0 +1,16 @@
package com.tribune.backend.infrastructure.config.security;
import org.keycloak.representations.idm.CredentialRepresentation;
public class CredentialsUtils {
private CredentialsUtils(){}
public static CredentialRepresentation createPasswordCredentials(String password) {
CredentialRepresentation passwordCredentials = new CredentialRepresentation();
passwordCredentials.setTemporary(false);
passwordCredentials.setType(CredentialRepresentation.PASSWORD);
passwordCredentials.setValue(password);
return passwordCredentials;
}
}

View File

@@ -0,0 +1,21 @@
package com.tribune.backend.infrastructure.config.security;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.*;
import java.io.IOException;
@Slf4j
public class CustomFilter extends GenericFilterBean {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
log.error("XXX");
chain.doFilter(request, response);
}
}

View File

@@ -0,0 +1,45 @@
package com.tribune.backend.infrastructure.config.security;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.admin.client.resource.UsersResource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Slf4j
@Getter
@Setter
@ConfigurationProperties(prefix = "tribune.keycloak.client.user-management")
public class KeycloakConfigProperties {
@Value("${keycloak.auth-server-url}")
private String authServerUrl;
@Value("${keycloak.realm}")
private String realm;
private String resource;
private String clientSecret;
private String username;
private String password;
public UsersResource getInstance(){
ResteasyClient resteasyClient=new ResteasyClientBuilder()
.connectionPoolSize(10)
.build();
return KeycloakBuilder.builder()
.serverUrl(authServerUrl)
.realm(realm)
.grantType(OAuth2Constants.PASSWORD)
.username(username)
.password(password)
.clientId(resource)
.clientSecret(clientSecret)
.resteasyClient(resteasyClient)
.build().realm(realm).users();
}
}

View File

@@ -0,0 +1,94 @@
package com.tribune.backend.infrastructure.config.security;
import lombok.extern.slf4j.Slf4j;
import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
/**
* The {@link EnableGlobalMethodSecurity} enables direct config of role-based access
* to our controllers. See the following example:
* <pre>{@code
* @PreAuthorize("hasRole('USER')")
* @GetMapping("/title)
* public ResponseEntity<String>getTitle(){
* //
* return title;
* }
* }</pre>
*/
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@KeycloakConfiguration
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
/**
* The other way around
* return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
* */
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
// Enable CORS and disable CSRF
http
.cors()
.and()
.csrf().disable()
// Set session management to stateless
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/v1/transaction/status/**").hasRole(MERCHANT)
.antMatchers(HttpMethod.POST, "/v1/transaction/**").hasRole(MERCHANT)
.antMatchers(HttpMethod.POST, "/v1/users/**").anonymous()
.antMatchers(HttpMethod.GET, "/api/user-data/me", "/actuator/**").permitAll()
.antMatchers(HttpMethod.GET, "/v1/dummy/**").permitAll()
.antMatchers("/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs", "/v3/api-docs/**").permitAll()
.anyRequest().fullyAuthenticated();
}
/**
* provided by keycloak to handle authentication failures.
* */
@Bean
@Override
protected KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter() throws Exception {
KeycloakAuthenticationProcessingFilter filter = new KeycloakAuthenticationProcessingFilter(this.authenticationManagerBean());
filter.setSessionAuthenticationStrategy(this.sessionAuthenticationStrategy());
filter.setAuthenticationFailureHandler(new TribuneKeycloakAuthenticationFailureHandler());
return filter;
}
public static final String MERCHANT = "merchant";
public static final String USER = "user";
public static final String MANAGE_USERS = "manage-users";
}

View File

@@ -0,0 +1,36 @@
package com.tribune.backend.infrastructure.config.security;
import com.tribune.backend.domain.dto.GenericResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static org.keycloak.util.JsonSerialization.mapper;
@Slf4j
@AllArgsConstructor
public class TribuneKeycloakAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException {
ex.printStackTrace();
log.error("Authentication Error: {}", ex.getMessage());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//todo:check removal of WWW_AUTHENTICATE header from response
GenericResponse<Void> genericResponse = GenericResponse.<Void>builder()
.message(ex.getMessage())
.reason(response.getHeader(HttpHeaders.WWW_AUTHENTICATE))
.code(response.getStatus())
.build();
response.getWriter().write(mapper.writeValueAsString(genericResponse));
}
}

View File

@@ -0,0 +1,24 @@
package com.tribune.backend.infrastructure.config.security;
import lombok.*;
import javax.validation.constraints.NotBlank;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserDTO {
@NotBlank
private String username;
@NotBlank
private String email;
@NotBlank
private String password;
@NotBlank
private String firstName;
@NotBlank
private String lastName;
}

View File

@@ -0,0 +1,21 @@
package com.tribune.backend.infrastructure.config.security;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
@Getter
@Setter
@AllArgsConstructor
@Builder
public class UserLoginRequest {
@NotBlank
private String username;
@NotBlank
private String password;
}

View File

@@ -0,0 +1,25 @@
package com.tribune.backend.infrastructure.config.security;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tribune.backend.domain.dto.GenericResponse;
import org.keycloak.representations.idm.UserRepresentation;
import javax.ws.rs.core.Response;
import java.util.List;
public interface UserManagementService {
Response addUser(UserDTO userDTO);
List<UserRepresentation> getUser(String userName);
void updateUser(String userId, UserDTO userDTO);
void deleteUser(String userId);
void sendVerificationLink(String userId);
void sendResetPassword(String userId);
GenericResponse<ObjectNode> authenticate(UserLoginRequest userDTO);
}

View File

@@ -0,0 +1,139 @@
package com.tribune.backend.infrastructure.config.security;
import com.tribune.backend.domain.dto.GenericResponse;
import com.tribune.backend.infrastructure.error.BackendException;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.netty.http.client.HttpClient;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
@Slf4j
@Service
public class UserManagementServiceImpl implements UserManagementService {
@Value("${keycloak.resource}")
private String tribuneSpringbootClient;
private final KeycloakConfigProperties properties;
@Autowired
public UserManagementServiceImpl(KeycloakConfigProperties properties) {
this.properties = properties;
}
@Override
public Response addUser(UserDTO userDTO) {
CredentialRepresentation credential = CredentialsUtils
.createPasswordCredentials(userDTO.getPassword());
UserRepresentation user = new UserRepresentation();
user.setUsername(userDTO.getUsername());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setCredentials(Collections.singletonList(credential));
user.setEnabled(true);
return properties.getInstance().create(user);
}
@Override
public List<UserRepresentation> getUser(String userName) {
return properties.getInstance().search(userName, true);
}
@Override
public void updateUser(String userId, UserDTO userDTO) {
CredentialRepresentation credential = CredentialsUtils
.createPasswordCredentials(userDTO.getPassword());
UserRepresentation user = new UserRepresentation();
user.setUsername(userDTO.getUsername());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setCredentials(Collections.singletonList(credential));
//todo:needs confirmation
properties.getInstance().get(userId).update(user);
}
@Override
public void deleteUser(String userId) {
//todo:needs confirmation
properties.getInstance().get(userId)
.remove();
}
@Override
public void sendVerificationLink(String userId) {
//todo:needs confirmation
properties.getInstance().get(userId)
.sendVerifyEmail();
}
@Override
public void sendResetPassword(String userId) {
//todo:needs confirmation
properties.getInstance().get(userId)
.executeActionsEmail(List.of("UPDATE_PASSWORD"));
}
@Override
public GenericResponse<ObjectNode> authenticate(UserLoginRequest userDTO) {
URI uri=UriComponentsBuilder.fromUriString(
String.format("%s/realms/%s/protocol/openid-connect/token",
properties.getAuthServerUrl(), properties.getRealm())
).build().toUri();
HttpClient httpClient = HttpClient.create()
.responseTimeout(Duration.ofSeconds(2));
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("username", userDTO.getUsername());
formData.add("password", userDTO.getPassword());
formData.add("client_id", tribuneSpringbootClient);
formData.add("grant_type", CredentialRepresentation.PASSWORD);
ObjectNode node= WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build()
.post()
.uri(uri)
.body(BodyInserters.fromFormData(formData))
.accept(MediaType.APPLICATION_JSON)
.exchangeToMono(clientResponse -> {
if (clientResponse.statusCode().is4xxClientError()) {
log.error("error");
return clientResponse.bodyToMono(ObjectNode.class).map(val -> {
throw new BackendException(val, clientResponse.statusCode());
});
} else
return clientResponse.bodyToMono(ObjectNode.class);
})
.block();
return GenericResponse.<ObjectNode>builder()
.code(200)
.message("Success!")
.data(node)
.build();
}
}

View File

@@ -0,0 +1,19 @@
package com.tribune.backend.infrastructure.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RequestMapping("/v1/dummy")
@RestController
public class DummyController {
@GetMapping("/hello")
public String hello(){
return "Hello";
}
}

View File

@@ -0,0 +1,30 @@
package com.tribune.backend.infrastructure.controller;
import com.tribune.backend.domain.dto.PlaceOrderRequest;
import com.tribune.backend.domain.dto.GenericResponse;
import com.tribune.backend.domain.dto.SingleOrderResponse;
import com.tribune.backend.infrastructure.services.OrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@Slf4j
@AllArgsConstructor
@RequestMapping("/v1/orders")
@RestController
public class OrdersController {
private final OrderService orderService;
@PostMapping("/order")
public GenericResponse<SingleOrderResponse> createBlog(@Valid @RequestBody PlaceOrderRequest createOrderRequest) {
return GenericResponse.<SingleOrderResponse>builder()
.code(201)
.data(orderService.placeOrder(createOrderRequest))
.message("Created!")
.build();
}
}

View File

@@ -0,0 +1,64 @@
package com.tribune.backend.infrastructure.controller;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tribune.backend.domain.dto.GenericResponse;
import com.tribune.backend.infrastructure.config.security.UserDTO;
import com.tribune.backend.infrastructure.config.security.UserLoginRequest;
import com.tribune.backend.infrastructure.config.security.UserManagementService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.keycloak.representations.idm.UserRepresentation;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.ws.rs.core.Response;
import java.util.List;
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping(path = "/v1/users")
public class UserController {
private final UserManagementService service;
@PostMapping("/user/auth")
public GenericResponse<ObjectNode> authenticate(@Valid @RequestBody UserLoginRequest userDTO){
return service.authenticate(userDTO);
}
@PostMapping("/user")
public Response addUser(@Valid @RequestBody UserDTO userDTO){
return service.addUser(userDTO);
}
@GetMapping(path = "/user/{userName}")
public List<UserRepresentation> getUser(@PathVariable("userName") String userName){
return service.getUser(userName);
}
@PutMapping(path = "/user/{userId}")
public String updateUser(@PathVariable("userId") String userId, @RequestBody UserDTO userDTO){
service.updateUser(userId, userDTO);
return "User Details Updated Successfully.";
}
@DeleteMapping(path = "/user/{userId}")
public String deleteUser(@PathVariable("userId") String userId){
service.deleteUser(userId);
return "User Deleted Successfully.";
}
@GetMapping(path = "/user/verify/{userId}")
public String sendVerificationLink(@PathVariable("userId") String userId){
service.sendVerificationLink(userId);
return "Verification Link Send to Registered E-mail Id.";
}
@GetMapping(path = "/user/reset-password/{userId}")
public String sendResetPasswordLink(@PathVariable("userId") String userId){
service.sendResetPassword(userId);
return "Reset Password Link Send Successfully to Registered E-mail Id.";
}
}

View File

@@ -0,0 +1,28 @@
package com.tribune.backend.infrastructure.db.entities;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.util.UUID;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class AddressEntity {
@Id
private UUID id;
@ManyToOne
@JoinColumn(name = "customer",referencedColumnName = "id")
private CustomerEntity customerEntity;
}

View File

@@ -0,0 +1,40 @@
package com.tribune.backend.infrastructure.db.entities;
import com.tribune.backend.domain.dto.customer.CustomerState;
import com.tribune.backend.domain.dto.customer.CustomerType;
import lombok.*;
import javax.persistence.*;
import java.util.List;
import java.util.UUID;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class CustomerEntity {
@Id
private UUID id;
private String displayName;
private String firstName;
private String lastName;
@Enumerated(value = EnumType.STRING)
private CustomerState state;
@Enumerated(value = EnumType.STRING)
private CustomerType type;
@OneToMany(mappedBy = "customerEntity", fetch = FetchType.LAZY)
private List<PaymentEntity> paymentEntityList;
@OneToMany(mappedBy = "customerEntity", fetch = FetchType.LAZY)
private List<AddressEntity> addressEntityList;
}

View File

@@ -0,0 +1,26 @@
package com.tribune.backend.infrastructure.db.entities;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import java.util.UUID;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class InvoiceEntity {
@Id
private UUID id;
@ManyToOne
private CustomerEntity customerEntity;
}

View File

@@ -0,0 +1,25 @@
package com.tribune.backend.infrastructure.db.entities;
import lombok.*;
import javax.persistence.*;
import java.util.UUID;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class LineItemEntity {
@Id
private UUID id;
@ManyToOne
private OrderEntity orderEntity;
@OneToOne
private ProductEntity productEntity;
}

View File

@@ -0,0 +1,28 @@
package com.tribune.backend.infrastructure.db.entities;
import com.tribune.backend.domain.enums.OrderStatus;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.List;
import java.util.UUID;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class OrderEntity {
@Id
private UUID id;
private OrderStatus status;
@OneToMany
private List<LineItemEntity> lineItemEntities;
}

View File

@@ -0,0 +1,27 @@
package com.tribune.backend.infrastructure.db.entities;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.util.UUID;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class PaymentEntity {
@Id
private UUID id;
@ManyToOne
@JoinColumn(name = "customer",referencedColumnName = "id")
private CustomerEntity customerEntity;
}

View File

@@ -0,0 +1,20 @@
package com.tribune.backend.infrastructure.db.entities;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.UUID;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class ProductEntity {
@Id
private UUID id;
}

View File

@@ -0,0 +1,14 @@
package com.tribune.backend.infrastructure.db.repository;
import com.tribune.backend.infrastructure.db.entities.CustomerEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.UUID;
@Repository
public interface CustomerRepository extends JpaRepository<CustomerEntity, UUID> {
}

View File

@@ -0,0 +1,12 @@
package com.tribune.backend.infrastructure.db.repository;
import com.tribune.backend.infrastructure.db.entities.OrderEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface OrderRepository extends JpaRepository<OrderEntity, Long> {
}

View File

@@ -0,0 +1,19 @@
package com.tribune.backend.infrastructure.error;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;
@Getter
@Setter
public class BackendException extends RuntimeException{
private final ObjectNode error;
private final HttpStatus status;
public BackendException(ObjectNode error, HttpStatus status) {
this.error= error;
this.status=status;
}
}

View File

@@ -0,0 +1,12 @@
package com.tribune.backend.infrastructure.error;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class NotFoundException extends Exception {
public NotFoundException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,27 @@
package com.tribune.backend.infrastructure.error;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tribune.backend.domain.dto.GenericResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@Slf4j
@RestControllerAdvice
public class TribuneAdvisor extends ResponseEntityExceptionHandler {
@ExceptionHandler(BackendException.class)
public ResponseEntity<GenericResponse<ObjectNode>> handleException(BackendException e) {
log.error("status:{} --- error: {}",e.getStatus(),e.getError());
GenericResponse<ObjectNode> response=GenericResponse.<ObjectNode>builder()
.message(e.getMessage())
.code(e.getStatus().value())
.data(e.getError())
.build();
return ResponseEntity.status(e.getStatus()).body(response);
}
}

View File

@@ -0,0 +1,10 @@
package com.tribune.backend.infrastructure.services;
import com.tribune.backend.infrastructure.db.entities.CustomerEntity;
import java.util.UUID;
public interface CustomerService {
CustomerEntity getCustomerById(UUID userId);
}

View File

@@ -0,0 +1,17 @@
package com.tribune.backend.infrastructure.services;
import com.tribune.backend.infrastructure.db.entities.CustomerEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.UUID;
@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {
@Override
public CustomerEntity getCustomerById(UUID userId) {
return null;
}
}

View File

@@ -0,0 +1,16 @@
package com.tribune.backend.infrastructure.services;
import com.tribune.backend.domain.dto.*;
import com.tribune.backend.infrastructure.db.entities.OrderEntity;
public interface OrderService {
OrderEntity getById(String id);
SingleOrderResponse placeOrder(PlaceOrderRequest placeOrderRequest);
OrderEntity updateOrder(String id, UpdateOrderRequest updateOrderRequest);
OrdersResponse getAll(Integer page, Integer size, String sortBy, String direction);
GenericResponse<Void> deleteById(String id, String token);
}

View File

@@ -0,0 +1,38 @@
package com.tribune.backend.infrastructure.services;
import com.tribune.backend.domain.dto.*;
import com.tribune.backend.infrastructure.db.entities.OrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
@Override
public OrderEntity getById(String id) {
return null;
}
@Override
public SingleOrderResponse placeOrder(PlaceOrderRequest placeOrderRequest) {
return null;
}
@Override
public OrderEntity updateOrder(String id, UpdateOrderRequest updateOrderRequest) {
return null;
}
@Override
public OrdersResponse getAll(Integer page, Integer size, String sortBy, String direction) {
return null;
}
@Override
public GenericResponse<Void> deleteById(String id, String token) {
return null;
}
}

View File

@@ -0,0 +1,13 @@
package com.tribune.backend.domain;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DataApplicationTests {
@Test
void contextLoads() {
}
}

166
pom.xml Normal file
View File

@@ -0,0 +1,166 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<modules>
<module>backend-domain</module>
<module>backend-api-definition</module>
<module>backend-infrastructure</module>
<module>backend-application</module>
</modules>
<groupId>com.tribune</groupId>
<artifactId>backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>backend</name>
<description>An example for adapting Domain Driven Development within a Spring Boot Web Application</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<spring-boot-version>2.7.0</spring-boot-version>
<maven-jar-plugin.version>3.2.0</maven-jar-plugin.version>
<apache.commons.validator.version>1.7</apache.commons.validator.version>
<keycloak-version>18.0.0</keycloak-version>
<lombok.version>1.18.12</lombok.version>
<dockerfile.tag>${project.version}</dockerfile.tag>
</properties>
<repositories>
<!-- if needed -->
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-application</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-api-definition</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-domain</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-infrastructure</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>${apache.commons.validator.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Security dependencies-->
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
<version>${keycloak-version}</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-admin-client</artifactId>
<version>${keycloak-version}</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-domain</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>backend-infrastructure</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.9.0</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<container>
<mainClass>com.tribune.backend.BackendApplication</mainClass>
</container>
<from>
<image>gcr.io/distroless/java:11</image>
</from>
<to>
<image>tribune.jfrog.io/tribune/tribune-blogs:${project.version}</image>
</to>
</configuration>
</plugin>
</plugins>
</build>
</project>