├── .dockerignore ├── .editorconfig ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── config.yml │ └── feature_request.md ├── icon.png └── workflows │ ├── codeql-analysis.yml │ └── dotnetcore.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CleanArchitecture.sln ├── LICENSE ├── README.md ├── docker-compose.dcproj ├── docker-compose.override.yml ├── docker-compose.yml ├── global.json ├── src ├── Application │ ├── Application.csproj │ ├── Common │ │ ├── Behaviours │ │ │ ├── AuthorizationBehaviour.cs │ │ │ ├── LoggingBehaviour.cs │ │ │ ├── PerformanceBehaviour.cs │ │ │ ├── UnhandledExceptionBehaviour.cs │ │ │ └── ValidationBehaviour.cs │ │ ├── Exceptions │ │ │ ├── ForbiddenAccessException.cs │ │ │ ├── NotFoundException.cs │ │ │ └── ValidationException.cs │ │ ├── Interfaces │ │ │ ├── IApplicationDbContext.cs │ │ │ ├── ICsvFileBuilder.cs │ │ │ ├── ICurrentUserService.cs │ │ │ ├── IDateTime.cs │ │ │ ├── IDomainEventService.cs │ │ │ └── IIdentityService.cs │ │ ├── Mappings │ │ │ ├── IMapFrom.cs │ │ │ ├── MappingExtensions.cs │ │ │ └── MappingProfile.cs │ │ ├── Models │ │ │ ├── DomainEventNotification.cs │ │ │ ├── PaginatedList.cs │ │ │ └── Result.cs │ │ └── Security │ │ │ └── AuthorizeAttribute.cs │ ├── DependencyInjection.cs │ ├── TodoItems │ │ ├── Commands │ │ │ ├── CreateTodoItem │ │ │ │ ├── CreateTodoItemCommand.cs │ │ │ │ └── CreateTodoItemCommandValidator.cs │ │ │ ├── DeleteTodoItem │ │ │ │ └── DeleteTodoItemCommand.cs │ │ │ ├── UpdateTodoItem │ │ │ │ ├── UpdateTodoItemCommand.cs │ │ │ │ └── UpdateTodoItemCommandValidator.cs │ │ │ └── UpdateTodoItemDetail │ │ │ │ └── UpdateTodoItemDetailCommand.cs │ │ ├── EventHandlers │ │ │ ├── TodoItemCompletedEventHandler.cs │ │ │ └── TodoItemCreatedEventHandler.cs │ │ └── Queries │ │ │ └── GetTodoItemsWithPagination │ │ │ ├── GetTodoItemsWithPaginationQuery.cs │ │ │ ├── GetTodoItemsWithPaginationQueryValidator.cs │ │ │ └── TodoItemBriefDto.cs │ ├── TodoLists │ │ ├── Commands │ │ │ ├── CreateTodoList │ │ │ │ ├── CreateTodoListCommand.cs │ │ │ │ └── CreateTodoListCommandValidator.cs │ │ │ ├── DeleteTodoList │ │ │ │ └── DeleteTodoListCommand.cs │ │ │ ├── PurgeTodoLists │ │ │ │ └── PurgeTodoListsCommand.cs │ │ │ └── UpdateTodoList │ │ │ │ ├── UpdateTodoListCommand.cs │ │ │ │ └── UpdateTodoListCommandValidator.cs │ │ └── Queries │ │ │ ├── ExportTodos │ │ │ ├── ExportTodosQuery.cs │ │ │ ├── ExportTodosVm.cs │ │ │ └── TodoItemFileRecord.cs │ │ │ └── GetTodos │ │ │ ├── GetTodosQuery.cs │ │ │ ├── PriorityLevelDto.cs │ │ │ ├── TodoItemDto.cs │ │ │ ├── TodoListDto.cs │ │ │ └── TodosVm.cs │ └── WeatherForecasts │ │ └── Queries │ │ └── GetWeatherForecasts │ │ ├── GetWeatherForecastsQuery.cs │ │ └── WeatherForecast.cs ├── Domain │ ├── Common │ │ ├── AuditableEntity.cs │ │ ├── DomainEvent.cs │ │ └── ValueObject.cs │ ├── Domain.csproj │ ├── Entities │ │ ├── TodoItem.cs │ │ └── TodoList.cs │ ├── Enums │ │ └── PriorityLevel.cs │ ├── Events │ │ ├── TodoItemCompletedEvent.cs │ │ ├── TodoItemCreatedEvent.cs │ │ └── TodoItemDeletedEvent.cs │ ├── Exceptions │ │ └── UnsupportedColourException.cs │ ├── ValueObjects │ │ └── Colour.cs │ └── _Imports.cs ├── Infrastructure │ ├── DependencyInjection.cs │ ├── Files │ │ ├── CsvFileBuilder.cs │ │ └── Maps │ │ │ └── TodoItemRecordMap.cs │ ├── Identity │ │ ├── ApplicationUser.cs │ │ ├── IdentityResultExtensions.cs │ │ └── IdentityService.cs │ ├── Infrastructure.csproj │ ├── Persistence │ │ ├── ApplicationDbContext.cs │ │ ├── ApplicationDbContextSeed.cs │ │ ├── Configurations │ │ │ ├── TodoItemConfiguration.cs │ │ │ └── TodoListConfiguration.cs │ │ └── Migrations │ │ │ ├── 00000000000000_InitialCreate.Designer.cs │ │ │ ├── 00000000000000_InitialCreate.cs │ │ │ └── ApplicationDbContextModelSnapshot.cs │ └── Services │ │ ├── DateTimeService.cs │ │ └── DomainEventService.cs └── WebUI │ ├── ClientApp │ ├── .browserslistrc │ ├── .dockerignore │ ├── .editorconfig │ ├── .gitignore │ ├── Dockerfile │ ├── angular.json │ ├── e2e │ │ ├── protractor.conf.js │ │ ├── src │ │ │ ├── app.e2e-spec.ts │ │ │ └── app.po.ts │ │ └── tsconfig.e2e.json │ ├── package-lock.json │ ├── package.json │ ├── src │ │ ├── api-authorization │ │ │ ├── api-authorization.constants.ts │ │ │ ├── api-authorization.module.spec.ts │ │ │ ├── api-authorization.module.ts │ │ │ ├── authorize.guard.spec.ts │ │ │ ├── authorize.guard.ts │ │ │ ├── authorize.interceptor.spec.ts │ │ │ ├── authorize.interceptor.ts │ │ │ ├── authorize.service.spec.ts │ │ │ ├── authorize.service.ts │ │ │ ├── login-menu │ │ │ │ ├── login-menu.component.html │ │ │ │ ├── login-menu.component.scss │ │ │ │ ├── login-menu.component.spec.ts │ │ │ │ └── login-menu.component.ts │ │ │ ├── login │ │ │ │ ├── login.component.html │ │ │ │ ├── login.component.scss │ │ │ │ ├── login.component.spec.ts │ │ │ │ └── login.component.ts │ │ │ └── logout │ │ │ │ ├── logout.component.html │ │ │ │ ├── logout.component.scss │ │ │ │ ├── logout.component.spec.ts │ │ │ │ └── logout.component.ts │ │ ├── app │ │ │ ├── app-routing.module.ts │ │ │ ├── app.component.html │ │ │ ├── app.component.ts │ │ │ ├── app.module.ts │ │ │ ├── app.server.module.ts │ │ │ ├── counter │ │ │ │ ├── counter.component.html │ │ │ │ ├── counter.component.spec.ts │ │ │ │ └── counter.component.ts │ │ │ ├── fetch-data │ │ │ │ ├── fetch-data.component.html │ │ │ │ └── fetch-data.component.ts │ │ │ ├── home │ │ │ │ ├── home.component.html │ │ │ │ └── home.component.ts │ │ │ ├── nav-menu │ │ │ │ ├── dev-env.guard.ts │ │ │ │ ├── nav-menu.component.html │ │ │ │ ├── nav-menu.component.scss │ │ │ │ └── nav-menu.component.ts │ │ │ ├── todo │ │ │ │ ├── todo.component.html │ │ │ │ ├── todo.component.scss │ │ │ │ └── todo.component.ts │ │ │ ├── token │ │ │ │ ├── token.component.html │ │ │ │ └── token.component.ts │ │ │ └── web-api-client.ts │ │ ├── assets │ │ │ └── .gitkeep │ │ ├── environments │ │ │ ├── environment.prod.ts │ │ │ └── environment.ts │ │ ├── index.html │ │ ├── karma.conf.js │ │ ├── main.ts │ │ ├── polyfills.ts │ │ ├── styles.scss │ │ ├── test.ts │ │ ├── tsconfig.app.json │ │ ├── tsconfig.server.json │ │ ├── tsconfig.spec.json │ │ └── tslint.json │ ├── tsconfig.json │ └── tslint.json │ ├── Controllers │ ├── ApiControllerBase.cs │ ├── OidcConfigurationController.cs │ ├── TodoItemsController.cs │ ├── TodoListsController.cs │ └── WeatherForecastController.cs │ ├── Dockerfile │ ├── Filters │ └── ApiExceptionFilterAttribute.cs │ ├── Pages │ ├── Error.cshtml │ ├── Error.cshtml.cs │ ├── Shared │ │ └── _LoginPartial.cshtml │ └── _ViewImports.cshtml │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Services │ └── CurrentUserService.cs │ ├── Startup.cs │ ├── WebUI.csproj │ ├── appsettings.Development.json │ ├── appsettings.Production.json │ ├── appsettings.json │ ├── nswag.json │ └── wwwroot │ ├── api │ └── specification.json │ └── favicon.ico └── tests ├── Application.IntegrationTests ├── Application.IntegrationTests.csproj ├── TestBase.cs ├── Testing.cs ├── TodoItems │ └── Commands │ │ ├── CreateTodoItemTests.cs │ │ ├── DeleteTodoItemTests.cs │ │ ├── UpdateTodoItemDetailTests.cs │ │ └── UpdateTodoItemTests.cs ├── TodoLists │ ├── Commands │ │ ├── CreateTodoListTests.cs │ │ ├── DeleteTodoListTests.cs │ │ ├── PurgeTodoListsTests.cs │ │ └── UpdateTodoListTests.cs │ └── Queries │ │ └── GetTodosTests.cs └── appsettings.json ├── Application.UnitTests ├── Application.UnitTests.csproj └── Common │ ├── Behaviours │ └── RequestLoggerTests.cs │ ├── Exceptions │ └── ValidationExceptionTests.cs │ └── Mappings │ └── MappingTests.cs └── Domain.UnitTests ├── Domain.UnitTests.csproj └── ValueObjects └── ColourTests.cs /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 🐛 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Additional context** 27 | Add any other context about the problem here. 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: true 2 | contact_links: 3 | - name: Ask a question ❓ 4 | url: https://github.com/jasontaylordev/cleanarchitecture/discussions/new 5 | about: Ask a question or request support for using the template -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request ✨ 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/CleanArchitecture/35b490110f699c2ba427fd6b49e98babc16390c0/.github/icon.png -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ main ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ main ] 20 | schedule: 21 | - cron: '24 3 * * 1' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'csharp', 'javascript' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://git.io/codeql-language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v2 42 | 43 | # Initializes the CodeQL tools for scanning. 44 | - name: Initialize CodeQL 45 | uses: github/codeql-action/init@v1 46 | with: 47 | languages: ${{ matrix.language }} 48 | # If you wish to specify custom queries, you can do so here or in a config file. 49 | # By default, queries listed here will override any specified in a config file. 50 | # Prefix the list here with "+" to use these queries and those in the config file. 51 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 52 | 53 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 54 | # If this step fails, then you should remove it and run the build manually (see below) 55 | - name: Autobuild 56 | uses: github/codeql-action/autobuild@v1 57 | 58 | # ℹ️ Command-line programs to run using the OS shell. 59 | # 📚 https://git.io/JvXDl 60 | 61 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 62 | # and modify them (or add more) to build your code if your project 63 | # uses a compiled language 64 | 65 | #- run: | 66 | # make bootstrap 67 | # make release 68 | 69 | - name: Perform CodeQL Analysis 70 | uses: github/codeql-action/analyze@v1 71 | -------------------------------------------------------------------------------- /.github/workflows/dotnetcore.yml: -------------------------------------------------------------------------------- 1 | name: .NET 2 | on: 3 | push: 4 | branches: [ main ] 5 | pull_request: 6 | branches: [ main ] 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Setup .NET 14 | uses: actions/setup-dotnet@v1 15 | - name: Install dotnet ef 16 | run: dotnet tool install --global dotnet-ef 17 | - name: Build with dotnet 18 | run: dotnet build --configuration Release CleanArchitecture.sln 19 | 20 | test: 21 | runs-on: ubuntu-latest 22 | services: 23 | sql: 24 | image: mcr.microsoft.com/mssql/server 25 | ports: 26 | - 1433:1433 27 | env: 28 | SA_PASSWORD: Your_password123 29 | ACCEPT_EULA: Y 30 | steps: 31 | - uses: actions/checkout@v2 32 | - name: Setup .NET 33 | uses: actions/setup-dotnet@v1 34 | - name: run tests 35 | run: dotnet test CleanArchitecture.sln --configuration Release 36 | env: 37 | ConnectionStrings__DefaultConnection: Server=.;Database=CleanArchitectureTestDb;User=sa;Password=Your_password123;MultipleActiveResultSets=true -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | build/ 21 | bld/ 22 | bin/ 23 | Bin/ 24 | obj/ 25 | Obj/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | 30 | # Jetbrains Rider cache/options directory 31 | .idea/ 32 | 33 | # MSTest test Results 34 | [Tt]est[Rr]esult*/ 35 | [Bb]uild[Ll]og.* 36 | 37 | # NUNIT 38 | *.VisualState.xml 39 | TestResult.xml 40 | 41 | # Build Results of an ATL Project 42 | [Dd]ebugPS/ 43 | [Rr]eleasePS/ 44 | dlldata.c 45 | 46 | *_i.c 47 | *_p.c 48 | *_i.h 49 | *.ilk 50 | *.meta 51 | *.obj 52 | *.pch 53 | *.pdb 54 | *.pgc 55 | *.pgd 56 | *.rsp 57 | *.sbr 58 | *.tlb 59 | *.tli 60 | *.tlh 61 | *.tmp 62 | *.tmp_proj 63 | *.log 64 | *.vspscc 65 | *.vssscc 66 | .builds 67 | *.pidb 68 | *.svclog 69 | *.scc 70 | 71 | # Chutzpah Test files 72 | _Chutzpah* 73 | 74 | # Visual C++ cache files 75 | ipch/ 76 | *.aps 77 | *.ncb 78 | *.opendb 79 | *.opensdf 80 | *.sdf 81 | *.cachefile 82 | 83 | # Visual Studio profiler 84 | *.psess 85 | *.vsp 86 | *.vspx 87 | *.sap 88 | 89 | # TFS 2012 Local Workspace 90 | $tf/ 91 | 92 | # Guidance Automation Toolkit 93 | *.gpState 94 | 95 | # ReSharper is a .NET coding add-in 96 | _ReSharper*/ 97 | *.[Rr]e[Ss]harper 98 | *.DotSettings.user 99 | 100 | # JustCode is a .NET coding add-in 101 | .JustCode 102 | 103 | # TeamCity is a build add-in 104 | _TeamCity* 105 | 106 | # DotCover is a Code Coverage Tool 107 | *.dotCover 108 | 109 | # NCrunch 110 | _NCrunch_* 111 | .*crunch*.local.xml 112 | nCrunchTemp_* 113 | 114 | # MightyMoose 115 | *.mm.* 116 | AutoTest.Net/ 117 | 118 | # Web workbench (sass) 119 | .sass-cache/ 120 | 121 | # Installshield output folder 122 | [Ee]xpress/ 123 | 124 | # DocProject is a documentation generator add-in 125 | DocProject/buildhelp/ 126 | DocProject/Help/*.HxT 127 | DocProject/Help/*.HxC 128 | DocProject/Help/*.hhc 129 | DocProject/Help/*.hhk 130 | DocProject/Help/*.hhp 131 | DocProject/Help/Html2 132 | DocProject/Help/html 133 | 134 | # Click-Once directory 135 | publish/ 136 | 137 | # Publish Web Output 138 | *.[Pp]ublish.xml 139 | *.azurePubxml 140 | # TODO: Comment the next line if you want to checkin your web deploy settings 141 | # but database connection strings (with potential passwords) will be unencrypted 142 | *.pubxml 143 | *.publishproj 144 | 145 | # NuGet Packages 146 | *.nupkg 147 | # The packages folder can be ignored because of Package Restore 148 | **/packages/* 149 | # except build/, which is used as an MSBuild target. 150 | !**/packages/build/ 151 | # Uncomment if necessary however generally it will be regenerated when needed 152 | #!**/packages/repositories.config 153 | 154 | # Microsoft Azure Build Output 155 | csx/ 156 | *.build.csdef 157 | 158 | # Microsoft Azure Emulator 159 | ecf/ 160 | rcf/ 161 | 162 | # Microsoft Azure ApplicationInsights config file 163 | ApplicationInsights.config 164 | 165 | # Windows Store app package directory 166 | AppPackages/ 167 | BundleArtifacts/ 168 | 169 | # Visual Studio cache files 170 | # files ending in .cache can be ignored 171 | *.[Cc]ache 172 | # but keep track of directories ending in .cache 173 | !*.[Cc]ache/ 174 | 175 | # Others 176 | ClientBin/ 177 | ~$* 178 | *~ 179 | *.dbmdl 180 | *.dbproj.schemaview 181 | *.pfx 182 | *.publishsettings 183 | orleans.codegen.cs 184 | 185 | /node_modules 186 | 187 | # RIA/Silverlight projects 188 | Generated_Code/ 189 | 190 | # Backup & report files from converting an old project file 191 | # to a newer Visual Studio version. Backup files are not needed, 192 | # because we have git ;-) 193 | _UpgradeReport_Files/ 194 | Backup*/ 195 | UpgradeLog*.XML 196 | UpgradeLog*.htm 197 | 198 | # SQL Server files 199 | *.mdf 200 | *.ldf 201 | 202 | # Business Intelligence projects 203 | *.rdl.data 204 | *.bim.layout 205 | *.bim_*.settings 206 | 207 | # Microsoft Fakes 208 | FakesAssemblies/ 209 | 210 | # GhostDoc plugin setting file 211 | *.GhostDoc.xml 212 | 213 | # Node.js Tools for Visual Studio 214 | .ntvs_analysis.dat 215 | 216 | # Visual Studio 6 build log 217 | *.plg 218 | 219 | # Visual Studio 6 workspace options file 220 | *.opt 221 | 222 | # Visual Studio LightSwitch build output 223 | **/*.HTMLClient/GeneratedArtifacts 224 | **/*.DesktopClient/GeneratedArtifacts 225 | **/*.DesktopClient/ModelManifest.xml 226 | **/*.Server/GeneratedArtifacts 227 | **/*.Server/ModelManifest.xml 228 | _Pvt_Extensions 229 | 230 | # Paket dependency manager 231 | .paket/paket.exe 232 | 233 | # FAKE - F# Make 234 | .fake/ 235 | /NDependOut 236 | /CleanArchitecture.ndproj 237 | /.mfractor 238 | src/WebUI/ClientApp/package-lock.json 239 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at cleanarchitecture@outlook.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Jason Taylor 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /docker-compose.dcproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 2.1 5 | Linux 6 | 6bd2ec46-fa8f-44f3-af33-903bbb347116 7 | LaunchBrowser 8 | {Scheme}://localhost:{ServicePort} 9 | webui 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /docker-compose.override.yml: -------------------------------------------------------------------------------- 1 | version: '3.4' 2 | 3 | services: 4 | webui: 5 | environment: 6 | - "ASPNETCORE_ENVIRONMENT=Development" 7 | - "SpaBaseUrl=http://clientapp:4200" 8 | 9 | clientapp: 10 | image: ${DOCKER_REGISTRY-}clientapp 11 | build: 12 | context: src/WebUI/ClientApp 13 | dockerfile: Dockerfile 14 | depends_on: 15 | - webui 16 | restart: on-failure 17 | 18 | db: 19 | ports: 20 | - "1433:1433" -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.4' 2 | 3 | services: 4 | webui: 5 | image: ${DOCKER_REGISTRY-}webui 6 | build: 7 | context: . 8 | dockerfile: src/WebUI/Dockerfile 9 | environment: 10 | - "UseInMemoryDatabase=false" 11 | - "ConnectionStrings__DefaultConnection=Server=db;Database=CleanArchitectureDb;User=sa;Password=Your_password123;MultipleActiveResultSets=true" 12 | - "IdentityServer__Key__Type=Development" 13 | - "ASPNETCORE_Kestrel__Certificates__Default__Password=Your_password123" 14 | - "ASPNETCORE_Kestrel__Certificates__Default__Path=/https/aspnetapp.pfx" 15 | volumes: 16 | - ~/.aspnet/https:/https:ro 17 | ports: 18 | - "5000:5000" 19 | - "5001:5001" 20 | depends_on: 21 | - db 22 | restart: on-failure 23 | 24 | db: 25 | image: "mcr.microsoft.com/mssql/server" 26 | environment: 27 | - "SA_PASSWORD=Your_password123" 28 | - "ACCEPT_EULA=Y" -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "6.0.100", 4 | "rollForward": "latestMajor" 5 | } 6 | } -------------------------------------------------------------------------------- /src/Application/Application.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | CleanArchitecture.Application 6 | CleanArchitecture.Application 7 | enable 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/Application/Common/Behaviours/AuthorizationBehaviour.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using CleanArchitecture.Application.Common.Exceptions; 3 | using CleanArchitecture.Application.Common.Interfaces; 4 | using CleanArchitecture.Application.Common.Security; 5 | using MediatR; 6 | 7 | namespace CleanArchitecture.Application.Common.Behaviours; 8 | 9 | public class AuthorizationBehaviour : IPipelineBehavior where TRequest : notnull 10 | { 11 | private readonly ICurrentUserService _currentUserService; 12 | private readonly IIdentityService _identityService; 13 | 14 | public AuthorizationBehaviour( 15 | ICurrentUserService currentUserService, 16 | IIdentityService identityService) 17 | { 18 | _currentUserService = currentUserService; 19 | _identityService = identityService; 20 | } 21 | 22 | public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) 23 | { 24 | var authorizeAttributes = request.GetType().GetCustomAttributes(); 25 | 26 | if (authorizeAttributes.Any()) 27 | { 28 | // Must be authenticated user 29 | if (_currentUserService.UserId == null) 30 | { 31 | throw new UnauthorizedAccessException(); 32 | } 33 | 34 | // Role-based authorization 35 | var authorizeAttributesWithRoles = authorizeAttributes.Where(a => !string.IsNullOrWhiteSpace(a.Roles)); 36 | 37 | if (authorizeAttributesWithRoles.Any()) 38 | { 39 | var authorized = false; 40 | 41 | foreach (var roles in authorizeAttributesWithRoles.Select(a => a.Roles.Split(','))) 42 | { 43 | foreach (var role in roles) 44 | { 45 | var isInRole = await _identityService.IsInRoleAsync(_currentUserService.UserId, role.Trim()); 46 | if (isInRole) 47 | { 48 | authorized = true; 49 | break; 50 | } 51 | } 52 | } 53 | 54 | // Must be a member of at least one role in roles 55 | if (!authorized) 56 | { 57 | throw new ForbiddenAccessException(); 58 | } 59 | } 60 | 61 | // Policy-based authorization 62 | var authorizeAttributesWithPolicies = authorizeAttributes.Where(a => !string.IsNullOrWhiteSpace(a.Policy)); 63 | if (authorizeAttributesWithPolicies.Any()) 64 | { 65 | foreach (var policy in authorizeAttributesWithPolicies.Select(a => a.Policy)) 66 | { 67 | var authorized = await _identityService.AuthorizeAsync(_currentUserService.UserId, policy); 68 | 69 | if (!authorized) 70 | { 71 | throw new ForbiddenAccessException(); 72 | } 73 | } 74 | } 75 | } 76 | 77 | // User is authorized / authorization not required 78 | return await next(); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/Application/Common/Behaviours/LoggingBehaviour.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Interfaces; 2 | using MediatR.Pipeline; 3 | using Microsoft.Extensions.Logging; 4 | 5 | namespace CleanArchitecture.Application.Common.Behaviours; 6 | 7 | public class LoggingBehaviour : IRequestPreProcessor where TRequest : notnull 8 | { 9 | private readonly ILogger _logger; 10 | private readonly ICurrentUserService _currentUserService; 11 | private readonly IIdentityService _identityService; 12 | 13 | public LoggingBehaviour(ILogger logger, ICurrentUserService currentUserService, IIdentityService identityService) 14 | { 15 | _logger = logger; 16 | _currentUserService = currentUserService; 17 | _identityService = identityService; 18 | } 19 | 20 | public async Task Process(TRequest request, CancellationToken cancellationToken) 21 | { 22 | var requestName = typeof(TRequest).Name; 23 | var userId = _currentUserService.UserId ?? string.Empty; 24 | string userName = string.Empty; 25 | 26 | if (!string.IsNullOrEmpty(userId)) 27 | { 28 | userName = await _identityService.GetUserNameAsync(userId); 29 | } 30 | 31 | _logger.LogInformation("CleanArchitecture Request: {Name} {@UserId} {@UserName} {@Request}", 32 | requestName, userId, userName, request); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Application/Common/Behaviours/PerformanceBehaviour.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using CleanArchitecture.Application.Common.Interfaces; 3 | using MediatR; 4 | using Microsoft.Extensions.Logging; 5 | 6 | namespace CleanArchitecture.Application.Common.Behaviours; 7 | 8 | public class PerformanceBehaviour : IPipelineBehavior where TRequest : notnull 9 | { 10 | private readonly Stopwatch _timer; 11 | private readonly ILogger _logger; 12 | private readonly ICurrentUserService _currentUserService; 13 | private readonly IIdentityService _identityService; 14 | 15 | public PerformanceBehaviour( 16 | ILogger logger, 17 | ICurrentUserService currentUserService, 18 | IIdentityService identityService) 19 | { 20 | _timer = new Stopwatch(); 21 | 22 | _logger = logger; 23 | _currentUserService = currentUserService; 24 | _identityService = identityService; 25 | } 26 | 27 | public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) 28 | { 29 | _timer.Start(); 30 | 31 | var response = await next(); 32 | 33 | _timer.Stop(); 34 | 35 | var elapsedMilliseconds = _timer.ElapsedMilliseconds; 36 | 37 | if (elapsedMilliseconds > 500) 38 | { 39 | var requestName = typeof(TRequest).Name; 40 | var userId = _currentUserService.UserId ?? string.Empty; 41 | var userName = string.Empty; 42 | 43 | if (!string.IsNullOrEmpty(userId)) 44 | { 45 | userName = await _identityService.GetUserNameAsync(userId); 46 | } 47 | 48 | _logger.LogWarning("CleanArchitecture Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@UserName} {@Request}", 49 | requestName, elapsedMilliseconds, userId, userName, request); 50 | } 51 | 52 | return response; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Application/Common/Behaviours/UnhandledExceptionBehaviour.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Microsoft.Extensions.Logging; 3 | 4 | namespace CleanArchitecture.Application.Common.Behaviours; 5 | 6 | public class UnhandledExceptionBehaviour : IPipelineBehavior where TRequest : notnull 7 | { 8 | private readonly ILogger _logger; 9 | 10 | public UnhandledExceptionBehaviour(ILogger logger) 11 | { 12 | _logger = logger; 13 | } 14 | 15 | public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) 16 | { 17 | try 18 | { 19 | return await next(); 20 | } 21 | catch (Exception ex) 22 | { 23 | var requestName = typeof(TRequest).Name; 24 | 25 | _logger.LogError(ex, "CleanArchitecture Request: Unhandled Exception for Request {Name} {@Request}", requestName, request); 26 | 27 | throw; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Application/Common/Behaviours/ValidationBehaviour.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using MediatR; 3 | using ValidationException = CleanArchitecture.Application.Common.Exceptions.ValidationException; 4 | 5 | namespace CleanArchitecture.Application.Common.Behaviours; 6 | 7 | public class ValidationBehaviour : IPipelineBehavior 8 | where TRequest : notnull 9 | { 10 | private readonly IEnumerable> _validators; 11 | 12 | public ValidationBehaviour(IEnumerable> validators) 13 | { 14 | _validators = validators; 15 | } 16 | 17 | public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) 18 | { 19 | if (_validators.Any()) 20 | { 21 | var context = new ValidationContext(request); 22 | 23 | var validationResults = await Task.WhenAll( 24 | _validators.Select(v => 25 | v.ValidateAsync(context, cancellationToken))); 26 | 27 | var failures = validationResults 28 | .Where(r => r.Errors.Any()) 29 | .SelectMany(r => r.Errors) 30 | .ToList(); 31 | 32 | if (failures.Any()) 33 | throw new ValidationException(failures); 34 | } 35 | return await next(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Application/Common/Exceptions/ForbiddenAccessException.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Application.Common.Exceptions; 2 | 3 | public class ForbiddenAccessException : Exception 4 | { 5 | public ForbiddenAccessException() : base() { } 6 | } 7 | -------------------------------------------------------------------------------- /src/Application/Common/Exceptions/NotFoundException.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Application.Common.Exceptions; 2 | 3 | public class NotFoundException : Exception 4 | { 5 | public NotFoundException() 6 | : base() 7 | { 8 | } 9 | 10 | public NotFoundException(string message) 11 | : base(message) 12 | { 13 | } 14 | 15 | public NotFoundException(string message, Exception innerException) 16 | : base(message, innerException) 17 | { 18 | } 19 | 20 | public NotFoundException(string name, object key) 21 | : base($"Entity \"{name}\" ({key}) was not found.") 22 | { 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Application/Common/Exceptions/ValidationException.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation.Results; 2 | 3 | namespace CleanArchitecture.Application.Common.Exceptions; 4 | 5 | public class ValidationException : Exception 6 | { 7 | public ValidationException() 8 | : base("One or more validation failures have occurred.") 9 | { 10 | Errors = new Dictionary(); 11 | } 12 | 13 | public ValidationException(IEnumerable failures) 14 | : this() 15 | { 16 | Errors = failures 17 | .GroupBy(e => e.PropertyName, e => e.ErrorMessage) 18 | .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray()); 19 | } 20 | 21 | public IDictionary Errors { get; } 22 | } 23 | -------------------------------------------------------------------------------- /src/Application/Common/Interfaces/IApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Domain.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace CleanArchitecture.Application.Common.Interfaces; 5 | 6 | public interface IApplicationDbContext 7 | { 8 | DbSet TodoLists { get; } 9 | 10 | DbSet TodoItems { get; } 11 | 12 | Task SaveChangesAsync(CancellationToken cancellationToken); 13 | } 14 | -------------------------------------------------------------------------------- /src/Application/Common/Interfaces/ICsvFileBuilder.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.TodoLists.Queries.ExportTodos; 2 | 3 | namespace CleanArchitecture.Application.Common.Interfaces; 4 | 5 | public interface ICsvFileBuilder 6 | { 7 | byte[] BuildTodoItemsFile(IEnumerable records); 8 | } 9 | -------------------------------------------------------------------------------- /src/Application/Common/Interfaces/ICurrentUserService.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Application.Common.Interfaces; 2 | 3 | public interface ICurrentUserService 4 | { 5 | string? UserId { get; } 6 | } 7 | -------------------------------------------------------------------------------- /src/Application/Common/Interfaces/IDateTime.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Application.Common.Interfaces; 2 | 3 | public interface IDateTime 4 | { 5 | DateTime Now { get; } 6 | } 7 | -------------------------------------------------------------------------------- /src/Application/Common/Interfaces/IDomainEventService.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Domain.Common; 2 | 3 | namespace CleanArchitecture.Application.Common.Interfaces; 4 | 5 | public interface IDomainEventService 6 | { 7 | Task Publish(DomainEvent domainEvent); 8 | } 9 | -------------------------------------------------------------------------------- /src/Application/Common/Interfaces/IIdentityService.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Models; 2 | 3 | namespace CleanArchitecture.Application.Common.Interfaces; 4 | 5 | public interface IIdentityService 6 | { 7 | Task GetUserNameAsync(string userId); 8 | 9 | Task IsInRoleAsync(string userId, string role); 10 | 11 | Task AuthorizeAsync(string userId, string policyName); 12 | 13 | Task<(Result Result, string UserId)> CreateUserAsync(string userName, string password); 14 | 15 | Task DeleteUserAsync(string userId); 16 | } 17 | -------------------------------------------------------------------------------- /src/Application/Common/Mappings/IMapFrom.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace CleanArchitecture.Application.Common.Mappings; 4 | 5 | public interface IMapFrom 6 | { 7 | void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType()); 8 | } 9 | -------------------------------------------------------------------------------- /src/Application/Common/Mappings/MappingExtensions.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using AutoMapper.QueryableExtensions; 3 | using CleanArchitecture.Application.Common.Models; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace CleanArchitecture.Application.Common.Mappings; 7 | 8 | public static class MappingExtensions 9 | { 10 | public static Task> PaginatedListAsync(this IQueryable queryable, int pageNumber, int pageSize) 11 | => PaginatedList.CreateAsync(queryable, pageNumber, pageSize); 12 | 13 | public static Task> ProjectToListAsync(this IQueryable queryable, IConfigurationProvider configuration) 14 | => queryable.ProjectTo(configuration).ToListAsync(); 15 | } 16 | -------------------------------------------------------------------------------- /src/Application/Common/Mappings/MappingProfile.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using AutoMapper; 3 | 4 | namespace CleanArchitecture.Application.Common.Mappings; 5 | 6 | public class MappingProfile : Profile 7 | { 8 | public MappingProfile() 9 | { 10 | ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly()); 11 | } 12 | 13 | private void ApplyMappingsFromAssembly(Assembly assembly) 14 | { 15 | var types = assembly.GetExportedTypes() 16 | .Where(t => t.GetInterfaces().Any(i => 17 | i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>))) 18 | .ToList(); 19 | 20 | foreach (var type in types) 21 | { 22 | var instance = Activator.CreateInstance(type); 23 | 24 | var methodInfo = type.GetMethod("Mapping") 25 | ?? type.GetInterface("IMapFrom`1")!.GetMethod("Mapping"); 26 | 27 | methodInfo?.Invoke(instance, new object[] { this }); 28 | 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Application/Common/Models/DomainEventNotification.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Domain.Common; 2 | using MediatR; 3 | 4 | namespace CleanArchitecture.Application.Common.Models; 5 | 6 | public class DomainEventNotification : INotification where TDomainEvent : DomainEvent 7 | { 8 | public DomainEventNotification(TDomainEvent domainEvent) 9 | { 10 | DomainEvent = domainEvent; 11 | } 12 | 13 | public TDomainEvent DomainEvent { get; } 14 | } 15 | -------------------------------------------------------------------------------- /src/Application/Common/Models/PaginatedList.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace CleanArchitecture.Application.Common.Models; 4 | 5 | public class PaginatedList 6 | { 7 | public List Items { get; } 8 | public int PageNumber { get; } 9 | public int TotalPages { get; } 10 | public int TotalCount { get; } 11 | 12 | public PaginatedList(List items, int count, int pageNumber, int pageSize) 13 | { 14 | PageNumber = pageNumber; 15 | TotalPages = (int)Math.Ceiling(count / (double)pageSize); 16 | TotalCount = count; 17 | Items = items; 18 | } 19 | 20 | public bool HasPreviousPage => PageNumber > 1; 21 | 22 | public bool HasNextPage => PageNumber < TotalPages; 23 | 24 | public static async Task> CreateAsync(IQueryable source, int pageNumber, int pageSize) 25 | { 26 | var count = await source.CountAsync(); 27 | var items = await source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync(); 28 | 29 | return new PaginatedList(items, count, pageNumber, pageSize); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Application/Common/Models/Result.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Application.Common.Models; 2 | 3 | public class Result 4 | { 5 | internal Result(bool succeeded, IEnumerable errors) 6 | { 7 | Succeeded = succeeded; 8 | Errors = errors.ToArray(); 9 | } 10 | 11 | public bool Succeeded { get; set; } 12 | 13 | public string[] Errors { get; set; } 14 | 15 | public static Result Success() 16 | { 17 | return new Result(true, Array.Empty()); 18 | } 19 | 20 | public static Result Failure(IEnumerable errors) 21 | { 22 | return new Result(false, errors); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Application/Common/Security/AuthorizeAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Application.Common.Security; 2 | 3 | /// 4 | /// Specifies the class this attribute is applied to requires authorization. 5 | /// 6 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 7 | public class AuthorizeAttribute : Attribute 8 | { 9 | /// 10 | /// Initializes a new instance of the class. 11 | /// 12 | public AuthorizeAttribute() { } 13 | 14 | /// 15 | /// Gets or sets a comma delimited list of roles that are allowed to access the resource. 16 | /// 17 | public string Roles { get; set; } = string.Empty; 18 | 19 | /// 20 | /// Gets or sets the policy name that determines access to the resource. 21 | /// 22 | public string Policy { get; set; } = string.Empty; 23 | } 24 | -------------------------------------------------------------------------------- /src/Application/DependencyInjection.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using CleanArchitecture.Application.Common.Behaviours; 3 | using FluentValidation; 4 | using MediatR; 5 | using Microsoft.Extensions.DependencyInjection; 6 | 7 | namespace CleanArchitecture.Application; 8 | 9 | public static class DependencyInjection 10 | { 11 | public static IServiceCollection AddApplication(this IServiceCollection services) 12 | { 13 | services.AddAutoMapper(Assembly.GetExecutingAssembly()); 14 | services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); 15 | services.AddMediatR(Assembly.GetExecutingAssembly()); 16 | services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehaviour<,>)); 17 | services.AddTransient(typeof(IPipelineBehavior<,>), typeof(AuthorizationBehaviour<,>)); 18 | services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>)); 19 | services.AddTransient(typeof(IPipelineBehavior<,>), typeof(PerformanceBehaviour<,>)); 20 | 21 | return services; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Application/TodoItems/Commands/CreateTodoItem/CreateTodoItemCommand.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Interfaces; 2 | using CleanArchitecture.Domain.Entities; 3 | using CleanArchitecture.Domain.Events; 4 | using MediatR; 5 | 6 | namespace CleanArchitecture.Application.TodoItems.Commands.CreateTodoItem; 7 | 8 | public class CreateTodoItemCommand : IRequest 9 | { 10 | public int ListId { get; set; } 11 | 12 | public string? Title { get; set; } 13 | } 14 | 15 | public class CreateTodoItemCommandHandler : IRequestHandler 16 | { 17 | private readonly IApplicationDbContext _context; 18 | 19 | public CreateTodoItemCommandHandler(IApplicationDbContext context) 20 | { 21 | _context = context; 22 | } 23 | 24 | public async Task Handle(CreateTodoItemCommand request, CancellationToken cancellationToken) 25 | { 26 | var entity = new TodoItem 27 | { 28 | ListId = request.ListId, 29 | Title = request.Title, 30 | Done = false 31 | }; 32 | 33 | entity.DomainEvents.Add(new TodoItemCreatedEvent(entity)); 34 | 35 | _context.TodoItems.Add(entity); 36 | 37 | await _context.SaveChangesAsync(cancellationToken); 38 | 39 | return entity.Id; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Application/TodoItems/Commands/CreateTodoItem/CreateTodoItemCommandValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | 3 | namespace CleanArchitecture.Application.TodoItems.Commands.CreateTodoItem; 4 | 5 | public class CreateTodoItemCommandValidator : AbstractValidator 6 | { 7 | public CreateTodoItemCommandValidator() 8 | { 9 | RuleFor(v => v.Title) 10 | .MaximumLength(200) 11 | .NotEmpty(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Application/TodoItems/Commands/DeleteTodoItem/DeleteTodoItemCommand.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.Common.Interfaces; 3 | using CleanArchitecture.Domain.Entities; 4 | using CleanArchitecture.Domain.Events; 5 | using MediatR; 6 | 7 | namespace CleanArchitecture.Application.TodoItems.Commands.DeleteTodoItem; 8 | 9 | public class DeleteTodoItemCommand : IRequest 10 | { 11 | public int Id { get; set; } 12 | } 13 | 14 | public class DeleteTodoItemCommandHandler : IRequestHandler 15 | { 16 | private readonly IApplicationDbContext _context; 17 | 18 | public DeleteTodoItemCommandHandler(IApplicationDbContext context) 19 | { 20 | _context = context; 21 | } 22 | 23 | public async Task Handle(DeleteTodoItemCommand request, CancellationToken cancellationToken) 24 | { 25 | var entity = await _context.TodoItems 26 | .FindAsync(new object[] { request.Id }, cancellationToken); 27 | 28 | if (entity == null) 29 | { 30 | throw new NotFoundException(nameof(TodoItem), request.Id); 31 | } 32 | 33 | _context.TodoItems.Remove(entity); 34 | 35 | entity.DomainEvents.Add(new TodoItemDeletedEvent(entity)); 36 | 37 | await _context.SaveChangesAsync(cancellationToken); 38 | 39 | return Unit.Value; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Application/TodoItems/Commands/UpdateTodoItem/UpdateTodoItemCommand.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.Common.Interfaces; 3 | using CleanArchitecture.Domain.Entities; 4 | using MediatR; 5 | 6 | namespace CleanArchitecture.Application.TodoItems.Commands.UpdateTodoItem; 7 | 8 | public class UpdateTodoItemCommand : IRequest 9 | { 10 | public int Id { get; set; } 11 | 12 | public string? Title { get; set; } 13 | 14 | public bool Done { get; set; } 15 | } 16 | 17 | public class UpdateTodoItemCommandHandler : IRequestHandler 18 | { 19 | private readonly IApplicationDbContext _context; 20 | 21 | public UpdateTodoItemCommandHandler(IApplicationDbContext context) 22 | { 23 | _context = context; 24 | } 25 | 26 | public async Task Handle(UpdateTodoItemCommand request, CancellationToken cancellationToken) 27 | { 28 | var entity = await _context.TodoItems 29 | .FindAsync(new object[] { request.Id }, cancellationToken); 30 | 31 | if (entity == null) 32 | { 33 | throw new NotFoundException(nameof(TodoItem), request.Id); 34 | } 35 | 36 | entity.Title = request.Title; 37 | entity.Done = request.Done; 38 | 39 | await _context.SaveChangesAsync(cancellationToken); 40 | 41 | return Unit.Value; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Application/TodoItems/Commands/UpdateTodoItem/UpdateTodoItemCommandValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | 3 | namespace CleanArchitecture.Application.TodoItems.Commands.UpdateTodoItem; 4 | 5 | public class UpdateTodoItemCommandValidator : AbstractValidator 6 | { 7 | public UpdateTodoItemCommandValidator() 8 | { 9 | RuleFor(v => v.Title) 10 | .MaximumLength(200) 11 | .NotEmpty(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Application/TodoItems/Commands/UpdateTodoItemDetail/UpdateTodoItemDetailCommand.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.Common.Interfaces; 3 | using CleanArchitecture.Domain.Entities; 4 | using CleanArchitecture.Domain.Enums; 5 | using MediatR; 6 | 7 | namespace CleanArchitecture.Application.TodoItems.Commands.UpdateTodoItemDetail; 8 | 9 | public class UpdateTodoItemDetailCommand : IRequest 10 | { 11 | public int Id { get; set; } 12 | 13 | public int ListId { get; set; } 14 | 15 | public PriorityLevel Priority { get; set; } 16 | 17 | public string? Note { get; set; } 18 | } 19 | 20 | public class UpdateTodoItemDetailCommandHandler : IRequestHandler 21 | { 22 | private readonly IApplicationDbContext _context; 23 | 24 | public UpdateTodoItemDetailCommandHandler(IApplicationDbContext context) 25 | { 26 | _context = context; 27 | } 28 | 29 | public async Task Handle(UpdateTodoItemDetailCommand request, CancellationToken cancellationToken) 30 | { 31 | var entity = await _context.TodoItems 32 | .FindAsync(new object[] { request.Id }, cancellationToken); 33 | 34 | if (entity == null) 35 | { 36 | throw new NotFoundException(nameof(TodoItem), request.Id); 37 | } 38 | 39 | entity.ListId = request.ListId; 40 | entity.Priority = request.Priority; 41 | entity.Note = request.Note; 42 | 43 | await _context.SaveChangesAsync(cancellationToken); 44 | 45 | return Unit.Value; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Application/TodoItems/EventHandlers/TodoItemCompletedEventHandler.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Models; 2 | using CleanArchitecture.Domain.Events; 3 | using MediatR; 4 | using Microsoft.Extensions.Logging; 5 | 6 | namespace CleanArchitecture.Application.TodoItems.EventHandlers; 7 | 8 | public class TodoItemCompletedEventHandler : INotificationHandler> 9 | { 10 | private readonly ILogger _logger; 11 | 12 | public TodoItemCompletedEventHandler(ILogger logger) 13 | { 14 | _logger = logger; 15 | } 16 | 17 | public Task Handle(DomainEventNotification notification, CancellationToken cancellationToken) 18 | { 19 | var domainEvent = notification.DomainEvent; 20 | 21 | _logger.LogInformation("CleanArchitecture Domain Event: {DomainEvent}", domainEvent.GetType().Name); 22 | 23 | return Task.CompletedTask; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Application/TodoItems/EventHandlers/TodoItemCreatedEventHandler.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Models; 2 | using CleanArchitecture.Domain.Events; 3 | using MediatR; 4 | using Microsoft.Extensions.Logging; 5 | 6 | namespace CleanArchitecture.Application.TodoItems.EventHandlers; 7 | 8 | public class TodoItemCreatedEventHandler : INotificationHandler> 9 | { 10 | private readonly ILogger _logger; 11 | 12 | public TodoItemCreatedEventHandler(ILogger logger) 13 | { 14 | _logger = logger; 15 | } 16 | 17 | public Task Handle(DomainEventNotification notification, CancellationToken cancellationToken) 18 | { 19 | var domainEvent = notification.DomainEvent; 20 | 21 | _logger.LogInformation("CleanArchitecture Domain Event: {DomainEvent}", domainEvent.GetType().Name); 22 | 23 | return Task.CompletedTask; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Application/TodoItems/Queries/GetTodoItemsWithPagination/GetTodoItemsWithPaginationQuery.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using AutoMapper.QueryableExtensions; 3 | using CleanArchitecture.Application.Common.Interfaces; 4 | using CleanArchitecture.Application.Common.Mappings; 5 | using CleanArchitecture.Application.Common.Models; 6 | using MediatR; 7 | 8 | namespace CleanArchitecture.Application.TodoItems.Queries.GetTodoItemsWithPagination; 9 | 10 | public class GetTodoItemsWithPaginationQuery : IRequest> 11 | { 12 | public int ListId { get; set; } 13 | public int PageNumber { get; set; } = 1; 14 | public int PageSize { get; set; } = 10; 15 | } 16 | 17 | public class GetTodoItemsWithPaginationQueryHandler : IRequestHandler> 18 | { 19 | private readonly IApplicationDbContext _context; 20 | private readonly IMapper _mapper; 21 | 22 | public GetTodoItemsWithPaginationQueryHandler(IApplicationDbContext context, IMapper mapper) 23 | { 24 | _context = context; 25 | _mapper = mapper; 26 | } 27 | 28 | public async Task> Handle(GetTodoItemsWithPaginationQuery request, CancellationToken cancellationToken) 29 | { 30 | return await _context.TodoItems 31 | .Where(x => x.ListId == request.ListId) 32 | .OrderBy(x => x.Title) 33 | .ProjectTo(_mapper.ConfigurationProvider) 34 | .PaginatedListAsync(request.PageNumber, request.PageSize); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Application/TodoItems/Queries/GetTodoItemsWithPagination/GetTodoItemsWithPaginationQueryValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | 3 | namespace CleanArchitecture.Application.TodoItems.Queries.GetTodoItemsWithPagination; 4 | 5 | public class GetTodoItemsWithPaginationQueryValidator : AbstractValidator 6 | { 7 | public GetTodoItemsWithPaginationQueryValidator() 8 | { 9 | RuleFor(x => x.ListId) 10 | .NotEmpty().WithMessage("ListId is required."); 11 | 12 | RuleFor(x => x.PageNumber) 13 | .GreaterThanOrEqualTo(1).WithMessage("PageNumber at least greater than or equal to 1."); 14 | 15 | RuleFor(x => x.PageSize) 16 | .GreaterThanOrEqualTo(1).WithMessage("PageSize at least greater than or equal to 1."); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Application/TodoItems/Queries/GetTodoItemsWithPagination/TodoItemBriefDto.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Mappings; 2 | using CleanArchitecture.Domain.Entities; 3 | 4 | namespace CleanArchitecture.Application.TodoItems.Queries.GetTodoItemsWithPagination; 5 | 6 | public class TodoItemBriefDto : IMapFrom 7 | { 8 | public int Id { get; set; } 9 | 10 | public int ListId { get; set; } 11 | 12 | public string? Title { get; set; } 13 | 14 | public bool Done { get; set; } 15 | } 16 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Commands/CreateTodoList/CreateTodoListCommand.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Interfaces; 2 | using CleanArchitecture.Domain.Entities; 3 | using MediatR; 4 | 5 | namespace CleanArchitecture.Application.TodoLists.Commands.CreateTodoList; 6 | 7 | public class CreateTodoListCommand : IRequest 8 | { 9 | public string? Title { get; set; } 10 | } 11 | 12 | public class CreateTodoListCommandHandler : IRequestHandler 13 | { 14 | private readonly IApplicationDbContext _context; 15 | 16 | public CreateTodoListCommandHandler(IApplicationDbContext context) 17 | { 18 | _context = context; 19 | } 20 | 21 | public async Task Handle(CreateTodoListCommand request, CancellationToken cancellationToken) 22 | { 23 | var entity = new TodoList(); 24 | 25 | entity.Title = request.Title; 26 | 27 | _context.TodoLists.Add(entity); 28 | 29 | await _context.SaveChangesAsync(cancellationToken); 30 | 31 | return entity.Id; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Commands/CreateTodoList/CreateTodoListCommandValidator.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Interfaces; 2 | using FluentValidation; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace CleanArchitecture.Application.TodoLists.Commands.CreateTodoList; 6 | 7 | public class CreateTodoListCommandValidator : AbstractValidator 8 | { 9 | private readonly IApplicationDbContext _context; 10 | 11 | public CreateTodoListCommandValidator(IApplicationDbContext context) 12 | { 13 | _context = context; 14 | 15 | RuleFor(v => v.Title) 16 | .NotEmpty().WithMessage("Title is required.") 17 | .MaximumLength(200).WithMessage("Title must not exceed 200 characters.") 18 | .MustAsync(BeUniqueTitle).WithMessage("The specified title already exists."); 19 | } 20 | 21 | public async Task BeUniqueTitle(string title, CancellationToken cancellationToken) 22 | { 23 | return await _context.TodoLists 24 | .AllAsync(l => l.Title != title, cancellationToken); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Commands/DeleteTodoList/DeleteTodoListCommand.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.Common.Interfaces; 3 | using CleanArchitecture.Domain.Entities; 4 | using MediatR; 5 | using Microsoft.EntityFrameworkCore; 6 | 7 | namespace CleanArchitecture.Application.TodoLists.Commands.DeleteTodoList; 8 | 9 | public class DeleteTodoListCommand : IRequest 10 | { 11 | public int Id { get; set; } 12 | } 13 | 14 | public class DeleteTodoListCommandHandler : IRequestHandler 15 | { 16 | private readonly IApplicationDbContext _context; 17 | 18 | public DeleteTodoListCommandHandler(IApplicationDbContext context) 19 | { 20 | _context = context; 21 | } 22 | 23 | public async Task Handle(DeleteTodoListCommand request, CancellationToken cancellationToken) 24 | { 25 | var entity = await _context.TodoLists 26 | .Where(l => l.Id == request.Id) 27 | .SingleOrDefaultAsync(cancellationToken); 28 | 29 | if (entity == null) 30 | { 31 | throw new NotFoundException(nameof(TodoList), request.Id); 32 | } 33 | 34 | _context.TodoLists.Remove(entity); 35 | 36 | await _context.SaveChangesAsync(cancellationToken); 37 | 38 | return Unit.Value; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Commands/PurgeTodoLists/PurgeTodoListsCommand.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Interfaces; 2 | using CleanArchitecture.Application.Common.Security; 3 | using MediatR; 4 | 5 | namespace CleanArchitecture.Application.TodoLists.Commands.PurgeTodoLists; 6 | 7 | [Authorize(Roles = "Administrator")] 8 | [Authorize(Policy = "CanPurge")] 9 | public class PurgeTodoListsCommand : IRequest 10 | { 11 | } 12 | 13 | public class PurgeTodoListsCommandHandler : IRequestHandler 14 | { 15 | private readonly IApplicationDbContext _context; 16 | 17 | public PurgeTodoListsCommandHandler(IApplicationDbContext context) 18 | { 19 | _context = context; 20 | } 21 | 22 | public async Task Handle(PurgeTodoListsCommand request, CancellationToken cancellationToken) 23 | { 24 | _context.TodoLists.RemoveRange(_context.TodoLists); 25 | 26 | await _context.SaveChangesAsync(cancellationToken); 27 | 28 | return Unit.Value; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Commands/UpdateTodoList/UpdateTodoListCommand.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.Common.Interfaces; 3 | using CleanArchitecture.Domain.Entities; 4 | using MediatR; 5 | 6 | namespace CleanArchitecture.Application.TodoLists.Commands.UpdateTodoList; 7 | 8 | public class UpdateTodoListCommand : IRequest 9 | { 10 | public int Id { get; set; } 11 | 12 | public string? Title { get; set; } 13 | } 14 | 15 | public class UpdateTodoListCommandHandler : IRequestHandler 16 | { 17 | private readonly IApplicationDbContext _context; 18 | 19 | public UpdateTodoListCommandHandler(IApplicationDbContext context) 20 | { 21 | _context = context; 22 | } 23 | 24 | public async Task Handle(UpdateTodoListCommand request, CancellationToken cancellationToken) 25 | { 26 | var entity = await _context.TodoLists 27 | .FindAsync(new object[] { request.Id }, cancellationToken); 28 | 29 | if (entity == null) 30 | { 31 | throw new NotFoundException(nameof(TodoList), request.Id); 32 | } 33 | 34 | entity.Title = request.Title; 35 | 36 | await _context.SaveChangesAsync(cancellationToken); 37 | 38 | return Unit.Value; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Commands/UpdateTodoList/UpdateTodoListCommandValidator.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Interfaces; 2 | using FluentValidation; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace CleanArchitecture.Application.TodoLists.Commands.UpdateTodoList; 6 | 7 | public class UpdateTodoListCommandValidator : AbstractValidator 8 | { 9 | private readonly IApplicationDbContext _context; 10 | 11 | public UpdateTodoListCommandValidator(IApplicationDbContext context) 12 | { 13 | _context = context; 14 | 15 | RuleFor(v => v.Title) 16 | .NotEmpty().WithMessage("Title is required.") 17 | .MaximumLength(200).WithMessage("Title must not exceed 200 characters.") 18 | .MustAsync(BeUniqueTitle).WithMessage("The specified title already exists."); 19 | } 20 | 21 | public async Task BeUniqueTitle(UpdateTodoListCommand model, string title, CancellationToken cancellationToken) 22 | { 23 | return await _context.TodoLists 24 | .Where(l => l.Id != model.Id) 25 | .AllAsync(l => l.Title != title, cancellationToken); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Queries/ExportTodos/ExportTodosQuery.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using AutoMapper.QueryableExtensions; 3 | using CleanArchitecture.Application.Common.Interfaces; 4 | using MediatR; 5 | using Microsoft.EntityFrameworkCore; 6 | 7 | namespace CleanArchitecture.Application.TodoLists.Queries.ExportTodos; 8 | 9 | public class ExportTodosQuery : IRequest 10 | { 11 | public int ListId { get; set; } 12 | } 13 | 14 | public class ExportTodosQueryHandler : IRequestHandler 15 | { 16 | private readonly IApplicationDbContext _context; 17 | private readonly IMapper _mapper; 18 | private readonly ICsvFileBuilder _fileBuilder; 19 | 20 | public ExportTodosQueryHandler(IApplicationDbContext context, IMapper mapper, ICsvFileBuilder fileBuilder) 21 | { 22 | _context = context; 23 | _mapper = mapper; 24 | _fileBuilder = fileBuilder; 25 | } 26 | 27 | public async Task Handle(ExportTodosQuery request, CancellationToken cancellationToken) 28 | { 29 | var records = await _context.TodoItems 30 | .Where(t => t.ListId == request.ListId) 31 | .ProjectTo(_mapper.ConfigurationProvider) 32 | .ToListAsync(cancellationToken); 33 | 34 | var vm = new ExportTodosVm( 35 | "TodoItems.csv", 36 | "text/csv", 37 | _fileBuilder.BuildTodoItemsFile(records)); 38 | 39 | return vm; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Queries/ExportTodos/ExportTodosVm.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Application.TodoLists.Queries.ExportTodos; 2 | 3 | public class ExportTodosVm 4 | { 5 | public ExportTodosVm(string fileName, string contentType, byte[] content) 6 | { 7 | FileName = fileName; 8 | ContentType = contentType; 9 | Content = content; 10 | } 11 | 12 | public string FileName { get; set; } 13 | 14 | public string ContentType { get; set; } 15 | 16 | public byte[] Content { get; set; } 17 | } 18 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Queries/ExportTodos/TodoItemFileRecord.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Mappings; 2 | using CleanArchitecture.Domain.Entities; 3 | 4 | namespace CleanArchitecture.Application.TodoLists.Queries.ExportTodos; 5 | 6 | public class TodoItemRecord : IMapFrom 7 | { 8 | public string? Title { get; set; } 9 | 10 | public bool Done { get; set; } 11 | } 12 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Queries/GetTodos/GetTodosQuery.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using AutoMapper.QueryableExtensions; 3 | using CleanArchitecture.Application.Common.Interfaces; 4 | using CleanArchitecture.Domain.Enums; 5 | using MediatR; 6 | using Microsoft.EntityFrameworkCore; 7 | 8 | namespace CleanArchitecture.Application.TodoLists.Queries.GetTodos; 9 | 10 | public class GetTodosQuery : IRequest 11 | { 12 | } 13 | 14 | public class GetTodosQueryHandler : IRequestHandler 15 | { 16 | private readonly IApplicationDbContext _context; 17 | private readonly IMapper _mapper; 18 | 19 | public GetTodosQueryHandler(IApplicationDbContext context, IMapper mapper) 20 | { 21 | _context = context; 22 | _mapper = mapper; 23 | } 24 | 25 | public async Task Handle(GetTodosQuery request, CancellationToken cancellationToken) 26 | { 27 | return new TodosVm 28 | { 29 | PriorityLevels = Enum.GetValues(typeof(PriorityLevel)) 30 | .Cast() 31 | .Select(p => new PriorityLevelDto { Value = (int)p, Name = p.ToString() }) 32 | .ToList(), 33 | 34 | Lists = await _context.TodoLists 35 | .AsNoTracking() 36 | .ProjectTo(_mapper.ConfigurationProvider) 37 | .OrderBy(t => t.Title) 38 | .ToListAsync(cancellationToken) 39 | }; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Queries/GetTodos/PriorityLevelDto.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Application.TodoLists.Queries.GetTodos; 2 | 3 | public class PriorityLevelDto 4 | { 5 | public int Value { get; set; } 6 | 7 | public string? Name { get; set; } 8 | } 9 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Queries/GetTodos/TodoItemDto.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using CleanArchitecture.Application.Common.Mappings; 3 | using CleanArchitecture.Domain.Entities; 4 | 5 | namespace CleanArchitecture.Application.TodoLists.Queries.GetTodos; 6 | 7 | public class TodoItemDto : IMapFrom 8 | { 9 | public int Id { get; set; } 10 | 11 | public int ListId { get; set; } 12 | 13 | public string? Title { get; set; } 14 | 15 | public bool Done { get; set; } 16 | 17 | public int Priority { get; set; } 18 | 19 | public string? Note { get; set; } 20 | 21 | public void Mapping(Profile profile) 22 | { 23 | profile.CreateMap() 24 | .ForMember(d => d.Priority, opt => opt.MapFrom(s => (int)s.Priority)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Queries/GetTodos/TodoListDto.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Mappings; 2 | using CleanArchitecture.Domain.Entities; 3 | 4 | namespace CleanArchitecture.Application.TodoLists.Queries.GetTodos; 5 | 6 | public class TodoListDto : IMapFrom 7 | { 8 | public TodoListDto() 9 | { 10 | Items = new List(); 11 | } 12 | 13 | public int Id { get; set; } 14 | 15 | public string? Title { get; set; } 16 | 17 | public string? Colour { get; set; } 18 | 19 | public IList Items { get; set; } 20 | } 21 | -------------------------------------------------------------------------------- /src/Application/TodoLists/Queries/GetTodos/TodosVm.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Application.TodoLists.Queries.GetTodos; 2 | 3 | public class TodosVm 4 | { 5 | public IList PriorityLevels { get; set; } = new List(); 6 | 7 | public IList Lists { get; set; } = new List(); 8 | } 9 | -------------------------------------------------------------------------------- /src/Application/WeatherForecasts/Queries/GetWeatherForecasts/GetWeatherForecastsQuery.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | 3 | namespace CleanArchitecture.Application.WeatherForecasts.Queries.GetWeatherForecasts; 4 | 5 | public class GetWeatherForecastsQuery : IRequest> 6 | { 7 | } 8 | 9 | public class GetWeatherForecastsQueryHandler : IRequestHandler> 10 | { 11 | private static readonly string[] Summaries = new[] 12 | { 13 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 14 | }; 15 | 16 | public Task> Handle(GetWeatherForecastsQuery request, CancellationToken cancellationToken) 17 | { 18 | var rng = new Random(); 19 | 20 | var vm = Enumerable.Range(1, 5).Select(index => new WeatherForecast 21 | { 22 | Date = DateTime.Now.AddDays(index), 23 | TemperatureC = rng.Next(-20, 55), 24 | Summary = Summaries[rng.Next(Summaries.Length)] 25 | }); 26 | 27 | return Task.FromResult(vm); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Application/WeatherForecasts/Queries/GetWeatherForecasts/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Application.WeatherForecasts.Queries.GetWeatherForecasts; 2 | 3 | public class WeatherForecast 4 | { 5 | public DateTime Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } 13 | -------------------------------------------------------------------------------- /src/Domain/Common/AuditableEntity.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Domain.Common; 2 | 3 | public abstract class AuditableEntity 4 | { 5 | public DateTime Created { get; set; } 6 | 7 | public string? CreatedBy { get; set; } 8 | 9 | public DateTime? LastModified { get; set; } 10 | 11 | public string? LastModifiedBy { get; set; } 12 | } 13 | -------------------------------------------------------------------------------- /src/Domain/Common/DomainEvent.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Domain.Common; 2 | 3 | public interface IHasDomainEvent 4 | { 5 | public List DomainEvents { get; set; } 6 | } 7 | 8 | public abstract class DomainEvent 9 | { 10 | protected DomainEvent() 11 | { 12 | DateOccurred = DateTimeOffset.UtcNow; 13 | } 14 | public bool IsPublished { get; set; } 15 | public DateTimeOffset DateOccurred { get; protected set; } = DateTime.UtcNow; 16 | } 17 | -------------------------------------------------------------------------------- /src/Domain/Common/ValueObject.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Domain.Common; 2 | 3 | // Learn more: https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/implement-value-objects 4 | public abstract class ValueObject 5 | { 6 | protected static bool EqualOperator(ValueObject left, ValueObject right) 7 | { 8 | if (left is null ^ right is null) 9 | { 10 | return false; 11 | } 12 | 13 | return left?.Equals(right!) != false; 14 | } 15 | 16 | protected static bool NotEqualOperator(ValueObject left, ValueObject right) 17 | { 18 | return !(EqualOperator(left, right)); 19 | } 20 | 21 | protected abstract IEnumerable GetEqualityComponents(); 22 | 23 | public override bool Equals(object? obj) 24 | { 25 | if (obj == null || obj.GetType() != GetType()) 26 | { 27 | return false; 28 | } 29 | 30 | var other = (ValueObject)obj; 31 | return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents()); 32 | } 33 | 34 | public override int GetHashCode() 35 | { 36 | return GetEqualityComponents() 37 | .Select(x => x != null ? x.GetHashCode() : 0) 38 | .Aggregate((x, y) => x ^ y); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Domain/Domain.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | CleanArchitecture.Domain 6 | CleanArchitecture.Domain 7 | enable 8 | enable 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/Domain/Entities/TodoItem.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Domain.Entities; 2 | 3 | public class TodoItem : AuditableEntity, IHasDomainEvent 4 | { 5 | public int Id { get; set; } 6 | 7 | public int ListId { get; set; } 8 | 9 | public string? Title { get; set; } 10 | 11 | public string? Note { get; set; } 12 | 13 | public PriorityLevel Priority { get; set; } 14 | 15 | public DateTime? Reminder { get; set; } 16 | 17 | private bool _done; 18 | public bool Done 19 | { 20 | get => _done; 21 | set 22 | { 23 | if (value == true && _done == false) 24 | { 25 | DomainEvents.Add(new TodoItemCompletedEvent(this)); 26 | } 27 | 28 | _done = value; 29 | } 30 | } 31 | 32 | public TodoList List { get; set; } = null!; 33 | 34 | public List DomainEvents { get; set; } = new List(); 35 | } 36 | -------------------------------------------------------------------------------- /src/Domain/Entities/TodoList.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Domain.Entities; 2 | 3 | public class TodoList : AuditableEntity 4 | { 5 | public int Id { get; set; } 6 | 7 | public string? Title { get; set; } 8 | 9 | public Colour Colour { get; set; } = Colour.White; 10 | 11 | public IList Items { get; private set; } = new List(); 12 | } 13 | -------------------------------------------------------------------------------- /src/Domain/Enums/PriorityLevel.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Domain.Enums; 2 | 3 | public enum PriorityLevel 4 | { 5 | None = 0, 6 | Low = 1, 7 | Medium = 2, 8 | High = 3 9 | } 10 | -------------------------------------------------------------------------------- /src/Domain/Events/TodoItemCompletedEvent.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Domain.Events; 2 | 3 | public class TodoItemCompletedEvent : DomainEvent 4 | { 5 | public TodoItemCompletedEvent(TodoItem item) 6 | { 7 | Item = item; 8 | } 9 | 10 | public TodoItem Item { get; } 11 | } 12 | -------------------------------------------------------------------------------- /src/Domain/Events/TodoItemCreatedEvent.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Domain.Events; 2 | 3 | public class TodoItemCreatedEvent : DomainEvent 4 | { 5 | public TodoItemCreatedEvent(TodoItem item) 6 | { 7 | Item = item; 8 | } 9 | 10 | public TodoItem Item { get; } 11 | } 12 | -------------------------------------------------------------------------------- /src/Domain/Events/TodoItemDeletedEvent.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Domain.Events; 2 | 3 | public class TodoItemDeletedEvent : DomainEvent 4 | { 5 | public TodoItemDeletedEvent(TodoItem item) 6 | { 7 | Item = item; 8 | } 9 | 10 | public TodoItem Item { get; } 11 | } 12 | -------------------------------------------------------------------------------- /src/Domain/Exceptions/UnsupportedColourException.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Domain.Exceptions; 2 | 3 | public class UnsupportedColourException : Exception 4 | { 5 | public UnsupportedColourException(string code) 6 | : base($"Colour \"{code}\" is unsupported.") 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Domain/ValueObjects/Colour.cs: -------------------------------------------------------------------------------- 1 | namespace CleanArchitecture.Domain.ValueObjects; 2 | 3 | public class Colour : ValueObject 4 | { 5 | static Colour() 6 | { 7 | } 8 | 9 | private Colour() 10 | { 11 | } 12 | 13 | private Colour(string code) 14 | { 15 | Code = code; 16 | } 17 | 18 | public static Colour From(string code) 19 | { 20 | var colour = new Colour { Code = code }; 21 | 22 | if (!SupportedColours.Contains(colour)) 23 | { 24 | throw new UnsupportedColourException(code); 25 | } 26 | 27 | return colour; 28 | } 29 | 30 | public static Colour White => new("#FFFFFF"); 31 | 32 | public static Colour Red => new("#FF5733"); 33 | 34 | public static Colour Orange => new("#FFC300"); 35 | 36 | public static Colour Yellow => new("#FFFF66"); 37 | 38 | public static Colour Green => new("#CCFF99 "); 39 | 40 | public static Colour Blue => new("#6666FF"); 41 | 42 | public static Colour Purple => new("#9966CC"); 43 | 44 | public static Colour Grey => new("#999999"); 45 | 46 | public string Code { get; private set; } = "#000000"; 47 | 48 | public static implicit operator string(Colour colour) 49 | { 50 | return colour.ToString(); 51 | } 52 | 53 | public static explicit operator Colour(string code) 54 | { 55 | return From(code); 56 | } 57 | 58 | public override string ToString() 59 | { 60 | return Code; 61 | } 62 | 63 | protected static IEnumerable SupportedColours 64 | { 65 | get 66 | { 67 | yield return White; 68 | yield return Red; 69 | yield return Orange; 70 | yield return Yellow; 71 | yield return Green; 72 | yield return Blue; 73 | yield return Purple; 74 | yield return Grey; 75 | } 76 | } 77 | 78 | protected override IEnumerable GetEqualityComponents() 79 | { 80 | yield return Code; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/Domain/_Imports.cs: -------------------------------------------------------------------------------- 1 | global using CleanArchitecture.Domain.Common; 2 | global using CleanArchitecture.Domain.Entities; 3 | global using CleanArchitecture.Domain.Enums; 4 | global using CleanArchitecture.Domain.Events; 5 | global using CleanArchitecture.Domain.Exceptions; 6 | global using CleanArchitecture.Domain.ValueObjects; -------------------------------------------------------------------------------- /src/Infrastructure/DependencyInjection.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Interfaces; 2 | using CleanArchitecture.Infrastructure.Files; 3 | using CleanArchitecture.Infrastructure.Identity; 4 | using CleanArchitecture.Infrastructure.Persistence; 5 | using CleanArchitecture.Infrastructure.Services; 6 | using Microsoft.AspNetCore.Authentication; 7 | using Microsoft.AspNetCore.Identity; 8 | using Microsoft.EntityFrameworkCore; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.DependencyInjection; 11 | 12 | namespace CleanArchitecture.Infrastructure; 13 | 14 | public static class DependencyInjection 15 | { 16 | public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) 17 | { 18 | if (configuration.GetValue("UseInMemoryDatabase")) 19 | { 20 | services.AddDbContext(options => 21 | options.UseInMemoryDatabase("CleanArchitectureDb")); 22 | } 23 | else 24 | { 25 | services.AddDbContext(options => 26 | options.UseSqlServer( 27 | configuration.GetConnectionString("DefaultConnection"), 28 | b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName))); 29 | } 30 | 31 | services.AddScoped(provider => provider.GetRequiredService()); 32 | 33 | services.AddScoped(); 34 | 35 | services 36 | .AddDefaultIdentity() 37 | .AddRoles() 38 | .AddEntityFrameworkStores(); 39 | 40 | services.AddIdentityServer() 41 | .AddApiAuthorization(); 42 | 43 | services.AddTransient(); 44 | services.AddTransient(); 45 | services.AddTransient(); 46 | 47 | services.AddAuthentication() 48 | .AddIdentityServerJwt(); 49 | 50 | services.AddAuthorization(options => 51 | options.AddPolicy("CanPurge", policy => policy.RequireRole("Administrator"))); 52 | 53 | return services; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Infrastructure/Files/CsvFileBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using CleanArchitecture.Application.Common.Interfaces; 3 | using CleanArchitecture.Application.TodoLists.Queries.ExportTodos; 4 | using CleanArchitecture.Infrastructure.Files.Maps; 5 | using CsvHelper; 6 | 7 | namespace CleanArchitecture.Infrastructure.Files; 8 | 9 | public class CsvFileBuilder : ICsvFileBuilder 10 | { 11 | public byte[] BuildTodoItemsFile(IEnumerable records) 12 | { 13 | using var memoryStream = new MemoryStream(); 14 | using (var streamWriter = new StreamWriter(memoryStream)) 15 | { 16 | using var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture); 17 | 18 | csvWriter.Configuration.RegisterClassMap(); 19 | csvWriter.WriteRecords(records); 20 | } 21 | 22 | return memoryStream.ToArray(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Infrastructure/Files/Maps/TodoItemRecordMap.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using CleanArchitecture.Application.TodoLists.Queries.ExportTodos; 3 | using CsvHelper.Configuration; 4 | 5 | namespace CleanArchitecture.Infrastructure.Files.Maps; 6 | 7 | public class TodoItemRecordMap : ClassMap 8 | { 9 | public TodoItemRecordMap() 10 | { 11 | AutoMap(CultureInfo.InvariantCulture); 12 | 13 | Map(m => m.Done).ConvertUsing(c => c.Done ? "Yes" : "No"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Infrastructure/Identity/ApplicationUser.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | 3 | namespace CleanArchitecture.Infrastructure.Identity; 4 | 5 | public class ApplicationUser : IdentityUser 6 | { 7 | } 8 | -------------------------------------------------------------------------------- /src/Infrastructure/Identity/IdentityResultExtensions.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Models; 2 | using Microsoft.AspNetCore.Identity; 3 | 4 | namespace CleanArchitecture.Infrastructure.Identity; 5 | 6 | public static class IdentityResultExtensions 7 | { 8 | public static Result ToApplicationResult(this IdentityResult result) 9 | { 10 | return result.Succeeded 11 | ? Result.Success() 12 | : Result.Failure(result.Errors.Select(e => e.Description)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Infrastructure/Identity/IdentityService.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Interfaces; 2 | using CleanArchitecture.Application.Common.Models; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.AspNetCore.Identity; 5 | using Microsoft.EntityFrameworkCore; 6 | 7 | namespace CleanArchitecture.Infrastructure.Identity; 8 | 9 | public class IdentityService : IIdentityService 10 | { 11 | private readonly UserManager _userManager; 12 | private readonly IUserClaimsPrincipalFactory _userClaimsPrincipalFactory; 13 | private readonly IAuthorizationService _authorizationService; 14 | 15 | public IdentityService( 16 | UserManager userManager, 17 | IUserClaimsPrincipalFactory userClaimsPrincipalFactory, 18 | IAuthorizationService authorizationService) 19 | { 20 | _userManager = userManager; 21 | _userClaimsPrincipalFactory = userClaimsPrincipalFactory; 22 | _authorizationService = authorizationService; 23 | } 24 | 25 | public async Task GetUserNameAsync(string userId) 26 | { 27 | var user = await _userManager.Users.FirstAsync(u => u.Id == userId); 28 | 29 | return user.UserName; 30 | } 31 | 32 | public async Task<(Result Result, string UserId)> CreateUserAsync(string userName, string password) 33 | { 34 | var user = new ApplicationUser 35 | { 36 | UserName = userName, 37 | Email = userName, 38 | }; 39 | 40 | var result = await _userManager.CreateAsync(user, password); 41 | 42 | return (result.ToApplicationResult(), user.Id); 43 | } 44 | 45 | public async Task IsInRoleAsync(string userId, string role) 46 | { 47 | var user = _userManager.Users.SingleOrDefault(u => u.Id == userId); 48 | 49 | return user != null && await _userManager.IsInRoleAsync(user, role); 50 | } 51 | 52 | public async Task AuthorizeAsync(string userId, string policyName) 53 | { 54 | var user = _userManager.Users.SingleOrDefault(u => u.Id == userId); 55 | 56 | if (user == null) 57 | { 58 | return false; 59 | } 60 | 61 | var principal = await _userClaimsPrincipalFactory.CreateAsync(user); 62 | 63 | var result = await _authorizationService.AuthorizeAsync(principal, policyName); 64 | 65 | return result.Succeeded; 66 | } 67 | 68 | public async Task DeleteUserAsync(string userId) 69 | { 70 | var user = _userManager.Users.SingleOrDefault(u => u.Id == userId); 71 | 72 | return user != null ? await DeleteUserAsync(user) : Result.Success(); 73 | } 74 | 75 | public async Task DeleteUserAsync(ApplicationUser user) 76 | { 77 | var result = await _userManager.DeleteAsync(user); 78 | 79 | return result.ToApplicationResult(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/Infrastructure/Infrastructure.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | CleanArchitecture.Infrastructure 6 | CleanArchitecture.Infrastructure 7 | enable 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/Infrastructure/Persistence/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using CleanArchitecture.Application.Common.Interfaces; 3 | using CleanArchitecture.Domain.Common; 4 | using CleanArchitecture.Domain.Entities; 5 | using CleanArchitecture.Infrastructure.Identity; 6 | using Duende.IdentityServer.EntityFramework.Options; 7 | using Microsoft.AspNetCore.ApiAuthorization.IdentityServer; 8 | using Microsoft.EntityFrameworkCore; 9 | using Microsoft.Extensions.Options; 10 | 11 | namespace CleanArchitecture.Infrastructure.Persistence; 12 | 13 | public class ApplicationDbContext : ApiAuthorizationDbContext, IApplicationDbContext 14 | { 15 | private readonly ICurrentUserService _currentUserService; 16 | private readonly IDateTime _dateTime; 17 | private readonly IDomainEventService _domainEventService; 18 | 19 | public ApplicationDbContext( 20 | DbContextOptions options, 21 | IOptions operationalStoreOptions, 22 | ICurrentUserService currentUserService, 23 | IDomainEventService domainEventService, 24 | IDateTime dateTime) : base(options, operationalStoreOptions) 25 | { 26 | _currentUserService = currentUserService; 27 | _domainEventService = domainEventService; 28 | _dateTime = dateTime; 29 | } 30 | 31 | public DbSet TodoLists => Set(); 32 | 33 | public DbSet TodoItems => Set(); 34 | 35 | public override async Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) 36 | { 37 | foreach (var entry in ChangeTracker.Entries()) 38 | { 39 | switch (entry.State) 40 | { 41 | case EntityState.Added: 42 | entry.Entity.CreatedBy = _currentUserService.UserId; 43 | entry.Entity.Created = _dateTime.Now; 44 | break; 45 | 46 | case EntityState.Modified: 47 | entry.Entity.LastModifiedBy = _currentUserService.UserId; 48 | entry.Entity.LastModified = _dateTime.Now; 49 | break; 50 | } 51 | } 52 | 53 | var events = ChangeTracker.Entries() 54 | .Select(x => x.Entity.DomainEvents) 55 | .SelectMany(x => x) 56 | .Where(domainEvent => !domainEvent.IsPublished) 57 | .ToArray(); 58 | 59 | var result = await base.SaveChangesAsync(cancellationToken); 60 | 61 | await DispatchEvents(events); 62 | 63 | return result; 64 | } 65 | 66 | protected override void OnModelCreating(ModelBuilder builder) 67 | { 68 | builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); 69 | 70 | base.OnModelCreating(builder); 71 | } 72 | 73 | private async Task DispatchEvents(DomainEvent[] events) 74 | { 75 | foreach (var @event in events) 76 | { 77 | @event.IsPublished = true; 78 | await _domainEventService.Publish(@event); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/Infrastructure/Persistence/ApplicationDbContextSeed.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Domain.Entities; 2 | using CleanArchitecture.Domain.ValueObjects; 3 | using CleanArchitecture.Infrastructure.Identity; 4 | using Microsoft.AspNetCore.Identity; 5 | 6 | namespace CleanArchitecture.Infrastructure.Persistence; 7 | 8 | public static class ApplicationDbContextSeed 9 | { 10 | public static async Task SeedDefaultUserAsync(UserManager userManager, RoleManager roleManager) 11 | { 12 | var administratorRole = new IdentityRole("Administrator"); 13 | 14 | if (roleManager.Roles.All(r => r.Name != administratorRole.Name)) 15 | { 16 | await roleManager.CreateAsync(administratorRole); 17 | } 18 | 19 | var administrator = new ApplicationUser { UserName = "administrator@localhost", Email = "administrator@localhost" }; 20 | 21 | if (userManager.Users.All(u => u.UserName != administrator.UserName)) 22 | { 23 | await userManager.CreateAsync(administrator, "Administrator1!"); 24 | await userManager.AddToRolesAsync(administrator, new[] { administratorRole.Name }); 25 | } 26 | } 27 | 28 | public static async Task SeedSampleDataAsync(ApplicationDbContext context) 29 | { 30 | // Seed, if necessary 31 | if (!context.TodoLists.Any()) 32 | { 33 | context.TodoLists.Add(new TodoList 34 | { 35 | Title = "Shopping", 36 | Colour = Colour.Blue, 37 | Items = 38 | { 39 | new TodoItem { Title = "Apples", Done = true }, 40 | new TodoItem { Title = "Milk", Done = true }, 41 | new TodoItem { Title = "Bread", Done = true }, 42 | new TodoItem { Title = "Toilet paper" }, 43 | new TodoItem { Title = "Pasta" }, 44 | new TodoItem { Title = "Tissues" }, 45 | new TodoItem { Title = "Tuna" }, 46 | new TodoItem { Title = "Water" } 47 | } 48 | }); 49 | 50 | await context.SaveChangesAsync(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Infrastructure/Persistence/Configurations/TodoItemConfiguration.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Domain.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace CleanArchitecture.Infrastructure.Persistence.Configurations; 6 | 7 | public class TodoItemConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.Ignore(e => e.DomainEvents); 12 | 13 | builder.Property(t => t.Title) 14 | .HasMaxLength(200) 15 | .IsRequired(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Infrastructure/Persistence/Configurations/TodoListConfiguration.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Domain.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace CleanArchitecture.Infrastructure.Persistence.Configurations; 6 | 7 | public class TodoListConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.Property(t => t.Title) 12 | .HasMaxLength(200) 13 | .IsRequired(); 14 | 15 | builder 16 | .OwnsOne(b => b.Colour); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Infrastructure/Services/DateTimeService.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Interfaces; 2 | 3 | namespace CleanArchitecture.Infrastructure.Services; 4 | 5 | public class DateTimeService : IDateTime 6 | { 7 | public DateTime Now => DateTime.Now; 8 | } 9 | -------------------------------------------------------------------------------- /src/Infrastructure/Services/DomainEventService.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Interfaces; 2 | using CleanArchitecture.Application.Common.Models; 3 | using CleanArchitecture.Domain.Common; 4 | using MediatR; 5 | using Microsoft.Extensions.Logging; 6 | 7 | namespace CleanArchitecture.Infrastructure.Services; 8 | 9 | public class DomainEventService : IDomainEventService 10 | { 11 | private readonly ILogger _logger; 12 | private readonly IPublisher _mediator; 13 | 14 | public DomainEventService(ILogger logger, IPublisher mediator) 15 | { 16 | _logger = logger; 17 | _mediator = mediator; 18 | } 19 | 20 | public async Task Publish(DomainEvent domainEvent) 21 | { 22 | _logger.LogInformation("Publishing domain event. Event - {event}", domainEvent.GetType().Name); 23 | await _mediator.Publish(GetNotificationCorrespondingToDomainEvent(domainEvent)); 24 | } 25 | 26 | private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent domainEvent) 27 | { 28 | return (INotification)Activator.CreateInstance( 29 | typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent)!; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/.browserslistrc: -------------------------------------------------------------------------------- 1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | # For IE 9-11 support, please uncomment the last line of the file and adjust as needed 5 | > 0.5% 6 | last 2 versions 7 | Firefox ESR 8 | not dead 9 | # IE 9-11 -------------------------------------------------------------------------------- /src/WebUI/ClientApp/.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-debug.log 3 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /dist-server 6 | /tmp 7 | /out-tsc 8 | 9 | # dependencies 10 | /node_modules 11 | 12 | # IDEs and editors 13 | /.idea 14 | .project 15 | .classpath 16 | .c9/ 17 | *.launch 18 | .settings/ 19 | *.sublime-workspace 20 | 21 | # IDE - VSCode 22 | .vscode/* 23 | !.vscode/settings.json 24 | !.vscode/tasks.json 25 | !.vscode/launch.json 26 | !.vscode/extensions.json 27 | 28 | # misc 29 | /.sass-cache 30 | /connect.lock 31 | /coverage 32 | /libpeerconnection.log 33 | npm-debug.log 34 | yarn-error.log 35 | testem.log 36 | /typings 37 | 38 | # System Files 39 | .DS_Store 40 | Thumbs.db 41 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:12 2 | EXPOSE 4200 3 | WORKDIR /usr/src/app 4 | COPY package*.json ./ 5 | RUN npm install 6 | COPY . . 7 | RUN npm build 8 | ENTRYPOINT ["npm", "run", "start:dev"] 9 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require("jasmine-spec-reporter"); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: ["./src/**/*.e2e-spec.ts"], 9 | capabilities: { 10 | browserName: "chrome" 11 | }, 12 | directConnect: true, 13 | baseUrl: "http://localhost:4200/", 14 | framework: "jasmine", 15 | jasmineNodeOpts: { 16 | showColors: true, 17 | defaultTimeoutInterval: 30000, 18 | print: function() {} 19 | }, 20 | onPrepare() { 21 | require("ts-node").register({ 22 | project: require("path").join(__dirname, "./tsconfig.e2e.json") 23 | }); 24 | jasmine 25 | .getEnv() 26 | .addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('App', () => { 4 | let page: AppPage; 5 | 6 | beforeEach(() => { 7 | page = new AppPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getMainHeading()).toEqual('Hello, world!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getMainHeading() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } -------------------------------------------------------------------------------- /src/WebUI/ClientApp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cleanarchitecture.webui", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "echo 'Starting...' && ng serve", 7 | "start:dev": "echo 'Starting (Dev)...' && ng serve --host 0.0.0.0 --disable-host-check", 8 | "build": "ng build", 9 | "build:ssr": "ng run CleanArchitecture.WebUI:server:dev", 10 | "test": "ng test", 11 | "lint": "ng lint", 12 | "e2e": "ng e2e" 13 | }, 14 | "private": true, 15 | "dependencies": { 16 | "@angular/animations": "12.0.1", 17 | "@angular/common": "12.0.1", 18 | "@angular/compiler": "12.0.1", 19 | "@angular/core": "12.0.1", 20 | "@angular/forms": "12.0.1", 21 | "@angular/platform-browser": "12.0.1", 22 | "@angular/platform-browser-dynamic": "12.0.1", 23 | "@angular/platform-server": "12.0.1", 24 | "@angular/router": "12.0.1", 25 | "@fortawesome/angular-fontawesome": "^0.9.0", 26 | "@fortawesome/fontawesome-svg-core": "1.2.30", 27 | "@fortawesome/free-solid-svg-icons": "5.14.0", 28 | "aspnet-prerendering": "^3.0.1", 29 | "bootstrap": "^4.3.1", 30 | "core-js": "^2.6.5", 31 | "jquery": "3.5.0", 32 | "ngx-bootstrap": "^5.2.0", 33 | "oidc-client": "^1.9.0", 34 | "popper.js": "^1.14.3", 35 | "rxjs": "^6.5.4", 36 | "tslib": "^2.0.0", 37 | "zone.js": "~0.11.4" 38 | }, 39 | "devDependencies": { 40 | "@angular-devkit/build-angular": "^12.0.1", 41 | "@angular/cli": "12.0.1", 42 | "@angular/compiler-cli": "12.0.1", 43 | "@angular/language-service": "12.0.1", 44 | "@types/jasmine": "~3.6.0", 45 | "@types/jasminewd2": "~2.0.6", 46 | "@types/node": "^12.11.1", 47 | "codelyzer": "^6.0.0", 48 | "jasmine-core": "~3.6.0", 49 | "jasmine-spec-reporter": "~5.0.0", 50 | "karma": "~6.3.2", 51 | "karma-chrome-launcher": "~3.1.0", 52 | "karma-coverage-istanbul-reporter": "~3.0.2", 53 | "karma-jasmine": "~4.0.0", 54 | "karma-jasmine-html-reporter": "^1.5.0", 55 | "typescript": "4.2.4" 56 | }, 57 | "optionalDependencies": { 58 | "protractor": "~7.0.0", 59 | "ts-node": "~5.0.1", 60 | "tslint": "~6.1.0" 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/api-authorization.constants.ts: -------------------------------------------------------------------------------- 1 | export const ApplicationName = 'CleanArchitecture.WebUI'; 2 | 3 | export const ReturnUrlType = 'returnUrl'; 4 | 5 | export const QueryParameterNames = { 6 | ReturnUrl: ReturnUrlType, 7 | Message: 'message' 8 | }; 9 | 10 | export const LogoutActions = { 11 | LogoutCallback: 'logout-callback', 12 | Logout: 'logout', 13 | LoggedOut: 'logged-out' 14 | }; 15 | 16 | export const LoginActions = { 17 | Login: 'login', 18 | LoginCallback: 'login-callback', 19 | LoginFailed: 'login-failed', 20 | Profile: 'profile', 21 | Register: 'register' 22 | }; 23 | 24 | let applicationPaths: ApplicationPathsType = { 25 | DefaultLoginRedirectPath: '/', 26 | ApiAuthorizationClientConfigurationUrl: `/_configuration/${ApplicationName}`, 27 | Login: `authentication/${LoginActions.Login}`, 28 | LoginFailed: `authentication/${LoginActions.LoginFailed}`, 29 | LoginCallback: `authentication/${LoginActions.LoginCallback}`, 30 | Register: `authentication/${LoginActions.Register}`, 31 | Profile: `authentication/${LoginActions.Profile}`, 32 | LogOut: `authentication/${LogoutActions.Logout}`, 33 | LoggedOut: `authentication/${LogoutActions.LoggedOut}`, 34 | LogOutCallback: `authentication/${LogoutActions.LogoutCallback}`, 35 | LoginPathComponents: [], 36 | LoginFailedPathComponents: [], 37 | LoginCallbackPathComponents: [], 38 | RegisterPathComponents: [], 39 | ProfilePathComponents: [], 40 | LogOutPathComponents: [], 41 | LoggedOutPathComponents: [], 42 | LogOutCallbackPathComponents: [], 43 | IdentityRegisterPath: '/Identity/Account/Register', 44 | IdentityManagePath: '/Identity/Account/Manage' 45 | }; 46 | 47 | applicationPaths = { 48 | ...applicationPaths, 49 | LoginPathComponents: applicationPaths.Login.split('/'), 50 | LoginFailedPathComponents: applicationPaths.LoginFailed.split('/'), 51 | RegisterPathComponents: applicationPaths.Register.split('/'), 52 | ProfilePathComponents: applicationPaths.Profile.split('/'), 53 | LogOutPathComponents: applicationPaths.LogOut.split('/'), 54 | LoggedOutPathComponents: applicationPaths.LoggedOut.split('/'), 55 | LogOutCallbackPathComponents: applicationPaths.LogOutCallback.split('/') 56 | }; 57 | 58 | interface ApplicationPathsType { 59 | readonly DefaultLoginRedirectPath: string; 60 | readonly ApiAuthorizationClientConfigurationUrl: string; 61 | readonly Login: string; 62 | readonly LoginFailed: string; 63 | readonly LoginCallback: string; 64 | readonly Register: string; 65 | readonly Profile: string; 66 | readonly LogOut: string; 67 | readonly LoggedOut: string; 68 | readonly LogOutCallback: string; 69 | readonly LoginPathComponents: string[]; 70 | readonly LoginFailedPathComponents: string[]; 71 | readonly LoginCallbackPathComponents: string[]; 72 | readonly RegisterPathComponents: string[]; 73 | readonly ProfilePathComponents: string[]; 74 | readonly LogOutPathComponents: string[]; 75 | readonly LoggedOutPathComponents: string[]; 76 | readonly LogOutCallbackPathComponents: string[]; 77 | readonly IdentityRegisterPath: string; 78 | readonly IdentityManagePath: string; 79 | } 80 | 81 | export const ApplicationPaths: ApplicationPathsType = applicationPaths; 82 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/api-authorization.module.spec.ts: -------------------------------------------------------------------------------- 1 | import { ApiAuthorizationModule } from './api-authorization.module'; 2 | 3 | describe('ApiAuthorizationModule', () => { 4 | let apiAuthorizationModule: ApiAuthorizationModule; 5 | 6 | beforeEach(() => { 7 | apiAuthorizationModule = new ApiAuthorizationModule(); 8 | }); 9 | 10 | it('should create an instance', () => { 11 | expect(apiAuthorizationModule).toBeTruthy(); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/api-authorization.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { LoginMenuComponent } from './login-menu/login-menu.component'; 4 | import { LoginComponent } from './login/login.component'; 5 | import { LogoutComponent } from './logout/logout.component'; 6 | import { RouterModule } from '@angular/router'; 7 | import { ApplicationPaths } from './api-authorization.constants'; 8 | import { HttpClientModule } from '@angular/common/http'; 9 | 10 | @NgModule({ 11 | imports: [ 12 | CommonModule, 13 | HttpClientModule, 14 | RouterModule.forChild( 15 | [ 16 | { path: ApplicationPaths.Register, component: LoginComponent }, 17 | { path: ApplicationPaths.Profile, component: LoginComponent }, 18 | { path: ApplicationPaths.Login, component: LoginComponent }, 19 | { path: ApplicationPaths.LoginFailed, component: LoginComponent }, 20 | { path: ApplicationPaths.LoginCallback, component: LoginComponent }, 21 | { path: ApplicationPaths.LogOut, component: LogoutComponent }, 22 | { path: ApplicationPaths.LoggedOut, component: LogoutComponent }, 23 | { path: ApplicationPaths.LogOutCallback, component: LogoutComponent } 24 | ] 25 | ) 26 | ], 27 | declarations: [LoginMenuComponent, LoginComponent, LogoutComponent], 28 | exports: [LoginMenuComponent, LoginComponent, LogoutComponent] 29 | }) 30 | export class ApiAuthorizationModule { } 31 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/authorize.guard.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, inject } from '@angular/core/testing'; 2 | 3 | import { AuthorizeGuard } from './authorize.guard'; 4 | 5 | describe('AuthorizeGuard', () => { 6 | beforeEach(() => { 7 | TestBed.configureTestingModule({ 8 | providers: [AuthorizeGuard] 9 | }); 10 | }); 11 | 12 | it('should ...', inject([AuthorizeGuard], (guard: AuthorizeGuard) => { 13 | expect(guard).toBeTruthy(); 14 | })); 15 | }); 16 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/authorize.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import { AuthorizeService } from './authorize.service'; 5 | import { tap } from 'rxjs/operators'; 6 | import { ApplicationPaths, QueryParameterNames } from './api-authorization.constants'; 7 | 8 | @Injectable({ 9 | providedIn: 'root' 10 | }) 11 | export class AuthorizeGuard implements CanActivate { 12 | constructor(private authorize: AuthorizeService, private router: Router) { 13 | } 14 | canActivate( 15 | _next: ActivatedRouteSnapshot, 16 | state: RouterStateSnapshot): Observable | Promise | boolean { 17 | return this.authorize.isAuthenticated() 18 | .pipe(tap(isAuthenticated => this.handleAuthorization(isAuthenticated, state))); 19 | } 20 | 21 | private handleAuthorization(isAuthenticated: boolean, state: RouterStateSnapshot) { 22 | if (!isAuthenticated) { 23 | this.router.navigate(ApplicationPaths.LoginPathComponents, { 24 | queryParams: { 25 | [QueryParameterNames.ReturnUrl]: state.url 26 | } 27 | }); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/authorize.interceptor.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, inject } from '@angular/core/testing'; 2 | 3 | import { AuthorizeInterceptor } from './authorize.interceptor'; 4 | 5 | describe('AuthorizeInterceptor', () => { 6 | beforeEach(() => { 7 | TestBed.configureTestingModule({ 8 | providers: [AuthorizeInterceptor] 9 | }); 10 | }); 11 | 12 | it('should be created', inject([AuthorizeInterceptor], (service: AuthorizeInterceptor) => { 13 | expect(service).toBeTruthy(); 14 | })); 15 | }); 16 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/authorize.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | import { AuthorizeService } from './authorize.service'; 5 | import { mergeMap } from 'rxjs/operators'; 6 | 7 | @Injectable({ 8 | providedIn: 'root' 9 | }) 10 | export class AuthorizeInterceptor implements HttpInterceptor { 11 | constructor(private authorize: AuthorizeService) { } 12 | 13 | intercept(req: HttpRequest, next: HttpHandler): Observable> { 14 | return this.authorize.getAccessToken() 15 | .pipe(mergeMap(token => this.processRequestWithToken(token, req, next))); 16 | } 17 | 18 | // Checks if there is an access_token available in the authorize service 19 | // and adds it to the request in case it's targeted at the same origin as the 20 | // single page application. 21 | private processRequestWithToken(token: string, req: HttpRequest, next: HttpHandler) { 22 | if (!!token && this.isSameOriginUrl(req)) { 23 | req = req.clone({ 24 | setHeaders: { 25 | Authorization: `Bearer ${token}` 26 | } 27 | }); 28 | } 29 | 30 | return next.handle(req); 31 | } 32 | 33 | private isSameOriginUrl(req: any) { 34 | // It's an absolute url with the same origin. 35 | if (req.url.startsWith(`${window.location.origin}/`)) { 36 | return true; 37 | } 38 | 39 | // It's a protocol relative url with the same origin. 40 | // For example: //www.example.com/api/Products 41 | if (req.url.startsWith(`//${window.location.host}/`)) { 42 | return true; 43 | } 44 | 45 | // It's a relative url like /api/Products 46 | if (/^\/[^\/].*/.test(req.url)) { 47 | return true; 48 | } 49 | 50 | // It's an absolute or protocol relative url that 51 | // doesn't have the same origin. 52 | return false; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/authorize.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, inject } from '@angular/core/testing'; 2 | 3 | import { AuthorizeService } from './authorize.service'; 4 | 5 | describe('AuthorizeService', () => { 6 | beforeEach(() => { 7 | TestBed.configureTestingModule({ 8 | providers: [AuthorizeService] 9 | }); 10 | }); 11 | 12 | it('should be created', inject([AuthorizeService], (service: AuthorizeService) => { 13 | expect(service).toBeTruthy(); 14 | })); 15 | }); 16 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/login-menu/login-menu.component.html: -------------------------------------------------------------------------------- 1 | 9 | 17 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/login-menu/login-menu.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/CleanArchitecture/35b490110f699c2ba427fd6b49e98babc16390c0/src/WebUI/ClientApp/src/api-authorization/login-menu/login-menu.component.scss -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/login-menu/login-menu.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { LoginMenuComponent } from './login-menu.component'; 4 | 5 | describe('LoginMenuComponent', () => { 6 | let component: LoginMenuComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ LoginMenuComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(LoginMenuComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/login-menu/login-menu.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthorizeService } from '../authorize.service'; 3 | import { Observable } from 'rxjs'; 4 | import { map, tap } from 'rxjs/operators'; 5 | 6 | @Component({ 7 | selector: 'app-login-menu', 8 | templateUrl: './login-menu.component.html', 9 | styleUrls: ['./login-menu.component.scss'] 10 | }) 11 | export class LoginMenuComponent implements OnInit { 12 | public isAuthenticated: Observable; 13 | public userName: Observable; 14 | 15 | constructor(private authorizeService: AuthorizeService) { } 16 | 17 | ngOnInit() { 18 | this.isAuthenticated = this.authorizeService.isAuthenticated(); 19 | this.userName = this.authorizeService.getUser().pipe(map(u => u && u.name)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/login/login.component.html: -------------------------------------------------------------------------------- 1 |

{{ message | async }}

-------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/login/login.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/CleanArchitecture/35b490110f699c2ba427fd6b49e98babc16390c0/src/WebUI/ClientApp/src/api-authorization/login/login.component.scss -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/login/login.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { LoginComponent } from './login.component'; 4 | 5 | describe('LoginComponent', () => { 6 | let component: LoginComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ LoginComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(LoginComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthorizeService, AuthenticationResultStatus } from '../authorize.service'; 3 | import { ActivatedRoute, Router } from '@angular/router'; 4 | import { BehaviorSubject } from 'rxjs'; 5 | import { LoginActions, QueryParameterNames, ApplicationPaths, ReturnUrlType } from '../api-authorization.constants'; 6 | 7 | // The main responsibility of this component is to handle the user's login process. 8 | // This is the starting point for the login process. Any component that needs to authenticate 9 | // a user can simply perform a redirect to this component with a returnUrl query parameter and 10 | // let the component perform the login and return back to the return url. 11 | @Component({ 12 | selector: 'app-login', 13 | templateUrl: './login.component.html', 14 | styleUrls: ['./login.component.scss'] 15 | }) 16 | export class LoginComponent implements OnInit { 17 | public message = new BehaviorSubject(null); 18 | 19 | constructor( 20 | private authorizeService: AuthorizeService, 21 | private activatedRoute: ActivatedRoute, 22 | private router: Router) { } 23 | 24 | async ngOnInit() { 25 | const action = this.activatedRoute.snapshot.url[1]; 26 | switch (action.path) { 27 | case LoginActions.Login: 28 | await this.login(this.getReturnUrl()); 29 | break; 30 | case LoginActions.LoginCallback: 31 | await this.processLoginCallback(); 32 | break; 33 | case LoginActions.LoginFailed: 34 | const message = this.activatedRoute.snapshot.queryParamMap.get(QueryParameterNames.Message); 35 | this.message.next(message); 36 | break; 37 | case LoginActions.Profile: 38 | this.redirectToProfile(); 39 | break; 40 | case LoginActions.Register: 41 | this.redirectToRegister(); 42 | break; 43 | default: 44 | throw new Error(`Invalid action '${action}'`); 45 | } 46 | } 47 | 48 | 49 | private async login(returnUrl: string): Promise { 50 | const state: INavigationState = { returnUrl }; 51 | const result = await this.authorizeService.signIn(state); 52 | this.message.next(undefined); 53 | switch (result.status) { 54 | case AuthenticationResultStatus.Redirect: 55 | break; 56 | case AuthenticationResultStatus.Success: 57 | await this.navigateToReturnUrl(returnUrl); 58 | break; 59 | case AuthenticationResultStatus.Fail: 60 | await this.router.navigate(ApplicationPaths.LoginFailedPathComponents, { 61 | queryParams: { [QueryParameterNames.Message]: result.message } 62 | }); 63 | break; 64 | default: 65 | throw new Error(`Invalid status result ${(result as any).status}.`); 66 | } 67 | } 68 | 69 | private async processLoginCallback(): Promise { 70 | const url = window.location.href; 71 | const result = await this.authorizeService.completeSignIn(url); 72 | switch (result.status) { 73 | case AuthenticationResultStatus.Redirect: 74 | // There should not be any redirects as completeSignIn never redirects. 75 | throw new Error('Should not redirect.'); 76 | case AuthenticationResultStatus.Success: 77 | await this.navigateToReturnUrl(this.getReturnUrl(result.state)); 78 | break; 79 | case AuthenticationResultStatus.Fail: 80 | this.message.next(result.message); 81 | break; 82 | } 83 | } 84 | 85 | private redirectToRegister(): any { 86 | this.redirectToApiAuthorizationPath( 87 | `${ApplicationPaths.IdentityRegisterPath}?returnUrl=${encodeURI('/' + ApplicationPaths.Login)}`); 88 | } 89 | 90 | private redirectToProfile(): void { 91 | this.redirectToApiAuthorizationPath(ApplicationPaths.IdentityManagePath); 92 | } 93 | 94 | private async navigateToReturnUrl(returnUrl: string) { 95 | // It's important that we do a replace here so that we remove the callback uri with the 96 | // fragment containing the tokens from the browser history. 97 | await this.router.navigateByUrl(returnUrl, { 98 | replaceUrl: true 99 | }); 100 | } 101 | 102 | private getReturnUrl(state?: INavigationState): string { 103 | const fromQuery = (this.activatedRoute.snapshot.queryParams as INavigationState).returnUrl; 104 | // If the url is comming from the query string, check that is either 105 | // a relative url or an absolute url 106 | if (fromQuery && 107 | !(fromQuery.startsWith(`${window.location.origin}/`) || 108 | /\/[^\/].*/.test(fromQuery))) { 109 | // This is an extra check to prevent open redirects. 110 | throw new Error('Invalid return url. The return url needs to have the same origin as the current page.'); 111 | } 112 | return (state && state.returnUrl) || 113 | fromQuery || 114 | ApplicationPaths.DefaultLoginRedirectPath; 115 | } 116 | 117 | private redirectToApiAuthorizationPath(apiAuthorizationPath: string) { 118 | // It's important that we do a replace here so that when the user hits the back arrow on the 119 | // browser they get sent back to where it was on the app instead of to an endpoint on this 120 | // component. 121 | const redirectUrl = `${window.location.origin}${apiAuthorizationPath}`; 122 | window.location.replace(redirectUrl); 123 | } 124 | } 125 | 126 | interface INavigationState { 127 | [ReturnUrlType]: string; 128 | } 129 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/logout/logout.component.html: -------------------------------------------------------------------------------- 1 |

{{ message | async }}

-------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/logout/logout.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/CleanArchitecture/35b490110f699c2ba427fd6b49e98babc16390c0/src/WebUI/ClientApp/src/api-authorization/logout/logout.component.scss -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/logout/logout.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { LogoutComponent } from './logout.component'; 4 | 5 | describe('LogoutComponent', () => { 6 | let component: LogoutComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ LogoutComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(LogoutComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/api-authorization/logout/logout.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthenticationResultStatus, AuthorizeService } from '../authorize.service'; 3 | import { BehaviorSubject } from 'rxjs'; 4 | import { ActivatedRoute, Router } from '@angular/router'; 5 | import { take } from 'rxjs/operators'; 6 | import { LogoutActions, ApplicationPaths, ReturnUrlType } from '../api-authorization.constants'; 7 | 8 | // The main responsibility of this component is to handle the user's logout process. 9 | // This is the starting point for the logout process, which is usually initiated when a 10 | // user clicks on the logout button on the LoginMenu component. 11 | @Component({ 12 | selector: 'app-logout', 13 | templateUrl: './logout.component.html', 14 | styleUrls: ['./logout.component.scss'] 15 | }) 16 | export class LogoutComponent implements OnInit { 17 | public message = new BehaviorSubject(null); 18 | 19 | constructor( 20 | private authorizeService: AuthorizeService, 21 | private activatedRoute: ActivatedRoute, 22 | private router: Router) { } 23 | 24 | async ngOnInit() { 25 | const action = this.activatedRoute.snapshot.url[1]; 26 | switch (action.path) { 27 | case LogoutActions.Logout: 28 | if (!!window.history.state.local) { 29 | await this.logout(this.getReturnUrl()); 30 | } else { 31 | // This prevents regular links to /authentication/logout from triggering a logout 32 | this.message.next('The logout was not initiated from within the page.'); 33 | } 34 | 35 | break; 36 | case LogoutActions.LogoutCallback: 37 | await this.processLogoutCallback(); 38 | break; 39 | case LogoutActions.LoggedOut: 40 | this.message.next('You successfully logged out!'); 41 | break; 42 | default: 43 | throw new Error(`Invalid action '${action}'`); 44 | } 45 | } 46 | 47 | private async logout(returnUrl: string): Promise { 48 | const state: INavigationState = { returnUrl }; 49 | const isauthenticated = await this.authorizeService.isAuthenticated().pipe( 50 | take(1) 51 | ).toPromise(); 52 | if (isauthenticated) { 53 | const result = await this.authorizeService.signOut(state); 54 | switch (result.status) { 55 | case AuthenticationResultStatus.Redirect: 56 | break; 57 | case AuthenticationResultStatus.Success: 58 | await this.navigateToReturnUrl(returnUrl); 59 | break; 60 | case AuthenticationResultStatus.Fail: 61 | this.message.next(result.message); 62 | break; 63 | default: 64 | throw new Error('Invalid authentication result status.'); 65 | } 66 | } else { 67 | this.message.next('You successfully logged out!'); 68 | } 69 | } 70 | 71 | private async processLogoutCallback(): Promise { 72 | const url = window.location.href; 73 | const result = await this.authorizeService.completeSignOut(url); 74 | switch (result.status) { 75 | case AuthenticationResultStatus.Redirect: 76 | // There should not be any redirects as the only time completeAuthentication finishes 77 | // is when we are doing a redirect sign in flow. 78 | throw new Error('Should not redirect.'); 79 | case AuthenticationResultStatus.Success: 80 | await this.navigateToReturnUrl(this.getReturnUrl(result.state)); 81 | break; 82 | case AuthenticationResultStatus.Fail: 83 | this.message.next(result.message); 84 | break; 85 | default: 86 | throw new Error('Invalid authentication result status.'); 87 | } 88 | } 89 | 90 | private async navigateToReturnUrl(returnUrl: string) { 91 | await this.router.navigateByUrl(returnUrl, { 92 | replaceUrl: true 93 | }); 94 | } 95 | 96 | private getReturnUrl(state?: INavigationState): string { 97 | const fromQuery = (this.activatedRoute.snapshot.queryParams as INavigationState).returnUrl; 98 | // If the url is comming from the query string, check that is either 99 | // a relative url or an absolute url 100 | if (fromQuery && 101 | !(fromQuery.startsWith(`${window.location.origin}/`) || 102 | /\/[^\/].*/.test(fromQuery))) { 103 | // This is an extra check to prevent open redirects. 104 | throw new Error('Invalid return url. The return url needs to have the same origin as the current page.'); 105 | } 106 | return (state && state.returnUrl) || 107 | fromQuery || 108 | ApplicationPaths.LoggedOut; 109 | } 110 | } 111 | 112 | interface INavigationState { 113 | [ReturnUrlType]: string; 114 | } 115 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | import { AuthorizeGuard } from 'src/api-authorization/authorize.guard'; 4 | import { CounterComponent } from './counter/counter.component'; 5 | import { FetchDataComponent } from './fetch-data/fetch-data.component'; 6 | import { HomeComponent } from './home/home.component'; 7 | import { DevEnvGuard } from './nav-menu/dev-env.guard'; 8 | import { TodoComponent } from './todo/todo.component'; 9 | import { TokenComponent } from './token/token.component'; 10 | 11 | export const routes: Routes = [ 12 | 13 | { path: 'counter', component: CounterComponent }, 14 | { path: 'fetch-data', component: FetchDataComponent }, 15 | { path: '', component: HomeComponent, pathMatch: 'full' }, 16 | { path: 'todo', component: TodoComponent, canActivate: [AuthorizeGuard] }, 17 | { path: 'token', component: TokenComponent, canActivate: [AuthorizeGuard, DevEnvGuard] } 18 | ]; 19 | 20 | @NgModule({ 21 | imports: [RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })], 22 | exports: [RouterModule], 23 | }) 24 | export class AppRoutingModule {} 25 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
6 | 7 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | templateUrl: './app.component.html' 6 | }) 7 | export class AppComponent { 8 | title = 'app'; 9 | } 10 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | import { FormsModule } from '@angular/forms'; 4 | import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 5 | import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; 6 | 7 | import { AppComponent } from './app.component'; 8 | import { NavMenuComponent } from './nav-menu/nav-menu.component'; 9 | import { HomeComponent } from './home/home.component'; 10 | import { CounterComponent } from './counter/counter.component'; 11 | import { FetchDataComponent } from './fetch-data/fetch-data.component'; 12 | import { TodoComponent } from './todo/todo.component'; 13 | import { ApiAuthorizationModule } from 'src/api-authorization/api-authorization.module'; 14 | import { AuthorizeInterceptor } from 'src/api-authorization/authorize.interceptor'; 15 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 16 | import { ModalModule } from 'ngx-bootstrap/modal'; 17 | import { AppRoutingModule } from './app-routing.module'; 18 | import { TokenComponent } from './token/token.component'; 19 | 20 | @NgModule({ 21 | declarations: [ 22 | AppComponent, 23 | NavMenuComponent, 24 | HomeComponent, 25 | CounterComponent, 26 | FetchDataComponent, 27 | TodoComponent, 28 | TokenComponent 29 | ], 30 | imports: [ 31 | BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }), 32 | FontAwesomeModule, 33 | HttpClientModule, 34 | FormsModule, 35 | ApiAuthorizationModule, 36 | AppRoutingModule, 37 | BrowserAnimationsModule, 38 | ModalModule.forRoot() 39 | ], 40 | providers: [ 41 | { provide: HTTP_INTERCEPTORS, useClass: AuthorizeInterceptor, multi: true }, 42 | ], 43 | bootstrap: [AppComponent] 44 | }) 45 | export class AppModule { } 46 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/app.server.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { ServerModule } from '@angular/platform-server'; 3 | import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader'; 4 | import { AppComponent } from './app.component'; 5 | import { AppModule } from './app.module'; 6 | 7 | @NgModule({ 8 | imports: [AppModule, ServerModule, ModuleMapLoaderModule], 9 | bootstrap: [AppComponent] 10 | }) 11 | export class AppServerModule { } 12 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/counter/counter.component.html: -------------------------------------------------------------------------------- 1 |

Counter

2 | 3 |

This is a simple example of an Angular component.

4 | 5 |

Current count: {{ currentCount }}

6 | 7 | 8 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/counter/counter.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { CounterComponent } from './counter.component'; 4 | 5 | describe('CounterComponent', () => { 6 | let component: CounterComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ CounterComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(CounterComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should display a title', waitForAsync(() => { 23 | const titleText = fixture.nativeElement.querySelector('h1').textContent; 24 | expect(titleText).toEqual('Counter'); 25 | })); 26 | 27 | it('should start with count 0, then increments by 1 when clicked', waitForAsync(() => { 28 | const countElement = fixture.nativeElement.querySelector('strong'); 29 | expect(countElement.textContent).toEqual('0'); 30 | 31 | const incrementButton = fixture.nativeElement.querySelector('button'); 32 | incrementButton.click(); 33 | fixture.detectChanges(); 34 | expect(countElement.textContent).toEqual('1'); 35 | })); 36 | }); 37 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/counter/counter.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-counter-component', 5 | templateUrl: './counter.component.html' 6 | }) 7 | export class CounterComponent { 8 | public currentCount = 0; 9 | 10 | public incrementCounter() { 11 | this.currentCount++; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/fetch-data/fetch-data.component.html: -------------------------------------------------------------------------------- 1 |

Weather forecast

2 | 3 |

This component demonstrates fetching data from the server.

4 | 5 |

Loading...

6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
DateTemp. (C)Temp. (F)Summary
{{ forecast.date }}{{ forecast.temperatureC }}{{ forecast.temperatureF }}{{ forecast.summary }}
25 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/fetch-data/fetch-data.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { WeatherForecastClient, WeatherForecast } from '../web-api-client'; 3 | 4 | @Component({ 5 | selector: 'app-fetch-data', 6 | templateUrl: './fetch-data.component.html' 7 | }) 8 | export class FetchDataComponent { 9 | public forecasts: WeatherForecast[]; 10 | 11 | constructor(private client: WeatherForecastClient) { 12 | client.get().subscribe(result => { 13 | this.forecasts = result; 14 | }, error => console.error(error)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |

Hello, world!

2 |

Welcome to your new single-page application, built with:

3 | 8 |

To help you get started, we've also set up:

9 |
    10 |
  • Client-side navigation. For example, click Counter then Back to return here.
  • 11 |
  • Angular CLI integration. In development mode, there's no need to run ng serve. It runs in the background automatically, so your client-side resources are dynamically built on demand and the page refreshes when you modify any file.
  • 12 |
  • Efficient production builds. In production mode, development-time features are disabled, and your dotnet publish configuration automatically invokes ng build to produce minified, ahead-of-time compiled JavaScript files.
  • 13 |
14 |

The ClientApp subdirectory is a standard Angular CLI application. If you open a command prompt in that directory, you can run any ng command (e.g., ng test), or use npm to install extra packages into it.

15 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-home', 5 | templateUrl: './home.component.html', 6 | }) 7 | export class HomeComponent { 8 | } 9 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/nav-menu/dev-env.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from "@angular/core"; 2 | import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from "@angular/router"; 3 | import { Observable } from "rxjs"; 4 | import { environment } from "src/environments/environment"; 5 | 6 | @Injectable({ 7 | providedIn: 'root' 8 | }) 9 | export class DevEnvGuard implements CanActivate { 10 | constructor() {} 11 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable | Promise { 12 | return !environment.production; 13 | } 14 | } -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/nav-menu/nav-menu.component.html: -------------------------------------------------------------------------------- 1 |
2 | 60 |
61 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/nav-menu/nav-menu.component.scss: -------------------------------------------------------------------------------- 1 | a.navbar-brand { 2 | white-space: normal; 3 | text-align: center; 4 | word-break: break-all; 5 | } 6 | 7 | html { 8 | font-size: 14px; 9 | } 10 | @media (min-width: 768px) { 11 | html { 12 | font-size: 16px; 13 | } 14 | } 15 | 16 | .box-shadow { 17 | box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05); 18 | } 19 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/nav-menu/nav-menu.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { environment } from 'src/environments/environment'; 3 | 4 | @Component({ 5 | selector: 'app-nav-menu', 6 | templateUrl: './nav-menu.component.html', 7 | styleUrls: ['./nav-menu.component.scss'] 8 | }) 9 | export class NavMenuComponent implements OnInit { 10 | isExpanded = false; 11 | 12 | isProduction: boolean = false; 13 | 14 | ngOnInit() : void { 15 | this.isProduction = environment.production; 16 | } 17 | 18 | collapse() { 19 | this.isExpanded = false; 20 | } 21 | 22 | toggle() { 23 | this.isExpanded = !this.isExpanded; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/todo/todo.component.scss: -------------------------------------------------------------------------------- 1 | #listOptions { 2 | margin-right: 10px; 3 | } 4 | 5 | #todo-items { 6 | .item-input-control { 7 | border: 0; 8 | box-shadow: none; 9 | background-color: transparent; 10 | } 11 | 12 | .done-todo { 13 | text-decoration: line-through; 14 | } 15 | 16 | .todo-item-title { 17 | padding-top: 8px; 18 | } 19 | 20 | .list-group-item { 21 | padding-top: 8px; 22 | padding-bottom: 8px; 23 | 24 | .btn-xs { 25 | padding: 0; 26 | } 27 | } 28 | 29 | .todo-item-checkbox { 30 | padding-top: 8px; 31 | } 32 | 33 | .todo-item-commands { 34 | padding-top: 4px; 35 | } 36 | } 37 | 38 | .modal-footer { 39 | display: block; 40 | } 41 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/token/token.component.html: -------------------------------------------------------------------------------- 1 |

JWT

2 | 3 |
4 |

5 | This component demonstrates interacting with the authorization service to 6 | retrieve your 7 | JSON web token (JWT). 8 |

9 |
10 |
11 |

{{ token }}

12 |
13 |
14 |
15 |

16 | 19 |

20 |

21 | Copied! 22 |

23 |
24 | 25 |
26 | 27 |

28 | Something went wrong getting your access token from the auth service. Please 29 | try again. 30 |

31 |
32 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/app/token/token.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from "@angular/core"; 2 | import { AuthorizeService } from "../../api-authorization/authorize.service"; 3 | 4 | import { faCopy } from "@fortawesome/free-solid-svg-icons"; 5 | 6 | @Component({ 7 | selector: "app-token-component", 8 | templateUrl: "./token.component.html", 9 | }) 10 | export class TokenComponent implements OnInit { 11 | token: string; 12 | isError: boolean; 13 | isCopied: boolean; 14 | 15 | faCopy = faCopy; 16 | 17 | constructor(private authorizeService: AuthorizeService) {} 18 | 19 | ngOnInit(): void { 20 | this.isCopied = false; 21 | this.authorizeService.getAccessToken().subscribe( 22 | (t) => { 23 | this.token = "Bearer " + t; 24 | this.isError = false; 25 | }, 26 | (err) => { 27 | this.isError = true; 28 | } 29 | ); 30 | } 31 | 32 | copyToClipboard(): void { 33 | const selBox = document.createElement("textarea"); 34 | selBox.style.position = "fixed"; 35 | selBox.style.left = "0"; 36 | selBox.style.top = "0"; 37 | selBox.style.opacity = "0"; 38 | selBox.value = this.token; 39 | document.body.appendChild(selBox); 40 | selBox.focus(); 41 | selBox.select(); 42 | document.execCommand("copy"); 43 | document.body.removeChild(selBox); 44 | this.isCopied = true; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/CleanArchitecture/35b490110f699c2ba427fd6b49e98babc16390c0/src/WebUI/ClientApp/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false 7 | }; 8 | 9 | /* 10 | * In development mode, to ignore zone related error stack frames such as 11 | * `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can 12 | * import the following file, but please comment it out in production mode 13 | * because it will have performance impact when throw error 14 | */ 15 | // import 'zone.js/plugins/zone-error'; // Included with Angular CLI. 16 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CleanArchitecture 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, '../coverage'), 20 | reports: ['html', 'lcovonly'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false 30 | }); 31 | }; 32 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | export function getBaseUrl() { 8 | return document.getElementsByTagName('base')[0].href; 9 | } 10 | 11 | const providers = [ 12 | { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] } 13 | ]; 14 | 15 | if (environment.production) { 16 | enableProdMode(); 17 | } 18 | 19 | platformBrowserDynamic(providers).bootstrapModule(AppModule) 20 | .catch(err => console.log(err)); 21 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags.ts'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/styles.scss: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | 3 | /* Provide sufficient contrast against white background */ 4 | a { 5 | color: #0366d6; 6 | } 7 | 8 | code { 9 | color: #e01a76; 10 | } 11 | 12 | .btn-primary { 13 | color: #fff; 14 | background-color: #1b6ec2; 15 | border-color: #1861ac; 16 | } 17 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "types": [] 6 | }, 7 | "files": [ 8 | "main.ts", 9 | "polyfills.ts" 10 | ], 11 | "include": [ 12 | "src/**/*.d.ts" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/tsconfig.server.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "target": "es2016" 5 | }, 6 | "angularCompilerOptions": { 7 | "entryModule": "app/app.server.module#AppServerModule" 8 | } , 9 | "files": [ 10 | "main.ts" 11 | ], 12 | "include": [ 13 | "src/**/*.d.ts" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "test.ts", 12 | "polyfills.ts" 13 | ], 14 | "include": [ 15 | "**/*.spec.ts", 16 | "**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/src/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tslint.json", 3 | "rules": { 4 | "directive-selector": [ 5 | true, 6 | "attribute", 7 | "app", 8 | "camelCase" 9 | ], 10 | "component-selector": [ 11 | true, 12 | "element", 13 | "app", 14 | "kebab-case" 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "module": "es2020", 6 | "outDir": "./dist/out-tsc", 7 | "sourceMap": true, 8 | "declaration": false, 9 | "moduleResolution": "node", 10 | "experimentalDecorators": true, 11 | "target": "es2015", 12 | "typeRoots": [ 13 | "node_modules/@types" 14 | ], 15 | "lib": [ 16 | "es2017", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/WebUI/ClientApp/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "deprecation": { 15 | "severity": "warn" 16 | }, 17 | "eofline": true, 18 | "forin": true, 19 | "import-blacklist": [ 20 | true, 21 | "rxjs/Rx" 22 | ], 23 | "import-spacing": true, 24 | "indent": [ 25 | true, 26 | "spaces" 27 | ], 28 | "interface-over-type-literal": true, 29 | "label-position": true, 30 | "max-line-length": [ 31 | true, 32 | 140 33 | ], 34 | "member-access": false, 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-arg": true, 47 | "no-bitwise": true, 48 | "no-console": [ 49 | true, 50 | "debug", 51 | "info", 52 | "time", 53 | "timeEnd", 54 | "trace" 55 | ], 56 | "no-construct": true, 57 | "no-debugger": true, 58 | "no-duplicate-super": true, 59 | "no-empty": false, 60 | "no-empty-interface": true, 61 | "no-eval": true, 62 | "no-inferrable-types": [ 63 | true, 64 | "ignore-params" 65 | ], 66 | "no-misused-new": true, 67 | "no-non-null-assertion": true, 68 | "no-shadowed-variable": true, 69 | "no-string-literal": false, 70 | "no-string-throw": true, 71 | "no-switch-case-fall-through": true, 72 | "no-trailing-whitespace": true, 73 | "no-unnecessary-initializer": true, 74 | "no-unused-expression": true, 75 | "no-var-keyword": true, 76 | "object-literal-sort-keys": false, 77 | "one-line": [ 78 | true, 79 | "check-open-brace", 80 | "check-catch", 81 | "check-else", 82 | "check-whitespace" 83 | ], 84 | "prefer-const": true, 85 | "quotemark": [ 86 | true, 87 | "single" 88 | ], 89 | "radix": true, 90 | "semicolon": [ 91 | true, 92 | "always" 93 | ], 94 | "triple-equals": [ 95 | true, 96 | "allow-null-check" 97 | ], 98 | "typedef-whitespace": [ 99 | true, 100 | { 101 | "call-signature": "nospace", 102 | "index-signature": "nospace", 103 | "parameter": "nospace", 104 | "property-declaration": "nospace", 105 | "variable-declaration": "nospace" 106 | } 107 | ], 108 | "unified-signatures": true, 109 | "variable-name": false, 110 | "whitespace": [ 111 | true, 112 | "check-branch", 113 | "check-decl", 114 | "check-operator", 115 | "check-separator", 116 | "check-type" 117 | ], 118 | "no-output-on-prefix": true, 119 | "no-inputs-metadata-property": true, 120 | "no-outputs-metadata-property": true, 121 | "no-host-metadata-property": true, 122 | "no-input-rename": true, 123 | "no-output-rename": true, 124 | "use-lifecycle-interface": true, 125 | "use-pipe-transform-interface": true, 126 | "component-class-suffix": true, 127 | "directive-class-suffix": true 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/WebUI/Controllers/ApiControllerBase.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | 3 | using Microsoft.AspNetCore.Mvc; 4 | 5 | namespace CleanArchitecture.WebUI.Controllers; 6 | 7 | [ApiController] 8 | [Route("api/[controller]")] 9 | public abstract class ApiControllerBase : ControllerBase 10 | { 11 | private ISender _mediator = null!; 12 | 13 | protected ISender Mediator => _mediator ??= HttpContext.RequestServices.GetRequiredService(); 14 | } 15 | -------------------------------------------------------------------------------- /src/WebUI/Controllers/OidcConfigurationController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.ApiAuthorization.IdentityServer; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace CleanArchitecture.WebUI.Controllers; 5 | 6 | [ApiExplorerSettings(IgnoreApi = true)] 7 | public class OidcConfigurationController : Controller 8 | { 9 | private readonly ILogger logger; 10 | 11 | public OidcConfigurationController(IClientRequestParametersProvider clientRequestParametersProvider, ILogger _logger) 12 | { 13 | ClientRequestParametersProvider = clientRequestParametersProvider; 14 | logger = _logger; 15 | } 16 | 17 | public IClientRequestParametersProvider ClientRequestParametersProvider { get; } 18 | 19 | [HttpGet("_configuration/{clientId}")] 20 | public IActionResult GetClientRequestParameters([FromRoute] string clientId) 21 | { 22 | var parameters = ClientRequestParametersProvider.GetClientParameters(HttpContext, clientId); 23 | return Ok(parameters); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/WebUI/Controllers/TodoItemsController.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Models; 2 | using CleanArchitecture.Application.TodoItems.Commands.CreateTodoItem; 3 | using CleanArchitecture.Application.TodoItems.Commands.DeleteTodoItem; 4 | using CleanArchitecture.Application.TodoItems.Commands.UpdateTodoItem; 5 | using CleanArchitecture.Application.TodoItems.Commands.UpdateTodoItemDetail; 6 | using CleanArchitecture.Application.TodoItems.Queries.GetTodoItemsWithPagination; 7 | using Microsoft.AspNetCore.Authorization; 8 | using Microsoft.AspNetCore.Mvc; 9 | 10 | namespace CleanArchitecture.WebUI.Controllers; 11 | 12 | [Authorize] 13 | public class TodoItemsController : ApiControllerBase 14 | { 15 | [HttpGet] 16 | public async Task>> GetTodoItemsWithPagination([FromQuery] GetTodoItemsWithPaginationQuery query) 17 | { 18 | return await Mediator.Send(query); 19 | } 20 | 21 | [HttpPost] 22 | public async Task> Create(CreateTodoItemCommand command) 23 | { 24 | return await Mediator.Send(command); 25 | } 26 | 27 | [HttpPut("{id}")] 28 | public async Task Update(int id, UpdateTodoItemCommand command) 29 | { 30 | if (id != command.Id) 31 | { 32 | return BadRequest(); 33 | } 34 | 35 | await Mediator.Send(command); 36 | 37 | return NoContent(); 38 | } 39 | 40 | [HttpPut("[action]")] 41 | public async Task UpdateItemDetails(int id, UpdateTodoItemDetailCommand command) 42 | { 43 | if (id != command.Id) 44 | { 45 | return BadRequest(); 46 | } 47 | 48 | await Mediator.Send(command); 49 | 50 | return NoContent(); 51 | } 52 | 53 | [HttpDelete("{id}")] 54 | public async Task Delete(int id) 55 | { 56 | await Mediator.Send(new DeleteTodoItemCommand { Id = id }); 57 | 58 | return NoContent(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/WebUI/Controllers/TodoListsController.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.TodoLists.Commands.CreateTodoList; 2 | using CleanArchitecture.Application.TodoLists.Commands.DeleteTodoList; 3 | using CleanArchitecture.Application.TodoLists.Commands.UpdateTodoList; 4 | using CleanArchitecture.Application.TodoLists.Queries.ExportTodos; 5 | using CleanArchitecture.Application.TodoLists.Queries.GetTodos; 6 | using Microsoft.AspNetCore.Authorization; 7 | using Microsoft.AspNetCore.Mvc; 8 | 9 | namespace CleanArchitecture.WebUI.Controllers; 10 | 11 | [Authorize] 12 | public class TodoListsController : ApiControllerBase 13 | { 14 | [HttpGet] 15 | public async Task> Get() 16 | { 17 | return await Mediator.Send(new GetTodosQuery()); 18 | } 19 | 20 | [HttpGet("{id}")] 21 | public async Task Get(int id) 22 | { 23 | var vm = await Mediator.Send(new ExportTodosQuery { ListId = id }); 24 | 25 | return File(vm.Content, vm.ContentType, vm.FileName); 26 | } 27 | 28 | [HttpPost] 29 | public async Task> Create(CreateTodoListCommand command) 30 | { 31 | return await Mediator.Send(command); 32 | } 33 | 34 | [HttpPut("{id}")] 35 | public async Task Update(int id, UpdateTodoListCommand command) 36 | { 37 | if (id != command.Id) 38 | { 39 | return BadRequest(); 40 | } 41 | 42 | await Mediator.Send(command); 43 | 44 | return NoContent(); 45 | } 46 | 47 | [HttpDelete("{id}")] 48 | public async Task Delete(int id) 49 | { 50 | await Mediator.Send(new DeleteTodoListCommand { Id = id }); 51 | 52 | return NoContent(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/WebUI/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.WeatherForecasts.Queries.GetWeatherForecasts; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace CleanArchitecture.WebUI.Controllers; 5 | 6 | public class WeatherForecastController : ApiControllerBase 7 | { 8 | [HttpGet] 9 | public async Task> Get() 10 | { 11 | return await Mediator.Send(new GetWeatherForecastsQuery()); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/WebUI/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | # This stage is used for VS debugging on Docker 4 | FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base 5 | ENV ASPNETCORE_URLS=https://+:5001;http://+:5000 6 | WORKDIR /app 7 | EXPOSE 5000 8 | EXPOSE 5001 9 | 10 | FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build 11 | RUN curl -sL https://deb.nodesource.com/setup_12.x | bash - 12 | RUN apt install -y nodejs 13 | WORKDIR /src 14 | COPY ["src/WebUI/WebUI.csproj", "src/WebUI/"] 15 | COPY ["src/Application/Application.csproj", "src/Application/"] 16 | COPY ["src/Domain/Domain.csproj", "src/Domain/"] 17 | COPY ["src/Infrastructure/Infrastructure.csproj", "src/Infrastructure/"] 18 | RUN dotnet restore "src/WebUI/WebUI.csproj" 19 | COPY . . 20 | WORKDIR "/src/src/WebUI" 21 | RUN dotnet build "WebUI.csproj" -c Release -o /app/build 22 | 23 | FROM build AS publish 24 | RUN dotnet publish "WebUI.csproj" -c Release -o /app/publish 25 | 26 | FROM base AS final 27 | WORKDIR /app 28 | COPY --from=publish /app/publish . 29 | ENTRYPOINT ["dotnet", "CleanArchitecture.WebUI.dll"] -------------------------------------------------------------------------------- /src/WebUI/Filters/ApiExceptionFilterAttribute.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.AspNetCore.Mvc.Filters; 5 | 6 | namespace CleanArchitecture.WebUI.Filters; 7 | 8 | public class ApiExceptionFilterAttribute : ExceptionFilterAttribute 9 | { 10 | 11 | private readonly IDictionary> _exceptionHandlers; 12 | 13 | public ApiExceptionFilterAttribute() 14 | { 15 | // Register known exception types and handlers. 16 | _exceptionHandlers = new Dictionary> 17 | { 18 | { typeof(ValidationException), HandleValidationException }, 19 | { typeof(NotFoundException), HandleNotFoundException }, 20 | { typeof(UnauthorizedAccessException), HandleUnauthorizedAccessException }, 21 | { typeof(ForbiddenAccessException), HandleForbiddenAccessException }, 22 | }; 23 | } 24 | 25 | public override void OnException(ExceptionContext context) 26 | { 27 | HandleException(context); 28 | 29 | base.OnException(context); 30 | } 31 | 32 | private void HandleException(ExceptionContext context) 33 | { 34 | Type type = context.Exception.GetType(); 35 | if (_exceptionHandlers.ContainsKey(type)) 36 | { 37 | _exceptionHandlers[type].Invoke(context); 38 | return; 39 | } 40 | 41 | if (!context.ModelState.IsValid) 42 | { 43 | HandleInvalidModelStateException(context); 44 | return; 45 | } 46 | 47 | HandleUnknownException(context); 48 | } 49 | 50 | private void HandleValidationException(ExceptionContext context) 51 | { 52 | var exception = (ValidationException)context.Exception; 53 | 54 | var details = new ValidationProblemDetails(exception.Errors) 55 | { 56 | Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1" 57 | }; 58 | 59 | context.Result = new BadRequestObjectResult(details); 60 | 61 | context.ExceptionHandled = true; 62 | } 63 | 64 | private void HandleInvalidModelStateException(ExceptionContext context) 65 | { 66 | var details = new ValidationProblemDetails(context.ModelState) 67 | { 68 | Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1" 69 | }; 70 | 71 | context.Result = new BadRequestObjectResult(details); 72 | 73 | context.ExceptionHandled = true; 74 | } 75 | 76 | private void HandleNotFoundException(ExceptionContext context) 77 | { 78 | var exception = (NotFoundException)context.Exception; 79 | 80 | var details = new ProblemDetails() 81 | { 82 | Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4", 83 | Title = "The specified resource was not found.", 84 | Detail = exception.Message 85 | }; 86 | 87 | context.Result = new NotFoundObjectResult(details); 88 | 89 | context.ExceptionHandled = true; 90 | } 91 | 92 | private void HandleUnauthorizedAccessException(ExceptionContext context) 93 | { 94 | var details = new ProblemDetails 95 | { 96 | Status = StatusCodes.Status401Unauthorized, 97 | Title = "Unauthorized", 98 | Type = "https://tools.ietf.org/html/rfc7235#section-3.1" 99 | }; 100 | 101 | context.Result = new ObjectResult(details) 102 | { 103 | StatusCode = StatusCodes.Status401Unauthorized 104 | }; 105 | 106 | context.ExceptionHandled = true; 107 | } 108 | 109 | private void HandleForbiddenAccessException(ExceptionContext context) 110 | { 111 | var details = new ProblemDetails 112 | { 113 | Status = StatusCodes.Status403Forbidden, 114 | Title = "Forbidden", 115 | Type = "https://tools.ietf.org/html/rfc7231#section-6.5.3" 116 | }; 117 | 118 | context.Result = new ObjectResult(details) 119 | { 120 | StatusCode = StatusCodes.Status403Forbidden 121 | }; 122 | 123 | context.ExceptionHandled = true; 124 | } 125 | 126 | private void HandleUnknownException(ExceptionContext context) 127 | { 128 | var details = new ProblemDetails 129 | { 130 | Status = StatusCodes.Status500InternalServerError, 131 | Title = "An error occurred while processing your request.", 132 | Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1" 133 | }; 134 | 135 | context.Result = new ObjectResult(details) 136 | { 137 | StatusCode = StatusCodes.Status500InternalServerError 138 | }; 139 | 140 | context.ExceptionHandled = true; 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/WebUI/Pages/Error.cshtml: -------------------------------------------------------------------------------- 1 | @page 2 | @model ErrorModel 3 | @{ 4 | ViewData["Title"] = "Error"; 5 | } 6 | 7 |

Error.

8 |

An error occurred while processing your request.

9 | 10 | @if (Model.ShowRequestId) 11 | { 12 |

13 | Request ID: @Model.RequestId 14 |

15 | } 16 | 17 |

Development Mode

18 |

19 | Swapping to the Development environment displays detailed information about the error that occurred. 20 |

21 |

22 | The Development environment shouldn't be enabled for deployed applications. 23 | It can result in displaying sensitive information from exceptions to end users. 24 | For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development 25 | and restarting the app. 26 |

27 | -------------------------------------------------------------------------------- /src/WebUI/Pages/Error.cshtml.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.AspNetCore.Mvc.RazorPages; 5 | 6 | namespace CleanArchitecture.WebUI.Pages; 7 | 8 | [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] 9 | public class ErrorModel : PageModel 10 | { 11 | private readonly ILogger _logger; 12 | 13 | public ErrorModel(ILogger logger) 14 | { 15 | _logger = logger; 16 | } 17 | 18 | public string? RequestId { get; set; } 19 | 20 | public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); 21 | 22 | public void OnGet() 23 | { 24 | RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/WebUI/Pages/Shared/_LoginPartial.cshtml: -------------------------------------------------------------------------------- 1 | @using Microsoft.AspNetCore.Identity 2 | @using CleanArchitecture.Infrastructure.Identity; 3 | @inject SignInManager SignInManager 4 | @inject UserManager UserManager 5 | 6 | @{ 7 | string returnUrl = null; 8 | var query = ViewContext.HttpContext.Request.Query; 9 | if (query.ContainsKey("returnUrl")) 10 | { 11 | returnUrl = query["returnUrl"]; 12 | } 13 | } 14 | 15 | 37 | -------------------------------------------------------------------------------- /src/WebUI/Pages/_ViewImports.cshtml: -------------------------------------------------------------------------------- 1 | @using CleanArchitecture.WebUI 2 | @namespace CleanArchitecture.WebUI.Pages 3 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 4 | -------------------------------------------------------------------------------- /src/WebUI/Program.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Infrastructure.Identity; 2 | using CleanArchitecture.Infrastructure.Persistence; 3 | using Microsoft.AspNetCore.Identity; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace CleanArchitecture.WebUI; 7 | 8 | public class Program 9 | { 10 | public async static Task Main(string[] args) 11 | { 12 | var host = CreateHostBuilder(args).Build(); 13 | 14 | using (var scope = host.Services.CreateScope()) 15 | { 16 | var services = scope.ServiceProvider; 17 | 18 | try 19 | { 20 | var context = services.GetRequiredService(); 21 | 22 | if (context.Database.IsSqlServer()) 23 | { 24 | context.Database.Migrate(); 25 | } 26 | 27 | var userManager = services.GetRequiredService>(); 28 | var roleManager = services.GetRequiredService>(); 29 | 30 | await ApplicationDbContextSeed.SeedDefaultUserAsync(userManager, roleManager); 31 | await ApplicationDbContextSeed.SeedSampleDataAsync(context); 32 | } 33 | catch (Exception ex) 34 | { 35 | var logger = scope.ServiceProvider.GetRequiredService>(); 36 | 37 | logger.LogError(ex, "An error occurred while migrating or seeding the database."); 38 | 39 | throw; 40 | } 41 | } 42 | 43 | await host.RunAsync(); 44 | } 45 | 46 | public static IHostBuilder CreateHostBuilder(string[] args) => 47 | Host.CreateDefaultBuilder(args) 48 | .ConfigureWebHostDefaults(webBuilder => 49 | webBuilder.UseStartup()); 50 | } 51 | -------------------------------------------------------------------------------- /src/WebUI/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:61846", 7 | "sslPort": 44312 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "DOTNET_ENVIRONMENT": "Development" 16 | } 17 | }, 18 | "CleanArchitecture.WebUI": { 19 | "commandName": "Project", 20 | "launchBrowser": true, 21 | "environmentVariables": { 22 | "DOTNET_ENVIRONMENT": "Development" 23 | }, 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000" 25 | }, 26 | "Docker": { 27 | "commandName": "Docker", 28 | "launchBrowser": true, 29 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}", 30 | "environmentVariables": { 31 | "UseInMemoryDatabase": "true", 32 | "ASPNETCORE_HTTPS_PORT": "5001", 33 | "ASPNETCORE_URLS": "https://+:5001;http://+:5000" 34 | }, 35 | "httpPort": 5000, 36 | "useSSL": true, 37 | "sslPort": 5001 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/WebUI/Services/CurrentUserService.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | 3 | using CleanArchitecture.Application.Common.Interfaces; 4 | 5 | namespace CleanArchitecture.WebUI.Services; 6 | 7 | public class CurrentUserService : ICurrentUserService 8 | { 9 | private readonly IHttpContextAccessor _httpContextAccessor; 10 | 11 | public CurrentUserService(IHttpContextAccessor httpContextAccessor) 12 | { 13 | _httpContextAccessor = httpContextAccessor; 14 | } 15 | 16 | public string? UserId => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier); 17 | } 18 | -------------------------------------------------------------------------------- /src/WebUI/Startup.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application; 2 | using CleanArchitecture.Application.Common.Interfaces; 3 | using CleanArchitecture.Infrastructure; 4 | using CleanArchitecture.Infrastructure.Persistence; 5 | using CleanArchitecture.WebUI.Filters; 6 | using CleanArchitecture.WebUI.Services; 7 | using FluentValidation.AspNetCore; 8 | using Microsoft.AspNetCore.Mvc; 9 | using NSwag; 10 | using NSwag.Generation.Processors.Security; 11 | 12 | namespace CleanArchitecture.WebUI; 13 | 14 | public class Startup 15 | { 16 | public Startup(IConfiguration configuration) 17 | { 18 | Configuration = configuration; 19 | } 20 | 21 | public IConfiguration Configuration { get; } 22 | 23 | // This method gets called by the runtime. Use this method to add services to the container. 24 | public void ConfigureServices(IServiceCollection services) 25 | { 26 | services.AddApplication(); 27 | services.AddInfrastructure(Configuration); 28 | 29 | services.AddDatabaseDeveloperPageExceptionFilter(); 30 | 31 | services.AddSingleton(); 32 | 33 | services.AddHttpContextAccessor(); 34 | 35 | services.AddHealthChecks() 36 | .AddDbContextCheck(); 37 | 38 | services.AddControllersWithViews(options => 39 | options.Filters.Add()) 40 | .AddFluentValidation(x => x.AutomaticValidationEnabled = false); 41 | 42 | services.AddRazorPages(); 43 | 44 | // Customise default API behaviour 45 | services.Configure(options => 46 | options.SuppressModelStateInvalidFilter = true); 47 | 48 | // In production, the Angular files will be served from this directory 49 | services.AddSpaStaticFiles(configuration => 50 | configuration.RootPath = "ClientApp/dist"); 51 | 52 | services.AddOpenApiDocument(configure => 53 | { 54 | configure.Title = "CleanArchitecture API"; 55 | configure.AddSecurity("JWT", Enumerable.Empty(), new OpenApiSecurityScheme 56 | { 57 | Type = OpenApiSecuritySchemeType.ApiKey, 58 | Name = "Authorization", 59 | In = OpenApiSecurityApiKeyLocation.Header, 60 | Description = "Type into the textbox: Bearer {your JWT token}." 61 | }); 62 | 63 | configure.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("JWT")); 64 | }); 65 | } 66 | 67 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 68 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 69 | { 70 | if (env.IsDevelopment()) 71 | { 72 | app.UseDeveloperExceptionPage(); 73 | app.UseMigrationsEndPoint(); 74 | } 75 | else 76 | { 77 | app.UseExceptionHandler("/Error"); 78 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 79 | app.UseHsts(); 80 | } 81 | 82 | app.UseHealthChecks("/health"); 83 | app.UseHttpsRedirection(); 84 | app.UseStaticFiles(); 85 | if (!env.IsDevelopment()) 86 | { 87 | app.UseSpaStaticFiles(); 88 | } 89 | 90 | app.UseSwaggerUi3(settings => 91 | { 92 | settings.Path = "/api"; 93 | settings.DocumentPath = "/api/specification.json"; 94 | }); 95 | 96 | app.UseRouting(); 97 | 98 | app.UseAuthentication(); 99 | app.UseIdentityServer(); 100 | app.UseAuthorization(); 101 | app.UseEndpoints(endpoints => 102 | { 103 | endpoints.MapControllerRoute( 104 | name: "default", 105 | pattern: "{controller}/{action=Index}/{id?}"); 106 | endpoints.MapRazorPages(); 107 | }); 108 | 109 | app.UseSpa(spa => 110 | { 111 | // To learn more about options for serving an Angular SPA from ASP.NET Core, 112 | // see https://go.microsoft.com/fwlink/?linkid=864501 113 | 114 | spa.Options.SourcePath = "ClientApp"; 115 | 116 | if (env.IsDevelopment()) 117 | { 118 | //spa.UseAngularCliServer(npmScript: "start"); 119 | spa.UseProxyToSpaDevelopmentServer(Configuration["SpaBaseUrl"] ?? "http://localhost:4200"); 120 | } 121 | }); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/WebUI/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | }, 9 | "IdentityServer": { 10 | "Key": { 11 | "Type": "Development" 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/WebUI/appsettings.Production.json: -------------------------------------------------------------------------------- 1 | { 2 | "UseInMemoryDatabase": false, 3 | "Logging": { 4 | "LogLevel": { 5 | "Default": "Debug", 6 | "System": "Information", 7 | "Microsoft": "Information" 8 | } 9 | }, 10 | "IdentityServer": { 11 | "Key": { 12 | "Type": "Store", 13 | "StoreName": "My", 14 | "StoreLocation": "CurrentUser", 15 | "Name": "CN=MyApplication" 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/WebUI/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "UseInMemoryDatabase": true, 3 | "ConnectionStrings": { 4 | "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=CleanArchitectureDb;Trusted_Connection=True;MultipleActiveResultSets=true;" 5 | }, 6 | "Logging": { 7 | "LogLevel": { 8 | "Default": "Warning" 9 | } 10 | }, 11 | "IdentityServer": { 12 | "Clients": { 13 | "CleanArchitecture.WebUI": { 14 | "Profile": "IdentityServerSPA" 15 | } 16 | } 17 | }, 18 | "AllowedHosts": "*" 19 | } 20 | -------------------------------------------------------------------------------- /src/WebUI/nswag.json: -------------------------------------------------------------------------------- 1 | { 2 | "runtime": "Net60", 3 | "defaultVariables": null, 4 | "documentGenerator": { 5 | "aspNetCoreToOpenApi": { 6 | "project": "WebUI.csproj", 7 | "msBuildProjectExtensionsPath": null, 8 | "configuration": null, 9 | "runtime": null, 10 | "targetFramework": null, 11 | "noBuild": true, 12 | "verbose": false, 13 | "workingDirectory": null, 14 | "requireParametersWithoutDefault": true, 15 | "apiGroupNames": null, 16 | "defaultPropertyNameHandling": "CamelCase", 17 | "defaultReferenceTypeNullHandling": "Null", 18 | "defaultDictionaryValueReferenceTypeNullHandling": "NotNull", 19 | "defaultResponseReferenceTypeNullHandling": "NotNull", 20 | "defaultEnumHandling": "Integer", 21 | "flattenInheritanceHierarchy": false, 22 | "generateKnownTypes": true, 23 | "generateEnumMappingDescription": false, 24 | "generateXmlObjects": false, 25 | "generateAbstractProperties": false, 26 | "generateAbstractSchemas": true, 27 | "ignoreObsoleteProperties": false, 28 | "allowReferencesWithProperties": false, 29 | "excludedTypeNames": [], 30 | "serviceHost": null, 31 | "serviceBasePath": null, 32 | "serviceSchemes": [], 33 | "infoTitle": "CleanArchitecture API", 34 | "infoDescription": null, 35 | "infoVersion": "1.0.0", 36 | "documentTemplate": null, 37 | "documentProcessorTypes": [], 38 | "operationProcessorTypes": [], 39 | "typeNameGeneratorType": null, 40 | "schemaNameGeneratorType": null, 41 | "contractResolverType": null, 42 | "serializerSettingsType": null, 43 | "useDocumentProvider": true, 44 | "documentName": "v1", 45 | "aspNetCoreEnvironment": null, 46 | "createWebHostBuilderMethod": null, 47 | "startupType": null, 48 | "allowNullableBodyParameters": true, 49 | "output": "wwwroot/api/specification.json", 50 | "outputType": "OpenApi3", 51 | "assemblyPaths": [], 52 | "assemblyConfig": null, 53 | "referencePaths": [], 54 | "useNuGetCache": false 55 | } 56 | }, 57 | "codeGenerators": { 58 | "openApiToTypeScriptClient": { 59 | "className": "{controller}Client", 60 | "moduleName": "", 61 | "namespace": "", 62 | "typeScriptVersion": 2.7, 63 | "template": "Angular", 64 | "promiseType": "Promise", 65 | "httpClass": "HttpClient", 66 | "withCredentials": false, 67 | "useSingletonProvider": true, 68 | "injectionTokenType": "InjectionToken", 69 | "rxJsVersion": 6.0, 70 | "dateTimeType": "Date", 71 | "nullValue": "Undefined", 72 | "generateClientClasses": true, 73 | "generateClientInterfaces": true, 74 | "generateOptionalParameters": false, 75 | "exportTypes": true, 76 | "wrapDtoExceptions": false, 77 | "exceptionClass": "SwaggerException", 78 | "clientBaseClass": null, 79 | "wrapResponses": false, 80 | "wrapResponseMethods": [], 81 | "generateResponseClasses": true, 82 | "responseClass": "SwaggerResponse", 83 | "protectedMethods": [], 84 | "configurationClass": null, 85 | "useTransformOptionsMethod": false, 86 | "useTransformResultMethod": false, 87 | "generateDtoTypes": true, 88 | "operationGenerationMode": "MultipleClientsFromOperationId", 89 | "markOptionalProperties": true, 90 | "generateCloneMethod": false, 91 | "typeStyle": "Class", 92 | "classTypes": [], 93 | "extendedClasses": [], 94 | "extensionCode": null, 95 | "generateDefaultValues": true, 96 | "excludedTypeNames": [], 97 | "excludedParameterNames": [], 98 | "handleReferences": false, 99 | "generateConstructorInterface": true, 100 | "convertConstructorInterfaceData": false, 101 | "importRequiredTypes": true, 102 | "useGetBaseUrlMethod": false, 103 | "baseUrlTokenName": "API_BASE_URL", 104 | "queryNullValue": "", 105 | "inlineNamedDictionaries": false, 106 | "inlineNamedAny": false, 107 | "templateDirectory": null, 108 | "typeNameGeneratorType": null, 109 | "propertyNameGeneratorType": null, 110 | "enumNameGeneratorType": null, 111 | "serviceHost": null, 112 | "serviceSchemes": null, 113 | "output": "ClientApp/src/app/web-api-client.ts" 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/WebUI/wwwroot/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/CleanArchitecture/35b490110f699c2ba427fd6b49e98babc16390c0/src/WebUI/wwwroot/favicon.ico -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/Application.IntegrationTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | CleanArchitecture.Application.IntegrationTests 6 | CleanArchitecture.Application.IntegrationTests 7 | 8 | false 9 | enable 10 | enable 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | Always 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | all 28 | runtime; build; native; contentfiles; analyzers; buildtransitive 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/TestBase.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | 3 | namespace CleanArchitecture.Application.IntegrationTests; 4 | 5 | using static Testing; 6 | 7 | public class TestBase 8 | { 9 | [SetUp] 10 | public async Task TestSetUp() 11 | { 12 | await ResetState(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/TodoItems/Commands/CreateTodoItemTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.TodoItems.Commands.CreateTodoItem; 3 | using CleanArchitecture.Application.TodoLists.Commands.CreateTodoList; 4 | using CleanArchitecture.Domain.Entities; 5 | using FluentAssertions; 6 | using NUnit.Framework; 7 | 8 | namespace CleanArchitecture.Application.IntegrationTests.TodoItems.Commands; 9 | 10 | using static Testing; 11 | 12 | public class CreateTodoItemTests : TestBase 13 | { 14 | [Test] 15 | public async Task ShouldRequireMinimumFields() 16 | { 17 | var command = new CreateTodoItemCommand(); 18 | 19 | await FluentActions.Invoking(() => 20 | SendAsync(command)).Should().ThrowAsync(); 21 | } 22 | 23 | [Test] 24 | public async Task ShouldCreateTodoItem() 25 | { 26 | var userId = await RunAsDefaultUserAsync(); 27 | 28 | var listId = await SendAsync(new CreateTodoListCommand 29 | { 30 | Title = "New List" 31 | }); 32 | 33 | var command = new CreateTodoItemCommand 34 | { 35 | ListId = listId, 36 | Title = "Tasks" 37 | }; 38 | 39 | var itemId = await SendAsync(command); 40 | 41 | var item = await FindAsync(itemId); 42 | 43 | item.Should().NotBeNull(); 44 | item!.ListId.Should().Be(command.ListId); 45 | item.Title.Should().Be(command.Title); 46 | item.CreatedBy.Should().Be(userId); 47 | item.Created.Should().BeCloseTo(DateTime.Now, TimeSpan.FromMilliseconds(10000)); 48 | item.LastModifiedBy.Should().BeNull(); 49 | item.LastModified.Should().BeNull(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/TodoItems/Commands/DeleteTodoItemTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.TodoItems.Commands.CreateTodoItem; 3 | using CleanArchitecture.Application.TodoItems.Commands.DeleteTodoItem; 4 | using CleanArchitecture.Application.TodoLists.Commands.CreateTodoList; 5 | using CleanArchitecture.Domain.Entities; 6 | using FluentAssertions; 7 | using NUnit.Framework; 8 | 9 | namespace CleanArchitecture.Application.IntegrationTests.TodoItems.Commands; 10 | 11 | using static Testing; 12 | 13 | public class DeleteTodoItemTests : TestBase 14 | { 15 | [Test] 16 | public async Task ShouldRequireValidTodoItemId() 17 | { 18 | var command = new DeleteTodoItemCommand { Id = 99 }; 19 | 20 | await FluentActions.Invoking(() => 21 | SendAsync(command)).Should().ThrowAsync(); 22 | } 23 | 24 | [Test] 25 | public async Task ShouldDeleteTodoItem() 26 | { 27 | var listId = await SendAsync(new CreateTodoListCommand 28 | { 29 | Title = "New List" 30 | }); 31 | 32 | var itemId = await SendAsync(new CreateTodoItemCommand 33 | { 34 | ListId = listId, 35 | Title = "New Item" 36 | }); 37 | 38 | await SendAsync(new DeleteTodoItemCommand 39 | { 40 | Id = itemId 41 | }); 42 | 43 | var item = await FindAsync(itemId); 44 | 45 | item.Should().BeNull(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/TodoItems/Commands/UpdateTodoItemDetailTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.TodoItems.Commands.CreateTodoItem; 3 | using CleanArchitecture.Application.TodoItems.Commands.UpdateTodoItem; 4 | using CleanArchitecture.Application.TodoItems.Commands.UpdateTodoItemDetail; 5 | using CleanArchitecture.Application.TodoLists.Commands.CreateTodoList; 6 | using CleanArchitecture.Domain.Entities; 7 | using CleanArchitecture.Domain.Enums; 8 | using FluentAssertions; 9 | using NUnit.Framework; 10 | 11 | namespace CleanArchitecture.Application.IntegrationTests.TodoItems.Commands; 12 | 13 | using static Testing; 14 | 15 | public class UpdateTodoItemDetailTests : TestBase 16 | { 17 | [Test] 18 | public async Task ShouldRequireValidTodoItemId() 19 | { 20 | var command = new UpdateTodoItemCommand { Id = 99, Title = "New Title" }; 21 | await FluentActions.Invoking(() => SendAsync(command)).Should().ThrowAsync(); 22 | } 23 | 24 | [Test] 25 | public async Task ShouldUpdateTodoItem() 26 | { 27 | var userId = await RunAsDefaultUserAsync(); 28 | 29 | var listId = await SendAsync(new CreateTodoListCommand 30 | { 31 | Title = "New List" 32 | }); 33 | 34 | var itemId = await SendAsync(new CreateTodoItemCommand 35 | { 36 | ListId = listId, 37 | Title = "New Item" 38 | }); 39 | 40 | var command = new UpdateTodoItemDetailCommand 41 | { 42 | Id = itemId, 43 | ListId = listId, 44 | Note = "This is the note.", 45 | Priority = PriorityLevel.High 46 | }; 47 | 48 | await SendAsync(command); 49 | 50 | var item = await FindAsync(itemId); 51 | 52 | item.Should().NotBeNull(); 53 | item!.ListId.Should().Be(command.ListId); 54 | item.Note.Should().Be(command.Note); 55 | item.Priority.Should().Be(command.Priority); 56 | item.LastModifiedBy.Should().NotBeNull(); 57 | item.LastModifiedBy.Should().Be(userId); 58 | item.LastModified.Should().NotBeNull(); 59 | item.LastModified.Should().BeCloseTo(DateTime.Now, TimeSpan.FromMilliseconds(10000)); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/TodoItems/Commands/UpdateTodoItemTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.TodoItems.Commands.CreateTodoItem; 3 | using CleanArchitecture.Application.TodoItems.Commands.UpdateTodoItem; 4 | using CleanArchitecture.Application.TodoLists.Commands.CreateTodoList; 5 | using CleanArchitecture.Domain.Entities; 6 | using FluentAssertions; 7 | using NUnit.Framework; 8 | 9 | namespace CleanArchitecture.Application.IntegrationTests.TodoItems.Commands; 10 | 11 | using static Testing; 12 | 13 | public class UpdateTodoItemTests : TestBase 14 | { 15 | [Test] 16 | public async Task ShouldRequireValidTodoItemId() 17 | { 18 | var command = new UpdateTodoItemCommand { Id = 99, Title = "New Title" }; 19 | await FluentActions.Invoking(() => SendAsync(command)).Should().ThrowAsync(); 20 | } 21 | 22 | [Test] 23 | public async Task ShouldUpdateTodoItem() 24 | { 25 | var userId = await RunAsDefaultUserAsync(); 26 | 27 | var listId = await SendAsync(new CreateTodoListCommand 28 | { 29 | Title = "New List" 30 | }); 31 | 32 | var itemId = await SendAsync(new CreateTodoItemCommand 33 | { 34 | ListId = listId, 35 | Title = "New Item" 36 | }); 37 | 38 | var command = new UpdateTodoItemCommand 39 | { 40 | Id = itemId, 41 | Title = "Updated Item Title" 42 | }; 43 | 44 | await SendAsync(command); 45 | 46 | var item = await FindAsync(itemId); 47 | 48 | item.Should().NotBeNull(); 49 | item!.Title.Should().Be(command.Title); 50 | item.LastModifiedBy.Should().NotBeNull(); 51 | item.LastModifiedBy.Should().Be(userId); 52 | item.LastModified.Should().NotBeNull(); 53 | item.LastModified.Should().BeCloseTo(DateTime.Now, TimeSpan.FromMilliseconds(10000)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/TodoLists/Commands/CreateTodoListTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.TodoLists.Commands.CreateTodoList; 3 | using CleanArchitecture.Domain.Entities; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace CleanArchitecture.Application.IntegrationTests.TodoLists.Commands; 8 | 9 | using static Testing; 10 | 11 | public class CreateTodoListTests : TestBase 12 | { 13 | [Test] 14 | public async Task ShouldRequireMinimumFields() 15 | { 16 | var command = new CreateTodoListCommand(); 17 | await FluentActions.Invoking(() => SendAsync(command)).Should().ThrowAsync(); 18 | } 19 | 20 | [Test] 21 | public async Task ShouldRequireUniqueTitle() 22 | { 23 | await SendAsync(new CreateTodoListCommand 24 | { 25 | Title = "Shopping" 26 | }); 27 | 28 | var command = new CreateTodoListCommand 29 | { 30 | Title = "Shopping" 31 | }; 32 | 33 | await FluentActions.Invoking(() => 34 | SendAsync(command)).Should().ThrowAsync(); 35 | } 36 | 37 | [Test] 38 | public async Task ShouldCreateTodoList() 39 | { 40 | var userId = await RunAsDefaultUserAsync(); 41 | 42 | var command = new CreateTodoListCommand 43 | { 44 | Title = "Tasks" 45 | }; 46 | 47 | var id = await SendAsync(command); 48 | 49 | var list = await FindAsync(id); 50 | 51 | list.Should().NotBeNull(); 52 | list!.Title.Should().Be(command.Title); 53 | list.CreatedBy.Should().Be(userId); 54 | list.Created.Should().BeCloseTo(DateTime.Now, TimeSpan.FromMilliseconds(10000)); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/TodoLists/Commands/DeleteTodoListTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.TodoLists.Commands.CreateTodoList; 3 | using CleanArchitecture.Application.TodoLists.Commands.DeleteTodoList; 4 | using CleanArchitecture.Domain.Entities; 5 | using FluentAssertions; 6 | using NUnit.Framework; 7 | 8 | namespace CleanArchitecture.Application.IntegrationTests.TodoLists.Commands; 9 | 10 | using static Testing; 11 | 12 | public class DeleteTodoListTests : TestBase 13 | { 14 | [Test] 15 | public async Task ShouldRequireValidTodoListId() 16 | { 17 | var command = new DeleteTodoListCommand { Id = 99 }; 18 | await FluentActions.Invoking(() => SendAsync(command)).Should().ThrowAsync(); 19 | } 20 | 21 | [Test] 22 | public async Task ShouldDeleteTodoList() 23 | { 24 | var listId = await SendAsync(new CreateTodoListCommand 25 | { 26 | Title = "New List" 27 | }); 28 | 29 | await SendAsync(new DeleteTodoListCommand 30 | { 31 | Id = listId 32 | }); 33 | 34 | var list = await FindAsync(listId); 35 | 36 | list.Should().BeNull(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/TodoLists/Commands/PurgeTodoListsTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.Common.Security; 3 | using CleanArchitecture.Application.TodoLists.Commands.CreateTodoList; 4 | using CleanArchitecture.Application.TodoLists.Commands.PurgeTodoLists; 5 | using CleanArchitecture.Domain.Entities; 6 | using FluentAssertions; 7 | using NUnit.Framework; 8 | 9 | namespace CleanArchitecture.Application.IntegrationTests.TodoLists.Commands; 10 | 11 | using static Testing; 12 | 13 | public class PurgeTodoListsTests : TestBase 14 | { 15 | [Test] 16 | public async Task ShouldDenyAnonymousUser() 17 | { 18 | var command = new PurgeTodoListsCommand(); 19 | 20 | command.GetType().Should().BeDecoratedWith(); 21 | 22 | await FluentActions.Invoking(() => 23 | SendAsync(command)).Should().ThrowAsync(); 24 | } 25 | 26 | [Test] 27 | public async Task ShouldDenyNonAdministrator() 28 | { 29 | await RunAsDefaultUserAsync(); 30 | 31 | var command = new PurgeTodoListsCommand(); 32 | 33 | await FluentActions.Invoking(() => 34 | SendAsync(command)).Should().ThrowAsync(); 35 | } 36 | 37 | [Test] 38 | public async Task ShouldAllowAdministrator() 39 | { 40 | await RunAsAdministratorAsync(); 41 | 42 | var command = new PurgeTodoListsCommand(); 43 | 44 | await FluentActions.Invoking(() => SendAsync(command)) 45 | .Should().NotThrowAsync(); 46 | } 47 | 48 | [Test] 49 | public async Task ShouldDeleteAllLists() 50 | { 51 | await RunAsAdministratorAsync(); 52 | 53 | await SendAsync(new CreateTodoListCommand 54 | { 55 | Title = "New List #1" 56 | }); 57 | 58 | await SendAsync(new CreateTodoListCommand 59 | { 60 | Title = "New List #2" 61 | }); 62 | 63 | await SendAsync(new CreateTodoListCommand 64 | { 65 | Title = "New List #3" 66 | }); 67 | 68 | await SendAsync(new PurgeTodoListsCommand()); 69 | 70 | var count = await CountAsync(); 71 | 72 | count.Should().Be(0); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/TodoLists/Commands/UpdateTodoListTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using CleanArchitecture.Application.TodoLists.Commands.CreateTodoList; 3 | using CleanArchitecture.Application.TodoLists.Commands.UpdateTodoList; 4 | using CleanArchitecture.Domain.Entities; 5 | using FluentAssertions; 6 | using NUnit.Framework; 7 | 8 | namespace CleanArchitecture.Application.IntegrationTests.TodoLists.Commands; 9 | 10 | using static Testing; 11 | 12 | public class UpdateTodoListTests : TestBase 13 | { 14 | [Test] 15 | public async Task ShouldRequireValidTodoListId() 16 | { 17 | var command = new UpdateTodoListCommand { Id = 99, Title = "New Title" }; 18 | await FluentActions.Invoking(() => SendAsync(command)).Should().ThrowAsync(); 19 | } 20 | 21 | [Test] 22 | public async Task ShouldRequireUniqueTitle() 23 | { 24 | var listId = await SendAsync(new CreateTodoListCommand 25 | { 26 | Title = "New List" 27 | }); 28 | 29 | await SendAsync(new CreateTodoListCommand 30 | { 31 | Title = "Other List" 32 | }); 33 | 34 | var command = new UpdateTodoListCommand 35 | { 36 | Id = listId, 37 | Title = "Other List" 38 | }; 39 | 40 | (await FluentActions.Invoking(() => 41 | SendAsync(command)) 42 | .Should().ThrowAsync().Where(ex => ex.Errors.ContainsKey("Title"))) 43 | .And.Errors["Title"].Should().Contain("The specified title already exists."); 44 | } 45 | 46 | [Test] 47 | public async Task ShouldUpdateTodoList() 48 | { 49 | var userId = await RunAsDefaultUserAsync(); 50 | 51 | var listId = await SendAsync(new CreateTodoListCommand 52 | { 53 | Title = "New List" 54 | }); 55 | 56 | var command = new UpdateTodoListCommand 57 | { 58 | Id = listId, 59 | Title = "Updated List Title" 60 | }; 61 | 62 | await SendAsync(command); 63 | 64 | var list = await FindAsync(listId); 65 | 66 | list.Should().NotBeNull(); 67 | list!.Title.Should().Be(command.Title); 68 | list.LastModifiedBy.Should().NotBeNull(); 69 | list.LastModifiedBy.Should().Be(userId); 70 | list.LastModified.Should().NotBeNull(); 71 | list.LastModified.Should().BeCloseTo(DateTime.Now, TimeSpan.FromMilliseconds(10000)); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/TodoLists/Queries/GetTodosTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.TodoLists.Queries.GetTodos; 2 | using CleanArchitecture.Domain.Entities; 3 | using CleanArchitecture.Domain.ValueObjects; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace CleanArchitecture.Application.IntegrationTests.TodoLists.Queries; 8 | 9 | using static Testing; 10 | 11 | public class GetTodosTests : TestBase 12 | { 13 | [Test] 14 | public async Task ShouldReturnPriorityLevels() 15 | { 16 | var query = new GetTodosQuery(); 17 | 18 | var result = await SendAsync(query); 19 | 20 | result.PriorityLevels.Should().NotBeEmpty(); 21 | } 22 | 23 | [Test] 24 | public async Task ShouldReturnAllListsAndItems() 25 | { 26 | await AddAsync(new TodoList 27 | { 28 | Title = "Shopping", 29 | Colour = Colour.Blue, 30 | Items = 31 | { 32 | new TodoItem { Title = "Apples", Done = true }, 33 | new TodoItem { Title = "Milk", Done = true }, 34 | new TodoItem { Title = "Bread", Done = true }, 35 | new TodoItem { Title = "Toilet paper" }, 36 | new TodoItem { Title = "Pasta" }, 37 | new TodoItem { Title = "Tissues" }, 38 | new TodoItem { Title = "Tuna" } 39 | } 40 | }); 41 | 42 | var query = new GetTodosQuery(); 43 | 44 | var result = await SendAsync(query); 45 | 46 | result.Lists.Should().HaveCount(1); 47 | result.Lists.First().Items.Should().HaveCount(7); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/Application.IntegrationTests/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "UseInMemoryDatabase": false, // Application.IntegrationTests are not designed to work with InMemory database. 3 | "ConnectionStrings": { 4 | "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=CleanArchitectureTestDb;Trusted_Connection=True;MultipleActiveResultSets=true;" 5 | }, 6 | "IdentityServer": { 7 | "Clients": { 8 | "CleanArchitecture.WebUI": { 9 | "Profile": "IdentityServerSPA" 10 | } 11 | }, 12 | "Key": { 13 | "Type": "Development" 14 | } 15 | }, 16 | "Logging": { 17 | "LogLevel": { 18 | "Default": "Debug", 19 | "System": "Information", 20 | "Microsoft": "Information" 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /tests/Application.UnitTests/Application.UnitTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | CleanArchitecture.Application.UnitTests 6 | CleanArchitecture.Application.UnitTests 7 | 8 | false 9 | enable 10 | enable 11 | 12 | 13 | 14 | 15 | 16 | 17 | all 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /tests/Application.UnitTests/Common/Behaviours/RequestLoggerTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Behaviours; 2 | using CleanArchitecture.Application.Common.Interfaces; 3 | using CleanArchitecture.Application.TodoItems.Commands.CreateTodoItem; 4 | using Microsoft.Extensions.Logging; 5 | using Moq; 6 | using NUnit.Framework; 7 | 8 | namespace CleanArchitecture.Application.UnitTests.Common.Behaviours; 9 | 10 | public class RequestLoggerTests 11 | { 12 | private Mock> _logger = null!; 13 | private Mock _currentUserService = null!; 14 | private Mock _identityService = null!; 15 | 16 | [SetUp] 17 | public void Setup() 18 | { 19 | _logger = new Mock>(); 20 | _currentUserService = new Mock(); 21 | _identityService = new Mock(); 22 | } 23 | 24 | [Test] 25 | public async Task ShouldCallGetUserNameAsyncOnceIfAuthenticated() 26 | { 27 | _currentUserService.Setup(x => x.UserId).Returns(Guid.NewGuid().ToString()); 28 | 29 | var requestLogger = new LoggingBehaviour(_logger.Object, _currentUserService.Object, _identityService.Object); 30 | 31 | await requestLogger.Process(new CreateTodoItemCommand { ListId = 1, Title = "title" }, new CancellationToken()); 32 | 33 | _identityService.Verify(i => i.GetUserNameAsync(It.IsAny()), Times.Once); 34 | } 35 | 36 | [Test] 37 | public async Task ShouldNotCallGetUserNameAsyncOnceIfUnauthenticated() 38 | { 39 | var requestLogger = new LoggingBehaviour(_logger.Object, _currentUserService.Object, _identityService.Object); 40 | 41 | await requestLogger.Process(new CreateTodoItemCommand { ListId = 1, Title = "title" }, new CancellationToken()); 42 | 43 | _identityService.Verify(i => i.GetUserNameAsync(It.IsAny()), Times.Never); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /tests/Application.UnitTests/Common/Exceptions/ValidationExceptionTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Application.Common.Exceptions; 2 | using FluentAssertions; 3 | using FluentValidation.Results; 4 | using NUnit.Framework; 5 | 6 | namespace CleanArchitecture.Application.UnitTests.Common.Exceptions; 7 | 8 | public class ValidationExceptionTests 9 | { 10 | [Test] 11 | public void DefaultConstructorCreatesAnEmptyErrorDictionary() 12 | { 13 | var actual = new ValidationException().Errors; 14 | 15 | actual.Keys.Should().BeEquivalentTo(Array.Empty()); 16 | } 17 | 18 | [Test] 19 | public void SingleValidationFailureCreatesASingleElementErrorDictionary() 20 | { 21 | var failures = new List 22 | { 23 | new ValidationFailure("Age", "must be over 18"), 24 | }; 25 | 26 | var actual = new ValidationException(failures).Errors; 27 | 28 | actual.Keys.Should().BeEquivalentTo(new string[] { "Age" }); 29 | actual["Age"].Should().BeEquivalentTo(new string[] { "must be over 18" }); 30 | } 31 | 32 | [Test] 33 | public void MulitpleValidationFailureForMultiplePropertiesCreatesAMultipleElementErrorDictionaryEachWithMultipleValues() 34 | { 35 | var failures = new List 36 | { 37 | new ValidationFailure("Age", "must be 18 or older"), 38 | new ValidationFailure("Age", "must be 25 or younger"), 39 | new ValidationFailure("Password", "must contain at least 8 characters"), 40 | new ValidationFailure("Password", "must contain a digit"), 41 | new ValidationFailure("Password", "must contain upper case letter"), 42 | new ValidationFailure("Password", "must contain lower case letter"), 43 | }; 44 | 45 | var actual = new ValidationException(failures).Errors; 46 | 47 | actual.Keys.Should().BeEquivalentTo(new string[] { "Password", "Age" }); 48 | 49 | actual["Age"].Should().BeEquivalentTo(new string[] 50 | { 51 | "must be 25 or younger", 52 | "must be 18 or older", 53 | }); 54 | 55 | actual["Password"].Should().BeEquivalentTo(new string[] 56 | { 57 | "must contain lower case letter", 58 | "must contain upper case letter", 59 | "must contain at least 8 characters", 60 | "must contain a digit", 61 | }); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /tests/Application.UnitTests/Common/Mappings/MappingTests.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | using AutoMapper; 3 | using CleanArchitecture.Application.Common.Mappings; 4 | using CleanArchitecture.Application.TodoLists.Queries.GetTodos; 5 | using CleanArchitecture.Domain.Entities; 6 | using NUnit.Framework; 7 | 8 | namespace CleanArchitecture.Application.UnitTests.Common.Mappings; 9 | 10 | public class MappingTests 11 | { 12 | private readonly IConfigurationProvider _configuration; 13 | private readonly IMapper _mapper; 14 | 15 | public MappingTests() 16 | { 17 | _configuration = new MapperConfiguration(config => 18 | config.AddProfile()); 19 | 20 | _mapper = _configuration.CreateMapper(); 21 | } 22 | 23 | [Test] 24 | public void ShouldHaveValidConfiguration() 25 | { 26 | _configuration.AssertConfigurationIsValid(); 27 | } 28 | 29 | [Test] 30 | [TestCase(typeof(TodoList), typeof(TodoListDto))] 31 | [TestCase(typeof(TodoItem), typeof(TodoItemDto))] 32 | public void ShouldSupportMappingFromSourceToDestination(Type source, Type destination) 33 | { 34 | var instance = GetInstanceOf(source); 35 | 36 | _mapper.Map(instance, source, destination); 37 | } 38 | 39 | private object GetInstanceOf(Type type) 40 | { 41 | if (type.GetConstructor(Type.EmptyTypes) != null) 42 | return Activator.CreateInstance(type)!; 43 | 44 | // Type without parameterless constructor 45 | return FormatterServices.GetUninitializedObject(type); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /tests/Domain.UnitTests/Domain.UnitTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | CleanArchitecture.Domain.UnitTests 6 | CleanArchitecture.Domain.UnitTests 7 | 8 | false 9 | enable 10 | enable 11 | 12 | 13 | 14 | 15 | 16 | 17 | all 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /tests/Domain.UnitTests/ValueObjects/ColourTests.cs: -------------------------------------------------------------------------------- 1 | using CleanArchitecture.Domain.Exceptions; 2 | using CleanArchitecture.Domain.ValueObjects; 3 | using FluentAssertions; 4 | using NUnit.Framework; 5 | 6 | namespace CleanArchitecture.Domain.UnitTests.ValueObjects; 7 | 8 | public class ColourTests 9 | { 10 | [Test] 11 | public void ShouldReturnCorrectColourCode() 12 | { 13 | var code = "#FFFFFF"; 14 | 15 | var colour = Colour.From(code); 16 | 17 | colour.Code.Should().Be(code); 18 | } 19 | 20 | [Test] 21 | public void ToStringReturnsCode() 22 | { 23 | var colour = Colour.White; 24 | 25 | colour.ToString().Should().Be(colour.Code); 26 | } 27 | 28 | [Test] 29 | public void ShouldPerformImplicitConversionToColourCodeString() 30 | { 31 | string code = Colour.White; 32 | 33 | code.Should().Be("#FFFFFF"); 34 | } 35 | 36 | [Test] 37 | public void ShouldPerformExplicitConversionGivenSupportedColourCode() 38 | { 39 | var colour = (Colour)"#FFFFFF"; 40 | 41 | colour.Should().Be(Colour.White); 42 | } 43 | 44 | [Test] 45 | public void ShouldThrowUnsupportedColourExceptionGivenNotSupportedColourCode() 46 | { 47 | FluentActions.Invoking(() => Colour.From("##FF33CC")) 48 | .Should().Throw(); 49 | } 50 | } 51 | --------------------------------------------------------------------------------