Compare commits

...

111 Commits

Author SHA1 Message Date
2fcea78574 Add Swagger doc filter for /api/auth proxy login endpoint
Introduced AuthProxyDocumentFilter to programmatically document the POST /api/auth proxy login endpoint in Swagger. The filter defines request body schemas, example values, query parameter, and response codes. Registered the filter in Program.cs for OpenAPI generation.
2026-02-03 11:13:53 +01:00
e8e428f935 Update default Audience value in AuthTokenKeys
Changed the default Audience property in AuthTokenKeys from "sign-flow-gen.digitaldata.works" to "sign-flow.digitaldata.works" to reflect the correct expected audience for authentication tokens.
2026-02-03 11:13:29 +01:00
9450ed3486 Remove old Login endpoint and related documentation
Removed the previous Login method from AuthController, including its XML documentation and Swagger/OpenAPI annotations. This prepares the controller for a revised authentication implementation.
2026-02-03 10:45:17 +01:00
583a07c646 Add YARP reverse proxy support to API project
Integrated YARP by adding the Yarp.ReverseProxy package, including yarp.json for proxy configuration, and updating Program.cs to load and map reverse proxy routes. This enables the API to forward requests based on yarp.json settings.
2026-02-03 10:44:32 +01:00
51ad4fbc2c Add YARP reverse proxy route for auth login requests
Configured yarp.json to proxy POST /api/auth requests to the
auth-hub cluster at http://172.24.12.39:9090, rewriting the
path to /api/auth/sign-flow before forwarding.
2026-02-03 10:39:33 +01:00
50ac7570ea Refactor GetDocument to unify sender and receiver logic
Combined sender and receiver document retrieval into a single
GetDocument endpoint. The endpoint now authorizes both Sender
and Receiver.FullyAuth roles, handling their logic based on
role detection. Sender requires a query parameter; receiver
extracts envelope ID from claims and disallows query params.
Updated method signature and endpoint documentation.
2026-02-03 10:06:03 +01:00
5465996563 Refactor document retrieval endpoints and authorization
- Updated DocumentController to use class-level [Authorize] and method-level role-based authorization for sender and receiver endpoints.
- Replaced ReadEnvelopeReceiverQuery with ReadDocumentQuery for sender document retrieval; simplified response logic.
- Added a new endpoint for fully authenticated receivers to fetch documents by envelope ID from user claims.
- Refactored ReadDocumentQuery and handler to always return DocumentDto, throw NotFoundException when needed, and use _repo.Query.
- Cleaned up using directives and removed legacy error handling and logging.
2026-02-03 09:48:33 +01:00
1b840f4ae3 Refactor AuthController to use primary constructor
Refactored AuthController to use C# 12 primary constructor syntax for ILogger<AuthController> injection. Removed obsolete IUserService and IDirectorySearchService dependencies, their fields, and the old constructor. This streamlines the controller and prepares it for MediatR-based service handling.
2026-02-02 16:29:31 +01:00
3923a3b403 Refactor claim retrieval with GetRequiredClaimOfSender
Added a private extension method GetRequiredClaimOfSender to ClaimsPrincipal for retrieving the first available value from multiple claim types, throwing a detailed exception if none are found. Refactored GetId to use this method, improving code reuse and clarity when handling user claims.
2026-02-02 16:27:45 +01:00
ada621ac46 Refactor claim access to enforce required user claims
Replaced nullable claim accessors with strict versions that throw exceptions if required claims are missing or invalid. Updated controller logic to use new methods and removed fallback/error handling for missing claims, ensuring stricter claim validation throughout the codebase.
2026-02-02 16:17:53 +01:00
abbe6a26a9 Refactor ControllerExtensions to SenderClaimExtensions
Renamed the extension class for claims handling and added a private GetRequiredClaimOfSender method for ClaimsPrincipal. This method throws a detailed exception when a required claim is missing, improving error reporting and debugging.
2026-02-02 16:11:29 +01:00
3066dac541 Rename EnvelopeAuthExtensions to ReceiverClaimExtensions
Refactored the class name in ReceiverClaimExtensions.cs to better reflect its focus on receiver-specific claim extension methods rather than general envelope authentication. No functional changes were made.
2026-02-02 15:58:47 +01:00
b1aa6d6639 Refactor claim extraction methods for receiver context
Renamed authentication-related extension methods to clarify that they extract claims for the "receiver" context (e.g., GetAuthReceiverSignature → GetReceiverSignatureOfReceiver). Updated all usages in AnnotationController and ReadOnlyController. Also renamed the helper method GetRequiredClaim to GetRequiredClaimOfReceiver for improved clarity and reduced ambiguity.
2026-02-02 15:58:07 +01:00
31fe1c34f2 Remove GetClaimValue extension from EnvelopeAuthExtensions
The GetClaimValue method, which delegated to GetRequiredClaim for retrieving claim values by type, has been removed from the EnvelopeAuthExtensions class. Other functionality in the class remains unchanged.
2026-02-02 15:13:10 +01:00
d7644bfe07 Move ClaimsPrincipal extensions to API.Extensions namespace
Refactored ControllerExtensions: moved user claim extraction
methods from EnvelopeGenerator.API.Controllers to the new
EnvelopeGenerator.API.Extensions namespace. Updated all
references and using statements accordingly. No logic changes;
improves code organization and clarity.
2026-02-02 15:07:27 +01:00
4759b16a85 Mark GetAnnotationParams as obsolete (PSPDF Kit deprecated)
Added [Obsolete] attribute to GetAnnotationParams in ConfigController to indicate that PSPDF Kit will no longer be used and the method is deprecated. This warns developers to avoid using this method in future development.
2026-02-02 15:05:15 +01:00
cfdfb43631 Restrict annotation endpoints to Receiver.FullyAuth role
Updated [Authorize] attributes to require Receiver.FullyAuth role on AnnotationController and relevant methods. Removed redundant claim checks now enforced by role-based authorization. Clarified [Obsolete] message for PSPDF Kit endpoint.
2026-02-02 14:55:44 +01:00
6254bb6e3f Update auth role and envelopeId check in CreateAsync
Changed [Authorize] to require Receiver.FullyAuth role for CreateAsync, restricting access to receiver users. Removed explicit null check and logging for envelopeId claim, allowing the method to proceed without this validation.
2026-02-02 14:55:10 +01:00
f995fa9fc3 Refactor claim accessors to enforce required claims
Refactored EnvelopeAuthExtensions to require presence of all key authentication claims. Added GetRequiredClaim helper that throws detailed exceptions if claims are missing or invalid, replacing nullable return types with non-nullable ones. This ensures authentication logic fails fast and provides clearer error messages when claims are misconfigured or tampered with.
2026-02-02 14:54:59 +01:00
c2fefe798d Add Sender constant to Role in Domain.Constants
Added a new Sender constant to the Role class within the EnvelopeGenerator.Domain.Constants namespace, allowing it to be used alongside existing Receiver role constants.
2026-02-02 11:58:30 +01:00
849a282ec5 Refactor Role constants; add Receiver class, mark obsolete
Refactored the Role class by introducing a nested static Receiver class containing PreAuth and FullyAuth constants. Marked the original Role.PreAuth and Role.FullyAuth as [Obsolete] with guidance to use the new Receiver constants. Added a conditional using directive for System for NETFRAMEWORK compatibility.
2026-02-02 11:55:17 +01:00
6b23dcdba7 Refactor: unify role constants under new Role class
Replaced all usages of ReceiverRole with the new Role class in EnvelopeGenerator.Domain.Constants. Removed ReceiverRole.cs and added Role.cs with PreAuth and FullyAuth constants. Updated all [Authorize] attributes and role checks in controllers and authentication logic to use Role.FullyAuth and Role.PreAuth. This centralizes role management for improved maintainability and clarity.
2026-02-02 11:53:26 +01:00
a60d0f63e2 Update CORS origins and authentication config values
Expanded AllowedOrigins for CORS to include additional URLs. Updated AuthClientParams URL and adjusted Audience values in both AuthClientParams and AuthTokenKeys to use sign-flow.digitaldata.works. No other settings were changed.
2026-02-02 11:43:15 +01:00
2481059b49 Update AuthClientParams URL and Audience in dev settings
Changed AuthClientParams "Url" to use the new endpoint (http://172.24.12.39:9090/auth-hub) and updated the "Audience" in "PublicKeys" from "sign-flow-gen.digitaldata.works" to "sign-flow.digitaldata.works" in appsettings.Development.json.
2026-02-02 11:42:17 +01:00
6334097d5e Remove CommonServices project reference from API
The EnvelopeGenerator.API.csproj file no longer includes a direct ProjectReference to EnvelopeGenerator.CommonServices.vbproj. This change decouples the API project from the CommonServices project.
2026-02-02 10:30:09 +01:00
9baa126c8c Update LocalizationController namespace and localizer types
Changed namespace to EnvelopeGenerator.API.Controllers. Updated _mLocalizer and its constructor parameter to use IStringLocalizer<Resource> instead of IStringLocalizer<Model>. Removed unused EnvelopeGenerator.CommonServices using directive.
2026-02-02 10:29:44 +01:00
1ef46013cd Remove EnvelopeGenerator.Terminal from solution
EnvelopeGenerator.Terminal project and all related configuration
and solution folder mappings have been removed from
EnvelopeGenerator.sln. This cleans up the solution by excluding
the Terminal project and its build settings.
2026-02-02 10:26:12 +01:00
72dffd1043 Update SQL to use User.GetId() for current user context
Replaced usage of the userId variable with User.GetId() when formatting the SQL query in EnvelopeReceiverController. This ensures the user ID is dynamically retrieved from the authenticated user context, improving accuracy and security.
2026-02-02 10:17:55 +01:00
eda30472b9 No changes detected in diff
No code was added or removed in the provided diff; only context lines were present.
2026-02-02 10:14:15 +01:00
75846573da Add XML docs and standardize repository access patterns
Added XML documentation to extension and handler classes for improved maintainability. Refactored repository access to use .Query instead of .ReadOnly() for consistency. Updated async extension methods for better readability and error handling.
2026-02-02 10:07:50 +01:00
f59c0d90ad Refactor namespaces to EnvelopeGenerator.API
Replaced all EnvelopeGenerator.GeneratorAPI namespaces with EnvelopeGenerator.API across controllers, models, extensions, middleware, and annotation-related files. Updated using/import statements and namespace declarations accordingly. Added wwwroot folder to project file. Minor code adjustments made for consistency. This unifies API naming for improved clarity and maintainability.
2026-02-02 10:00:21 +01:00
cf40449112 remove angular website 2026-02-02 09:56:31 +01:00
a59d4836d4 Add EnvelopeGenerator.API project, remove GeneratorAPI
Added EnvelopeGenerator.API project to the solution with appropriate build configurations and folder placement. Removed the EnvelopeGenerator.GeneratorAPI project and all related solution references and configurations.
2026-01-30 15:12:28 +01:00
f475cf4ea9 Remove dotnet-ef tool config and IIS publish profiles
Deleted dotnet-tools.json (dotnet-ef config) and IIS publish profiles for .NET 7 and .NET 9 (IISProfileNet7Win64.pubxml, IISProfileNet9Win64.pubxml) to clean up unused deployment and tooling files.
2026-01-30 15:12:10 +01:00
d39018ca39 Add TfaRegistrationController for receiver TFA endpoints
Introduced TfaRegistrationController with endpoints to register and manage two-factor authentication for envelope receivers. Includes a GET endpoint to generate TFA registration metadata (QR code and deadline) and a POST endpoint to log out receivers. Implements error handling, logging, and uses dependency injection for required services. Added necessary using directives.
2026-01-30 15:05:32 +01:00
b49482137f Add ReadOnlyController for envelope sharing flows
Introduced ReadOnlyController to manage read-only envelope sharing. Added a POST endpoint for authorized users to create read-only receivers, send notification emails, and record sharing events in envelope history. Includes error handling and logging throughout the process.
2026-01-30 15:04:05 +01:00
bd40404d97 Add DocumentController for envelope document retrieval
Introduced DocumentController to provide a secured GET endpoint for authenticated receivers to download envelope documents. Handles missing or empty documents with error logging and NotFoundException. Utilizes MediatR and ILogger via dependency injection.
2026-01-30 14:48:10 +01:00
6f16921a79 Remove Obsolete attributes and update FirstAsync behavior
Removed Obsolete attributes from FirstAsync and Exceptions class. Changed FirstAsync return type to non-nullable Task<T> and updated its logic to throw the provided exception when the sequence is empty, instead of returning null.
2026-01-30 14:41:54 +01:00
1afc95f9c6 Add obsolete FirstAsync extension to TaskExtensions
Added FirstAsync<T, TException> as an obsolete extension method for Task<IEnumerable<T>>. This method returns the first element or throws a custom exception if the result is null, using a provided factory delegate. Intended for legacy .NET projects.
2026-01-30 14:24:57 +01:00
6aed820196 Mark TaskExtensions and new helpers as [Obsolete]
Marked TaskExtensions class and all its methods as [Obsolete] with guidance to implement Mediator behaviors instead. Added new [Obsolete] extension methods for null/empty checks and chaining. Introduced an [Obsolete] Exceptions class with factory methods for common exceptions. All changes are intended for legacy or transitional use only.
2026-01-30 14:20:05 +01:00
e17c4d02f8 Update Annotation model import to PsPdfKitAnnotation
Changed the import in ConfigController to use the PsPdfKitAnnotation namespace for annotation models instead of the previous Annotation namespace. This ensures the controller works with the updated annotation model definitions.
2026-01-30 13:07:00 +01:00
8187924a8c Add EnvelopeAuthExtensions for envelope claim handling
Introduces EnvelopeAuthExtensions with helper methods to retrieve envelope-specific claims from ClaimsPrincipal and to sign in envelope receivers using cookie authentication. Supports extracting envelope and receiver details via claims for authentication flows.
2026-01-30 13:06:40 +01:00
1bf530f7e7 Add EnvelopeClaimTypes for custom envelope claim strings
Introduced EnvelopeGenerator.GeneratorAPI namespace and EnvelopeClaimTypes static class. Added Title and Id claim type constants for envelope-related information, with XML documentation for clarity.
2026-01-30 13:06:27 +01:00
9cadc8e901 Add PSPDFKit annotation model and utilities
Introduce classes and interfaces for modeling PDF annotations, including support for layout, relative positioning, background rendering, and color. Added Annotation, AnnotationParams, Background, Color, Extensions, and IAnnotation to EnvelopeGenerator.GeneratorAPI.Models.PsPdfKitAnnotation. Enables flexible annotation management and rendering.
2026-01-30 13:02:34 +01:00
1d4ad13532 Add core model classes for auth, culture, images, and links
Introduced new models in EnvelopeGenerator.GeneratorAPI.Models:
- Auth, ContactLink, Culture, Cultures, CustomImages, ErrorViewModel, Image, MainViewModel, and TFARegParams.
These provide foundational structures for authentication, localization, error handling, image management, and contact links. All changes are new file additions.
2026-01-30 12:55:44 +01:00
03a8154b1c Add ConfigController to expose annotation config via API
Introduced a secured ConfigController with a GET endpoint at /api/Config/Annotations to provide annotation configuration data to clients. Utilizes dependency injection for configuration and includes necessary using directives.
2026-01-30 09:43:26 +01:00
20b8acd3fc Add AnnotationController for envelope annotation workflow
Introduces AnnotationController to manage envelope annotations and signature lifecycle. Includes endpoints for creating/updating annotations (for PSPDF Kit, obsolete) and rejecting documents, both requiring "FullyAuth" role. Utilizes MediatR for CQRS operations, dependency injection, and provides detailed logging and error handling. Legacy service dependencies are marked as obsolete.
2026-01-30 09:42:29 +01:00
a3afeb175f Refactor controllers for MediatR and cleaner API design
- Switch EnvelopeController and ReceiverController to MediatR for all operations
- Encapsulate UserId in CreateEnvelopeCommand via Authorize() method
- Change CreateEnvelopeCommand binding to [FromBody]
- Add CancellationToken support to EnvelopeReceiverController
- Remove obsolete CRUD logic from ReceiverController; now only supports GET via MediatR
- Clean up unused dependencies and update controller summaries for clarity
2026-01-28 14:14:04 +01:00
114555c843 Add XML docs to ReadEnvelopeReceiverQueryHandler ctor
Added XML documentation comments to the constructor of the ReadEnvelopeReceiverQueryHandler class, including parameter descriptions for envelopeReceiver, rcvRepo, and mapper. The summary section is currently empty.
2026-01-28 14:10:03 +01:00
f294ef2fde Refactor EnvelopeTypeController to use MediatR
Replace IEnvelopeTypeService with IMediator in EnvelopeTypeController and update GetAllAsync to use ReadEnvelopeTypesQuery. Remove obsolete service-based code and attributes. Also, remove AsNoTracking() from repository query in ReadEnvelopeTypesQueryHandler.
2026-01-28 13:48:02 +01:00
02ad819da9 Refactor EnvelopeReceiverController to use MediatR only
Remove all usage of IEnvelopeReceiverService from EnvelopeReceiverController, including constructor injection and obsolete attributes. Update endpoints to exclusively use MediatR for handling queries. Clean up related obsolete code, comments, and unused usings. Update documentation to reflect these changes.
2026-01-28 13:43:34 +01:00
041d98ca78 Refactor EnvelopeController to use MediatR exclusively
Removed all usage of the obsolete IEnvelopeService from EnvelopeController, refactoring endpoints to use MediatR with ReadEnvelopeQuery. Simplified GetAsync and GetDocResultAsync logic, updated method signatures, and eliminated obsolete code paths and attributes. Cleaned up unused usings and updated constructor dependencies.
2026-01-28 13:41:43 +01:00
afea2fb5ea Refactor envelope queries into unified ReadEnvelopeQuery
Consolidate envelope querying logic by extending ReadEnvelopeQuery to support user filtering and status options, and introduce ReadEnvelopeQueryHandler to process all envelope queries. Remove ReadUserEnvelopesQuery and its handler, reducing duplication and improving maintainability.
2026-01-28 13:34:54 +01:00
beeb9e4e75 Refactor EmailTemplateController to use generic IRepository
Replaces IEmailTemplateRepository with IRepository<EmailTemplate> in EmailTemplateController. Removes unused ILogger dependency and updates the Get method to use the new repository interface. Cleans up obsolete attributes and using directives.
2026-01-28 13:13:37 +01:00
30d13b1ffb Add MediatR query handler for reading receiver details
Introduced a CQRS-style ReadReceiverQueryHandler using MediatR to enable flexible querying of receivers by Id, EmailAddress, or Signature. Integrated AutoMapper for DTO mapping and updated ReadReceiverQuery to support MediatR's request/response pipeline.
2026-01-28 13:09:51 +01:00
814df63306 Add MediatR query/handler for reading envelope types
Introduced ReadEnvelopeTypesQuery and its handler to fetch all
envelope types from the repository, map them to DTOs, and
return the result via MediatR. This enables clean, decoupled
retrieval of envelope types in the application.
2026-01-28 12:55:44 +01:00
830d1af44a Add ReadUserEnvelopesQuery and handler with filtering
Implemented ReadUserEnvelopesQuery and its handler to fetch user envelopes with support for filtering by user ID, status (range, include, ignore), envelope ID, and UUID. Utilizes repository and AutoMapper to return EnvelopeDto results.
2026-01-28 12:54:22 +01:00
94018d2a36 Add query handler to fetch receiver's latest used name
Introduced ReadReceiverNameQueryHandler to retrieve the most recently used name ("Anrede") for a receiver, supporting envelope generation. Updated ReadReceiverNameQuery to use MediatR and CQRS patterns, and implemented repository-based lookups for receiver identification and name retrieval. Added necessary using directives for repository and MediatR support.
2026-01-28 12:51:40 +01:00
cf5a724bf2 Add username filter to ReadEnvelopeReceiverQuery handler
Extended ReadEnvelopeReceiverQuery to support optional username-based filtering. Refactored the handler to apply this filter, updated repository access for consistency, and improved code clarity and null-safety. Cleaned up comments and formatting.
2026-01-28 12:42:21 +01:00
172f2e27d7 Bump version to 3.9.0 in EnvelopeGenerator.Web.csproj
Updated the project, assembly, and file versions from 3.8.2 to 3.9.0 in the EnvelopeGenerator.Web.csproj file. This prepares the project for the next release.
2026-01-27 12:07:02 +01:00
d350e2ae48 Add envelope validation to BurnAnnotsToPDF function
Retrieve envelope by ID before burning annotations. Throw an exception if not found, and return the original PDF if the envelope is read-only. This adds validation and early exit logic before processing signatures and annotations.
2026-01-27 11:49:19 +01:00
2779452d72 Add ReadOnly property to Envelope class
Added a ReadOnly property to the Envelope class that returns true when EnvelopeTypeId is 2. The property is marked with [JsonIgnore] and [NotMapped] to exclude it from JSON serialization and database mapping.
2026-01-27 11:49:02 +01:00
5ebc6c6739 Update SQL to include ENVELOPE_TYPE in envelope query
The GetEnvelopeData function's SQL query now selects the ENVELOPE_TYPE column from the TBSIG_ENVELOPE table, allowing retrieval of envelope type information along with other envelope data.
2026-01-26 15:07:58 +01:00
891593755e Remove DLL ref, update configs, add WCF metadata
Removed EnvelopeGenerator.CommonServices DLL reference from BBTests project file, updated project GUIDs to lowercase, added WCFMetadata ItemGroup for connected services, and set BBTests Release config to use Debug in solution file.
2026-01-26 15:02:49 +01:00
b20260674e Improve PDF font handling; simplify report SQL fields
Enhanced PDFBurner to use a static FontProvider for better font support when rendering form field values. In ReportCreator, removed unused HEAD_TITLE and HEAD_SUBJECT fields from the SQL query and related mapping, streamlining report item loading.
2026-01-22 15:57:09 +01:00
7e5ff6bcb2 Refactor APIEnvelopeJob to use primary constructor
Simplifies APIEnvelopeJob by adopting C# primary constructor syntax.
Removes explicit constructors and initializes logger inline,
enabling direct dependency injection and reducing boilerplate.
2026-01-22 12:47:58 +01:00
6eed9b1e31 Update WorkerSettings with SQL Server connection string
Updated the ConnectionString property in both appsettings.json and appsettings.Development.json from an empty value to a specific SQL Server connection string, including server, database, credentials, and security options. This enables the application to connect to the designated database environment.
2026-01-22 10:14:44 +01:00
d4b1a4921c Refactor worker to use config, DI, and Quartz scheduling
- Add WorkerSettings class and update appsettings for config-driven setup
- Integrate Quartz.NET for job scheduling (FinalizeDocumentJob, APIEnvelopeJob)
- Refactor Program.cs for DI of services (TempFileManager, PDFBurner, etc.)
- Implement TempFileManager for temp folder management and cleanup
- Rewrite Worker class for config validation, DB check, and lifecycle logging
- Update csproj to include Quartz and EnvelopeGenerator.Jobs references
- Improve maintainability, error handling, and logging throughout
2026-01-22 09:51:35 +01:00
f078bafdde Refactor Jobs namespace and improve PDF handling
Refactored all EnvelopeGenerator.Jobs files to use the EnvelopeGenerator.Jobs namespace instead of EnvelopeGenerator.CommonServices.Jobs. Updated the .csproj to remove custom content and compile includes for the Jobs folder. Switched FinalizeDocumentJob to use dependency injection for PDFBurner, PDFMerger, and ReportCreator. Improved image annotation logic in PDFBurner for better placement and scaling, and refactored form field value rendering for conditional font styling. Aliased Document as LayoutDocument in ReportCreator to avoid ambiguity. Removed the obsolete Class1.cs file and made minor type safety improvements. These changes modernize the codebase and enhance maintainability.
2026-01-22 09:51:16 +01:00
786a3e128d Add EnvelopeGenerator.WorkerService as background worker
Added a new WorkerService project to the solution, targeting .NET 8.0 and using Microsoft.Extensions.Hosting. Implemented a Worker class that logs periodically, set up hosting in Program.cs, and included configuration files for logging and development. Updated the solution file to include and configure the new project.
2026-01-20 16:46:30 +01:00
ff3a146636 Add job framework for envelope processing and PDF finalization
Introduced new job classes for envelope processing and document finalization, including APIEnvelopeJob and FinalizeDocumentJob, both implementing Quartz IJob. Added supporting utilities for PDF annotation burning (PDFBurner), PDF merging (PDFMerger), and report generation (ReportCreator), along with related data models and exception types. Updated project references and dependencies to support Quartz scheduling, SQL Server access, and PDF manipulation with iText. This establishes a modular, extensible job-processing framework for envelope management and reporting.
2026-01-20 16:28:05 +01:00
40b2cad598 Add EnvelopeGenerator.Jobs project to the solution
Added new EnvelopeGenerator.Jobs project targeting .NET 8.0, with initial Class1.cs placeholder. Updated solution file to include the project with appropriate build configurations and solution folder nesting.
2026-01-20 15:52:41 +01:00
5c675be0ed Add type check to Handle method in AnnotationHandler
Refactored the Handle method to include a type check for PsPdfKitAnnotation before creating an annotation. This prevents errors when the notification does not contain the expected annotation type.
2026-01-20 13:57:52 +01:00
58164be640 Handle missing PsPdfKitAnnotation with blank JSON
Refactored DocStatusHandler to assign a blank JSON object ("{}")
to the Value property when PsPdfKitAnnotation is not present or
not of the expected type, preventing potential runtime errors.
2026-01-20 13:57:43 +01:00
a639377195 Make PsPdfKitAnnotation property and param nullable
Changed PsPdfKitAnnotation in DocSignedNotification to be nullable, removing the need for the null-forgiving operator. Updated ToDocSignedNotification to accept a nullable PsPdfKitAnnotation, ensuring consistency and allowing for cases where the annotation may be absent.
2026-01-20 13:57:29 +01:00
e3d6e87ee5 Allow nullable annotation param; validate for non-readonly
Make psPdfKitAnnotation optional in CreateOrUpdate. Add validation to require an annotation for non read-and-confirm envelopes, returning BadRequest if missing.
2026-01-20 12:11:49 +01:00
2795b91386 Refactor handleFinish to streamline READ_AND_CONFIRM flow and improve validation checks 2026-01-20 11:57:04 +01:00
ca248c3aa6 Support READ_AND_CONFIRM flow in handleFinish
Add logic to require all pages viewed before allowing finish when READ_AND_CONFIRM is enabled. Skip annotation and form field validations in this mode. Show warnings for unviewed pages and handle errors for save/sign actions. Update minified app to match new flow.
2026-01-20 11:44:40 +01:00
383634fca6 Conditionally add btn_refresh event based on READ_AND_CONFIRM
Only attach click handlers to btn_refresh elements when
READ_AND_CONFIRM is false. btn_complete and btn_reject
handlers remain unaffected. This change applies to both
app.js and app.min.js.
2026-01-20 11:11:59 +01:00
75097afa06 Add refresh button to envelope UI when not read-only
A "Refresh" button with a counterclockwise arrow icon is now shown in the envelope UI, but only when the envelope is not in read-only mode. The button uses standard styling classes for consistency.
2026-01-20 11:11:39 +01:00
77975c0644 Conditionally show "reset" button in mobile toolbar
The "reset" button in getMobileWritableItems is now only included if READ_AND_CONFIRM is falsy. This prevents the button from appearing when READ_AND_CONFIRM is true. The same conditional logic was applied to the minified ui.min.js. Code was also refactored for clarity.
2026-01-20 11:11:25 +01:00
5707213edd Conditionally apply PDF background for read-only envelopes
When preparing the PDF for the view, only apply the Background
method if the envelope is not read-only. This ensures that
read-only envelopes are displayed without additional background
elements.
2026-01-20 10:54:31 +01:00
ad54ba9dc4 Conditionally load annotations based on READ_AND_CONFIRM
Annotations are now only loaded if READ_AND_CONFIRM is falsy.
This prevents unnecessary annotation creation in read-and-confirm
scenarios. Changes applied to both app.js and app.min.js.
2026-01-20 10:54:16 +01:00
1f233153cf Restrict page view tracking to READ_AND_CONFIRM mode
Previously, page view tracking and sessionStorage updates ran unconditionally. Now, this logic is only executed when READ_AND_CONFIRM is enabled, ensuring viewed/unviewed page state is only tracked when required. Updated both source and minified files accordingly.
2026-01-20 10:38:37 +01:00
513ec007eb Set ViewData["ReadAndConfirm"] for envelope read-only state
Added "ReadAndConfirm" to ViewData, passing the envelope's ReadOnly property to the "ShowEnvelope" view. This enables the view to adjust its behavior or UI based on whether the envelope is read-only.
2026-01-20 10:30:25 +01:00
1305714da2 Move ReadOnly property from Envelope to EnvelopeDto
The ReadOnly property logic was shifted from the Envelope entity
to the EnvelopeDto record, ensuring that read-only status is
determined at the DTO layer rather than in the data model.
2026-01-20 10:30:07 +01:00
1e90cda393 Add READ_AND_CONFIRM JS constant from ViewData flag
Introduced a READ_AND_CONFIRM JavaScript constant in _Layout.cshtml, which reflects the server-side ViewData["ReadAndConfirm"] boolean value. This enables client-side scripts to easily check if the "ReadAndConfirm" flag is set.
2026-01-20 09:54:45 +01:00
5a5cbcb14d Track viewed PDF pages and persist state in sessionStorage
Added logic to monitor which PDF pages have been viewed by the user. The list of unviewed pages and a flag for all pages viewed are stored in sessionStorage and updated as the user navigates. Changes applied to both ui.js and ui.min.js.
2026-01-19 17:06:43 +01:00
a35f06070a Remove total page count logging after PSPDFKit load
Refactored ui.js and ui.min.js to eliminate retrieval and logging of the total page count after loading the PSPDFKit instance. The code now returns the instance directly after setting up the page change event listener, reducing unnecessary logging and simplifying the load process.
2026-01-19 17:03:05 +01:00
2606066103 Add logging for page changes and total pages in PSPDFKit
Added a .then() handler to loadPSPDFKit to log the active page number on page change events and log the total number of pages after loading. This aids in debugging and tracking user navigation within the document.
2026-01-19 16:57:34 +01:00
7495e062a9 Remove EnvelopeSigningType enum and update envelope logic
Removed EnvelopeSigningType enum and related normalization logic. Added a ReadOnly property to Envelope that uses EnvelopeTypeId to determine read-only status. Envelope type handling now relies on EnvelopeTypeId (int?) instead of the enum.
2026-01-19 16:50:02 +01:00
293044bec3 Handle envelope type with framework-specific properties
Add conditional logic to map "ENVELOPE_TYPE" to either an int? EnvelopeTypeId (for .NET Framework) or a type-safe EnvelopeSigningType SigningType (for .NET), supporting both legacy and modern approaches.
2026-01-19 16:21:58 +01:00
e0ff976d21 Add unit tests for EnvelopeSigningType.Normalize method
Added ConstantsTests to verify Normalize behavior for EnvelopeSigningType, including handling of valid and out-of-range enum values using NUnit test cases. Ensures normalization logic works as expected.
2026-01-19 16:08:39 +01:00
bec45ab1f1 Refactor test namespaces to EnvelopeGenerator.Tests.Application
All test files and utilities now use the EnvelopeGenerator.Tests.Application namespace for improved organization and clarity. No functional changes were made; updates are limited to namespaces and using directives. This makes it explicit that these are application-level tests and related helpers.
2026-01-19 16:02:39 +01:00
fecd054a5c Add EnvelopeSigningType enum and Normalize extension
Introduced EnvelopeSigningType enum with WetSignature and ReadAndSign values in the EnvelopeGenerator.Domain.Constants namespace. Added EnvelopeSigningTypeExtensions with a Normalize method to standardize enum values.
2026-01-19 16:01:13 +01:00
32b488c50f Refactor test dependency resolution in DocSignedNotificationTests
Refactored DocSignedNotificationTests to use typed repository
retrieval and explicit service resolution for PsPdfKitAnnotation.
Added a Services property to TestBase for easier access to
IServiceProvider. These changes improve clarity and robustness
of test dependency management.
2026-01-19 15:56:12 +01:00
9cfdd16970 Refactor test DB config to support SQL Server and fix seeding
Refactored Fake.cs to configure both in-memory and SQL Server
database contexts for testing, using the "Default" connection
string from configuration. Added detailed EF logging and SQL
executor setup. In TestBase.cs, fixed Setup to use the correct
repository instance for seeding email templates.
2026-01-19 15:51:09 +01:00
4da5848253 Refactor test namespaces; update package version
Changed test file namespaces from EnvelopeGenerator.Tests.Application to EnvelopeGenerator.Tests for consistency. Updated DigitalData.Core.Abstraction.Application package from 1.4.0 to 1.6.0 to incorporate latest improvements.
2026-01-19 15:14:59 +01:00
88da210ba2 Update DigitalData.Core.Abstraction.Application to 1.6.0
Updated DigitalData.Core.Abstraction.Application from 1.4.0 to 1.6.0 across all relevant project files and package configs. Also updated DigitalData.Core.Infrastructure from 2.4.5 to 2.6.1 in EnvelopeGenerator.Infrastructure.csproj. No other code changes were made.
2026-01-19 15:13:53 +01:00
fc23ba840e chore(Web): bump to 3.8.2 2025-11-20 16:47:45 +01:00
140d271b28 refactor(privacy-policy): remove 6. Hinweisgebersystem 2025-11-20 16:46:31 +01:00
a3b12a6957 bump to 3.8.1 2025-11-20 14:49:10 +01:00
16bdc7820d update privacy policy (English) 2025-11-20 14:14:25 +01:00
06e32b99ea update privacy policy (German) title and last updated date 2025-11-20 14:06:51 +01:00
c7c78f96a6 refactor(PDFBurner): fix merging errors 2025-11-20 12:34:30 +01:00
5c232e61f2 merge PDFBurner changes 2025-11-20 11:57:00 +01:00
24c9321c0f bump to 3.8.0 2025-11-20 10:34:19 +01:00
c75c2b1dd5 feat(envelope-api.js): append envKey query parameter to all outgoing requests
Added automatic injection of the envKey query parameter into all request URLs within sendRequest.
Updated URL handling to use the URL API, ensuring consistent parameter merging and preventing missing envKey issues.
2025-11-20 10:33:54 +01:00
8445757f34 feat: replace default cookie events with custom EnvelopeCookieManager and introduce custom auth cookie name (env_auth) 2025-11-20 10:32:32 +01:00
b088eb089f feat(EnvelopeCookieManager): add EnvelopeCookieManager to support envelope-specific cookie names
- Introduce EnvelopeCookieManager wrapper around ChunkingCookieManager to generate dynamic cookie names based on envelopeReceiverId or envKey. Ensures request/response cookies are scoped per envelope.
2025-11-20 10:30:49 +01:00
1f745ae79c refactor(pdfburner): simplify form field handling and improve default field naming
- Replaced ImmutableDictionary-based FormFieldIndex with a simpler Dictionary
- Updated form field ordering to: NoName, signature, position, city, date
- Removed manual formFieldIndex counter, now using dictionary lookup by fieldName
- Introduced FieldNames class with NoName constant (guid-based) for unnamed fields
- Defaulted Annotation.fieldName to FieldNames.NoName instead of Nothing
2025-10-09 18:59:18 +02:00
234 changed files with 3558 additions and 1366 deletions

View File

@@ -0,0 +1,118 @@
using DigitalData.Core.Abstraction.Application.DTO;
using DigitalData.Core.Exceptions;
using EnvelopeGenerator.Application.Common.Extensions;
using EnvelopeGenerator.Application.Common.Interfaces.Services;
using EnvelopeGenerator.Application.Common.Notifications.DocSigned;
using EnvelopeGenerator.Application.EnvelopeReceivers.Queries;
using EnvelopeGenerator.Application.Histories.Queries;
using EnvelopeGenerator.Domain.Constants;
using EnvelopeGenerator.API.Extensions;
using MediatR;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace EnvelopeGenerator.API.Controllers;
/// <summary>
/// Manages annotations and signature lifecycle for envelopes.
/// </summary>
[Authorize(Roles = Role.Receiver.FullyAuth)]
[ApiController]
[Route("api/[controller]")]
public class AnnotationController : ControllerBase
{
[Obsolete("Use MediatR")]
private readonly IEnvelopeHistoryService _historyService;
[Obsolete("Use MediatR")]
private readonly IEnvelopeReceiverService _envelopeReceiverService;
private readonly IMediator _mediator;
private readonly ILogger<AnnotationController> _logger;
/// <summary>
/// Initializes a new instance of <see cref="AnnotationController"/>.
/// </summary>
[Obsolete("Use MediatR")]
public AnnotationController(
ILogger<AnnotationController> logger,
IEnvelopeHistoryService envelopeHistoryService,
IEnvelopeReceiverService envelopeReceiverService,
IMediator mediator)
{
_historyService = envelopeHistoryService;
_envelopeReceiverService = envelopeReceiverService;
_mediator = mediator;
_logger = logger;
}
/// <summary>
/// Creates or updates annotations for the authenticated envelope receiver.
/// </summary>
/// <param name="psPdfKitAnnotation">Annotation payload.</param>
/// <param name="cancel">Cancellation token.</param>
[Authorize(Roles = Role.Receiver.FullyAuth)]
[HttpPost]
[Obsolete("PSPDF Kit will no longer be used.")]
public async Task<IActionResult> CreateOrUpdate([FromBody] PsPdfKitAnnotation? psPdfKitAnnotation = null, CancellationToken cancel = default)
{
var signature = User.GetReceiverSignatureOfReceiver();
var uuid = User.GetEnvelopeUuidOfReceiver();
var envelopeReceiver = await _mediator.ReadEnvelopeReceiverAsync(uuid, signature, cancel).ThrowIfNull(Exceptions.NotFound);
if (!envelopeReceiver.Envelope!.ReadOnly && psPdfKitAnnotation is null)
return BadRequest();
if (await _mediator.IsSignedAsync(uuid, signature, cancel))
return Problem(statusCode: StatusCodes.Status409Conflict);
else if (await _mediator.AnyHistoryAsync(uuid, new[] { EnvelopeStatus.EnvelopeRejected, EnvelopeStatus.DocumentRejected }, cancel))
return Problem(statusCode: StatusCodes.Status423Locked);
var docSignedNotification = await _mediator
.ReadEnvelopeReceiverAsync(uuid, signature, cancel)
.ToDocSignedNotification(psPdfKitAnnotation)
?? throw new NotFoundException("Envelope receiver is not found.");
await _mediator.PublishSafely(docSignedNotification, cancel);
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
/// <summary>
/// Rejects the document for the current receiver.
/// </summary>
/// <param name="reason">Optional rejection reason.</param>
[Authorize(Roles = Role.Receiver.FullyAuth)]
[HttpPost("reject")]
[Obsolete("Use MediatR")]
public async Task<IActionResult> Reject([FromBody] string? reason = null)
{
var signature = User.GetReceiverSignatureOfReceiver();
var uuid = User.GetEnvelopeUuidOfReceiver();
var mail = User.GetReceiverMailOfReceiver();
var envRcvRes = await _envelopeReceiverService.ReadByUuidSignatureAsync(uuid: uuid, signature: signature);
if (envRcvRes.IsFailed)
{
_logger.LogNotice(envRcvRes.Notices);
return Unauthorized("you are not authorized");
}
var histRes = await _historyService.RecordAsync(envRcvRes.Data.EnvelopeId, userReference: mail, EnvelopeStatus.DocumentRejected, comment: reason);
if (histRes.IsSuccess)
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return NoContent();
}
_logger.LogEnvelopeError(uuid: uuid, signature: signature, message: "Unexpected error happened in api/envelope/reject");
_logger.LogNotice(histRes.Notices);
return StatusCode(500, histRes.Messages);
}
}

View File

@@ -0,0 +1,59 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using EnvelopeGenerator.API.Models;
namespace EnvelopeGenerator.API.Controllers;
/// <summary>
/// Controller verantwortlich für die Benutzer-Authentifizierung, einschließlich Anmelden, Abmelden und Überprüfung des Authentifizierungsstatus.
/// </summary>
/// <param name="logger"></param>
[Route("api/[controller]")]
[ApiController]
public partial class AuthController(ILogger<AuthController> logger) : ControllerBase
{
/// <summary>
/// Entfernt das Authentifizierungs-Cookie des Benutzers (AuthCookie)
/// </summary>
/// <returns>
/// Gibt eine HTTP 200 oder 401.
/// </returns>
/// <remarks>
/// Sample request:
///
/// POST /api/auth/logout
///
/// </remarks>
/// <response code="200">Erfolgreich gelöscht, wenn der Benutzer ein berechtigtes Cookie hat.</response>
/// <response code="401">Wenn es kein zugelassenes Cookie gibt, wird „nicht zugelassen“ zurückgegeben.</response>
[ProducesResponseType(typeof(string), StatusCodes.Status200OK, "text/javascript")]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
[Authorize]
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
/// <summary>
/// Prüft, ob der Benutzer ein autorisiertes Token hat.
/// </summary>
/// <returns>Wenn ein autorisiertes Token vorhanden ist HTTP 200 asynchron 401</returns>
/// <remarks>
/// Sample request:
///
/// GET /api/auth
///
/// </remarks>
/// <response code="200">Wenn es einen autorisierten Cookie gibt.</response>
/// <response code="401">Wenn kein Cookie vorhanden ist oder nicht autorisierte.</response>
[ProducesResponseType(typeof(string), StatusCodes.Status200OK, "text/javascript")]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
[Authorize]
[HttpGet]
public IActionResult IsAuthenticated() => Ok();
}

View File

@@ -0,0 +1,30 @@
using EnvelopeGenerator.API.Models.PsPdfKitAnnotation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace EnvelopeGenerator.API.Controllers;
/// <summary>
/// Exposes configuration data required by the client applications.
/// </summary>
/// <remarks>
/// Initializes a new instance of <see cref="ConfigController"/>.
/// </remarks>
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ConfigController(IOptionsMonitor<AnnotationParams> annotationParamsOptions) : ControllerBase
{
private readonly AnnotationParams _annotationParams = annotationParamsOptions.CurrentValue;
/// <summary>
/// Returns annotation configuration that was previously rendered by MVC.
/// </summary>
[HttpGet("Annotations")]
[Obsolete("PSPDF Kit will no longer be used.")]
public IActionResult GetAnnotationParams()
{
return Ok(_annotationParams.AnnotationJSObject);
}
}

View File

@@ -0,0 +1,57 @@
using EnvelopeGenerator.API.Extensions;
using EnvelopeGenerator.Application.Documents.Queries;
using EnvelopeGenerator.Domain.Constants;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace EnvelopeGenerator.API.Controllers;
/// <summary>
/// Provides access to envelope documents for authenticated receivers.
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="DocumentController"/> class.
/// </remarks>
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class DocumentController(IMediator mediator, ILogger<DocumentController> logger) : ControllerBase
{
/// <summary>
/// Returns the document bytes receiver.
/// </summary>
/// <param name="query">Encoded envelope key.</param>
/// <param name="cancel">Cancellation token.</param>
[HttpGet]
[Authorize(Roles = $"{Role.Sender},{Role.Receiver.FullyAuth}")]
public async Task<IActionResult> GetDocument(CancellationToken cancel, [FromQuery] ReadDocumentQuery? query = null)
{
// Sender: expects query with envelope key
if (User.IsInRole(Role.Sender))
{
if (query is null)
return BadRequest("Missing document query.");
var senderDoc = await mediator.Send(query, cancel);
return senderDoc.ByteData is byte[] senderDocByte
? File(senderDocByte, "application/octet-stream")
: NotFound("Document is empty.");
}
// Receiver: resolve envelope id from claims
if (User.IsInRole(Role.Receiver.FullyAuth))
{
if (query is not null)
return BadRequest("Query parameters are not allowed for receiver role.");
var envelopeId = User.GetEnvelopeIdOfReceiver();
var receiverDoc = await mediator.Send(new ReadDocumentQuery { EnvelopeId = envelopeId }, cancel);
return receiverDoc.ByteData is byte[] receiverDocByte
? File(receiverDocByte, "application/octet-stream")
: NotFound("Document is empty.");
}
return Unauthorized();
}
}

View File

@@ -7,12 +7,12 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using MediatR; using MediatR;
using System.Threading.Tasks; using System.Threading.Tasks;
using DigitalData.UserManager.Application.Services;
using DigitalData.Core.Exceptions;
using EnvelopeGenerator.Application.Common.Dto; using EnvelopeGenerator.Application.Common.Dto;
using EnvelopeGenerator.Application.Common.Interfaces.Repositories; using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace EnvelopeGenerator.GeneratorAPI.Controllers; namespace EnvelopeGenerator.API.Controllers;
/// <summary> /// <summary>
/// Controller for managing temp templates. /// Controller for managing temp templates.
@@ -23,12 +23,9 @@ namespace EnvelopeGenerator.GeneratorAPI.Controllers;
[Authorize] [Authorize]
public class EmailTemplateController : ControllerBase public class EmailTemplateController : ControllerBase
{ {
private readonly ILogger<EmailTemplateController> _logger;
private readonly IMapper _mapper; private readonly IMapper _mapper;
[Obsolete("Use IRepository")] private readonly IRepository<EmailTemplate> _repository;
private readonly IEmailTemplateRepository _repository;
private readonly IMediator _mediator; private readonly IMediator _mediator;
@@ -39,12 +36,11 @@ public class EmailTemplateController : ControllerBase
/// <param name="repository"> /// <param name="repository">
/// Die AutoMapper-Instanz, die zum Zuordnen von Objekten verwendet wird. /// Die AutoMapper-Instanz, die zum Zuordnen von Objekten verwendet wird.
/// </param> /// </param>
[Obsolete("Use IRepository")] [Obsolete("Use MediatR")]
public EmailTemplateController(IMapper mapper, IEmailTemplateRepository repository, ILogger<EmailTemplateController> logger, IMediator mediator) public EmailTemplateController(IMapper mapper, IRepository<EmailTemplate> repository, IMediator mediator)
{ {
_mapper = mapper; _mapper = mapper;
_repository = repository; _repository = repository;
_logger = logger;
_mediator = mediator; _mediator = mediator;
} }
@@ -67,7 +63,7 @@ public class EmailTemplateController : ControllerBase
{ {
if (emailTemplate is null || (emailTemplate.Id is null && emailTemplate.Type is null)) if (emailTemplate is null || (emailTemplate.Id is null && emailTemplate.Type is null))
{ {
var temps = await _repository.ReadAllAsync(); var temps = await _repository.Query.ToListAsync();
return Ok(_mapper.Map<IEnumerable<EmailTemplateDto>>(temps)); return Ok(_mapper.Map<IEnumerable<EmailTemplateDto>>(temps));
} }
else else

View File

@@ -0,0 +1,111 @@
using EnvelopeGenerator.API.Extensions;
using EnvelopeGenerator.Application.Envelopes.Commands;
using EnvelopeGenerator.Application.Envelopes.Queries;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace EnvelopeGenerator.API.Controllers;
/// <summary>
/// Dieser Controller stellt Endpunkte für die Verwaltung von Umschlägen bereit.
/// </summary>
/// <remarks>
/// Die API ermöglicht das Abrufen und Verwalten von Umschlägen basierend auf Benutzerinformationen und Statusfiltern.
///
/// Mögliche Antworten:
/// - 200 OK: Die Anfrage war erfolgreich, und die angeforderten Daten werden zurückgegeben.
/// - 400 Bad Request: Die Anfrage war fehlerhaft oder unvollständig.
/// - 401 Unauthorized: Der Benutzer ist nicht authentifiziert.
/// - 403 Forbidden: Der Benutzer hat keine Berechtigung, auf die Ressource zuzugreifen.
/// - 404 Not Found: Die angeforderte Ressource wurde nicht gefunden.
/// - 500 Internal Server Error: Ein unerwarteter Fehler ist aufgetreten.
/// </remarks>
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class EnvelopeController : ControllerBase
{
private readonly ILogger<EnvelopeController> _logger;
private readonly IMediator _mediator;
/// <summary>
/// Erstellt eine neue Instanz des EnvelopeControllers.
/// </summary>
/// <param name="logger">Der Logger, der für das Protokollieren von Informationen verwendet wird.</param>
/// <param name="mediator"></param>
public EnvelopeController(ILogger<EnvelopeController> logger, IMediator mediator)
{
_logger = logger;
_mediator = mediator;
}
/// <summary>
/// Ruft eine Liste von Umschlägen basierend auf dem Benutzer und den angegebenen Statusfiltern ab.
/// </summary>
/// <param name="envelope"></param>
/// <returns>Eine IActionResult-Instanz, die die abgerufenen Umschläge oder einen Fehlerstatus enthält.</returns>
/// <response code="200">Die Anfrage war erfolgreich, und die Umschläge werden zurückgegeben.</response>
/// <response code="400">Die Anfrage war fehlerhaft oder unvollständig.</response>
/// <response code="401">Der Benutzer ist nicht authentifiziert.</response>
/// <response code="403">Der Benutzer hat keine Berechtigung, auf die Ressource zuzugreifen.</response>
/// <response code="500">Ein unerwarteter Fehler ist aufgetreten.</response>
[Authorize]
[HttpGet]
public async Task<IActionResult> GetAsync([FromQuery] ReadEnvelopeQuery envelope)
{
var result = await _mediator.Send(envelope.Authorize(User.GetId()));
return result.Any() ? Ok(result) : NotFound();
}
/// <summary>
/// Ruft das Ergebnis eines Dokuments basierend auf der ID ab.
/// </summary>
/// <param name="query"></param>
/// <param name="view">Gibt an, ob das Dokument inline angezeigt werden soll (true) oder als Download bereitgestellt wird (false).</param>
/// <returns>Eine IActionResult-Instanz, die das Dokument oder einen Fehlerstatus enthält.</returns>
/// <response code="200">Das Dokument wurde erfolgreich abgerufen.</response>
/// <response code="404">Das Dokument wurde nicht gefunden oder ist nicht verfügbar.</response>
/// <response code="500">Ein unerwarteter Fehler ist aufgetreten.</response>
[HttpGet("doc-result")]
public async Task<IActionResult> GetDocResultAsync([FromQuery] ReadEnvelopeQuery query, [FromQuery] bool view = false)
{
var envelopes = await _mediator.Send(query.Authorize(User.GetId()));
var envelope = envelopes.FirstOrDefault();
if (envelope is null)
return NotFound("Envelope not available.");
if (envelope.DocResult is null)
return NotFound("The document has not been fully signed or the result has not yet been released.");
if (view)
{
Response.Headers.Append("Content-Disposition", "inline; filename=\"" + envelope.Uuid + ".pdf\"");
return File(envelope.DocResult, "application/pdf");
}
return File(envelope.DocResult, "application/pdf", $"{envelope.Uuid}.pdf");
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[NonAction]
[Authorize]
[HttpPost]
public async Task<IActionResult> CreateAsync([FromBody] CreateEnvelopeCommand command)
{
var res = await _mediator.Send(command.Authorize(User.GetId()));
if (res is null)
{
_logger.LogError("Failed to create envelope. Envelope details: {EnvelopeDetails}", JsonConvert.SerializeObject(command));
return StatusCode(StatusCodes.Status500InternalServerError);
}
else
return Ok(res);
}
}

View File

@@ -1,25 +1,21 @@
using AutoMapper; using AutoMapper;
using DigitalData.Core.Abstraction.Application.DTO;
using EnvelopeGenerator.Application.EnvelopeReceivers.Commands; using EnvelopeGenerator.Application.EnvelopeReceivers.Commands;
using EnvelopeGenerator.Application.EnvelopeReceivers.Queries; using EnvelopeGenerator.Application.EnvelopeReceivers.Queries;
using EnvelopeGenerator.Application.Envelopes.Queries; using EnvelopeGenerator.Application.Envelopes.Queries;
using EnvelopeGenerator.Domain.Entities; using EnvelopeGenerator.Domain.Entities;
using EnvelopeGenerator.GeneratorAPI.Models; using EnvelopeGenerator.API.Models;
using MediatR; using MediatR;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient; using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using System.Data; using System.Data;
using System.Reflection.Metadata;
using EnvelopeGenerator.Domain;
using EnvelopeGenerator.Domain.Constants;
using EnvelopeGenerator.Application.Common.SQL; using EnvelopeGenerator.Application.Common.SQL;
using EnvelopeGenerator.Application.Common.Dto.Receiver; using EnvelopeGenerator.Application.Common.Dto.Receiver;
using EnvelopeGenerator.Application.Common.Interfaces.Services;
using EnvelopeGenerator.Application.Common.Interfaces.SQLExecutor; using EnvelopeGenerator.Application.Common.Interfaces.SQLExecutor;
using EnvelopeGenerator.API.Extensions;
namespace EnvelopeGenerator.GeneratorAPI.Controllers; namespace EnvelopeGenerator.API.Controllers;
/// <summary> /// <summary>
/// Controller für die Verwaltung von Umschlagempfängern. /// Controller für die Verwaltung von Umschlagempfängern.
@@ -33,38 +29,19 @@ namespace EnvelopeGenerator.GeneratorAPI.Controllers;
public class EnvelopeReceiverController : ControllerBase public class EnvelopeReceiverController : ControllerBase
{ {
private readonly ILogger<EnvelopeReceiverController> _logger; private readonly ILogger<EnvelopeReceiverController> _logger;
[Obsolete("Use MediatR")]
private readonly IEnvelopeReceiverService _erService;
private readonly IMediator _mediator; private readonly IMediator _mediator;
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly IEnvelopeExecutor _envelopeExecutor; private readonly IEnvelopeExecutor _envelopeExecutor;
private readonly IEnvelopeReceiverExecutor _erExecutor; private readonly IEnvelopeReceiverExecutor _erExecutor;
private readonly IDocumentExecutor _documentExecutor; private readonly IDocumentExecutor _documentExecutor;
private readonly string _cnnStr; private readonly string _cnnStr;
/// <summary> /// <summary>
/// Konstruktor für den EnvelopeReceiverController. /// Konstruktor für den EnvelopeReceiverController.
/// </summary> /// </summary>
/// <param name="logger">Logger-Instanz zur Protokollierung von Informationen und Fehlern.</param> public EnvelopeReceiverController(ILogger<EnvelopeReceiverController> logger, IMediator mediator, IMapper mapper, IEnvelopeExecutor envelopeExecutor, IEnvelopeReceiverExecutor erExecutor, IDocumentExecutor documentExecutor, IOptions<ConnectionString> csOpt)
/// <param name="envelopeReceiverService">Service zur Verwaltung von Umschlagempfängern.</param>
/// <param name="mediator">Mediator-Instanz zur Verarbeitung von Befehlen und Abfragen.</param>
/// <param name="mapper"></param>
/// <param name="envelopeExecutor"></param>
/// <param name="erExecutor"></param>
/// <param name="documentExecutor"></param>
/// <param name="csOpt"></param>
[Obsolete("Use MediatR")]
public EnvelopeReceiverController(ILogger<EnvelopeReceiverController> logger, IEnvelopeReceiverService envelopeReceiverService, IMediator mediator, IMapper mapper, IEnvelopeExecutor envelopeExecutor, IEnvelopeReceiverExecutor erExecutor, IDocumentExecutor documentExecutor, IOptions<ConnectionString> csOpt)
{ {
_logger = logger; _logger = logger;
_erService = envelopeReceiverService;
_mediator = mediator; _mediator = mediator;
_mapper = mapper; _mapper = mapper;
_envelopeExecutor = envelopeExecutor; _envelopeExecutor = envelopeExecutor;
@@ -87,32 +64,13 @@ public class EnvelopeReceiverController : ControllerBase
/// <response code="500">Ein unerwarteter Fehler ist aufgetreten.</response> /// <response code="500">Ein unerwarteter Fehler ist aufgetreten.</response>
[Authorize] [Authorize]
[HttpGet] [HttpGet]
[Obsolete("Use MediatR")]
public async Task<IActionResult> GetEnvelopeReceiver([FromQuery] ReadEnvelopeReceiverQuery envelopeReceiver) public async Task<IActionResult> GetEnvelopeReceiver([FromQuery] ReadEnvelopeReceiverQuery envelopeReceiver)
{ {
var username = User.GetUsernameOrDefault(); envelopeReceiver = envelopeReceiver with { Username = User.GetUsername() };
if (username is null) var result = await _mediator.Send(envelopeReceiver);
{
_logger.LogError(@"Envelope Receiver dto cannot be sent because username claim is null. Potential authentication and authorization error. The value of other claims are [id: {id}], [username: {username}], [name: {name}], [prename: {prename}], [email: {email}].",
User.GetId(), User.GetUsernameOrDefault(), User.GetNameOrDefault(), User.GetPrenameOrDefault(), User.GetEmailOrDefault());
return StatusCode(StatusCodes.Status500InternalServerError);
}
return await _erService.ReadByUsernameAsync( return Ok(result);
username: username,
min_status: envelopeReceiver.Envelope.Status?.Min,
max_status: envelopeReceiver.Envelope.Status?.Max,
envelopeQuery: envelopeReceiver.Envelope,
receiverQuery: envelopeReceiver.Receiver,
ignore_statuses: envelopeReceiver.Envelope.Status?.Ignore ?? Array.Empty<EnvelopeStatus>())
.ThenAsync(
Success: Ok,
Fail: IActionResult (msg, ntc) =>
{
_logger.LogNotice(ntc);
return StatusCode(StatusCodes.Status500InternalServerError, msg);
});
} }
/// <summary> /// <summary>
@@ -129,25 +87,17 @@ public class EnvelopeReceiverController : ControllerBase
/// <response code="500">Ein unerwarteter Fehler ist aufgetreten.</response> /// <response code="500">Ein unerwarteter Fehler ist aufgetreten.</response>
[Authorize] [Authorize]
[HttpGet("salute")] [HttpGet("salute")]
[Obsolete("Use MediatR")]
public async Task<IActionResult> GetReceiverName([FromQuery] ReadReceiverNameQuery receiver) public async Task<IActionResult> GetReceiverName([FromQuery] ReadReceiverNameQuery receiver)
{ {
return await _erService.ReadLastUsedReceiverNameByMailAsync(receiver.EmailAddress, receiver.Id, receiver.Signature).ThenAsync( var name = await _mediator.Send(receiver);
Success: res => res is null ? NotFound() : Ok(res), return name is null ? NotFound() : Ok(name);
Fail: IActionResult (msg, ntc) =>
{
if (ntc.HasFlag(Flag.NotFound))
return NotFound();
_logger.LogNotice(ntc);
return StatusCode(StatusCodes.Status500InternalServerError);
});
} }
/// <summary> /// <summary>
/// Datenübertragungsobjekt mit Informationen zu Umschlägen, Empfängern und Unterschriften. /// Datenübertragungsobjekt mit Informationen zu Umschlägen, Empfängern und Unterschriften.
/// </summary> /// </summary>
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="cancel"></param>
/// <returns>HTTP-Antwort</returns> /// <returns>HTTP-Antwort</returns>
/// <remarks> /// <remarks>
/// Sample request: /// Sample request:
@@ -183,13 +133,10 @@ public class EnvelopeReceiverController : ControllerBase
/// <response code="500">Es handelt sich um einen unerwarteten Fehler. Die Protokolle sollten überprüft werden.</response> /// <response code="500">Es handelt sich um einen unerwarteten Fehler. Die Protokolle sollten überprüft werden.</response>
[Authorize] [Authorize]
[HttpPost] [HttpPost]
public async Task<IActionResult> CreateAsync([FromBody] CreateEnvelopeReceiverCommand request) public async Task<IActionResult> CreateAsync([FromBody] CreateEnvelopeReceiverCommand request, CancellationToken cancel)
{ {
CancellationToken cancel = default;
int userId = User.GetId();
#region Create Envelope #region Create Envelope
var envelope = await _envelopeExecutor.CreateEnvelopeAsync(userId, request.Title, request.Message, request.TFAEnabled, cancel); var envelope = await _envelopeExecutor.CreateEnvelopeAsync(User.GetId(), request.Title, request.Message, request.TFAEnabled, cancel);
#endregion #endregion
#region Add receivers #region Add receivers
@@ -270,18 +217,14 @@ public class EnvelopeReceiverController : ControllerBase
using (SqlConnection conn = new(_cnnStr)) using (SqlConnection conn = new(_cnnStr))
{ {
conn.Open(); conn.Open();
var formattedSQL_hist = string.Format(sql_hist, envelope.Uuid.ToSqlParam(), 1003.ToSqlParam(), userId.ToSqlParam()); var formattedSQL_hist = string.Format(sql_hist, envelope.Uuid.ToSqlParam(), 1003.ToSqlParam(), User.GetId().ToSqlParam());
using (SqlCommand cmd = new SqlCommand(formattedSQL_hist, conn)) using SqlCommand cmd = new(formattedSQL_hist, conn);
{ cmd.CommandType = CommandType.Text;
cmd.CommandType = CommandType.Text;
using (SqlDataReader reader = cmd.ExecuteReader()) using SqlDataReader reader = cmd.ExecuteReader();
{ if (reader.Read())
if (reader.Read()) {
{ bool outSuccess = reader.GetBoolean(0);
bool outSuccess = reader.GetBoolean(0);
}
}
} }
} }
#endregion #endregion

View File

@@ -0,0 +1,39 @@
using MediatR;
using EnvelopeGenerator.Application.EnvelopeTypes.Queries;
using Microsoft.AspNetCore.Mvc;
namespace EnvelopeGenerator.GeneratorAPI.Controllers;
/// <summary>
///
/// </summary>
[ApiExplorerSettings(IgnoreApi = true)]
[Route("api/[controller]")]
[ApiController]
public class EnvelopeTypeController : ControllerBase
{
private readonly ILogger<EnvelopeTypeController> _logger;
private readonly IMediator _mediator;
/// <summary>
///
/// </summary>
/// <param name="logger"></param>
/// <param name="mediator"></param>
public EnvelopeTypeController(ILogger<EnvelopeTypeController> logger, IMediator mediator)
{
_logger = logger;
_mediator = mediator;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> GetAllAsync()
{
var result = await _mediator.Send(new ReadEnvelopeTypesQuery());
return Ok(result);
}
}

View File

@@ -6,7 +6,7 @@ using EnvelopeGenerator.Application.Histories.Queries;
using EnvelopeGenerator.Domain.Constants; using EnvelopeGenerator.Domain.Constants;
using EnvelopeGenerator.Application.Common.Extensions; using EnvelopeGenerator.Application.Common.Extensions;
namespace EnvelopeGenerator.GeneratorAPI.Controllers; namespace EnvelopeGenerator.API.Controllers;
/// <summary> /// <summary>
/// Dieser Controller stellt Endpunkte für den Zugriff auf die Umschlaghistorie bereit. /// Dieser Controller stellt Endpunkte für den Zugriff auf die Umschlaghistorie bereit.
@@ -113,6 +113,6 @@ public class HistoryController : ControllerBase
public async Task<IActionResult> GetAllAsync([FromQuery] ReadHistoryQuery historyQuery, CancellationToken cancel) public async Task<IActionResult> GetAllAsync([FromQuery] ReadHistoryQuery historyQuery, CancellationToken cancel)
{ {
var history = await _mediator.Send(historyQuery, cancel).ThrowIfEmpty(Exceptions.NotFound); var history = await _mediator.Send(historyQuery, cancel).ThrowIfEmpty(Exceptions.NotFound);
return Ok((historyQuery.OnlyLast ?? false) ? history.MaxBy(h => h.AddedWhen) : history); return Ok((historyQuery.OnlyLast) ? history.MaxBy(h => h.AddedWhen) : history);
} }
} }

View File

@@ -1,12 +1,12 @@
using DigitalData.Core.API; using DigitalData.Core.API;
using EnvelopeGenerator.Application.Resources; using EnvelopeGenerator.Application.Resources;
using EnvelopeGenerator.CommonServices;
using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using EnvelopeGenerator.Application.Resources;
namespace EnvelopeGenerator.GeneratorAPI.Controllers; namespace EnvelopeGenerator.API.Controllers;
/// <summary> /// <summary>
/// Controller für die Verwaltung der Lokalisierung und Spracheinstellungen. /// Controller für die Verwaltung der Lokalisierung und Spracheinstellungen.
@@ -19,7 +19,7 @@ public class LocalizationController : ControllerBase
private static readonly Guid L_KEY = Guid.NewGuid(); private static readonly Guid L_KEY = Guid.NewGuid();
private readonly ILogger<LocalizationController> _logger; private readonly ILogger<LocalizationController> _logger;
private readonly IStringLocalizer<Model> _mLocalizer; private readonly IStringLocalizer<Resource> _mLocalizer;
private readonly IStringLocalizer<Resource> _localizer; private readonly IStringLocalizer<Resource> _localizer;
private readonly IMemoryCache _cache; private readonly IMemoryCache _cache;
@@ -34,7 +34,7 @@ public class LocalizationController : ControllerBase
ILogger<LocalizationController> logger, ILogger<LocalizationController> logger,
IStringLocalizer<Resource> localizer, IStringLocalizer<Resource> localizer,
IMemoryCache memoryCache, IMemoryCache memoryCache,
IStringLocalizer<Model> _modelLocalizer) IStringLocalizer<Resource> _modelLocalizer)
{ {
_logger = logger; _logger = logger;
_localizer = localizer; _localizer = localizer;

View File

@@ -0,0 +1,90 @@
using DigitalData.Core.Abstraction.Application.DTO;
using EnvelopeGenerator.Application.Common.Dto.EnvelopeReceiverReadOnly;
using EnvelopeGenerator.Application.Common.Interfaces.Services;
using EnvelopeGenerator.Domain.Constants;
using EnvelopeGenerator.API.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace EnvelopeGenerator.API.Controllers;
/// <summary>
/// Manages read-only envelope sharing flows.
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class ReadOnlyController : ControllerBase
{
private readonly ILogger<ReadOnlyController> _logger;
private readonly IEnvelopeReceiverReadOnlyService _readOnlyService;
private readonly IEnvelopeMailService _mailService;
private readonly IEnvelopeHistoryService _historyService;
/// <summary>
/// Initializes a new instance of the <see cref="ReadOnlyController"/> class.
/// </summary>
public ReadOnlyController(ILogger<ReadOnlyController> logger, IEnvelopeReceiverReadOnlyService readOnlyService, IEnvelopeMailService mailService, IEnvelopeHistoryService historyService)
{
_logger = logger;
_readOnlyService = readOnlyService;
_mailService = mailService;
_historyService = historyService;
}
/// <summary>
/// Creates a new read-only receiver for the current envelope.
/// </summary>
/// <param name="createDto">Creation payload.</param>
[HttpPost]
[Authorize(Roles = Role.Receiver.FullyAuth)]
public async Task<IActionResult> CreateAsync([FromBody] EnvelopeReceiverReadOnlyCreateDto createDto)
{
var authReceiverMail = User.GetReceiverMailOfReceiver();
if (authReceiverMail is null)
{
_logger.LogError("EmailAddress claim is not found in envelope-receiver-read-only creation process. Create DTO is:\n {dto}", JsonConvert.SerializeObject(createDto));
return Unauthorized();
}
var envelopeId = User.GetEnvelopeIdOfReceiver();
createDto.AddedWho = authReceiverMail;
createDto.EnvelopeId = envelopeId;
var creationRes = await _readOnlyService.CreateAsync(createDto: createDto);
if (creationRes.IsFailed)
{
_logger.LogNotice(creationRes);
return StatusCode(StatusCodes.Status500InternalServerError);
}
var readRes = await _readOnlyService.ReadByIdAsync(creationRes.Data.Id);
if (readRes.IsFailed)
{
_logger.LogNotice(creationRes);
return StatusCode(StatusCodes.Status500InternalServerError);
}
var newReadOnly = readRes.Data;
return await _mailService.SendAsync(newReadOnly).ThenAsync<int, IActionResult>(SuccessAsync: async _ =>
{
var histRes = await _historyService.RecordAsync((int)createDto.EnvelopeId, createDto.AddedWho, EnvelopeStatus.EnvelopeShared);
if (histRes.IsFailed)
{
_logger.LogError("Although the envelope was sent as read-only, the EnvelopeShared history could not be saved. Create DTO:\n{createDto}", JsonConvert.SerializeObject(createDto));
_logger.LogNotice(histRes.Notices);
}
return Ok();
},
Fail: (msg, ntc) =>
{
_logger.LogNotice(ntc);
return StatusCode(StatusCodes.Status500InternalServerError);
});
}
}

View File

@@ -0,0 +1,47 @@
using MediatR;
using EnvelopeGenerator.Application.Receivers.Queries;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace EnvelopeGenerator.GeneratorAPI.Controllers;
/// <summary>
/// Controller für die Verwaltung von Empfängern.
/// </summary>
/// <remarks>
/// Dieser Controller bietet Endpunkte für das Abrufen von Empfängern basierend auf E-Mail-Adresse oder Signatur.
/// </remarks>
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ReceiverController : ControllerBase
{
private readonly IMediator _mediator;
/// <summary>
/// Initialisiert eine neue Instanz des <see cref="ReceiverController"/>-Controllers.
/// </summary>
/// <param name="mediator">Mediator für Anfragen.</param>
public ReceiverController(IMediator mediator)
{
_mediator = mediator;
}
/// <summary>
/// Ruft eine Liste von Empfängern ab, basierend auf den angegebenen Abfrageparametern.
/// </summary>
/// <param name="receiver">Die Abfrageparameter, einschließlich E-Mail-Adresse und Signatur.</param>
/// <returns>Eine Liste von Empfängern oder ein Fehlerstatus.</returns>
[HttpGet]
public async Task<IActionResult> Get([FromQuery] ReadReceiverQuery receiver)
{
if (!receiver.HasAnyCriteria)
{
var all = await _mediator.Send(new ReadReceiverQuery());
return Ok(all);
}
var result = await _mediator.Send(receiver);
return result is null ? NotFound() : Ok(result);
}
}

View File

@@ -0,0 +1,129 @@
using DigitalData.Core.Abstraction.Application.DTO;
using EnvelopeGenerator.Application.Common.Extensions;
using EnvelopeGenerator.Application.Common.Interfaces.Services;
using EnvelopeGenerator.Application.Resources;
using EnvelopeGenerator.Domain.Constants;
using EnvelopeGenerator.API.Models;
using Ganss.Xss;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
namespace EnvelopeGenerator.API.Controllers;
/// <summary>
/// Exposes endpoints for registering and managing two-factor authentication for envelope receivers.
/// </summary>
[ApiController]
[Route("api/tfa")]
public class TfaRegistrationController : ControllerBase
{
private readonly ILogger<TfaRegistrationController> _logger;
private readonly IEnvelopeReceiverService _envelopeReceiverService;
private readonly IAuthenticator _authenticator;
private readonly IReceiverService _receiverService;
private readonly TFARegParams _parameters;
private readonly IStringLocalizer<Resource> _localizer;
/// <summary>
/// Initializes a new instance of the <see cref="TfaRegistrationController"/> class.
/// </summary>
public TfaRegistrationController(
ILogger<TfaRegistrationController> logger,
IEnvelopeReceiverService envelopeReceiverService,
IAuthenticator authenticator,
IReceiverService receiverService,
IOptions<TFARegParams> tfaRegParamsOptions,
IStringLocalizer<Resource> localizer)
{
_logger = logger;
_envelopeReceiverService = envelopeReceiverService;
_authenticator = authenticator;
_receiverService = receiverService;
_parameters = tfaRegParamsOptions.Value;
_localizer = localizer;
}
/// <summary>
/// Generates registration metadata (QR code and deadline) for a receiver.
/// </summary>
/// <param name="envelopeReceiverId">Encoded envelope receiver id.</param>
[Authorize]
[HttpGet("{envelopeReceiverId}")]
public async Task<IActionResult> RegisterAsync(string envelopeReceiverId)
{
try
{
var (uuid, signature) = envelopeReceiverId.DecodeEnvelopeReceiverId();
if (uuid is null || signature is null)
{
_logger.LogEnvelopeError(uuid: uuid, signature: signature, message: _localizer.WrongEnvelopeReceiverId());
return Unauthorized(new { message = _localizer.WrongEnvelopeReceiverId() });
}
var secretResult = await _envelopeReceiverService.ReadWithSecretByUuidSignatureAsync(uuid: uuid, signature: signature);
if (secretResult.IsFailed)
{
_logger.LogNotice(secretResult.Notices);
return NotFound(new { message = _localizer.WrongEnvelopeReceiverId() });
}
var envelopeReceiver = secretResult.Data;
if (!envelopeReceiver.Envelope!.TFAEnabled)
return Unauthorized(new { message = _localizer.WrongAccessCode() });
var receiver = envelopeReceiver.Receiver;
receiver!.TotpSecretkey = _authenticator.GenerateTotpSecretKey();
await _receiverService.UpdateAsync(receiver);
var totpQr64 = _authenticator.GenerateTotpQrCode(userEmail: receiver.EmailAddress, secretKey: receiver.TotpSecretkey).ToBase64String();
if (receiver.TfaRegDeadline is null)
{
receiver.TfaRegDeadline = _parameters.Deadline;
await _receiverService.UpdateAsync(receiver);
}
else if (receiver.TfaRegDeadline <= DateTime.Now)
{
return StatusCode(StatusCodes.Status410Gone, new { message = _localizer.WrongAccessCode() });
}
return Ok(new
{
envelopeReceiver.EnvelopeId,
envelopeReceiver.Envelope!.Uuid,
envelopeReceiver.Receiver!.Signature,
receiver.TfaRegDeadline,
TotpQR64 = totpQr64
});
}
catch (Exception ex)
{
_logger.LogEnvelopeError(envelopeReceiverId: envelopeReceiverId, exception: ex, message: _localizer.WrongEnvelopeReceiverId());
return StatusCode(StatusCodes.Status500InternalServerError, new { message = _localizer.UnexpectedError() });
}
}
/// <summary>
/// Logs out the envelope receiver from cookie authentication.
/// </summary>
[Authorize(Roles = Role.FullyAuth)]
[HttpPost("auth/logout")]
public async Task<IActionResult> LogOutAsync()
{
try
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, "{message}", ex.Message);
return StatusCode(StatusCodes.Status500InternalServerError, new { message = _localizer.UnexpectedError() });
}
}
}

View File

@@ -0,0 +1,70 @@
using EnvelopeGenerator.API.Models;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace EnvelopeGenerator.API.Documentation;
/// <summary>
///
/// </summary>
public sealed class AuthProxyDocumentFilter : IDocumentFilter
{
/// <summary>
///
/// </summary>
/// <param name="swaggerDoc"></param>
/// <param name="context"></param>
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
const string path = "/api/auth";
var loginSchema = context.SchemaGenerator.GenerateSchema(typeof(Login), context.SchemaRepository);
var loginExample = new OpenApiObject
{
["password"] = new OpenApiString(""),
["username"] = new OpenApiString("")
};
var operation = new OpenApiOperation
{
Summary = "Proxy login (auth-hub)",
Description = "Proxies the request to the auth service. Add query parameter `cookie=true|false`.",
Tags = [new() { Name = "Auth" }],
Parameters =
{
new OpenApiParameter
{
Name = "cookie",
In = ParameterLocation.Query,
Required = false,
Schema = new OpenApiSchema { Type = "boolean", Default = new OpenApiBoolean(true) },
Example = new OpenApiBoolean(true),
Description = "If true, auth service sets the auth cookie."
}
},
RequestBody = new OpenApiRequestBody
{
Required = true,
Content =
{
["application/json"] = new OpenApiMediaType { Schema = loginSchema, Example = loginExample },
["multipart/form-data"] = new OpenApiMediaType { Schema = loginSchema, Example = loginExample }
}
},
Responses =
{
["200"] = new OpenApiResponse { Description = "OK (proxied response)" },
["401"] = new OpenApiResponse { Description = "Unauthorized" }
}
};
swaggerDoc.Paths[path] = new OpenApiPathItem
{
Operations =
{
[OperationType.Post] = operation
}
};
}
}

View File

@@ -0,0 +1,17 @@
namespace EnvelopeGenerator.API;
/// <summary>
/// Provides custom claim types for envelope-related information.
/// </summary>
public static class EnvelopeClaimTypes
{
/// <summary>
/// Claim type for the title of an envelope.
/// </summary>
public static readonly string Title = $"Envelope{nameof(Title)}";
/// <summary>
/// Claim type for the ID of an envelope.
/// </summary>
public static readonly string Id = $"Envelope{nameof(Id)}";
}

View File

@@ -17,6 +17,17 @@
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile> <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Remove="ClientApp\**" />
<Content Remove="ClientApp\**" />
<EmbeddedResource Remove="ClientApp\**" />
<None Remove="ClientApp\**" />
</ItemGroup>
<ItemGroup>
<None Include="yarp.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AspNetCore.Scalar" Version="1.1.8" /> <PackageReference Include="AspNetCore.Scalar" Version="1.1.8" />
<PackageReference Include="DigitalData.Auth.Client" Version="1.3.7" /> <PackageReference Include="DigitalData.Auth.Client" Version="1.3.7" />
@@ -28,6 +39,7 @@
<PackageReference Include="Scalar.AspNetCore" Version="2.2.1" /> <PackageReference Include="Scalar.AspNetCore" Version="2.2.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.1" />
<PackageReference Include="DigitalData.EmailProfilerDispatcher.Abstraction" Version="3.2.0" /> <PackageReference Include="DigitalData.EmailProfilerDispatcher.Abstraction" Version="3.2.0" />
<PackageReference Include="Yarp.ReverseProxy" Version="2.1.0" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net7.0'"> <ItemGroup Condition="'$(TargetFramework)' == 'net7.0'">
@@ -49,41 +61,13 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="ClientApp\" /> <Folder Include="wwwroot\" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\EnvelopeGenerator.Application\EnvelopeGenerator.Application.csproj" /> <ProjectReference Include="..\EnvelopeGenerator.Application\EnvelopeGenerator.Application.csproj" />
<ProjectReference Include="..\EnvelopeGenerator.CommonServices\EnvelopeGenerator.CommonServices.vbproj" />
<ProjectReference Include="..\EnvelopeGenerator.Domain\EnvelopeGenerator.Domain.csproj" /> <ProjectReference Include="..\EnvelopeGenerator.Domain\EnvelopeGenerator.Domain.csproj" />
<ProjectReference Include="..\EnvelopeGenerator.Infrastructure\EnvelopeGenerator.Infrastructure.csproj" /> <ProjectReference Include="..\EnvelopeGenerator.Infrastructure\EnvelopeGenerator.Infrastructure.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="ClientApp\envelope-generator-ui\dist\envelope-generator-ui\browser\chunk-35PBLQEP.js">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Update="ClientApp\envelope-generator-ui\dist\envelope-generator-ui\browser\chunk-IUSOII6E.js">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Update="ClientApp\envelope-generator-ui\dist\envelope-generator-ui\browser\favicon.ico">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Update="ClientApp\envelope-generator-ui\dist\envelope-generator-ui\browser\index.html">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Update="ClientApp\envelope-generator-ui\dist\envelope-generator-ui\browser\login\index.html">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Update="ClientApp\envelope-generator-ui\dist\envelope-generator-ui\browser\main-ZN7C4PGY.js">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Update="ClientApp\envelope-generator-ui\dist\envelope-generator-ui\browser\polyfills-N6LQB2YD.js">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Update="ClientApp\envelope-generator-ui\dist\envelope-generator-ui\browser\styles-S5ZWIC2V.css">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@@ -0,0 +1,101 @@
using System.Linq;
using System.Security.Claims;
using EnvelopeGenerator.Application.Common.Dto.EnvelopeReceiver;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
namespace EnvelopeGenerator.API.Extensions;
/// <summary>
/// Provides helper methods for working with envelope-specific authentication claims.
/// </summary>
public static class ReceiverClaimExtensions
{
private static string GetRequiredClaimOfReceiver(this ClaimsPrincipal user, string claimType)
{
var value = user.FindFirstValue(claimType);
if (value is not null)
{
return value;
}
var identity = user.Identity;
var principalName = identity?.Name ?? "(anonymous)";
var authType = identity?.AuthenticationType ?? "(none)";
var availableClaims = string.Join(", ", user.Claims.Select(c => $"{c.Type}={c.Value}"));
var message = $"Required claim '{claimType}' is missing for user '{principalName}' (auth: {authType}). Available claims: [{availableClaims}].";
throw new InvalidOperationException(message);
}
/// <summary>
/// Gets the authenticated envelope UUID from the claims.
/// </summary>
public static string GetEnvelopeUuidOfReceiver(this ClaimsPrincipal user) => user.GetRequiredClaimOfReceiver(ClaimTypes.NameIdentifier);
/// <summary>
/// Gets the authenticated receiver signature from the claims.
/// </summary>
public static string GetReceiverSignatureOfReceiver(this ClaimsPrincipal user) => user.GetRequiredClaimOfReceiver(ClaimTypes.Hash);
/// <summary>
/// Gets the authenticated receiver display name from the claims.
/// </summary>
public static string GetReceiverNameOfReceiver(this ClaimsPrincipal user) => user.GetRequiredClaimOfReceiver(ClaimTypes.Name);
/// <summary>
/// Gets the authenticated receiver email address from the claims.
/// </summary>
public static string GetReceiverMailOfReceiver(this ClaimsPrincipal user) => user.GetRequiredClaimOfReceiver(ClaimTypes.Email);
/// <summary>
/// Gets the authenticated envelope title from the claims.
/// </summary>
public static string GetEnvelopeTitleOfReceiver(this ClaimsPrincipal user) => user.GetRequiredClaimOfReceiver(EnvelopeClaimTypes.Title);
/// <summary>
/// Gets the authenticated envelope identifier from the claims.
/// </summary>
public static int GetEnvelopeIdOfReceiver(this ClaimsPrincipal user)
{
var envIdStr = user.GetRequiredClaimOfReceiver(EnvelopeClaimTypes.Id);
if (!int.TryParse(envIdStr, out var envId))
{
throw new InvalidOperationException($"Claim '{EnvelopeClaimTypes.Id}' is not a valid integer.");
}
return envId;
}
/// <summary>
/// Signs in an envelope receiver using cookie authentication and attaches envelope claims.
/// </summary>
/// <param name="context">The current HTTP context.</param>
/// <param name="envelopeReceiver">Envelope receiver DTO to extract claims from.</param>
/// <param name="receiverRole">Role to attach to the authentication ticket.</param>
public static async Task SignInEnvelopeAsync(this HttpContext context, EnvelopeReceiverDto envelopeReceiver, string receiverRole)
{
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, envelopeReceiver.Envelope!.Uuid),
new(ClaimTypes.Hash, envelopeReceiver.Receiver!.Signature),
new(ClaimTypes.Name, envelopeReceiver.Name ?? string.Empty),
new(ClaimTypes.Email, envelopeReceiver.Receiver.EmailAddress),
new(EnvelopeClaimTypes.Title, envelopeReceiver.Envelope.Title),
new(EnvelopeClaimTypes.Id, envelopeReceiver.Envelope.Id.ToString()),
new(ClaimTypes.Role, receiverRole)
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
AllowRefresh = false,
IsPersistent = false
};
await context.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
}
}

View File

@@ -0,0 +1,95 @@
using System.Security.Claims;
namespace EnvelopeGenerator.API.Extensions
{
/// <summary>
/// Provides extension methods for extracting user information from a <see cref="ClaimsPrincipal"/>.
/// </summary>
public static class SenderClaimExtensions
{
private static string GetRequiredClaimOfSender(this ClaimsPrincipal user, string claimType)
{
var value = user.FindFirstValue(claimType);
if (value is not null)
{
return value;
}
var identity = user.Identity;
var principalName = identity?.Name ?? "(anonymous)";
var authType = identity?.AuthenticationType ?? "(none)";
var availableClaims = string.Join(", ", user.Claims.Select(c => $"{c.Type}={c.Value}"));
var message = $"Required claim '{claimType}' is missing for user '{principalName}' (auth: {authType}). Available claims: [{availableClaims}].";
throw new InvalidOperationException(message);
}
private static string GetRequiredClaimOfSender(this ClaimsPrincipal user, params string[] claimTypes)
{
string? value = null;
foreach (var claimType in claimTypes)
{
value = user.FindFirstValue(claimType);
if (value is not null)
return value;
}
var identity = user.Identity;
var principalName = identity?.Name ?? "(anonymous)";
var authType = identity?.AuthenticationType ?? "(none)";
var availableClaims = string.Join(", ", user.Claims.Select(c => $"{c.Type}={c.Value}"));
var message = $"Required claim among [{string.Join(", ", claimTypes)}] is missing for user '{principalName}' (auth: {authType}). Available claims: [{availableClaims}].";
throw new InvalidOperationException(message);
}
/// <summary>
/// Retrieves the user's ID from the claims. Throws an exception if the ID is missing or invalid.
/// </summary>
/// <param name="user">The <see cref="ClaimsPrincipal"/> representing the user.</param>
/// <returns>The user's ID as an integer.</returns>
/// <exception cref="InvalidOperationException">Thrown if the user ID claim is missing or invalid.</exception>
public static int GetId(this ClaimsPrincipal user)
{
var idValue = user.GetRequiredClaimOfSender(ClaimTypes.NameIdentifier, "sub");
if (!int.TryParse(idValue, out var result))
{
throw new InvalidOperationException("User ID claim is missing or invalid. This may indicate a misconfigured or forged JWT token.");
}
return result;
}
/// <summary>
/// Retrieves the username from the claims.
/// </summary>
/// <param name="user">The <see cref="ClaimsPrincipal"/> representing the user.</param>
/// <returns>The username as a string.</returns>
public static string GetUsername(this ClaimsPrincipal user)
=> user.GetRequiredClaimOfSender(ClaimTypes.Name);
/// <summary>
/// Retrieves the user's surname (last name) from the claims.
/// </summary>
/// <param name="user">The <see cref="ClaimsPrincipal"/> representing the user.</param>
/// <returns>The surname as a string.</returns>
public static string GetName(this ClaimsPrincipal user)
=> user.GetRequiredClaimOfSender(ClaimTypes.Surname);
/// <summary>
/// Retrieves the user's given name (first name) from the claims.
/// </summary>
/// <param name="user">The <see cref="ClaimsPrincipal"/> representing the user.</param>
/// <returns>The given name as a string.</returns>
public static string GetPrename(this ClaimsPrincipal user)
=> user.GetRequiredClaimOfSender(ClaimTypes.GivenName);
/// <summary>
/// Retrieves the user's email address from the claims.
/// </summary>
/// <param name="user">The <see cref="ClaimsPrincipal"/> representing the user.</param>
/// <returns>The email address as a string.</returns>
public static string GetEmail(this ClaimsPrincipal user)
=> user.GetRequiredClaimOfSender(ClaimTypes.Email);
}
}

View File

@@ -1,4 +1,4 @@
namespace EnvelopeGenerator.GeneratorAPI.Middleware; namespace EnvelopeGenerator.API.Middleware;
using DigitalData.Core.Exceptions; using DigitalData.Core.Exceptions;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;

View File

@@ -0,0 +1,14 @@
namespace EnvelopeGenerator.API.Models;
public record Auth(string? AccessCode = null, string? SmsCode = null, string? AuthenticatorCode = null, bool UserSelectSMS = default)
{
public bool HasAccessCode => AccessCode is not null;
public bool HasSmsCode => SmsCode is not null;
public bool HasAuthenticatorCode => AuthenticatorCode is not null;
public bool HasMulti => new[] { HasAccessCode, HasSmsCode, HasAuthenticatorCode }.Count(state => state) > 1;
public bool HasNone => !(HasAccessCode || HasSmsCode || HasAuthenticatorCode);
}

View File

@@ -1,4 +1,4 @@
namespace EnvelopeGenerator.GeneratorAPI.Models; namespace EnvelopeGenerator.API.Models;
/// <summary> /// <summary>
/// Represents the keys and default values used for authentication token handling /// Represents the keys and default values used for authentication token handling
@@ -24,5 +24,5 @@ public class AuthTokenKeys
/// <summary> /// <summary>
/// Gets the expected audience value for the authentication token. /// Gets the expected audience value for the authentication token.
/// </summary> /// </summary>
public string Audience { get; init; } = "sign-flow-gen.digitaldata.works"; public string Audience { get; init; } = "sign-flow.digitaldata.works";
} }

View File

@@ -1,4 +1,4 @@
namespace EnvelopeGenerator.GeneratorAPI.Models; namespace EnvelopeGenerator.API.Models;
/// <summary> /// <summary>
/// ///

View File

@@ -0,0 +1,60 @@
namespace EnvelopeGenerator.API.Models
{
/// <summary>
/// Represents a hyperlink for contact purposes with various HTML attributes.
/// </summary>
public class ContactLink
{
/// <summary>
/// Gets or sets the label of the hyperlink.
/// </summary>
public string Label { get; init; } = "Contact";
/// <summary>
/// Gets or sets the URL that the hyperlink points to.
/// </summary>
public string Href { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the target where the hyperlink should open.
/// Commonly used values are "_blank", "_self", "_parent", "_top".
/// </summary>
public string Target { get; set; } = "_blank";
/// <summary>
/// Gets or sets the relationship of the linked URL as space-separated link types.
/// Examples include "nofollow", "noopener", "noreferrer".
/// </summary>
public string Rel { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the filename that should be downloaded when clicking the hyperlink.
/// This attribute will only have an effect if the href attribute is set.
/// </summary>
public string Download { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the language of the linked resource. Useful when linking to
/// content in another language.
/// </summary>
public string HrefLang { get; set; } = "en";
/// <summary>
/// Gets or sets the MIME type of the linked URL. Helps browsers to handle
/// the type correctly when the link is clicked.
/// </summary>
public string Type { get; set; } = string.Empty;
/// <summary>
/// Gets or sets additional information about the hyperlink, typically viewed
/// as a tooltip when the mouse hovers over the link.
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// Gets or sets an identifier for the hyperlink, unique within the HTML document.
/// </summary>
public string Id { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,17 @@
using System.Globalization;
namespace EnvelopeGenerator.API.Models;
public class Culture
{
private string _language = string.Empty;
public string Language { get => _language;
init {
_language = value;
Info = new(value);
}
}
public string FIClass { get; init; } = string.Empty;
public CultureInfo? Info { get; init; }
}

View File

@@ -0,0 +1,12 @@
namespace EnvelopeGenerator.API.Models;
public class Cultures : List<Culture>
{
public IEnumerable<string> Languages => this.Select(c => c.Language);
public IEnumerable<string> FIClasses => this.Select(c => c.FIClass);
public Culture Default => this.First();
public Culture? this[string? language] => language is null ? null : this.Where(c => c.Language == language).FirstOrDefault();
}

View File

@@ -0,0 +1,6 @@
namespace EnvelopeGenerator.API.Models;
public class CustomImages : Dictionary<string, Image>
{
public new Image this[string key] => TryGetValue(key, out var img) && img is not null ? img : new();
}

View File

@@ -0,0 +1,10 @@
namespace EnvelopeGenerator.API.Models;
public class ErrorViewModel
{
public string Title { get; init; } = "404";
public string Subtitle { get; init; } = "Hmmm...";
public string Body { get; init; } = "It looks like one of the developers fell asleep";
}

View File

@@ -0,0 +1,10 @@
namespace EnvelopeGenerator.API.Models;
public class Image
{
public string Src { get; init; } = string.Empty;
public Dictionary<string, string> Classes { get; init; } = new();
public string GetClassIn(string page) => Classes.TryGetValue(page, out var cls) && cls is not null ? cls : string.Empty;
}

View File

@@ -1,6 +1,6 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace EnvelopeGenerator.GeneratorAPI.Models; namespace EnvelopeGenerator.API.Models;
/// <summary> /// <summary>
/// Repräsentiert ein Login-Modell mit erforderlichem Passwort und optionaler ID und Benutzername. /// Repräsentiert ein Login-Modell mit erforderlichem Passwort und optionaler ID und Benutzername.

View File

@@ -0,0 +1,6 @@
namespace EnvelopeGenerator.API.Models;
public class MainViewModel
{
public string? Title { get; init; }
}

View File

@@ -0,0 +1,93 @@
using EnvelopeGenerator.API.Models.PsPdfKitAnnotation;
using System.Text.Json.Serialization;
namespace EnvelopeGenerator.API.Models.PsPdfKitAnnotation;
public record Annotation : IAnnotation
{
public required string Name { get; init; }
#region Bound Annotation
[JsonIgnore]
public string? HorBoundAnnotName { get; init; }
[JsonIgnore]
public string? VerBoundAnnotName { get; init; }
#endregion
#region Layout
[JsonIgnore]
public double? MarginLeft { get; set; }
[JsonIgnore]
public double MarginLeftRatio { get; init; } = 1;
[JsonIgnore]
public double? MarginTop { get; set; }
[JsonIgnore]
public double MarginTopRatio { get; init; } = 1;
public double? Width { get; set; }
[JsonIgnore]
public double WidthRatio { get; init; } = 1;
public double? Height { get; set; }
[JsonIgnore]
public double HeightRatio { get; init; } = 1;
#endregion
#region Position
public double Left => (MarginLeft ?? 0) + (HorBoundAnnot?.HorBoundary ?? 0);
public double Top => (MarginTop ?? 0) + (VerBoundAnnot?.VerBoundary ?? 0);
#endregion
#region Boundary
[JsonIgnore]
public double HorBoundary => Left + (Width ?? 0);
[JsonIgnore]
public double VerBoundary => Top + (Height ?? 0);
#endregion
#region BoundAnnot
[JsonIgnore]
public Annotation? HorBoundAnnot { get; set; }
[JsonIgnore]
public Annotation? VerBoundAnnot { get; set; }
#endregion
public Color? BackgroundColor { get; init; }
#region Border
public Color? BorderColor { get; init; }
public string? BorderStyle { get; init; }
public int? BorderWidth { get; set; }
#endregion
[JsonIgnore]
internal Annotation Default
{
set
{
// To set null value, annotation must have null (0) value but null must has non-null value
if (MarginLeft == null && value.MarginLeft != null)
MarginLeft = value.MarginLeft * MarginLeftRatio;
if (MarginTop == null && value.MarginTop != null)
MarginTop = value.MarginTop * MarginTopRatio;
if (Width == null && value.Width != null)
Width = value.Width * WidthRatio;
if (Height == null && value.Height != null)
Height = value.Height * HeightRatio;
}
}
};

View File

@@ -0,0 +1,80 @@
using EnvelopeGenerator.API.Models.PsPdfKitAnnotation;
using System.Text.Json.Serialization;
namespace EnvelopeGenerator.API.Models.PsPdfKitAnnotation;
public class AnnotationParams
{
public AnnotationParams()
{
_AnnotationJSObjectInitor = new(CreateAnnotationJSObject);
}
public Background? Background { get; init; }
#region Annotation
[JsonIgnore]
public Annotation? DefaultAnnotation { get; init; }
private readonly List<Annotation> _annots = new List<Annotation>();
public bool TryGet(string name, out Annotation annotation)
{
#pragma warning disable CS8601 // Possible null reference assignment.
annotation = _annots.FirstOrDefault(a => a.Name == name);
#pragma warning restore CS8601 // Possible null reference assignment.
return annotation is not null;
}
public required IEnumerable<Annotation> Annotations
{
get => _annots;
init
{
_annots = value.ToList();
if (DefaultAnnotation is not null)
foreach (var annot in _annots)
annot.Default = DefaultAnnotation;
for (int i = 0; i < _annots.Count; i++)
{
#region set bound annotations
// horizontal
if (_annots[i].HorBoundAnnotName is string horBoundAnnotName)
if (TryGet(horBoundAnnotName, out var horBoundAnnot))
_annots[i].HorBoundAnnot = horBoundAnnot;
else
throw new InvalidOperationException($"{horBoundAnnotName} added as bound anotation. However, it is not defined.");
// vertical
if (_annots[i].VerBoundAnnotName is string verBoundAnnotName)
if (TryGet(verBoundAnnotName, out var verBoundAnnot))
_annots[i].VerBoundAnnot = verBoundAnnot;
else
throw new InvalidOperationException($"{verBoundAnnotName} added as bound anotation. However, it is not defined.");
#endregion
}
}
}
#endregion
#region AnnotationJSObject
private Dictionary<string, IAnnotation> CreateAnnotationJSObject()
{
var dict = _annots.ToDictionary(a => a.Name.ToLower(), a => a as IAnnotation);
if (Background is not null)
{
Background.Locate(_annots);
dict.Add(Background.Name.ToLower(), Background);
}
return dict;
}
private readonly Lazy<Dictionary<string, IAnnotation>> _AnnotationJSObjectInitor;
public Dictionary<string, IAnnotation> AnnotationJSObject => _AnnotationJSObjectInitor.Value;
#endregion
}

View File

@@ -0,0 +1,58 @@
using System.Text.Json.Serialization;
namespace EnvelopeGenerator.API.Models.PsPdfKitAnnotation;
/// <summary>
/// The Background is an annotation for the PSPDF Kit. However, it has no function.
/// It is only the first annotation as a background for other annotations.
/// </summary>
public record Background : IAnnotation
{
[JsonIgnore]
public double Margin { get; init; }
public string Name { get; } = "Background";
public double? Width { get; set; }
public double? Height { get; set; }
public double Left { get; set; }
public double Top { get; set; }
public Color? BackgroundColor { get; init; }
#region Border
public Color? BorderColor { get; init; }
public string? BorderStyle { get; init; }
public int? BorderWidth { get; set; }
#endregion
public void Locate(IEnumerable<IAnnotation> annotations)
{
// set Top
if (annotations.MinBy(a => a.Top)?.Top is double minTop)
Top = minTop;
// set Left
if (annotations.MinBy(a => a.Left)?.Left is double minLeft)
Left = minLeft;
// set Width
if(annotations.MaxBy(a => a.GetRight())?.GetRight() is double maxRight)
Width = maxRight - Left;
// set Height
if (annotations.MaxBy(a => a.GetBottom())?.GetBottom() is double maxBottom)
Height = maxBottom - Top;
// add margins
Top -= Margin;
Left -= Margin;
Width += Margin * 2;
Height += Margin * 2;
}
}

View File

@@ -0,0 +1,10 @@
namespace EnvelopeGenerator.API.Models.PsPdfKitAnnotation;
public record Color
{
public int R { get; init; } = 0;
public int G { get; init; } = 0;
public int B { get; init; } = 0;
}

View File

@@ -0,0 +1,8 @@
namespace EnvelopeGenerator.API.Models.PsPdfKitAnnotation;
public static class Extensions
{
public static double GetRight(this IAnnotation annotation) => annotation.Left + annotation?.Width ?? 0;
public static double GetBottom(this IAnnotation annotation) => annotation.Top + annotation?.Height ?? 0;
}

View File

@@ -0,0 +1,22 @@
namespace EnvelopeGenerator.API.Models.PsPdfKitAnnotation;
public interface IAnnotation
{
string Name { get; }
double? Width { get; }
double? Height { get; }
double Left { get; }
double Top { get; }
Color? BackgroundColor { get; }
Color? BorderColor { get; }
string? BorderStyle { get; }
int? BorderWidth { get; }
}

View File

@@ -0,0 +1,17 @@
namespace EnvelopeGenerator.API.Models;
/// <summary>
/// Represents the parameters for two-factor authentication (2FA) registration.
/// </summary>
public class TFARegParams
{
/// <summary>
/// The maximum allowed time for completing the registration process.
/// </summary>
public TimeSpan TimeLimit { get; init; } = new(0, 30, 0);
/// <summary>
/// The deadline for registration, calculated as the current time plus the <see cref="TimeLimit"/>.
/// </summary>
public DateTime Deadline => DateTime.Now.AddTicks(TimeLimit.Ticks);
}

View File

@@ -11,11 +11,11 @@ using DigitalData.UserManager.DependencyInjection;
using EnvelopeGenerator.Application; using EnvelopeGenerator.Application;
using DigitalData.Auth.Client; using DigitalData.Auth.Client;
using DigitalData.Core.Abstractions; using DigitalData.Core.Abstractions;
using EnvelopeGenerator.GeneratorAPI.Models; using EnvelopeGenerator.API.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using DigitalData.Core.Abstractions.Security.Extensions; using DigitalData.Core.Abstractions.Security.Extensions;
using EnvelopeGenerator.GeneratorAPI.Middleware; using EnvelopeGenerator.API.Middleware;
using NLog.Web; using NLog.Web;
using NLog; using NLog;
@@ -26,6 +26,8 @@ try
{ {
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("yarp.json", optional: true, reloadOnChange: true);
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
if (!builder.Environment.IsDevelopment()) if (!builder.Environment.IsDevelopment())
@@ -39,6 +41,8 @@ try
var deferredProvider = new DeferredServiceProvider(); var deferredProvider = new DeferredServiceProvider();
builder.Services.AddControllers(); builder.Services.AddControllers();
builder.Services.AddHttpClient();
builder.Services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
// CORS Policy // CORS Policy
var allowedOrigins = config.GetSection("AllowedOrigins").Get<string[]>() ?? var allowedOrigins = config.GetSection("AllowedOrigins").Get<string[]>() ??
@@ -102,6 +106,8 @@ try
{ {
options.IncludeXmlComments(xmlFile); options.IncludeXmlComments(xmlFile);
} }
options.DocumentFilter<EnvelopeGenerator.API.Documentation.AuthProxyDocumentFilter>();
}); });
builder.Services.AddOpenApi(); builder.Services.AddOpenApi();
@@ -241,6 +247,7 @@ try
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.MapReverseProxy();
app.MapControllers(); app.MapControllers();
app.Run(); app.Run();

View File

@@ -6,11 +6,11 @@
} }
}, },
"AuthClientParams": { "AuthClientParams": {
"Url": "https://localhost:7192/auth-hub", "Url": "http://172.24.12.39:9090/auth-hub",
"PublicKeys": [ "PublicKeys": [
{ {
"Issuer": "auth.digitaldata.works", "Issuer": "auth.digitaldata.works",
"Audience": "sign-flow-gen.digitaldata.works" "Audience": "sign-flow.digitaldata.works"
} }
], ],
"RetryDelay": "00:00:05" "RetryDelay": "00:00:05"

View File

@@ -9,7 +9,7 @@
} }
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"AllowedOrigins": [ "http://localhost:4200" ], "AllowedOrigins": [ "http://localhost:4200", "http://172.24.12.39:9090", "https://localhost:8088", "http://localhost:5131", "http://localhost:7192" ],
"ConnectionStrings": { "ConnectionStrings": {
"Default": "Server=SDD-VMP04-SQL17\\DD_DEVELOP01;Database=DD_ECM;User Id=sa;Password=dd;Encrypt=false;TrustServerCertificate=True;", "Default": "Server=SDD-VMP04-SQL17\\DD_DEVELOP01;Database=DD_ECM;User Id=sa;Password=dd;Encrypt=false;TrustServerCertificate=True;",
"DbMigrationTest": "Server=SDD-VMP04-SQL17\\DD_DEVELOP01;Database=DD_ECM_DATA_MIGR_TEST;User Id=sa;Password=dd;Encrypt=false;TrustServerCertificate=True;" "DbMigrationTest": "Server=SDD-VMP04-SQL17\\DD_DEVELOP01;Database=DD_ECM_DATA_MIGR_TEST;User Id=sa;Password=dd;Encrypt=false;TrustServerCertificate=True;"
@@ -24,11 +24,11 @@
} }
}, },
"AuthClientParams": { "AuthClientParams": {
"Url": "https://localhost:7192/auth-hub", "Url": "http://172.24.12.39:9090/auth-hub",
"PublicKeys": [ "PublicKeys": [
{ {
"Issuer": "auth.digitaldata.works", "Issuer": "auth.digitaldata.works",
"Audience": "sign-flow-gen.digitaldata.works" "Audience": "sign-flow.digitaldata.works"
} }
], ],
"RetryDelay": "00:00:05" "RetryDelay": "00:00:05"
@@ -37,7 +37,7 @@
"Cookie": "AuthToken", "Cookie": "AuthToken",
"QueryString": "AuthToken", "QueryString": "AuthToken",
"Issuer": "auth.digitaldata.works", "Issuer": "auth.digitaldata.works",
"Audience": "work-flow.digitaldata.works" "Audience": "sign-flow.digitaldata.works"
}, },
"PSPDFKitLicenseKey": "SXCtGGY9XA-31OGUXQK-r7c6AkdLGPm2ljuyDr1qu0kkhLvydg-Do-fxpNUF4Rq3fS_xAnZRNFRHbXpE6sQ2BMcCSVTcXVJO6tPviexjpiT-HnrDEySlUERJnnvh-tmeOWprxS6BySPnSILkmaVQtUfOIUS-cUbvvEYHTvQBKbSF8di4XHQFyfv49ihr51axm3NVV3AXwh2EiKL5C5XdqBZ4sQ4O7vXBjM2zvxdPxlxdcNYmiU83uAzw7B83O_jubPzya4CdUHh_YH7Nlp2gP56MeG1Sw2JhMtfG3Rj14Sg4ctaeL9p6AEWca5dDjJ2li5tFIV2fQSsw6A_cowLu0gtMm5i8IfJXeIcQbMC2-0wGv1oe9hZYJvFMdzhTM_FiejM0agemxt3lJyzuyP8zbBSOgp7Si6A85krLWPZptyZBTG7pp7IHboUHfPMxCXqi-zMsqewOJtQBE2mjntU-lPryKnssOpMPfswwQX7QSkJYV5EMqNmEhQX6mEkp2wcqFzMC7bJQew1aO4pOpvChUaMvb1vgRek0HxLag0nwQYX2YrYGh7F_xXJs-8HNwJe8H0-eW4x4faayCgM5rB5772CCCsD9ThZcvXFrjNHHLGJ8WuBUFm6LArvSfFQdii_7j-_sqHMpeKZt26NFgivj1A==", "PSPDFKitLicenseKey": "SXCtGGY9XA-31OGUXQK-r7c6AkdLGPm2ljuyDr1qu0kkhLvydg-Do-fxpNUF4Rq3fS_xAnZRNFRHbXpE6sQ2BMcCSVTcXVJO6tPviexjpiT-HnrDEySlUERJnnvh-tmeOWprxS6BySPnSILkmaVQtUfOIUS-cUbvvEYHTvQBKbSF8di4XHQFyfv49ihr51axm3NVV3AXwh2EiKL5C5XdqBZ4sQ4O7vXBjM2zvxdPxlxdcNYmiU83uAzw7B83O_jubPzya4CdUHh_YH7Nlp2gP56MeG1Sw2JhMtfG3Rj14Sg4ctaeL9p6AEWca5dDjJ2li5tFIV2fQSsw6A_cowLu0gtMm5i8IfJXeIcQbMC2-0wGv1oe9hZYJvFMdzhTM_FiejM0agemxt3lJyzuyP8zbBSOgp7Si6A85krLWPZptyZBTG7pp7IHboUHfPMxCXqi-zMsqewOJtQBE2mjntU-lPryKnssOpMPfswwQX7QSkJYV5EMqNmEhQX6mEkp2wcqFzMC7bJQew1aO4pOpvChUaMvb1vgRek0HxLag0nwQYX2YrYGh7F_xXJs-8HNwJe8H0-eW4x4faayCgM5rB5772CCCsD9ThZcvXFrjNHHLGJ8WuBUFm6LArvSfFQdii_7j-_sqHMpeKZt26NFgivj1A==",
"Content-Security-Policy": [ // The first format parameter {0} will be replaced by the nonce value. "Content-Security-Policy": [ // The first format parameter {0} will be replaced by the nonce value.

View File

@@ -0,0 +1,25 @@
{
"ReverseProxy": {
"Routes": {
"auth-login": {
"ClusterId": "auth-hub",
"Match": {
"Path": "/api/auth",
"Methods": [ "POST" ]
},
"Transforms": [
{ "PathSet": "/api/auth/sign-flow" }
]
}
},
"Clusters": {
"auth-hub": {
"Destinations": {
"primary": {
"Address": "http://172.24.12.39:9090"
}
}
}
}
}
}

View File

@@ -74,6 +74,11 @@ public record EnvelopeDto
/// </summary> /// </summary>
public int? EnvelopeTypeId { get; set; } public int? EnvelopeTypeId { get; set; }
/// <summary>
///
/// </summary>
public bool ReadOnly => EnvelopeTypeId == 2;
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>

View File

@@ -3,8 +3,19 @@ using System.Text;
namespace EnvelopeGenerator.Application.Common.Extensions namespace EnvelopeGenerator.Application.Common.Extensions
{ {
/// <summary>
///
/// </summary>
public static class LoggerExtensions public static class LoggerExtensions
{ {
/// <summary>
///
/// </summary>
/// <param name="logger"></param>
/// <param name="envelopeReceiverId"></param>
/// <param name="exception"></param>
/// <param name="message"></param>
/// <param name="args"></param>
public static void LogEnvelopeError(this ILogger logger, string envelopeReceiverId, Exception? exception = null, string? message = null, params object?[] args) public static void LogEnvelopeError(this ILogger logger, string envelopeReceiverId, Exception? exception = null, string? message = null, params object?[] args)
{ {
var sb = new StringBuilder().AppendLine(envelopeReceiverId.DecodeEnvelopeReceiverId().ToTitle()); var sb = new StringBuilder().AppendLine(envelopeReceiverId.DecodeEnvelopeReceiverId().ToTitle());
@@ -18,6 +29,15 @@ namespace EnvelopeGenerator.Application.Common.Extensions
logger.Log(LogLevel.Error, exception, sb.AppendLine(exception.Message).ToString(), args); logger.Log(LogLevel.Error, exception, sb.AppendLine(exception.Message).ToString(), args);
} }
/// <summary>
///
/// </summary>
/// <param name="logger"></param>
/// <param name="uuid"></param>
/// <param name="signature"></param>
/// <param name="exception"></param>
/// <param name="message"></param>
/// <param name="args"></param>
public static void LogEnvelopeError(this ILogger logger, string? uuid, string? signature = null, Exception? exception = null, string? message = null, params object?[] args) public static void LogEnvelopeError(this ILogger logger, string? uuid, string? signature = null, Exception? exception = null, string? message = null, params object?[] args)
{ {
var sb = new StringBuilder($"Envelope Uuid: {uuid}"); var sb = new StringBuilder($"Envelope Uuid: {uuid}");
@@ -34,6 +54,11 @@ namespace EnvelopeGenerator.Application.Common.Extensions
logger.Log(LogLevel.Error, exception, sb.ToString(), args); logger.Log(LogLevel.Error, exception, sb.ToString(), args);
} }
/// <summary>
///
/// </summary>
/// <param name="envelopeReceiverTuple"></param>
/// <returns></returns>
public static string ToTitle(this (string? UUID, string? Signature) envelopeReceiverTuple) public static string ToTitle(this (string? UUID, string? Signature) envelopeReceiverTuple)
{ {
return $"UUID is {envelopeReceiverTuple.UUID} and signature is {envelopeReceiverTuple.Signature}"; return $"UUID is {envelopeReceiverTuple.UUID} and signature is {envelopeReceiverTuple.Signature}";

View File

@@ -5,6 +5,7 @@ namespace EnvelopeGenerator.Application.Common.Extensions;
/// <summary> /// <summary>
/// Extension methods for tasks /// Extension methods for tasks
/// </summary> /// </summary>
[Obsolete("Implement Mediator behaviors in the Osolete .NET project.")]
public static class TaskExtensions public static class TaskExtensions
{ {
/// <summary> /// <summary>
@@ -17,6 +18,7 @@ public static class TaskExtensions
/// <param name="factory">Exception provider</param> /// <param name="factory">Exception provider</param>
/// <returns>The awaited result if not <c>null</c>.</returns> /// <returns>The awaited result if not <c>null</c>.</returns>
/// <exception>Thrown if the result is <c>null</c>.</exception> /// <exception>Thrown if the result is <c>null</c>.</exception>
[Obsolete("Implement Mediator behaviors in the Osolete .NET project.")]
public static async Task<T> ThrowIfNull<T, TException>(this Task<T?> task, Func<TException> factory) where TException : Exception public static async Task<T> ThrowIfNull<T, TException>(this Task<T?> task, Func<TException> factory) where TException : Exception
{ {
var result = await task; var result = await task;
@@ -33,6 +35,7 @@ public static class TaskExtensions
/// <param name="factory">Exception provider</param> /// <param name="factory">Exception provider</param>
/// <returns>The awaited collection if it is not <c>null</c> or empty.</returns> /// <returns>The awaited collection if it is not <c>null</c> or empty.</returns>
/// <exception cref="NotFoundException">Thrown if the result is <c>null</c> or empty.</exception> /// <exception cref="NotFoundException">Thrown if the result is <c>null</c> or empty.</exception>
[Obsolete("Implement Mediator behaviors in the Osolete .NET project.")]
public static async Task<IEnumerable<T>> ThrowIfEmpty<T, TException>(this Task<IEnumerable<T>> task, Func<TException> factory) where TException : Exception public static async Task<IEnumerable<T>> ThrowIfEmpty<T, TException>(this Task<IEnumerable<T>> task, Func<TException> factory) where TException : Exception
{ {
var result = await task; var result = await task;
@@ -47,11 +50,33 @@ public static class TaskExtensions
/// <param name="task"></param> /// <param name="task"></param>
/// <param name="act"></param> /// <param name="act"></param>
/// <returns></returns> /// <returns></returns>
[Obsolete("Implement Mediator behaviors in the Osolete .NET project.")]
public static async Task<I> Then<T, I>(this Task<T> task, Func<T, I> act) public static async Task<I> Then<T, I>(this Task<T> task, Func<T, I> act)
{ {
var res = await task; var res = await task;
return act(res); return act(res);
} }
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="task"></param>
/// <returns></returns>
[Obsolete("Implement Mediator behaviors in the Osolete .NET project.")]
public static Task<T?> FirstOrDefaultAsync<T>(this Task<IEnumerable<T>> task) => task.Then(t => t.FirstOrDefault());
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TException"></typeparam>
/// <param name="task"></param>
/// <param name="factory"></param>
/// <returns></returns>
public static Task<T> FirstAsync<T, TException>(this Task<IEnumerable<T>> task, Func<TException> factory)
where TException : Exception
=> task.Then(t => t.FirstOrDefault() ?? throw factory());
} }
/// <summary> /// <summary>
@@ -68,11 +93,13 @@ public static class Exceptions
/// ///
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Obsolete("Implement Mediator behaviors in the Osolete .NET project.")]
public static BadRequestException BadRequest() => new(); public static BadRequestException BadRequest() => new();
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Obsolete("Implement Mediator behaviors in the Osolete .NET project.")]
public static ForbiddenException Forbidden() => new(); public static ForbiddenException Forbidden() => new();
} }

View File

@@ -2,16 +2,42 @@
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
namespace EnvelopeGenerator.Application.Common.Extensions namespace EnvelopeGenerator.Application.Common.Extensions;
/// <summary>
///
/// </summary>
public static class XSSExtensions
{ {
public static class XSSExtensions /// <summary>
{ ///
public static string? TryEncode(this string? value, UrlEncoder encoder) => value is null ? value : encoder.Encode(value); /// </summary>
/// <param name="value"></param>
/// <param name="encoder"></param>
/// <returns></returns>
public static string? TryEncode(this string? value, UrlEncoder encoder) => value is null ? value : encoder.Encode(value);
public static string? TryEncode(this LocalizedString? value, UrlEncoder encoder) => value is null ? null : encoder.Encode(value); /// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <param name="encoder"></param>
/// <returns></returns>
public static string? TryEncode(this LocalizedString? value, UrlEncoder encoder) => value is null ? null : encoder.Encode(value);
public static string? TrySanitize(this string? html, HtmlSanitizer sanitizer) => html is null ? html : sanitizer.Sanitize(html); /// <summary>
///
/// </summary>
/// <param name="html"></param>
/// <param name="sanitizer"></param>
/// <returns></returns>
public static string? TrySanitize(this string? html, HtmlSanitizer sanitizer) => html is null ? html : sanitizer.Sanitize(html);
public static string? TrySanitize(this LocalizedString? html, HtmlSanitizer sanitizer) => html is null ? null : sanitizer.Sanitize(html); /// <summary>
} ///
/// </summary>
/// <param name="html"></param>
/// <param name="sanitizer"></param>
/// <returns></returns>
public static string? TrySanitize(this LocalizedString? html, HtmlSanitizer sanitizer) => html is null ? null : sanitizer.Sanitize(html);
} }

View File

@@ -24,7 +24,7 @@ public record DocSignedNotification(EnvelopeReceiverDto Original) : EnvelopeRece
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public PsPdfKitAnnotation PsPdfKitAnnotation { get; init; } = null!; public PsPdfKitAnnotation? PsPdfKitAnnotation { get; init; }
/// <summary> /// <summary>
/// ///
@@ -59,7 +59,7 @@ public static class DocSignedNotificationExtensions
/// <param name="dtoTask"></param> /// <param name="dtoTask"></param>
/// <param name="psPdfKitAnnotation"></param> /// <param name="psPdfKitAnnotation"></param>
/// <returns></returns> /// <returns></returns>
public static async Task<DocSignedNotification?> ToDocSignedNotification(this Task<EnvelopeReceiverDto?> dtoTask, PsPdfKitAnnotation psPdfKitAnnotation) public static async Task<DocSignedNotification?> ToDocSignedNotification(this Task<EnvelopeReceiverDto?> dtoTask, PsPdfKitAnnotation? psPdfKitAnnotation)
=> await dtoTask is EnvelopeReceiverDto dto ? new(dto) { PsPdfKitAnnotation = psPdfKitAnnotation } : null; => await dtoTask is EnvelopeReceiverDto dto ? new(dto) { PsPdfKitAnnotation = psPdfKitAnnotation } : null;
/// <summary> /// <summary>

View File

@@ -29,6 +29,9 @@ public class AnnotationHandler : INotificationHandler<DocSignedNotification>
/// <param name="notification"></param> /// <param name="notification"></param>
/// <param name="cancel"></param> /// <param name="cancel"></param>
/// <returns></returns> /// <returns></returns>
public Task Handle(DocSignedNotification notification, CancellationToken cancel) public async Task Handle(DocSignedNotification notification, CancellationToken cancel)
=> _repo.CreateAsync(notification.PsPdfKitAnnotation.Structured, cancel); {
if (notification.PsPdfKitAnnotation is PsPdfKitAnnotation annot)
await _repo.CreateAsync(annot.Structured, cancel);
}
} }

View File

@@ -10,6 +10,8 @@ namespace EnvelopeGenerator.Application.Common.Notifications.DocSigned.Handlers;
/// </summary> /// </summary>
public class DocStatusHandler : INotificationHandler<DocSignedNotification> public class DocStatusHandler : INotificationHandler<DocSignedNotification>
{ {
private const string BlankAnnotationJson = "{}";
private readonly ISender _sender; private readonly ISender _sender;
/// <summary> /// <summary>
@@ -33,7 +35,9 @@ public class DocStatusHandler : INotificationHandler<DocSignedNotification>
{ {
Envelope = new() { Id = notification.EnvelopeId }, Envelope = new() { Id = notification.EnvelopeId },
Receiver = new() { Id = notification.ReceiverId}, Receiver = new() { Id = notification.ReceiverId},
Value = JsonSerializer.Serialize(notification.PsPdfKitAnnotation.Instant, Format.Json.ForAnnotations) Value = notification.PsPdfKitAnnotation is PsPdfKitAnnotation annot
? JsonSerializer.Serialize(annot.Instant, Format.Json.ForAnnotations)
: BlankAnnotationJson
}, cancel); }, cancel);
} }
} }

View File

@@ -4,6 +4,7 @@ using EnvelopeGenerator.Domain.Entities;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using AutoMapper; using AutoMapper;
using EnvelopeGenerator.Application.Common.Dto; using EnvelopeGenerator.Application.Common.Dto;
using DigitalData.Core.Exceptions;
namespace EnvelopeGenerator.Application.Documents.Queries; namespace EnvelopeGenerator.Application.Documents.Queries;
@@ -12,14 +13,14 @@ namespace EnvelopeGenerator.Application.Documents.Queries;
/// </summary> /// </summary>
/// <param name="Id">The unique identifier of the document. Optional.</param> /// <param name="Id">The unique identifier of the document. Optional.</param>
/// <param name="EnvelopeId">The identifier of the envelope associated with the document. Optional.</param> /// <param name="EnvelopeId">The identifier of the envelope associated with the document. Optional.</param>
public record ReadDocumentQuery(int? Id = null, int? EnvelopeId = null) : IRequest<DocumentDto?> public record ReadDocumentQuery(int? Id = null, int? EnvelopeId = null) : IRequest<DocumentDto>
{ {
} }
/// <summary> /// <summary>
/// Handles queries for reading <see cref="Document"/> data based on either the document ID or the envelope ID. /// Handles queries for reading <see cref="Document"/> data based on either the document ID or the envelope ID.
/// </summary> /// </summary>
public class ReadDocumentQueryHandler : IRequestHandler<ReadDocumentQuery, DocumentDto?> public class ReadDocumentQueryHandler : IRequestHandler<ReadDocumentQuery, DocumentDto>
{ {
/// <summary> /// <summary>
/// TempRepo for accessing <see cref="Document"/> entities. /// TempRepo for accessing <see cref="Document"/> entities.
@@ -50,20 +51,19 @@ public class ReadDocumentQueryHandler : IRequestHandler<ReadDocumentQuery, Docum
/// <exception cref="InvalidOperationException"> /// <exception cref="InvalidOperationException">
/// Thrown when neither <see cref="ReadDocumentQuery.Id"/> nor <see cref="ReadDocumentQuery.EnvelopeId"/> is provided. /// Thrown when neither <see cref="ReadDocumentQuery.Id"/> nor <see cref="ReadDocumentQuery.EnvelopeId"/> is provided.
/// </exception> /// </exception>
public async Task<DocumentDto?> Handle(ReadDocumentQuery query, CancellationToken cancel) public async Task<DocumentDto> Handle(ReadDocumentQuery query, CancellationToken cancel)
{ {
if (query.Id is not null) if (query.Id is not null)
{ {
var doc = await _repo.ReadOnly().Where(d => d.Id == query.Id).FirstOrDefaultAsync(cancel); var doc = await _repo.Query.Where(d => d.Id == query.Id).FirstOrDefaultAsync(cancel);
return _mapper.Map<DocumentDto>(doc); return _mapper.Map<DocumentDto>(doc);
} }
else if (query.EnvelopeId is not null) else if (query.EnvelopeId is not null)
{ {
var doc = await _repo.ReadOnly().Where(d => d.EnvelopeId == query.EnvelopeId).FirstOrDefaultAsync(cancel); var doc = await _repo.Query.Where(d => d.EnvelopeId == query.EnvelopeId).FirstOrDefaultAsync(cancel);
return _mapper.Map<DocumentDto>(doc); return _mapper.Map<DocumentDto>(doc);
} }
throw new InvalidOperationException( throw new NotFoundException();
$"Invalid {nameof(ReadDocumentQuery)}: either {nameof(query.Id)} or {nameof(query.EnvelopeId)} must be provided.");
} }
} }

View File

@@ -22,6 +22,7 @@ public class UpdateEmailTemplateCommandHandler : IRequestHandler<UpdateEmailTemp
/// ///
/// </summary> /// </summary>
/// <param name="repository"></param> /// <param name="repository"></param>
/// <param name="mapper"></param>
public UpdateEmailTemplateCommandHandler(IRepository<EmailTemplate> repository, IMapper mapper) public UpdateEmailTemplateCommandHandler(IRepository<EmailTemplate> repository, IMapper mapper)
{ {
_repository = repository; _repository = repository;

View File

@@ -14,7 +14,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Dapper" Version="2.1.66" /> <PackageReference Include="Dapper" Version="2.1.66" />
<PackageReference Include="DigitalData.Core.Abstraction.Application" Version="1.4.0" /> <PackageReference Include="DigitalData.Core.Abstraction.Application" Version="1.6.0" />
<PackageReference Include="DigitalData.Core.Application" Version="3.4.0" /> <PackageReference Include="DigitalData.Core.Application" Version="3.4.0" />
<PackageReference Include="DigitalData.Core.Client" Version="2.1.0" /> <PackageReference Include="DigitalData.Core.Client" Version="2.1.0" />
<PackageReference Include="DigitalData.Core.Exceptions" Version="1.1.0" /> <PackageReference Include="DigitalData.Core.Exceptions" Version="1.1.0" />

View File

@@ -1,4 +1,4 @@
using AutoMapper; using AutoMapper;
using DigitalData.Core.Abstraction.Application.Repository; using DigitalData.Core.Abstraction.Application.Repository;
using DigitalData.Core.Exceptions; using DigitalData.Core.Exceptions;
using EnvelopeGenerator.Application.Envelopes.Queries; using EnvelopeGenerator.Application.Envelopes.Queries;
@@ -47,7 +47,13 @@ namespace EnvelopeGenerator.Application.EnvelopeReceivers.Queries;
/// Die Antwort enthält Details wie den Include, die Zuordnung zwischen Umschlag und Empfänger /// Die Antwort enthält Details wie den Include, die Zuordnung zwischen Umschlag und Empfänger
/// sowie zusätzliche Metadaten. /// sowie zusätzliche Metadaten.
/// </remarks> /// </remarks>
public record ReadEnvelopeReceiverQuery : EnvelopeReceiverQueryBase<ReadEnvelopeQuery, ReadReceiverQuery>, IRequest<IEnumerable<EnvelopeReceiverDto>>; public record ReadEnvelopeReceiverQuery : EnvelopeReceiverQueryBase<ReadEnvelopeQuery, ReadReceiverQuery>, IRequest<IEnumerable<EnvelopeReceiverDto>>
{
/// <summary>
/// Optionaler Benutzernamefilter, um Ergebnisse auf Umschläge eines bestimmten Besitzers einzuschränken.
/// </summary>
public string? Username { get; init; }
}
/// <summary> /// <summary>
/// ///
@@ -61,10 +67,11 @@ public static class Extensions
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="cancel"></param> /// <param name="cancel"></param>
/// <returns></returns> /// <returns></returns>
public static Task<EnvelopeReceiverDto?> ReadEnvelopeReceiverAsync(this IMediator mediator, string key, CancellationToken cancel = default) public static async Task<EnvelopeReceiverDto?> ReadEnvelopeReceiverAsync(this IMediator mediator, string key, CancellationToken cancel = default)
{ {
var q = new ReadEnvelopeReceiverQuery() { Key = key }; var q = new ReadEnvelopeReceiverQuery() { Key = key };
return mediator.Send(q, cancel).Then(envRcvs => envRcvs.FirstOrDefault()); var envRcvs = await mediator.Send(q, cancel);
return envRcvs.FirstOrDefault();
} }
/// <summary> /// <summary>
@@ -75,80 +82,82 @@ public static class Extensions
/// <param name="signature"></param> /// <param name="signature"></param>
/// <param name="cancel"></param> /// <param name="cancel"></param>
/// <returns></returns> /// <returns></returns>
public static Task<EnvelopeReceiverDto?> ReadEnvelopeReceiverAsync(this IMediator mediator, string uuid, string signature, CancellationToken cancel = default) public static async Task<EnvelopeReceiverDto?> ReadEnvelopeReceiverAsync(this IMediator mediator, string uuid, string signature, CancellationToken cancel = default)
{ {
var q = new ReadEnvelopeReceiverQuery(); var q = new ReadEnvelopeReceiverQuery();
q.Envelope.Uuid = uuid; q.Envelope.Uuid = uuid;
q.Receiver.Signature = signature; q.Receiver.Signature = signature;
return mediator.Send(q, cancel).Then(envRcvs => envRcvs.FirstOrDefault()); var envRcvs = await mediator.Send(q, cancel);
return envRcvs.FirstOrDefault();
} }
}
/// <summary>
///
/// </summary>
public class ReadEnvelopeReceiverQueryHandler : IRequestHandler<ReadEnvelopeReceiverQuery, IEnumerable<EnvelopeReceiverDto>>
{
private readonly IRepository<EnvelopeReceiver> _repo;
private readonly IRepository<Receiver> _rcvRepo;
private readonly IMapper _mapper;
/// <summary> /// <summary>
/// /// Verarbeitet <see cref="ReadEnvelopeReceiverQuery"/> und liefert passende <see cref="EnvelopeReceiverDto"/>-Ergebnisse.
/// </summary> /// </summary>
/// <param name="envelopeReceiver"></param> public class ReadEnvelopeReceiverQueryHandler : IRequestHandler<ReadEnvelopeReceiverQuery, IEnumerable<EnvelopeReceiverDto>>
/// <param name="mapper"></param>
public ReadEnvelopeReceiverQueryHandler(IRepository<EnvelopeReceiver> envelopeReceiver, IRepository<Receiver> rcvRepo, IMapper mapper)
{ {
_repo = envelopeReceiver; private readonly IRepository<EnvelopeReceiver> _repo;
_mapper = mapper; private readonly IRepository<Receiver> _rcvRepo;
_rcvRepo = rcvRepo; private readonly IMapper _mapper;
}
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <param name="request"></param> /// <param name="envelopeReceiver"></param>
/// <param name="cancel"></param> /// <param name="rcvRepo"></param>
/// <returns></returns> /// <param name="mapper"></param>
/// <exception cref="BadRequestException"></exception> public ReadEnvelopeReceiverQueryHandler(IRepository<EnvelopeReceiver> envelopeReceiver, IRepository<Receiver> rcvRepo, IMapper mapper)
public async Task<IEnumerable<EnvelopeReceiverDto>> Handle(ReadEnvelopeReceiverQuery request, CancellationToken cancel)
{
var q = _repo.ReadOnly().Where(request, notnull: false);
if (request.Envelope.Status is not null)
{ {
var status = request.Envelope.Status; _repo = envelopeReceiver;
if (status.Min is not null) _mapper = mapper;
q = q.Where(er => er.Envelope!.Status >= status.Min); _rcvRepo = rcvRepo;
if (status.Max is not null)
q = q.Where(er => er.Envelope!.Status <= status.Max);
if (status.Include?.Length > 0)
q = q.Where(er => status.Include.Contains(er.Envelope!.Status));
if (status.Ignore is not null)
q = q.Where(er => !status.Ignore.Contains(er.Envelope!.Status));
} }
var envRcvs = await q /// <summary>
.Include(er => er.Envelope).ThenInclude(e => e!.Documents!).ThenInclude(d => d.Elements) ///
.Include(er => er.Envelope).ThenInclude(e => e!.Histories) /// </summary>
.Include(er => er.Envelope).ThenInclude(e => e!.User) /// <param name="request"></param>
.Include(er => er.Receiver) /// <param name="cancel"></param>
.ToListAsync(cancel); /// <returns></returns>
/// <exception cref="BadRequestException"></exception>
if (request.Receiver.HasAnyCriteria && envRcvs.Any()) public async Task<IEnumerable<EnvelopeReceiverDto>> Handle(ReadEnvelopeReceiverQuery request, CancellationToken cancel)
{ {
var receiver = await _rcvRepo.ReadOnly().Where(request.Receiver).FirstAsync(cancel); var q = _repo.Query.Where(request, notnull: false);
foreach (var envRcv in envRcvs) if (request.Username is string username)
envRcv.Envelope?.Documents?.First().Elements.RemoveAll(s => s.ReceiverId != receiver.Id); q = q.Where(er => er.Envelope!.User.Username == username);
if (request.Envelope.Status is not null)
{
var status = request.Envelope.Status;
if (status.Min is not null)
q = q.Where(er => er.Envelope!.Status >= status.Min);
if (status.Max is not null)
q = q.Where(er => er.Envelope!.Status <= status.Max);
if (status.Include?.Length > 0)
q = q.Where(er => status.Include.Contains(er.Envelope!.Status));
if (status.Ignore is not null)
q = q.Where(er => !status.Ignore.Contains(er.Envelope!.Status));
}
var envRcvs = await q
.Include(er => er.Envelope).ThenInclude(e => e!.Documents!).ThenInclude(d => d.Elements)
.Include(er => er.Envelope).ThenInclude(e => e!.Histories)
.Include(er => er.Envelope).ThenInclude(e => e!.User)
.Include(er => er.Receiver)
.ToListAsync(cancel);
if (request.Receiver.HasAnyCriteria && envRcvs.Count != 0)
{
var receiver = await _rcvRepo.Query.Where(request.Receiver).FirstAsync(cancel);
foreach (var envRcv in envRcvs)
envRcv.Envelope?.Documents?.FirstOrDefault()?.Elements?.RemoveAll(s => s.ReceiverId != receiver.Id);
}
return _mapper.Map<List<EnvelopeReceiverDto>>(envRcvs);
} }
return _mapper.Map<List<EnvelopeReceiverDto>>(envRcvs);
} }
} }

View File

@@ -68,6 +68,6 @@ public class ReceiverAlreadySignedQueryHandler : IRequestHandler<ReceiverAlready
/// <returns></returns> /// <returns></returns>
public async Task<bool> Handle(ReceiverAlreadySignedQuery request, CancellationToken cancel = default) public async Task<bool> Handle(ReceiverAlreadySignedQuery request, CancellationToken cancel = default)
{ {
return await _repo.ReadOnly().Where(request).Where(h => h.Status == EnvelopeStatus.DocumentSigned).AnyAsync(cancel); return await _repo.Query.Where(request).Where(h => h.Status == EnvelopeStatus.DocumentSigned).AnyAsync(cancel);
} }
} }

View File

@@ -0,0 +1,45 @@
using EnvelopeGenerator.Application.Common.Dto;
using MediatR;
using AutoMapper;
using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace EnvelopeGenerator.Application.EnvelopeTypes.Queries;
/// <summary>
///
/// </summary>
public record ReadEnvelopeTypesQuery : IRequest<IEnumerable<EnvelopeTypeDto>>;
/// <summary>
///
/// </summary>
public class ReadEnvelopeTypesQueryHandler : IRequestHandler<ReadEnvelopeTypesQuery, IEnumerable<EnvelopeTypeDto>>
{
private readonly IRepository<EnvelopeType> _repository;
private readonly IMapper _mapper;
/// <summary>
///
/// </summary>
/// <param name="repository"></param>
/// <param name="mapper"></param>
public ReadEnvelopeTypesQueryHandler(IRepository<EnvelopeType> repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<EnvelopeTypeDto>> Handle(ReadEnvelopeTypesQuery request, CancellationToken cancellationToken)
{
var types = await _repository.Query.ToListAsync(cancellationToken);
return _mapper.Map<IEnumerable<EnvelopeTypeDto>>(types);
}
}

View File

@@ -33,7 +33,18 @@ public record CreateEnvelopeCommand : IRequest<EnvelopeDto?>
/// <summary> /// <summary>
/// ID des Absenders /// ID des Absenders
/// </summary> /// </summary>
public int UserId { get; set; } internal int UserId { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public bool Authorize(int userId)
{
UserId = userId;
return true;
}
/// <summary> /// <summary>
/// Determines which component is used for envelope processing. /// Determines which component is used for envelope processing.

View File

@@ -1,18 +1,33 @@
using MediatR; using MediatR;
using EnvelopeGenerator.Domain.Constants; using EnvelopeGenerator.Domain.Constants;
using EnvelopeGenerator.Application.Common.Query; using EnvelopeGenerator.Application.Common.Query;
using EnvelopeGenerator.Application.Common.Dto;
using AutoMapper;
using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace EnvelopeGenerator.Application.Envelopes.Queries; namespace EnvelopeGenerator.Application.Envelopes.Queries;
/// <summary> /// <summary>
/// Repräsentiert eine Abfrage für Umschläge. /// Repräsentiert eine Abfrage für Umschläge.
/// </summary> /// </summary>
public record ReadEnvelopeQuery : EnvelopeQueryBase, IRequest public record ReadEnvelopeQuery : EnvelopeQueryBase, IRequest<IEnumerable<EnvelopeDto>>
{ {
/// <summary> /// <summary>
/// Abfrage des Include des Umschlags /// Abfrage des Include des Umschlags
/// </summary> /// </summary>
public EnvelopeStatusQuery? Status { get; init; } public EnvelopeStatusQuery? Status { get; init; }
/// <summary>
/// Optionaler Benutzerfilter; wenn gesetzt, werden nur Umschläge des Benutzers geladen.
/// </summary>
public int? UserId { get; init; }
/// <summary>
/// Setzt den Benutzerkontext für die Abfrage.
/// </summary>
public ReadEnvelopeQuery Authorize(int userId) => this with { UserId = userId };
} }
/// <summary> /// <summary>
@@ -66,3 +81,61 @@ public record EnvelopeStatusQuery
/// </summary> /// </summary>
public EnvelopeStatus[]? Ignore { get; init; } public EnvelopeStatus[]? Ignore { get; init; }
} }
/// <summary>
/// Verarbeitet <see cref="ReadEnvelopeQuery"/> und liefert passende <see cref="EnvelopeDto"/>-Ergebnisse.
/// </summary>
public class ReadEnvelopeQueryHandler : IRequestHandler<ReadEnvelopeQuery, IEnumerable<EnvelopeDto>>
{
private readonly IRepository<Envelope> _repository;
private readonly IMapper _mapper;
/// <summary>
///
/// </summary>
/// <param name="repository"></param>
/// <param name="mapper"></param>
public ReadEnvelopeQueryHandler(IRepository<Envelope> repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="cancel"></param>
/// <returns></returns>
public async Task<IEnumerable<EnvelopeDto>> Handle(ReadEnvelopeQuery request, CancellationToken cancel)
{
var query = _repository.Query;
if (request.UserId is int userId)
query = query.Where(e => e.UserId == userId);
if (request.Id is int id)
query = query.Where(e => e.Id == id);
if (request.Uuid is string uuid)
query = query.Where(e => e.Uuid == uuid);
if (request.Status is { } status)
{
if (status.Min is not null)
query = query.Where(e => e.Status >= status.Min);
if (status.Max is not null)
query = query.Where(e => e.Status <= status.Max);
if (status.Include?.Length > 0)
query = query.Where(e => status.Include.Contains(e.Status));
if (status.Ignore?.Length > 0)
query = query.Where(e => !status.Ignore.Contains(e.Status));
}
var envelopes = await query
.Include(e => e.Documents)
.ToListAsync(cancel);
return _mapper.Map<IEnumerable<EnvelopeDto>>(envelopes);
}
}

View File

@@ -1,4 +1,8 @@
using EnvelopeGenerator.Application.Receivers.Queries; using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Application.Common.Query;
using MediatR;
using EnvelopeGenerator.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace EnvelopeGenerator.Application.Envelopes.Queries; namespace EnvelopeGenerator.Application.Envelopes.Queries;
@@ -6,6 +10,54 @@ namespace EnvelopeGenerator.Application.Envelopes.Queries;
/// Eine Abfrage, um die zuletzt verwendete Anrede eines Empfängers zu ermitteln, /// Eine Abfrage, um die zuletzt verwendete Anrede eines Empfängers zu ermitteln,
/// damit diese für zukünftige Umschläge wiederverwendet werden kann. /// damit diese für zukünftige Umschläge wiederverwendet werden kann.
/// </summary> /// </summary>
public record ReadReceiverNameQuery() : ReadReceiverQuery public record ReadReceiverNameQuery() : ReceiverQueryBase, IRequest<string?>;
/// <summary>
///
/// </summary>
public class ReadReceiverNameQueryHandler : IRequestHandler<ReadReceiverNameQuery, string?>
{ {
private readonly IRepository<EnvelopeReceiver> _envelopeReceiverRepository;
private readonly IRepository<Receiver> _receiverRepository;
/// <summary>
///
/// </summary>
/// <param name="envelopeReceiverRepository"></param>
/// <param name="receiverRepository"></param>
public ReadReceiverNameQueryHandler(IRepository<EnvelopeReceiver> envelopeReceiverRepository, IRepository<Receiver> receiverRepository)
{
_envelopeReceiverRepository = envelopeReceiverRepository;
_receiverRepository = receiverRepository;
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<string?> Handle(ReadReceiverNameQuery request, CancellationToken cancellationToken)
{
var receiverQuery = _receiverRepository.Query.AsNoTracking();
if (request.Id is int id)
receiverQuery = receiverQuery.Where(r => r.Id == id);
if (request.EmailAddress is string email)
receiverQuery = receiverQuery.Where(r => r.EmailAddress == email);
if (request.Signature is string signature)
receiverQuery = receiverQuery.Where(r => r.Signature == signature);
var receiver = await receiverQuery.FirstOrDefaultAsync(cancellationToken);
if (receiver is null)
return null;
var erName = await _envelopeReceiverRepository.Query
.Where(er => er.ReceiverId == receiver.Id)
.OrderByDescending(er => er.AddedWhen)
.Select(er => er.Name)
.FirstOrDefaultAsync(cancellationToken);
return erName;
}
} }

View File

@@ -82,7 +82,7 @@ public class CreateHistoryCommandHandler : IRequestHandler<CreateHistoryCommand,
if(request.UserReference is null) if(request.UserReference is null)
{ {
var receivers = await _erRepo var receivers = await _erRepo
.ReadOnly() .Query
.Where(request) .Where(request)
.Include(er => er.Receiver) .Include(er => er.Receiver)
.ToListAsync(cancel); .ToListAsync(cancel);

View File

@@ -67,6 +67,7 @@ public class CreateReceiverCommandHandler : IRequestHandler<CreateReceiverComman
/// ///
/// </summary> /// </summary>
/// <param name="repo"></param> /// <param name="repo"></param>
/// <param name="mapper"></param>
public CreateReceiverCommandHandler(IRepository<Receiver> repo, IMapper mapper) public CreateReceiverCommandHandler(IRepository<Receiver> repo, IMapper mapper)
{ {
_repo = repo; _repo = repo;
@@ -81,7 +82,7 @@ public class CreateReceiverCommandHandler : IRequestHandler<CreateReceiverComman
/// <returns></returns> /// <returns></returns>
public async Task<(ReceiverDto Receiver, bool AlreadyExists)> Handle(CreateReceiverCommand request, CancellationToken cancel) public async Task<(ReceiverDto Receiver, bool AlreadyExists)> Handle(CreateReceiverCommand request, CancellationToken cancel)
{ {
var receiver = await _repo.ReadOnly() var receiver = await _repo.Query
.Where(r => r.EmailAddress == request.EmailAddress) .Where(r => r.EmailAddress == request.EmailAddress)
.SingleOrDefaultAsync(cancel); .SingleOrDefaultAsync(cancel);

View File

@@ -1,4 +1,10 @@
using EnvelopeGenerator.Application.Common.Query; using AutoMapper;
using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Application.Common.Dto.Receiver;
using EnvelopeGenerator.Application.Common.Query;
using MediatR;
using EnvelopeGenerator.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace EnvelopeGenerator.Application.Receivers.Queries; namespace EnvelopeGenerator.Application.Receivers.Queries;
@@ -6,4 +12,53 @@ namespace EnvelopeGenerator.Application.Receivers.Queries;
/// Stellt eine Abfrage dar, um die Details eines Empfängers zu lesen. /// Stellt eine Abfrage dar, um die Details eines Empfängers zu lesen.
/// um spezifische Informationen über einen Empfänger abzurufen. /// um spezifische Informationen über einen Empfänger abzurufen.
/// </summary> /// </summary>
public record ReadReceiverQuery : ReceiverQueryBase; public record ReadReceiverQuery : ReceiverQueryBase, IRequest<IEnumerable<ReceiverDto>>;
/// <summary>
///
/// </summary>
public class ReadReceiverQueryHandler : IRequestHandler<ReadReceiverQuery, IEnumerable<ReceiverDto>>
{
private readonly IRepository<Receiver> _repository;
private readonly IMapper _mapper;
/// <summary>
///
/// </summary>
/// <param name="repository"></param>
/// <param name="mapper"></param>
public ReadReceiverQueryHandler(IRepository<Receiver> repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<ReceiverDto>> Handle(ReadReceiverQuery request, CancellationToken cancellationToken)
{
var query = _repository.Query;
if (request.Id is int id)
{
query = query.Where(r => r.Id == id);
}
if (request.EmailAddress is string email)
{
query = query.Where(r => r.EmailAddress == email);
}
if (request.Signature is string signature)
{
query = query.Where(r => r.Signature == signature);
}
var receiver = await query.ToListAsync(cancellationToken);
return _mapper.Map<IEnumerable<ReceiverDto>>(receiver);
}
}

View File

@@ -70,8 +70,8 @@
<Reference Include="DigitalData.Controls.DocumentViewer, Version=1.9.8.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="DigitalData.Controls.DocumentViewer, Version=1.9.8.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\DigitalData.Controls.DocumentViewer.1.9.8\lib\net462\DigitalData.Controls.DocumentViewer.dll</HintPath> <HintPath>..\packages\DigitalData.Controls.DocumentViewer.1.9.8\lib\net462\DigitalData.Controls.DocumentViewer.dll</HintPath>
</Reference> </Reference>
<Reference Include="DigitalData.Core.Abstraction.Application, Version=1.4.0.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="DigitalData.Core.Abstraction.Application, Version=1.6.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\DigitalData.Core.Abstraction.Application.1.4.0\lib\net462\DigitalData.Core.Abstraction.Application.dll</HintPath> <HintPath>..\packages\DigitalData.Core.Abstraction.Application.1.6.0\lib\net462\DigitalData.Core.Abstraction.Application.dll</HintPath>
</Reference> </Reference>
<Reference Include="DigitalData.Core.Abstractions, Version=4.3.0.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="DigitalData.Core.Abstractions, Version=4.3.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\DigitalData.Core.Abstractions.4.3.0\lib\net462\DigitalData.Core.Abstractions.dll</HintPath> <HintPath>..\packages\DigitalData.Core.Abstractions.4.3.0\lib\net462\DigitalData.Core.Abstractions.dll</HintPath>
@@ -109,9 +109,6 @@
<Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"> <Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.5.1\lib\net45\EntityFramework.SqlServer.dll</HintPath> <HintPath>..\packages\EntityFramework.6.5.1\lib\net45\EntityFramework.SqlServer.dll</HintPath>
</Reference> </Reference>
<Reference Include="EnvelopeGenerator.CommonServices">
<HintPath>..\EnvelopeGenerator.CommonServices\bin\Debug\EnvelopeGenerator.CommonServices.dll</HintPath>
</Reference>
<Reference Include="FirebirdSql.Data.FirebirdClient, Version=7.5.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c, processorArchitecture=MSIL"> <Reference Include="FirebirdSql.Data.FirebirdClient, Version=7.5.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c, processorArchitecture=MSIL">
<HintPath>..\packages\FirebirdSql.Data.FirebirdClient.7.5.0\lib\net452\FirebirdSql.Data.FirebirdClient.dll</HintPath> <HintPath>..\packages\FirebirdSql.Data.FirebirdClient.7.5.0\lib\net452\FirebirdSql.Data.FirebirdClient.dll</HintPath>
</Reference> </Reference>
@@ -466,8 +463,12 @@
<Project>{6EA0C51F-C2B1-4462-8198-3DE0B32B74F8}</Project> <Project>{6EA0C51F-C2B1-4462-8198-3DE0B32B74F8}</Project>
<Name>EnvelopeGenerator.CommonServices</Name> <Name>EnvelopeGenerator.CommonServices</Name>
</ProjectReference> </ProjectReference>
<ProjectReference Include="..\EnvelopeGenerator.CommonServices\EnvelopeGenerator.CommonServices.vbproj">
<Project>{6ea0c51f-c2b1-4462-8198-3de0b32b74f8}</Project>
<Name>EnvelopeGenerator.CommonServices</Name>
</ProjectReference>
<ProjectReference Include="..\EnvelopeGenerator.Domain\EnvelopeGenerator.Domain.csproj"> <ProjectReference Include="..\EnvelopeGenerator.Domain\EnvelopeGenerator.Domain.csproj">
<Project>{4F32A98D-E6F0-4A09-BD97-1CF26107E837}</Project> <Project>{4f32a98d-e6f0-4a09-bd97-1cf26107e837}</Project>
<Name>EnvelopeGenerator.Domain</Name> <Name>EnvelopeGenerator.Domain</Name>
</ProjectReference> </ProjectReference>
<ProjectReference Include="..\EnvelopeGenerator.Infrastructure\EnvelopeGenerator.Infrastructure.csproj"> <ProjectReference Include="..\EnvelopeGenerator.Infrastructure\EnvelopeGenerator.Infrastructure.csproj">
@@ -495,6 +496,9 @@
<Content Include="MailLicense.xml" /> <Content Include="MailLicense.xml" />
<Content Include="README.txt" /> <Content Include="README.txt" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<WCFMetadata Include="Connected Services\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<Import Project="..\packages\GdPicture.runtimes.windows.14.3.3\build\net462\GdPicture.runtimes.windows.targets" Condition="Exists('..\packages\GdPicture.runtimes.windows.14.3.3\build\net462\GdPicture.runtimes.windows.targets')" /> <Import Project="..\packages\GdPicture.runtimes.windows.14.3.3\build\net462\GdPicture.runtimes.windows.targets" Condition="Exists('..\packages\GdPicture.runtimes.windows.14.3.3\build\net462\GdPicture.runtimes.windows.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">

View File

@@ -3,7 +3,7 @@
<package id="AutoMapper" version="10.1.1" targetFramework="net462" /> <package id="AutoMapper" version="10.1.1" targetFramework="net462" />
<package id="BouncyCastle.Cryptography" version="2.5.0" targetFramework="net462" /> <package id="BouncyCastle.Cryptography" version="2.5.0" targetFramework="net462" />
<package id="DigitalData.Controls.DocumentViewer" version="1.9.8" targetFramework="net462" /> <package id="DigitalData.Controls.DocumentViewer" version="1.9.8" targetFramework="net462" />
<package id="DigitalData.Core.Abstraction.Application" version="1.4.0" targetFramework="net462" /> <package id="DigitalData.Core.Abstraction.Application" version="1.6.0" targetFramework="net462" />
<package id="DigitalData.Core.Abstractions" version="4.3.0" targetFramework="net462" /> <package id="DigitalData.Core.Abstractions" version="4.3.0" targetFramework="net462" />
<package id="DigitalData.Modules.Base" version="1.3.8" targetFramework="net462" /> <package id="DigitalData.Modules.Base" version="1.3.8" targetFramework="net462" />
<package id="DigitalData.Modules.Config" version="1.3.0" targetFramework="net462" /> <package id="DigitalData.Modules.Config" version="1.3.0" targetFramework="net462" />

View File

@@ -72,8 +72,8 @@
<Reference Include="DevExpress.XtraEditors.v21.2, Version=21.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" /> <Reference Include="DevExpress.XtraEditors.v21.2, Version=21.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" />
<Reference Include="DevExpress.XtraGauges.v21.2.Core, Version=21.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a, processorArchitecture=MSIL" /> <Reference Include="DevExpress.XtraGauges.v21.2.Core, Version=21.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a, processorArchitecture=MSIL" />
<Reference Include="DevExpress.XtraReports.v21.2, Version=21.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a, processorArchitecture=MSIL" /> <Reference Include="DevExpress.XtraReports.v21.2, Version=21.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a, processorArchitecture=MSIL" />
<Reference Include="DigitalData.Core.Abstraction.Application, Version=1.4.0.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="DigitalData.Core.Abstraction.Application, Version=1.6.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\DigitalData.Core.Abstraction.Application.1.4.0\lib\net462\DigitalData.Core.Abstraction.Application.dll</HintPath> <HintPath>..\packages\DigitalData.Core.Abstraction.Application.1.6.0\lib\net462\DigitalData.Core.Abstraction.Application.dll</HintPath>
</Reference> </Reference>
<Reference Include="DigitalData.Core.Abstractions, Version=4.3.0.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="DigitalData.Core.Abstractions, Version=4.3.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\DigitalData.Core.Abstractions.4.3.0\lib\net462\DigitalData.Core.Abstractions.dll</HintPath> <HintPath>..\packages\DigitalData.Core.Abstractions.4.3.0\lib\net462\DigitalData.Core.Abstractions.dll</HintPath>

View File

@@ -422,7 +422,7 @@ Namespace Jobs
End Function End Function
Private Function GetEnvelopeData(pEnvelopeId As Integer) As EnvelopeData Private Function GetEnvelopeData(pEnvelopeId As Integer) As EnvelopeData
Dim oSql = $"SELECT T.GUID, T.ENVELOPE_UUID,T2.FILEPATH, T2.BYTE_DATA FROM [dbo].[TBSIG_ENVELOPE] T Dim oSql = $"SELECT T.GUID, T.ENVELOPE_UUID, T.ENVELOPE_TYPE, T2.FILEPATH, T2.BYTE_DATA FROM [dbo].[TBSIG_ENVELOPE] T
JOIN TBSIG_ENVELOPE_DOCUMENT T2 ON T.GUID = T2.ENVELOPE_ID JOIN TBSIG_ENVELOPE_DOCUMENT T2 ON T.GUID = T2.ENVELOPE_ID
WHERE T.GUID = {pEnvelopeId}" WHERE T.GUID = {pEnvelopeId}"
Dim oTable As DataTable = Database.GetDatatable(oSql) Dim oTable As DataTable = Database.GetDatatable(oSql)

View File

@@ -37,6 +37,15 @@ Namespace Jobs.FinalizeDocument
Public Function BurnAnnotsToPDF(pSourceBuffer As Byte(), pInstantJSONList As List(Of String), envelopeId As Integer) As Byte() Public Function BurnAnnotsToPDF(pSourceBuffer As Byte(), pInstantJSONList As List(Of String), envelopeId As Integer) As Byte()
'read the elements of envelope with their annotations 'read the elements of envelope with their annotations
Using scope = Factory.Shared.ScopeFactory.CreateScope() Using scope = Factory.Shared.ScopeFactory.CreateScope()
Dim envRepo = scope.ServiceProvider.Repository(Of Envelope)()
Dim envelope = envRepo.Where(Function(env) env.Id = envelopeId).FirstOrDefault()
If envelope Is Nothing Then
Throw New BurnAnnotationException($"Envelope with Id {envelopeId} not found.")
ElseIf envelope.ReadOnly Then
Return pSourceBuffer
End If
Dim sigRepo = scope.ServiceProvider.Repository(Of Signature)() Dim sigRepo = scope.ServiceProvider.Repository(Of Signature)()
Dim elements = sigRepo _ Dim elements = sigRepo _
.Where(Function(sig) sig.Document.EnvelopeId = envelopeId) _ .Where(Function(sig) sig.Document.EnvelopeId = envelopeId) _

View File

@@ -2,7 +2,7 @@
<packages> <packages>
<package id="AutoMapper" version="10.1.1" targetFramework="net462" /> <package id="AutoMapper" version="10.1.1" targetFramework="net462" />
<package id="BouncyCastle.Cryptography" version="2.5.0" targetFramework="net462" /> <package id="BouncyCastle.Cryptography" version="2.5.0" targetFramework="net462" />
<package id="DigitalData.Core.Abstraction.Application" version="1.4.0" targetFramework="net462" /> <package id="DigitalData.Core.Abstraction.Application" version="1.6.0" targetFramework="net462" />
<package id="DigitalData.Core.Abstractions" version="4.3.0" targetFramework="net462" /> <package id="DigitalData.Core.Abstractions" version="4.3.0" targetFramework="net462" />
<package id="DigitalData.Modules.Base" version="1.3.8" targetFramework="net462" /> <package id="DigitalData.Modules.Base" version="1.3.8" targetFramework="net462" />
<package id="DigitalData.Modules.Config" version="1.3.0" targetFramework="net462" /> <package id="DigitalData.Modules.Config" version="1.3.0" targetFramework="net462" />

View File

@@ -1,8 +0,0 @@
namespace EnvelopeGenerator.Domain.Constants
{
public static class ReceiverRole
{
public const string PreAuth = "PreAuth";
public const string FullyAuth = "FullyAuth";
}
}

View File

@@ -0,0 +1,23 @@
#if NETFRAMEWORK
using System;
#endif
namespace EnvelopeGenerator.Domain.Constants
{
public static class Role
{
[Obsolete("Use Receiver.PreAuth or Receiver.FullyAuth")]
public const string PreAuth = "PreAuth";
[Obsolete("Use Receiver.PreAuth or Receiver.FullyAuth")]
public const string FullyAuth = "FullyAuth";
public static class Receiver
{
public const string PreAuth = "PreAuth";
public const string FullyAuth = "FullyAuth";
}
public const string Sender = "Sender";
}
}

View File

@@ -2,6 +2,7 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using EnvelopeGenerator.Domain.Constants; using EnvelopeGenerator.Domain.Constants;
using Newtonsoft.Json;
#if NETFRAMEWORK #if NETFRAMEWORK
using System; using System;
@@ -107,6 +108,10 @@ public class Envelope
[Column("ENVELOPE_TYPE")] [Column("ENVELOPE_TYPE")]
public int? EnvelopeTypeId { get; set; } public int? EnvelopeTypeId { get; set; }
[JsonIgnore]
[NotMapped]
public bool ReadOnly => EnvelopeTypeId == 2;
[Column("CERTIFICATION_TYPE")] [Column("CERTIFICATION_TYPE")]
public int? CertificationType { get; set; } public int? CertificationType { get; set; }

View File

@@ -1,13 +0,0 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "9.0.3",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}

View File

@@ -1,144 +0,0 @@
using DigitalData.Core.Abstraction.Application;
using DigitalData.UserManager.Application.Contracts;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using EnvelopeGenerator.GeneratorAPI.Models;
namespace EnvelopeGenerator.GeneratorAPI.Controllers;
/// <summary>
/// Controller verantwortlich für die Benutzer-Authentifizierung, einschließlich Anmelden, Abmelden und Überprüfung des Authentifizierungsstatus.
/// </summary>
[Route("api/[controller]")]
[ApiController]
public partial class AuthController : ControllerBase
{
private readonly ILogger<AuthController> _logger;
[Obsolete("Use MediatR")]
private readonly IUserService _userService;
private readonly IDirectorySearchService _dirSearchService;
/// <summary>
/// Initializes a new instance of the <see cref="AuthController"/> class.
/// </summary>
/// <param name="logger">The logger instance.</param>
/// <param name="userService">The user service instance.</param>
/// <param name="dirSearchService">The directory search service instance.</param>
[Obsolete("Use MediatR")]
public AuthController(ILogger<AuthController> logger, IUserService userService, IDirectorySearchService dirSearchService)
{
_logger = logger;
_userService = userService;
_dirSearchService = dirSearchService;
}
/// <summary>
/// Authentifiziert einen Benutzer und generiert ein JWT-Token. Wenn 'cookie' wahr ist, wird das Token als HTTP-Only-Cookie zurückgegeben.
/// </summary>
/// <param name="login">Benutzeranmeldedaten (Benutzername und Passwort).</param>
/// <param name="cookie">Wenn wahr, wird das JWT-Token auch als HTTP-Only-Cookie gesendet.</param>
/// <returns>
/// Gibt eine HTTP 200 oder 401.
/// </returns>
/// <remarks>
/// Sample request:
///
/// POST /api/auth?cookie=true
/// {
/// "username": "MaxMustermann",
/// "password": "Geheim123!"
/// }
///
/// POST /api/auth?cookie=true
/// {
/// "id": "1",
/// "password": "Geheim123!"
/// }
///
/// </remarks>
/// <response code="200">Erfolgreiche Anmeldung. Gibt das JWT-Token im Antwortkörper oder als Cookie zurück, wenn 'cookie' wahr ist.</response>
/// <response code="401">Unbefugt. Ungültiger Benutzername oder Passwort.</response>
[ProducesResponseType(typeof(string), StatusCodes.Status200OK, "text/javascript")]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
[AllowAnonymous]
[HttpPost]
public Task<IActionResult> Login([FromBody] Login login, [FromQuery] bool cookie = false)
{
// added to configure open API (swagger and scalar)
throw new NotImplementedException();
}
/// <summary>
/// Authentifiziert einen Benutzer und generiert ein JWT-Token. Das Token wird als HTTP-only-Cookie zurückgegeben.
/// </summary>
/// <param name="login">Benutzeranmeldedaten (Benutzername und Passwort).</param>
/// <returns>
/// Gibt eine HTTP 200 oder 401.
/// </returns>
/// <remarks>
/// Sample request:
///
/// POST /api/auth/form
/// {
/// "username": "MaxMustermann",
/// "password": "Geheim123!"
/// }
///
/// </remarks>
/// <response code="200">Erfolgreiche Anmeldung. Gibt das JWT-Token im Antwortkörper oder als Cookie zurück, wenn 'cookie' wahr ist.</response>
/// <response code="401">Unbefugt. Ungültiger Benutzername oder Passwort.</response>
[ProducesResponseType(typeof(string), StatusCodes.Status200OK, "text/javascript")]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
[AllowAnonymous]
[HttpPost]
[Route("form")]
public Task<IActionResult> Login([FromForm] Login login)
{
// added to configure open API (swagger and scalar)
throw new NotImplementedException();
}
/// <summary>
/// Entfernt das Authentifizierungs-Cookie des Benutzers (AuthCookie)
/// </summary>
/// <returns>
/// Gibt eine HTTP 200 oder 401.
/// </returns>
/// <remarks>
/// Sample request:
///
/// POST /api/auth/logout
///
/// </remarks>
/// <response code="200">Erfolgreich gelöscht, wenn der Benutzer ein berechtigtes Cookie hat.</response>
/// <response code="401">Wenn es kein zugelassenes Cookie gibt, wird „nicht zugelassen“ zurückgegeben.</response>
[ProducesResponseType(typeof(string), StatusCodes.Status200OK, "text/javascript")]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
[Authorize]
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
/// <summary>
/// Prüft, ob der Benutzer ein autorisiertes Token hat.
/// </summary>
/// <returns>Wenn ein autorisiertes Token vorhanden ist HTTP 200 asynchron 401</returns>
/// <remarks>
/// Sample request:
///
/// GET /api/auth
///
/// </remarks>
/// <response code="200">Wenn es einen autorisierten Cookie gibt.</response>
/// <response code="401">Wenn kein Cookie vorhanden ist oder nicht autorisierte.</response>
[ProducesResponseType(typeof(string), StatusCodes.Status200OK, "text/javascript")]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
[Authorize]
[HttpGet]
public IActionResult IsAuthenticated() => Ok();
}

View File

@@ -1,62 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace EnvelopeGenerator.GeneratorAPI.Controllers
{
/// <summary>
/// Provides extension methods for extracting user information from a <see cref="ClaimsPrincipal"/>.
/// </summary>
public static class ControllerExtensions
{
/// <summary>
/// Attempts to retrieve the user's ID from the claims. Returns null if the ID is not found or invalid.
/// </summary>
/// <param name="user">The <see cref="ClaimsPrincipal"/> representing the user.</param>
/// <returns>The user's ID as an integer, or null if not found or invalid.</returns>
public static int? GetIdOrDefault(this ClaimsPrincipal user)
=> int.TryParse(user.FindFirstValue(ClaimTypes.NameIdentifier) ?? user.FindFirstValue("sub"), out int result)
? result : null;
/// <summary>
/// Retrieves the user's ID from the claims. Throws an exception if the ID is missing or invalid.
/// </summary>
/// <param name="user">The <see cref="ClaimsPrincipal"/> representing the user.</param>
/// <returns>The user's ID as an integer.</returns>
/// <exception cref="InvalidOperationException">Thrown if the user ID claim is missing or invalid.</exception>
public static int GetId(this ClaimsPrincipal user)
=> user.GetIdOrDefault()
?? throw new InvalidOperationException("User ID claim is missing or invalid. This may indicate a misconfigured or forged JWT token.");
/// <summary>
/// Retrieves the username from the claims, if available.
/// </summary>
/// <param name="user">The <see cref="ClaimsPrincipal"/> representing the user.</param>
/// <returns>The username as a string, or null if not found.</returns>
public static string? GetUsernameOrDefault(this ClaimsPrincipal user)
=> user.FindFirst(ClaimTypes.Name)?.Value;
/// <summary>
/// Retrieves the user's surname (last name) from the claims, if available.
/// </summary>
/// <param name="user">The <see cref="ClaimsPrincipal"/> representing the user.</param>
/// <returns>The surname as a string, or null if not found.</returns>
public static string? GetNameOrDefault(this ClaimsPrincipal user)
=> user.FindFirst(ClaimTypes.Surname)?.Value;
/// <summary>
/// Retrieves the user's given name (first name) from the claims, if available.
/// </summary>
/// <param name="user">The <see cref="ClaimsPrincipal"/> representing the user.</param>
/// <returns>The given name as a string, or null if not found.</returns>
public static string? GetPrenameOrDefault(this ClaimsPrincipal user)
=> user.FindFirst(ClaimTypes.GivenName)?.Value;
/// <summary>
/// Retrieves the user's email address from the claims, if available.
/// </summary>
/// <param name="user">The <see cref="ClaimsPrincipal"/> representing the user.</param>
/// <returns>The email address as a string, or null if not found.</returns>
public static string? GetEmailOrDefault(this ClaimsPrincipal user)
=> user.FindFirst(ClaimTypes.Email)?.Value;
}
}

View File

@@ -1,159 +0,0 @@
using DigitalData.Core.Abstraction.Application.DTO;
using EnvelopeGenerator.Application.Envelopes.Commands;
using EnvelopeGenerator.Application.Envelopes.Queries;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using EnvelopeGenerator.Application.Common.Interfaces.Services;
namespace EnvelopeGenerator.GeneratorAPI.Controllers;
/// <summary>
/// Dieser Controller stellt Endpunkte für die Verwaltung von Umschlägen bereit.
/// </summary>
/// <remarks>
/// Die API ermöglicht das Abrufen und Verwalten von Umschlägen basierend auf Benutzerinformationen und Statusfiltern.
///
/// Mögliche Antworten:
/// - 200 OK: Die Anfrage war erfolgreich, und die angeforderten Daten werden zurückgegeben.
/// - 400 Bad Request: Die Anfrage war fehlerhaft oder unvollständig.
/// - 401 Unauthorized: Der Benutzer ist nicht authentifiziert.
/// - 403 Forbidden: Der Benutzer hat keine Berechtigung, auf die Ressource zuzugreifen.
/// - 404 Not Found: Die angeforderte Ressource wurde nicht gefunden.
/// - 500 Internal Server Error: Ein unerwarteter Fehler ist aufgetreten.
/// </remarks>
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class EnvelopeController : ControllerBase
{
private readonly ILogger<EnvelopeController> _logger;
[Obsolete("Use MediatR")]
private readonly IEnvelopeService _envelopeService;
private readonly IMediator _mediator;
/// <summary>
/// Erstellt eine neue Instanz des EnvelopeControllers.
/// </summary>
/// <param name="logger">Der Logger, der für das Protokollieren von Informationen verwendet wird.</param>
/// <param name="envelopeService">Der Dienst, der für die Verarbeitung von Umschlägen zuständig ist.</param>
/// <param name="mediator"></param>
[Obsolete("Use MediatR")]
public EnvelopeController(ILogger<EnvelopeController> logger, IEnvelopeService envelopeService, IMediator mediator)
{
_logger = logger;
_envelopeService = envelopeService;
_mediator = mediator;
}
/// <summary>
/// Ruft eine Liste von Umschlägen basierend auf dem Benutzer und den angegebenen Statusfiltern ab.
/// </summary>
/// <param name="envelope"></param>
/// <returns>Eine IActionResult-Instanz, die die abgerufenen Umschläge oder einen Fehlerstatus enthält.</returns>
/// <response code="200">Die Anfrage war erfolgreich, und die Umschläge werden zurückgegeben.</response>
/// <response code="400">Die Anfrage war fehlerhaft oder unvollständig.</response>
/// <response code="401">Der Benutzer ist nicht authentifiziert.</response>
/// <response code="403">Der Benutzer hat keine Berechtigung, auf die Ressource zuzugreifen.</response>
/// <response code="500">Ein unerwarteter Fehler ist aufgetreten.</response>
[Authorize]
[HttpGet]
[Obsolete("Use MediatR")]
public async Task<IActionResult> GetAsync([FromQuery] ReadEnvelopeQuery envelope)
{
if (User.GetId() is int intId)
return await _envelopeService.ReadByUserAsync(intId, min_status: envelope.Status?.Min, max_status: envelope.Status?.Max).ThenAsync(
Success: envelopes =>
{
if (envelope.Id is int id)
envelopes = envelopes.Where(e => e.Id == id);
if (envelope.Status is EnvelopeStatusQuery status)
envelopes = envelopes.Where(e => e.Status == status);
if (envelope.Uuid is string uuid)
envelopes = envelopes.Where(e => e.Uuid == uuid);
return envelopes.Any() ? Ok(envelopes) : NotFound();
},
Fail: IActionResult (msg, ntc) =>
{
_logger.LogNotice(ntc);
return StatusCode(StatusCodes.Status500InternalServerError);
});
else
{
_logger.LogError("Trotz erfolgreicher Autorisierung wurde die Benutzer-ID nicht als Ganzzahl erkannt. Dies könnte auf eine fehlerhafte Erstellung der Anspruchsliste zurückzuführen sein.");
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// Ruft das Ergebnis eines Dokuments basierend auf der ID ab.
/// </summary>
/// <param name="id">Die eindeutige ID des Umschlags.</param>
/// <param name="view">Gibt an, ob das Dokument inline angezeigt werden soll (true) oder als Download bereitgestellt wird (false).</param>
/// <returns>Eine IActionResult-Instanz, die das Dokument oder einen Fehlerstatus enthält.</returns>
/// <response code="200">Das Dokument wurde erfolgreich abgerufen.</response>
/// <response code="404">Das Dokument wurde nicht gefunden oder ist nicht verfügbar.</response>
/// <response code="500">Ein unerwarteter Fehler ist aufgetreten.</response>
[HttpGet("doc-result")]
[Obsolete("Use MediatR")]
public async Task<IActionResult> GetDocResultAsync([FromQuery] int id, [FromQuery] bool view = false)
{
if (User.GetId() is int intId)
return await _envelopeService.ReadByUserAsync(intId).ThenAsync(
Success: envelopes =>
{
var envelope = envelopes.Where(e => e.Id == id).FirstOrDefault();
if (envelope is null)
return NotFound("Envelope not available.");
else if (envelope?.DocResult is null)
return NotFound("The document has not been fully signed or the result has not yet been released.");
else
{
if (view)
{
Response.Headers.Append("Content-Disposition", "inline; filename=\"" + envelope.Uuid + ".pdf\"");
return File(envelope.DocResult, "application/pdf");
}
else
return File(envelope.DocResult, "application/pdf", $"{envelope.Uuid}.pdf");
}
},
Fail: IActionResult (msg, ntc) =>
{
_logger.LogNotice(ntc);
return StatusCode(StatusCodes.Status500InternalServerError);
});
else
{
_logger.LogError("Trotz erfolgreicher Autorisierung wurde die Benutzer-ID nicht als Ganzzahl erkannt. Dies könnte auf eine fehlerhafte Erstellung der Anspruchsliste zurückzuführen sein.");
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
///
/// </summary>
/// <param name="envelope"></param>
/// <returns></returns>
[NonAction]
[Authorize]
[HttpPost]
public async Task<IActionResult> CreateAsync([FromQuery] CreateEnvelopeCommand envelope)
{
envelope.UserId = User.GetId();
var res = await _mediator.Send(envelope);
if (res is null)
{
_logger.LogError("Failed to create envelope. Envelope details: {EnvelopeDetails}", JsonConvert.SerializeObject(envelope));
return StatusCode(StatusCodes.Status500InternalServerError);
}
else
return Ok(res);
}
}

View File

@@ -1,48 +0,0 @@
using DigitalData.Core.Abstraction.Application.DTO;
using EnvelopeGenerator.Application.Common.Interfaces.Services;
using Microsoft.AspNetCore.Mvc;
namespace EnvelopeGenerator.GeneratorAPI.Controllers;
/// <summary>
///
/// </summary>
[ApiExplorerSettings(IgnoreApi = true)]
[Route("api/[controller]")]
[ApiController]
public class EnvelopeTypeController : ControllerBase
{
private readonly ILogger<EnvelopeTypeController> _logger;
[Obsolete("Use MediatR")]
private readonly IEnvelopeTypeService _service;
/// <summary>
///
/// </summary>
/// <param name="logger"></param>
/// <param name="service"></param>
[Obsolete("Use MediatR")]
public EnvelopeTypeController(ILogger<EnvelopeTypeController> logger, IEnvelopeTypeService service)
{
_logger = logger;
_service = service;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[Obsolete("Use MediatR")]
[HttpGet]
public async Task<IActionResult> GetAllAsync()
{
return await _service.ReadAllAsync().ThenAsync(
Success: Ok,
Fail: IActionResult (msg, ntc) =>
{
_logger.LogNotice(ntc);
return ntc.HasFlag(Flag.NotFound) ? NotFound() : StatusCode(StatusCodes.Status500InternalServerError);
});
}
}

View File

@@ -1,99 +0,0 @@
using DigitalData.Core.Abstraction.Application.DTO;
using DigitalData.Core.API;
using EnvelopeGenerator.Application.Receivers.Queries;
using EnvelopeGenerator.Domain.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using EnvelopeGenerator.Application.Receivers.Commands;
using EnvelopeGenerator.Application.Common.Dto.Receiver;
using EnvelopeGenerator.Application.Common.Interfaces.Services;
namespace EnvelopeGenerator.GeneratorAPI.Controllers;
/// <summary>
/// Controller für die Verwaltung von Empfängern.
/// </summary>
/// <remarks>
/// Dieser Controller bietet Endpunkte für CRUD-Operationen (Erstellen, Lesen, Aktualisieren, Löschen)
/// sowie zusätzliche Funktionen wie das Abrufen von Empfängern basierend auf E-Mail-Adresse oder Signatur.
/// </remarks>
[Route("api/[controller]")]
[ApiController]
[Authorize]
[Obsolete("Use MediatR")]
public class ReceiverController : CRUDControllerBaseWithErrorHandling<IReceiverService, CreateReceiverCommand, ReceiverDto, UpdateReceiverCommand, Receiver, int>
{
/// <summary>
/// Initialisiert eine neue Instanz des <see cref="ReceiverController"/>-Controllers.
/// </summary>
/// <param name="logger">Der Logger für die Protokollierung.</param>
/// <param name="service">Der Dienst für Empfängeroperationen.</param>
public ReceiverController(ILogger<ReceiverController> logger, IReceiverService service) : base(logger, service)
{
}
/// <summary>
/// Ruft eine Liste von Empfängern ab, basierend auf den angegebenen Abfrageparametern.
/// </summary>
/// <param name="receiver">Die Abfrageparameter, einschließlich E-Mail-Adresse und Signatur.</param>
/// <returns>Eine Liste von Empfängern oder ein Fehlerstatus.</returns>
[HttpGet]
public async Task<IActionResult> Get([FromQuery] ReadReceiverQuery receiver)
{
if (receiver.Id is null && receiver.EmailAddress is null && receiver.Signature is null)
return await base.GetAll();
if (receiver.Id is int id)
return await _service.ReadByIdAsync(id).ThenAsync(
Success: Ok,
Fail: IActionResult (msg, ntc) =>
{
return NotFound();
});
return await _service.ReadByAsync(emailAddress: receiver.EmailAddress, signature: receiver.Signature).ThenAsync(
Success: Ok,
Fail: IActionResult (msg, ntc) =>
{
return NotFound();
});
}
#region REMOVED ENDPOINTS
/// <summary>
/// Diese Methode ist deaktiviert und wird nicht verwendet.
/// </summary>
[NonAction]
public override Task<IActionResult> GetAll() => base.GetAll();
/// <summary>
/// Diese Methode ist deaktiviert und wird nicht verwendet.
/// </summary>
[NonAction]
public override Task<IActionResult> Delete([FromRoute] int id) => base.Delete(id);
/// <summary>
/// Diese Methode ist deaktiviert und wird nicht verwendet.
/// </summary>
[NonAction]
public override Task<IActionResult> Update(UpdateReceiverCommand updateDto) => base.Update(updateDto);
/// <summary>
/// Diese Methode ist deaktiviert und wird nicht verwendet.
/// </summary>
[NonAction]
public override Task<IActionResult> Create(CreateReceiverCommand createDto)
{
return base.Create(createDto);
}
/// <summary>
/// Diese Methode ist deaktiviert und wird nicht verwendet.
/// </summary>
[NonAction]
public override Task<IActionResult> GetById([FromRoute] int id)
{
return base.GetById(id);
}
#endregion
}

View File

@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<WebPublishMethod>Package</WebPublishMethod>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<ExcludeApp_Data>false</ExcludeApp_Data>
<ProjectGuid>4fdae4ba-f512-444a-9e18-111047d3ef02</ProjectGuid>
<DesktopBuildPackageLocation>P:\Install .Net\0 DD - Smart UP\signFLOW\Gen\Api\net7\win64\$(Version)\$(Version).zip</DesktopBuildPackageLocation>
<PackageAsSingleFile>true</PackageAsSingleFile>
<DeployIisAppPath>SignFlowGen</DeployIisAppPath>
<_TargetId>IISWebDeployPackage</_TargetId>
<TargetFramework>net7.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
</PropertyGroup>
</Project>

View File

@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<WebPublishMethod>Package</WebPublishMethod>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<ExcludeApp_Data>false</ExcludeApp_Data>
<ProjectGuid>4fdae4ba-f512-444a-9e18-111047d3ef02</ProjectGuid>
<DesktopBuildPackageLocation>P:\Install .Net\0 DD - Smart UP\signFLOW\Gen\Api\net9\win64\$(Version)\$(Version).zip</DesktopBuildPackageLocation>
<PackageAsSingleFile>true</PackageAsSingleFile>
<DeployIisAppPath>SignFlowGen</DeployIisAppPath>
<_TargetId>IISWebDeployPackage</_TargetId>
<TargetFramework>net9.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
</PropertyGroup>
</Project>

View File

@@ -1,4 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="3em" height="2.5em" viewBox="0 0 24 24" style="stroke: #a9a8ad;">
<path opacity="0.5" d="M15.9998 2L14.9998 2C12.1714 2 10.7576 2.00023 9.87891 2.87891C9.00023 3.75759 9.00023 5.1718 9.00023 8.00023L9.00023 16.0002C9.00023 18.8287 9.00023 20.2429 9.87891 21.1215C10.7574 22 12.1706 22 14.9976 22L14.9998 22L15.9998 22C18.8282 22 20.2424 22 21.1211 21.1213C21.9998 20.2426 21.9998 18.8284 21.9998 16L21.9998 8L21.9998 7.99998C21.9998 5.17157 21.9998 3.75736 21.1211 2.87868C20.2424 2 18.8282 2 15.9998 2Z" fill="#1C274C"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M1.25098 11.999C1.25098 11.5848 1.58676 11.249 2.00098 11.249L13.9735 11.249L12.0129 9.56845C11.6984 9.29889 11.662 8.82541 11.9315 8.51092C12.2011 8.19642 12.6746 8.16 12.9891 8.42957L16.4891 11.4296C16.6553 11.5721 16.751 11.7801 16.751 11.999C16.751 12.218 16.6553 12.426 16.4891 12.5685L12.9891 15.5685C12.6746 15.838 12.2011 15.8016 11.9315 15.4871C11.662 15.1726 11.6984 14.6991 12.0129 14.4296L13.9735 12.749L2.00098 12.749C1.58676 12.749 1.25098 12.4132 1.25098 11.999Z" fill="#1C274C"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 264 KiB

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -12,7 +12,7 @@ namespace EnvelopeGenerator.Infrastructure
public EGDbContext CreateDbContext(string[] args) public EGDbContext CreateDbContext(string[] args)
{ {
var config = new ConfigurationBuilder() var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) // Önemli! .SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.migration.json") .AddJsonFile("appsettings.migration.json")
.Build(); .Build();

View File

@@ -22,8 +22,8 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Dapper" Version="2.1.66" /> <PackageReference Include="Dapper" Version="2.1.66" />
<PackageReference Include="DigitalData.Core.Abstraction.Application" Version="1.4.0" /> <PackageReference Include="DigitalData.Core.Abstraction.Application" Version="1.6.0" />
<PackageReference Include="DigitalData.Core.Infrastructure" Version="2.4.5" /> <PackageReference Include="DigitalData.Core.Infrastructure" Version="2.6.1" />
<PackageReference Include="QuestPDF" Version="2025.7.1" /> <PackageReference Include="QuestPDF" Version="2025.7.1" />
</ItemGroup> </ItemGroup>

View File

@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Quartz" Version="3.9.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.2" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="6.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EnvelopeGenerator.Domain\EnvelopeGenerator.Domain.csproj" />
<ProjectReference Include="..\EnvelopeGenerator.Infrastructure\EnvelopeGenerator.Infrastructure.csproj" />
<ProjectReference Include="..\EnvelopeGenerator.PdfEditor\EnvelopeGenerator.PdfEditor.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,151 @@
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using EnvelopeGenerator.Domain.Constants;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Quartz;
namespace EnvelopeGenerator.Jobs.APIBackendJobs;
public class APIEnvelopeJob(ILogger<APIEnvelopeJob>? logger = null) : IJob
{
private readonly ILogger<APIEnvelopeJob> _logger = logger ?? NullLogger<APIEnvelopeJob>.Instance;
public async Task Execute(IJobExecutionContext context)
{
var jobId = context.JobDetail.Key.ToString();
_logger.LogDebug("API Envelopes - Starting job {JobId}", jobId);
try
{
var connectionString = context.MergedJobDataMap.GetString(Value.DATABASE);
if (string.IsNullOrWhiteSpace(connectionString))
{
_logger.LogWarning("API Envelopes - Connection string missing");
return;
}
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(context.CancellationToken);
await ProcessInvitationsAsync(connection, context.CancellationToken);
await ProcessWithdrawnAsync(connection, context.CancellationToken);
_logger.LogDebug("API Envelopes - Completed job {JobId} successfully", jobId);
}
catch (System.Exception ex)
{
_logger.LogError(ex, "API Envelopes job failed");
}
finally
{
_logger.LogDebug("API Envelopes execution for {JobId} ended", jobId);
}
}
private async Task ProcessInvitationsAsync(SqlConnection connection, System.Threading.CancellationToken cancellationToken)
{
const string sql = "SELECT GUID FROM TBSIG_ENVELOPE WHERE SOURCE = 'API' AND STATUS = 1003 ORDER BY GUID";
var envelopeIds = new List<int>();
await using (var command = new SqlCommand(sql, connection))
await using (var reader = await command.ExecuteReaderAsync(cancellationToken))
{
while (await reader.ReadAsync(cancellationToken))
{
if (reader[0] is int id)
{
envelopeIds.Add(id);
}
}
}
if (envelopeIds.Count == 0)
{
_logger.LogDebug("SendInvMail - No envelopes found");
return;
}
_logger.LogInformation("SendInvMail - Found {Count} envelopes", envelopeIds.Count);
var total = envelopeIds.Count;
var current = 1;
foreach (var id in envelopeIds)
{
_logger.LogInformation("SendInvMail - Processing Envelope {EnvelopeId} ({Current}/{Total})", id, current, total);
try
{
// Placeholder for invitation email sending logic.
_logger.LogDebug("SendInvMail - Marking envelope {EnvelopeId} as queued", id);
const string updateSql = "UPDATE TBSIG_ENVELOPE SET CURRENT_WORK_APP = @App WHERE GUID = @Id";
await using var updateCommand = new SqlCommand(updateSql, connection);
updateCommand.Parameters.AddWithValue("@App", "signFLOW_API_EnvJob_InvMail");
updateCommand.Parameters.AddWithValue("@Id", id);
await updateCommand.ExecuteNonQueryAsync(cancellationToken);
}
catch (System.Exception ex)
{
_logger.LogWarning(ex, "SendInvMail - Unhandled exception while working envelope {EnvelopeId}", id);
}
current++;
_logger.LogInformation("SendInvMail - Envelope finalized");
}
}
private async Task ProcessWithdrawnAsync(SqlConnection connection, System.Threading.CancellationToken cancellationToken)
{
const string sql = @"SELECT ENV.GUID, REJ.COMMENT AS REJECTION_REASON FROM
(SELECT * FROM TBSIG_ENVELOPE WHERE STATUS = 1009 AND SOURCE = 'API') ENV INNER JOIN
(SELECT MAX(GUID) GUID, ENVELOPE_ID, MAX(ADDED_WHEN) ADDED_WHEN, MAX(ACTION_DATE) ACTION_DATE, COMMENT FROM TBSIG_ENVELOPE_HISTORY WHERE STATUS = 1009 GROUP BY ENVELOPE_ID, COMMENT ) REJ ON ENV.GUID = REJ.ENVELOPE_ID LEFT JOIN
(SELECT * FROM TBSIG_ENVELOPE_HISTORY WHERE STATUS = 3004 ) M_Send ON ENV.GUID = M_Send.ENVELOPE_ID
WHERE M_Send.GUID IS NULL";
var withdrawn = new List<(int EnvelopeId, string Reason)>();
await using (var command = new SqlCommand(sql, connection))
await using (var reader = await command.ExecuteReaderAsync(cancellationToken))
{
while (await reader.ReadAsync(cancellationToken))
{
var id = reader.GetInt32(0);
var reason = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
withdrawn.Add((id, reason));
}
}
if (withdrawn.Count == 0)
{
_logger.LogDebug("WithdrawnEnv - No envelopes found");
return;
}
_logger.LogInformation("WithdrawnEnv - Found {Count} envelopes", withdrawn.Count);
var total = withdrawn.Count;
var current = 1;
foreach (var (envelopeId, reason) in withdrawn)
{
_logger.LogInformation("WithdrawnEnv - Processing Envelope {EnvelopeId} ({Current}/{Total})", envelopeId, current, total);
try
{
// Log withdrawn mail trigger placeholder
const string insertHistory = "INSERT INTO TBSIG_ENVELOPE_HISTORY (ENVELOPE_ID, STATUS, USER_REFERENCE, ADDED_WHEN, ACTION_DATE, COMMENT) VALUES (@EnvelopeId, @Status, @UserReference, GETDATE(), GETDATE(), @Comment)";
await using var insertCommand = new SqlCommand(insertHistory, connection);
insertCommand.Parameters.AddWithValue("@EnvelopeId", envelopeId);
insertCommand.Parameters.AddWithValue("@Status", 3004);
insertCommand.Parameters.AddWithValue("@UserReference", "API");
insertCommand.Parameters.AddWithValue("@Comment", reason ?? string.Empty);
await insertCommand.ExecuteNonQueryAsync(cancellationToken);
}
catch (System.Exception ex)
{
_logger.LogWarning(ex, "WithdrawnEnv - Unhandled exception while working envelope {EnvelopeId}", envelopeId);
}
current++;
_logger.LogInformation("WithdrawnEnv - Envelope finalized");
}
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Data;
namespace EnvelopeGenerator.Jobs;
public static class DataRowExtensions
{
public static T? GetValueOrDefault<T>(this DataRow row, string columnName, T? defaultValue = default)
{
if (!row.Table.Columns.Contains(columnName))
{
return defaultValue;
}
var value = row[columnName];
if (value == DBNull.Value)
{
return defaultValue;
}
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch
{
return defaultValue;
}
}
}

View File

@@ -0,0 +1,28 @@
namespace EnvelopeGenerator.Jobs.FinalizeDocument;
public static class FinalizeDocumentExceptions
{
public class MergeDocumentException : ApplicationException
{
public MergeDocumentException(string message) : base(message) { }
public MergeDocumentException(string message, Exception innerException) : base(message, innerException) { }
}
public class BurnAnnotationException : ApplicationException
{
public BurnAnnotationException(string message) : base(message) { }
public BurnAnnotationException(string message, Exception innerException) : base(message, innerException) { }
}
public class CreateReportException : ApplicationException
{
public CreateReportException(string message) : base(message) { }
public CreateReportException(string message, Exception innerException) : base(message, innerException) { }
}
public class ExportDocumentException : ApplicationException
{
public ExportDocumentException(string message) : base(message) { }
public ExportDocumentException(string message, Exception innerException) : base(message, innerException) { }
}
}

View File

@@ -0,0 +1,229 @@
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EnvelopeGenerator.Domain.Constants;
using EnvelopeGenerator.Domain.Entities;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;
using Quartz;
using static EnvelopeGenerator.Jobs.FinalizeDocument.FinalizeDocumentExceptions;
namespace EnvelopeGenerator.Jobs.FinalizeDocument;
public class FinalizeDocumentJob : IJob
{
private readonly ILogger<FinalizeDocumentJob> _logger;
private readonly PDFBurner _pdfBurner;
private readonly PDFMerger _pdfMerger;
private readonly ReportCreator _reportCreator;
private record ConfigSettings(string DocumentPath, string DocumentPathOrigin, string ExportPath);
public FinalizeDocumentJob(
ILogger<FinalizeDocumentJob> logger,
PDFBurner pdfBurner,
PDFMerger pdfMerger,
ReportCreator reportCreator)
{
_logger = logger;
_pdfBurner = pdfBurner;
_pdfMerger = pdfMerger;
_reportCreator = reportCreator;
}
public async Task Execute(IJobExecutionContext context)
{
var jobId = context.JobDetail.Key.ToString();
_logger.LogDebug("Starting job {JobId}", jobId);
try
{
var connectionString = context.MergedJobDataMap.GetString(Value.DATABASE);
if (string.IsNullOrWhiteSpace(connectionString))
{
_logger.LogWarning("FinalizeDocument - Connection string missing");
return;
}
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(context.CancellationToken);
var config = await LoadConfigurationAsync(connection, context.CancellationToken);
var envelopes = await LoadCompletedEnvelopesAsync(connection, context.CancellationToken);
if (envelopes.Count == 0)
{
_logger.LogInformation("No completed envelopes found");
return;
}
var total = envelopes.Count;
var current = 1;
foreach (var envelopeId in envelopes)
{
_logger.LogInformation("Finalizing Envelope {EnvelopeId} ({Current}/{Total})", envelopeId, current, total);
try
{
var envelopeData = await GetEnvelopeDataAsync(connection, envelopeId, context.CancellationToken);
if (envelopeData is null)
{
_logger.LogWarning("Envelope data not found for {EnvelopeId}", envelopeId);
continue;
}
var data = envelopeData.Value;
var envelope = new Envelope
{
Id = envelopeId,
Uuid = data.EnvelopeUuid ?? string.Empty,
Title = data.Title ?? string.Empty,
FinalEmailToCreator = (int)FinalEmailType.No,
FinalEmailToReceivers = (int)FinalEmailType.No
};
var burned = _pdfBurner.BurnAnnotsToPDF(data.DocumentBytes, data.AnnotationData, envelopeId);
var report = _reportCreator.CreateReport(connection, envelope);
var merged = _pdfMerger.MergeDocuments(burned, report);
var outputDirectory = Path.Combine(config.ExportPath, data.ParentFolderUid);
Directory.CreateDirectory(outputDirectory);
var outputPath = Path.Combine(outputDirectory, $"{envelope.Uuid}.pdf");
await File.WriteAllBytesAsync(outputPath, merged, context.CancellationToken);
await UpdateDocumentResultAsync(connection, envelopeId, merged, context.CancellationToken);
await ArchiveEnvelopeAsync(connection, envelopeId, context.CancellationToken);
}
catch (MergeDocumentException ex)
{
_logger.LogWarning(ex, "Certificate Document job failed at merging documents");
}
catch (ExportDocumentException ex)
{
_logger.LogWarning(ex, "Certificate Document job failed at exporting document");
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception while working envelope {EnvelopeId}", envelopeId);
}
current++;
_logger.LogInformation("Envelope {EnvelopeId} finalized", envelopeId);
}
_logger.LogDebug("Completed job {JobId} successfully", jobId);
}
catch (Exception ex)
{
_logger.LogError(ex, "Certificate Document job failed");
}
finally
{
_logger.LogDebug("Job execution for {JobId} ended", jobId);
}
}
private async Task<ConfigSettings> LoadConfigurationAsync(SqlConnection connection, CancellationToken cancellationToken)
{
const string sql = "SELECT TOP 1 DOCUMENT_PATH, EXPORT_PATH FROM TBSIG_CONFIG";
await using var command = new SqlCommand(sql, connection);
await using var reader = await command.ExecuteReaderAsync(cancellationToken);
if (await reader.ReadAsync(cancellationToken))
{
var documentPath = reader.IsDBNull(0) ? string.Empty : reader.GetString(0);
var exportPath = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
return new ConfigSettings(documentPath, documentPath, exportPath);
}
return new ConfigSettings(string.Empty, string.Empty, Path.GetTempPath());
}
private async Task<List<int>> LoadCompletedEnvelopesAsync(SqlConnection connection, CancellationToken cancellationToken)
{
const string sql = "SELECT GUID FROM TBSIG_ENVELOPE WHERE STATUS = @Status AND DATEDIFF(minute, CHANGED_WHEN, GETDATE()) >= 1 ORDER BY GUID";
var ids = new List<int>();
await using var command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@Status", (int)EnvelopeStatus.EnvelopeCompletelySigned);
await using var reader = await command.ExecuteReaderAsync(cancellationToken);
while (await reader.ReadAsync(cancellationToken))
{
ids.Add(reader.GetInt32(0));
}
return ids;
}
private async Task<(int EnvelopeId, string? EnvelopeUuid, string? Title, byte[] DocumentBytes, List<string> AnnotationData, string ParentFolderUid)?> GetEnvelopeDataAsync(SqlConnection connection, int envelopeId, CancellationToken cancellationToken)
{
const string sql = @"SELECT T.GUID, T.ENVELOPE_UUID, T.TITLE, T2.FILEPATH, T2.BYTE_DATA FROM [dbo].[TBSIG_ENVELOPE] T
JOIN TBSIG_ENVELOPE_DOCUMENT T2 ON T.GUID = T2.ENVELOPE_ID
WHERE T.GUID = @EnvelopeId";
await using var command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@EnvelopeId", envelopeId);
await using var reader = await command.ExecuteReaderAsync(CommandBehavior.SingleRow, cancellationToken);
if (!await reader.ReadAsync(cancellationToken))
{
return null;
}
var envelopeUuid = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
var title = reader.IsDBNull(2) ? string.Empty : reader.GetString(2);
var filePath = reader.IsDBNull(3) ? string.Empty : reader.GetString(3);
var bytes = reader.IsDBNull(4) ? Array.Empty<byte>() : (byte[])reader[4];
await reader.CloseAsync();
if (bytes.Length == 0 && !string.IsNullOrWhiteSpace(filePath) && File.Exists(filePath))
{
bytes = await File.ReadAllBytesAsync(filePath, cancellationToken);
}
var annotations = await GetAnnotationDataAsync(connection, envelopeId, cancellationToken);
var parentFolderUid = !string.IsNullOrWhiteSpace(filePath)
? Path.GetFileName(Path.GetDirectoryName(filePath) ?? string.Empty)
: envelopeUuid;
return (envelopeId, envelopeUuid, title, bytes, annotations, parentFolderUid ?? envelopeUuid ?? envelopeId.ToString());
}
private async Task<List<string>> GetAnnotationDataAsync(SqlConnection connection, int envelopeId, CancellationToken cancellationToken)
{
const string sql = "SELECT VALUE FROM TBSIG_DOCUMENT_STATUS WHERE ENVELOPE_ID = @EnvelopeId";
var result = new List<string>();
await using var command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@EnvelopeId", envelopeId);
await using var reader = await command.ExecuteReaderAsync(cancellationToken);
while (await reader.ReadAsync(cancellationToken))
{
if (!reader.IsDBNull(0))
{
result.Add(reader.GetString(0));
}
}
return result;
}
private static async Task UpdateDocumentResultAsync(SqlConnection connection, int envelopeId, byte[] bytes, CancellationToken cancellationToken)
{
const string sql = "UPDATE TBSIG_ENVELOPE SET DOC_RESULT = @ImageData WHERE GUID = @EnvelopeId";
await using var command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@ImageData", bytes);
command.Parameters.AddWithValue("@EnvelopeId", envelopeId);
await command.ExecuteNonQueryAsync(cancellationToken);
}
private static async Task ArchiveEnvelopeAsync(SqlConnection connection, int envelopeId, CancellationToken cancellationToken)
{
const string sql = "UPDATE TBSIG_ENVELOPE SET STATUS = @Status, CHANGED_WHEN = GETDATE() WHERE GUID = @EnvelopeId";
await using var command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@Status", (int)EnvelopeStatus.EnvelopeArchived);
command.Parameters.AddWithValue("@EnvelopeId", envelopeId);
await command.ExecuteNonQueryAsync(cancellationToken);
}
}

View File

@@ -0,0 +1,277 @@
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using iText.IO.Image;
using iText.Kernel.Colors;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Font;
using iText.Layout.Properties;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using static EnvelopeGenerator.Jobs.FinalizeDocument.FinalizeDocumentExceptions;
using LayoutImage = iText.Layout.Element.Image;
namespace EnvelopeGenerator.Jobs.FinalizeDocument;
public class PDFBurner
{
private static readonly FontProvider FontProvider = CreateFontProvider();
private readonly ILogger<PDFBurner> _logger;
private readonly PDFBurnerParams _pdfBurnerParams;
public PDFBurner() : this(NullLogger<PDFBurner>.Instance, new PDFBurnerParams())
{
}
public PDFBurner(ILogger<PDFBurner> logger, PDFBurnerParams? pdfBurnerParams = null)
{
_logger = logger;
_pdfBurnerParams = pdfBurnerParams ?? new PDFBurnerParams();
}
public byte[] BurnAnnotsToPDF(byte[] sourceBuffer, IList<string> instantJsonList, int envelopeId)
{
if (sourceBuffer is null || sourceBuffer.Length == 0)
{
throw new BurnAnnotationException("Source document is empty");
}
try
{
using var inputStream = new MemoryStream(sourceBuffer);
using var outputStream = new MemoryStream();
using var reader = new PdfReader(inputStream);
using var writer = new PdfWriter(outputStream);
using var pdf = new PdfDocument(reader, writer);
foreach (var json in instantJsonList ?? Enumerable.Empty<string>())
{
if (string.IsNullOrWhiteSpace(json))
{
continue;
}
var annotationData = JsonConvert.DeserializeObject<AnnotationData>(json);
if (annotationData?.annotations is null)
{
continue;
}
annotationData.annotations.Reverse();
foreach (var annotation in annotationData.annotations)
{
try
{
switch (annotation.type)
{
case AnnotationType.Image:
AddImageAnnotation(pdf, annotation, annotationData.attachments);
break;
case AnnotationType.Ink:
AddInkAnnotation(pdf, annotation);
break;
case AnnotationType.Widget:
var formFieldValue = annotationData.formFieldValues?.FirstOrDefault(fv => fv.name == annotation.id);
if (formFieldValue is not null && !_pdfBurnerParams.IgnoredLabels.Contains(formFieldValue.value))
{
AddFormFieldValue(pdf, annotation, formFieldValue.value);
}
break;
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Error applying annotation {AnnotationId} on envelope {EnvelopeId}", annotation.id, envelopeId);
throw new BurnAnnotationException("Adding annotation failed", ex);
}
}
}
pdf.Close();
return outputStream.ToArray();
}
catch (BurnAnnotationException)
{
throw;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to burn annotations for envelope {EnvelopeId}", envelopeId);
throw new BurnAnnotationException("Annotations could not be burned", ex);
}
}
private void AddImageAnnotation(PdfDocument pdf, Annotation annotation, Dictionary<string, Attachment>? attachments)
{
if (attachments is null || string.IsNullOrWhiteSpace(annotation.imageAttachmentId) || !attachments.TryGetValue(annotation.imageAttachmentId, out var attachment))
{
return;
}
var page = pdf.GetPage(annotation.pageIndex + 1);
var bounds = annotation.bbox.Select(ToInches).ToList();
var x = (float)bounds[0];
var y = (float)bounds[1];
var width = (float)bounds[2];
var height = (float)bounds[3];
var imageBytes = Convert.FromBase64String(attachment.binary);
var imageData = ImageDataFactory.Create(imageBytes);
var image = new LayoutImage(imageData)
.ScaleAbsolute(width, height)
.SetFixedPosition(annotation.pageIndex + 1, x, y);
using var canvas = new Canvas(new PdfCanvas(page), page.GetPageSize());
canvas.Add(image);
}
private void AddInkAnnotation(PdfDocument pdf, Annotation annotation)
{
if (annotation.lines?.points is null)
{
return;
}
var page = pdf.GetPage(annotation.pageIndex + 1);
var canvas = new PdfCanvas(page);
var color = ParseColor(annotation.strokeColor);
canvas.SetStrokeColor(color);
canvas.SetLineWidth(1);
foreach (var segment in annotation.lines.points)
{
var first = true;
foreach (var point in segment)
{
var (px, py) = (ToInches(point[0]), ToInches(point[1]));
if (first)
{
canvas.MoveTo(px, py);
first = false;
}
else
{
canvas.LineTo(px, py);
}
}
canvas.Stroke();
}
}
private static FontProvider CreateFontProvider()
{
var provider = new FontProvider();
provider.AddStandardPdfFonts();
provider.AddSystemFonts();
return provider;
}
private void AddFormFieldValue(PdfDocument pdf, Annotation annotation, string value)
{
var bounds = annotation.bbox.Select(ToInches).ToList();
var x = (float)bounds[0];
var y = (float)bounds[1];
var width = (float)bounds[2];
var height = (float)bounds[3];
var page = pdf.GetPage(annotation.pageIndex + 1);
var canvas = new Canvas(new PdfCanvas(page), page.GetPageSize());
canvas.SetProperty(Property.FONT_PROVIDER, FontProvider);
canvas.SetProperty(Property.FONT, FontProvider.GetFontSet());
var paragraph = new Paragraph(value)
.SetFontSize(_pdfBurnerParams.FontSize)
.SetFontColor(ColorConstants.BLACK)
.SetFontFamily(_pdfBurnerParams.FontName);
if (_pdfBurnerParams.FontStyle.HasFlag(FontStyle.Italic))
{
paragraph.SetItalic();
}
if (_pdfBurnerParams.FontStyle.HasFlag(FontStyle.Bold))
{
paragraph.SetBold();
}
canvas.ShowTextAligned(
paragraph,
x + (float)_pdfBurnerParams.TopMargin,
y + (float)_pdfBurnerParams.YOffset,
annotation.pageIndex + 1,
iText.Layout.Properties.TextAlignment.LEFT,
iText.Layout.Properties.VerticalAlignment.TOP,
0);
}
private static DeviceRgb ParseColor(string? color)
{
if (string.IsNullOrWhiteSpace(color))
{
return new DeviceRgb(0, 0, 0);
}
try
{
var drawingColor = ColorTranslator.FromHtml(color);
return new DeviceRgb(drawingColor.R, drawingColor.G, drawingColor.B);
}
catch
{
return new DeviceRgb(0, 0, 0);
}
}
private static double ToInches(double value) => value / 72d;
private static double ToInches(float value) => value / 72d;
#region Model
private static class AnnotationType
{
public const string Image = "pspdfkit/image";
public const string Ink = "pspdfkit/ink";
public const string Widget = "pspdfkit/widget";
}
private sealed class AnnotationData
{
public List<Annotation>? annotations { get; set; }
public Dictionary<string, Attachment>? attachments { get; set; }
public List<FormFieldValue>? formFieldValues { get; set; }
}
private sealed class Annotation
{
public string id { get; set; } = string.Empty;
public List<double> bbox { get; set; } = new();
public string type { get; set; } = string.Empty;
public string imageAttachmentId { get; set; } = string.Empty;
public Lines? lines { get; set; }
public int pageIndex { get; set; }
public string strokeColor { get; set; } = string.Empty;
public string egName { get; set; } = string.Empty;
}
private sealed class Lines
{
public List<List<List<float>>> points { get; set; } = new();
}
private sealed class Attachment
{
public string binary { get; set; } = string.Empty;
public string contentType { get; set; } = string.Empty;
}
private sealed class FormFieldValue
{
public string name { get; set; } = string.Empty;
public string value { get; set; } = string.Empty;
}
#endregion
}

View File

@@ -0,0 +1,19 @@
using System.Collections.Generic;
using System.Drawing;
namespace EnvelopeGenerator.Jobs.FinalizeDocument;
public class PDFBurnerParams
{
public List<string> IgnoredLabels { get; } = new() { "Date", "Datum", "ZIP", "PLZ", "Place", "Ort", "Position", "Stellung" };
public double TopMargin { get; set; } = 0.1;
public double YOffset { get; set; } = -0.3;
public string FontName { get; set; } = "Arial";
public int FontSize { get; set; } = 8;
public FontStyle FontStyle { get; set; } = FontStyle.Italic;
}

Some files were not shown because too many files have changed in this diff Show More