├── CaWorkshop.WebUI ├── ClientApp │ ├── src │ │ ├── assets │ │ │ └── .gitkeep │ │ ├── api-authorization │ │ │ ├── login │ │ │ │ ├── login.component.css │ │ │ │ ├── login.component.html │ │ │ │ ├── login.component.spec.ts │ │ │ │ └── login.component.ts │ │ │ ├── logout │ │ │ │ ├── logout.component.css │ │ │ │ ├── logout.component.html │ │ │ │ ├── logout.component.spec.ts │ │ │ │ └── logout.component.ts │ │ │ ├── login-menu │ │ │ │ ├── login-menu.component.css │ │ │ │ ├── login-menu.component.spec.ts │ │ │ │ ├── login-menu.component.html │ │ │ │ └── login-menu.component.ts │ │ │ ├── api-authorization.module.spec.ts │ │ │ ├── authorize.guard.spec.ts │ │ │ ├── authorize.service.spec.ts │ │ │ ├── authorize.interceptor.spec.ts │ │ │ ├── authorize.guard.ts │ │ │ ├── api-authorization.module.ts │ │ │ ├── authorize.interceptor.ts │ │ │ ├── api-authorization.constants.ts │ │ │ └── authorize.service.ts │ │ ├── environments │ │ │ ├── environment.prod.ts │ │ │ └── environment.ts │ │ ├── app │ │ │ ├── app.component.html │ │ │ ├── home │ │ │ │ ├── home.component.ts │ │ │ │ └── home.component.html │ │ │ ├── app.component.ts │ │ │ ├── counter │ │ │ │ ├── counter.component.html │ │ │ │ ├── counter.component.ts │ │ │ │ └── counter.component.spec.ts │ │ │ ├── nav-menu │ │ │ │ ├── nav-menu.component.css │ │ │ │ ├── nav-menu.component.ts │ │ │ │ └── nav-menu.component.html │ │ │ ├── app.server.module.ts │ │ │ ├── todo │ │ │ │ ├── todo.component.css │ │ │ │ ├── todo.component.ts │ │ │ │ └── todo.component.html │ │ │ ├── fetch-data │ │ │ │ ├── fetch-data.component.ts │ │ │ │ └── fetch-data.component.html │ │ │ └── app.module.ts │ │ ├── tsconfig.app.json │ │ ├── tsconfig.server.json │ │ ├── tsconfig.spec.json │ │ ├── styles.css │ │ ├── tslint.json │ │ ├── index.html │ │ ├── main.ts │ │ ├── test.ts │ │ ├── karma.conf.js │ │ └── polyfills.ts │ ├── e2e │ │ ├── src │ │ │ ├── app.po.ts │ │ │ └── app.e2e-spec.ts │ │ ├── tsconfig.e2e.json │ │ └── protractor.conf.js │ ├── .editorconfig │ ├── browserslist │ ├── tsconfig.json │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── tslint.json │ └── angular.json ├── wwwroot │ └── favicon.ico ├── Pages │ ├── _ViewImports.cshtml │ ├── Error.cshtml.cs │ ├── Error.cshtml │ └── Shared │ │ └── _LoginPartial.cshtml ├── appsettings.Development.json ├── WeatherForecast.cs ├── Services │ └── CurrentUserService.cs ├── appsettings.json ├── Properties │ └── launchSettings.json ├── Controllers │ ├── OidcConfigurationController.cs │ ├── WeatherForecastController.cs │ ├── TodoItemsController.cs │ └── TodoListsController.cs ├── Program.cs ├── Common │ └── CustomExceptionHandlerMiddleware.cs ├── Startup.cs ├── openapi.nswag ├── CaWorkshop.WebUI.csproj └── .gitignore ├── CaWorkshop.Domain ├── Entities │ ├── PriorityLevel.cs │ ├── TodoList.cs │ └── TodoItem.cs ├── CaWorkshop.Domain.csproj └── Common │ └── AuditableEntity.cs ├── CaWorkshop.Application ├── Common │ ├── Interfaces │ │ ├── ICurrentUserService.cs │ │ ├── IIdentityService.cs │ │ └── IApplicationDbContext.cs │ ├── Mappings │ │ ├── IMapFrom.cs │ │ └── MappingProfile.cs │ ├── Exceptions │ │ ├── NotFoundException.cs │ │ └── ValidationException.cs │ ├── Models │ │ └── Result.cs │ └── Behaviours │ │ ├── RequestLoggerBehaviour.cs │ │ ├── RequestValidationBehaviour.cs │ │ └── RequestPerformanceBehaviour.cs ├── TodoLists │ ├── Queries │ │ ├── GetTodoLists │ │ │ ├── PriorityDto.cs │ │ │ ├── TodoListDto.cs │ │ │ ├── TodosVm.cs │ │ │ ├── TodoItemDto.cs │ │ │ └── GetTodoListsQuery.cs │ │ └── package-lock.json │ └── Commands │ │ ├── CreateTodoList │ │ ├── CreateTodoListCommandValidator.cs │ │ └── CreateTodoListCommand.cs │ │ ├── DeleteTodoList │ │ └── DeleteTodoListCommand.cs │ │ └── UpdateTodoList │ │ └── UpdateTodoListCommand.cs ├── CaWorkshop.Application.csproj ├── TodoItems │ └── Commands │ │ ├── CreateTodoItem │ │ └── CreateTodoItemCommand.cs │ │ ├── DeleteTodoItem │ │ └── DeleteTodoItemCommand.cs │ │ └── UpdateTodoItem │ │ └── UpdateTodoItemCommand.cs └── DependencyInjection.cs ├── CaWorkshop.Application.UnitTests ├── QueryFixture.cs ├── MappingFixture.cs ├── MapperFactory.cs ├── TestBase.cs ├── CaWorkshop.Application.UnitTests.csproj ├── Common │ └── Mappings │ │ └── MappingTests.cs ├── TodoLists │ ├── Commands │ │ └── CreateTodoLists │ │ │ └── CreateTodoListCommandTests.cs │ └── Queries │ │ └── GetTodoLists │ │ └── GetTodoListsQueryTests.cs ├── TodoList │ └── Commands │ │ └── CreateTodoList │ │ └── CreateTodoListValidatorTests.cs └── DbContextFactory.cs ├── CaWorkshop.Infrastructure ├── Identity │ ├── ApplicationUser.cs │ └── IdentityService.cs ├── Persistence │ ├── Configurations │ │ ├── TodoListConfiguration.cs │ │ └── TodoItemConfiguration.cs │ ├── ApplicationDbContextSeeder.cs │ ├── ApplicationDbContext.cs │ └── Migrations │ │ ├── 20200225000904_Todo.cs │ │ ├── 20200225061624_Audit Todos.cs │ │ └── 00000000000000_CreateIdentitySchema.cs ├── CaWorkshop.Infrastructure.csproj └── DependencyInjection.cs ├── .editorconfig ├── CaWorkshop.sln └── .gitignore /CaWorkshop.WebUI/ClientApp/src/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/api-authorization/login/login.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/api-authorization/logout/logout.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/api-authorization/login-menu/login-menu.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/api-authorization/login/login.component.html: -------------------------------------------------------------------------------- 1 |

{{ message | async }}

-------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/api-authorization/logout/logout.component.html: -------------------------------------------------------------------------------- 1 |

{{ message | async }}

-------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/wwwroot/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SSWConsulting/CleanArchitectureSuperpowersFeb2020/HEAD/CaWorkshop.WebUI/wwwroot/favicon.ico -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Pages/_ViewImports.cshtml: -------------------------------------------------------------------------------- 1 | @using CaWorkshop.WebUI 2 | @namespace CaWorkshop.WebUI.Pages 3 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 4 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
6 | 7 | -------------------------------------------------------------------------------- /CaWorkshop.Domain/Entities/PriorityLevel.cs: -------------------------------------------------------------------------------- 1 | namespace CaWorkshop.Domain.Entities 2 | { 3 | public enum PriorityLevel 4 | { 5 | None, 6 | Low, 7 | Medium, 8 | High 9 | } 10 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/Common/Interfaces/ICurrentUserService.cs: -------------------------------------------------------------------------------- 1 | namespace CaWorkshop.Application.Common.Interfaces 2 | { 3 | public interface ICurrentUserService 4 | { 5 | public string UserId { get; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.Application.UnitTests/QueryFixture.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace CaWorkshop.Application.UnitTests 4 | { 5 | [CollectionDefinition("QueryTests")] 6 | public class QueryFixture 7 | : ICollectionFixture 8 | { } 9 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "types": [] 6 | }, 7 | "exclude": [ 8 | "src/test.ts", 9 | "**/*.spec.ts" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/tsconfig.server.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "module": "commonjs" 5 | }, 6 | "angularCompilerOptions": { 7 | "entryModule": "app/app.server.module#AppServerModule" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoLists/Queries/GetTodoLists/PriorityDto.cs: -------------------------------------------------------------------------------- 1 | namespace CaWorkshop.Application.TodoLists.Queries.GetTodoLists 2 | { 3 | public class PriorityLevelDto 4 | { 5 | public int Value { get; set; } 6 | 7 | public string Name { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/Common/Mappings/IMapFrom.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace CaWorkshop.Application.Common.Mappings 4 | { 5 | public interface IMapFrom 6 | { 7 | void Mapping(Profile profile) 8 | => profile.CreateMap(typeof(T), GetType()); 9 | } 10 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.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 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.Domain/CaWorkshop.Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "IdentityServer": { 10 | "Key": { 11 | "Type": "Development" 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /CaWorkshop.Infrastructure/Identity/ApplicationUser.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace CaWorkshop.Infrastructure.Identity 8 | { 9 | public class ApplicationUser : IdentityUser 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /CaWorkshop.Application.UnitTests/MappingFixture.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace CaWorkshop.Application.UnitTests 4 | { 5 | public class MappingFixture 6 | { 7 | public MappingFixture() 8 | { 9 | Mapper = MapperFactory.Create(); 10 | } 11 | 12 | public IMapper Mapper { get; set; } 13 | } 14 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/Common/Exceptions/NotFoundException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CaWorkshop.Application.Common.Exceptions 4 | { 5 | public class NotFoundException : Exception 6 | { 7 | public NotFoundException(string name, object key) 8 | : base($"Entity \"{name}\" ({key}) was not found.") 9 | { 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/styles.css: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/app/nav-menu/nav-menu.component.css: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CaWorkshop.WebUI 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /CaWorkshop.Domain/Common/AuditableEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CaWorkshop.Domain.Common 4 | { 5 | public class AuditableEntity 6 | { 7 | public string CreatedBy { get; set; } 8 | 9 | public DateTime CreatedUtc { get; set; } 10 | 11 | public string LastModifiedBy { get; set; } 12 | 13 | public DateTime? LastModifiedUtc { get; set; } 14 | } 15 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/browserslist: -------------------------------------------------------------------------------- 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 -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CaWorkshop.WebUI 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | 15 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/app/nav-menu/nav-menu.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-nav-menu', 5 | templateUrl: './nav-menu.component.html', 6 | styleUrls: ['./nav-menu.component.css'] 7 | }) 8 | export class NavMenuComponent { 9 | isExpanded = false; 10 | 11 | collapse() { 12 | this.isExpanded = false; 13 | } 14 | 15 | toggle() { 16 | this.isExpanded = !this.isExpanded; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoLists/Queries/GetTodoLists/TodoListDto.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Mappings; 2 | using CaWorkshop.Domain.Entities; 3 | using System.Collections.Generic; 4 | 5 | namespace CaWorkshop.Application.TodoLists.Queries.GetTodoLists 6 | { 7 | public class TodoListDto : IMapFrom 8 | { 9 | public int Id { get; set; } 10 | 11 | public string Title { get; set; } 12 | 13 | public IList Items { get; set; } 14 | } 15 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.Application/Common/Interfaces/IIdentityService.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Models; 2 | using System.Threading.Tasks; 3 | 4 | namespace CaWorkshop.Application.Common.Interfaces 5 | { 6 | public interface IIdentityService 7 | { 8 | Task GetUserNameAsync(string userId); 9 | 10 | Task<(Result Result, string UserId)> CreateUserAsync( 11 | string userName, 12 | string password); 13 | 14 | Task DeleteUserAsync(string userId); 15 | } 16 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.{cs,vb}] 2 | dotnet_naming_rule.private_members_with_underscore.symbols = private_fields 3 | dotnet_naming_rule.private_members_with_underscore.style = prefix_underscore 4 | dotnet_naming_rule.private_members_with_underscore.severity = suggestion 5 | 6 | dotnet_naming_symbols.private_fields.applicable_kinds = field 7 | dotnet_naming_symbols.private_fields.applicable_accessibilities = private 8 | 9 | dotnet_naming_style.prefix_underscore.capitalization = camel_case 10 | dotnet_naming_style.prefix_underscore.required_prefix = _ -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "module": "esnext", 6 | "outDir": "./dist/out-tsc", 7 | "sourceMap": true, 8 | "declaration": false, 9 | "moduleResolution": "node", 10 | "emitDecoratorMetadata": true, 11 | "experimentalDecorators": true, 12 | "target": "es2015", 13 | "typeRoots": [ 14 | "node_modules/@types" 15 | ], 16 | "lib": [ 17 | "es2017", 18 | "dom" 19 | ] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /CaWorkshop.Application/Common/Interfaces/IApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Domain.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | 6 | namespace CaWorkshop.Application.Common.Interfaces 7 | { 8 | public interface IApplicationDbContext 9 | { 10 | public DbSet TodoLists { get; set; } 11 | 12 | public DbSet TodoItems { get; set; } 13 | 14 | Task SaveChangesAsync(CancellationToken cancellationToken); 15 | } 16 | } -------------------------------------------------------------------------------- /CaWorkshop.Application.UnitTests/MapperFactory.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using CaWorkshop.Application.Common.Mappings; 3 | 4 | namespace CaWorkshop.Application.UnitTests 5 | { 6 | public static class MapperFactory 7 | { 8 | public static IMapper Create() 9 | { 10 | var configurationProvider = new MapperConfiguration(cfg => 11 | { 12 | cfg.AddProfile(); 13 | }); 14 | 15 | return configurationProvider.CreateMapper(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.Domain/Entities/TodoList.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Domain.Common; 2 | using System.Collections.Generic; 3 | 4 | namespace CaWorkshop.Domain.Entities 5 | { 6 | public class TodoList : AuditableEntity 7 | { 8 | public TodoList() 9 | { 10 | Items = new List(); 11 | } 12 | 13 | public int Id { get; set; } 14 | 15 | 16 | public string Title { get; set; } 17 | 18 | public string Colour { get; set; } 19 | 20 | public IList Items { get; set; } 21 | } 22 | } -------------------------------------------------------------------------------- /CaWorkshop.Infrastructure/Persistence/Configurations/TodoListConfiguration.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Domain.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace CaWorkshop.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(280) 13 | .IsRequired(); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /CaWorkshop.Domain/Entities/TodoItem.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Domain.Common; 2 | using System; 3 | 4 | namespace CaWorkshop.Domain.Entities 5 | { 6 | public class TodoItem : AuditableEntity 7 | { 8 | public long Id { get; set; } 9 | 10 | public int ListId { get; set; } 11 | 12 | public string Title { get; set; } 13 | 14 | public string Note { get; set; } 15 | 16 | public bool Done { get; set; } 17 | 18 | public DateTime? Reminder { get; set; } 19 | 20 | public PriorityLevel Priority { get; set; } 21 | 22 | public TodoList List { get; set; } 23 | } 24 | } -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Services/CurrentUserService.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Interfaces; 2 | using Microsoft.AspNetCore.Http; 3 | using System.Security.Claims; 4 | 5 | namespace CleanArchitecture.WebUI.Services 6 | { 7 | public class CurrentUserService : ICurrentUserService 8 | { 9 | public CurrentUserService(IHttpContextAccessor httpContextAccessor) 10 | { 11 | UserId = httpContextAccessor 12 | .HttpContext? 13 | .User? 14 | .FindFirstValue(ClaimTypes.NameIdentifier); 15 | } 16 | 17 | public string UserId { get; } 18 | } 19 | } -------------------------------------------------------------------------------- /CaWorkshop.WebUI/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-CaWorkshop.WebUI-53bc9b9d-9d6a-45d4-8429-2a2761773502;Trusted_Connection=True;MultipleActiveResultSets=true" 4 | }, 5 | "Logging": { 6 | "LogLevel": { 7 | "Default": "Information", 8 | "Microsoft": "Warning", 9 | "Microsoft.Hosting.Lifetime": "Information" 10 | } 11 | }, 12 | "IdentityServer": { 13 | "Clients": { 14 | "CaWorkshop.WebUI": { 15 | "Profile": "IdentityServerSPA" 16 | } 17 | } 18 | }, 19 | "AllowedHosts": "*" 20 | } 21 | -------------------------------------------------------------------------------- /CaWorkshop.Application.UnitTests/TestBase.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using CaWorkshop.Infrastructure.Persistence; 3 | using System; 4 | 5 | namespace CaWorkshop.Application.UnitTests 6 | { 7 | public class TestBase : IDisposable 8 | { 9 | public TestBase() 10 | { 11 | Context = DbContextFactory.Create(); 12 | Mapper = MapperFactory.Create(); 13 | } 14 | 15 | public ApplicationDbContext Context { get; } 16 | 17 | public IMapper Mapper { get; } 18 | 19 | public void Dispose() 20 | { 21 | DbContextFactory.Destroy(Context); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.Infrastructure/CaWorkshop.Infrastructure.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | netcoreapp3.1 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /CaWorkshop.Infrastructure/Persistence/Configurations/TodoItemConfiguration.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Domain.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace CaWorkshop.Infrastructure.Persistence.Configurations 6 | { 7 | public class TodoItemConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.Property(t => t.Title) 12 | .HasMaxLength(280) 13 | .IsRequired(); 14 | 15 | builder.Property(t => t.Note) 16 | .HasMaxLength(4000); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.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/dist/zone-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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/app/todo/todo.component.css: -------------------------------------------------------------------------------- 1 | #listOptions { 2 | margin-right: 10px; 3 | } 4 | 5 | #todo-items .item-input-control { 6 | border: 0; 7 | box-shadow: none; 8 | background-color: transparent; 9 | } 10 | 11 | #todo-items .done-todo { 12 | text-decoration: line-through; 13 | } 14 | 15 | #todo-items .todo-item-title { 16 | padding-top: 8px; 17 | } 18 | 19 | #todo-items .list-group-item { 20 | padding-top: 8px; 21 | padding-bottom: 8px; 22 | } 23 | 24 | #todo-items .list-group-item .btn-xs { 25 | padding: 0; 26 | } 27 | 28 | #todo-items .todo-item-checkbox { 29 | padding-top: 8px; 30 | } 31 | 32 | #todo-items .todo-item-commands { 33 | padding-top: 4px; 34 | } 35 | 36 | .modal-footer { 37 | display: block; 38 | } 39 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/app/fetch-data/fetch-data.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Inject } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 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(http: HttpClient, @Inject('BASE_URL') baseUrl: string) { 12 | http.get(baseUrl + 'weatherforecast').subscribe(result => { 13 | this.forecasts = result; 14 | }, error => console.error(error)); 15 | } 16 | } 17 | 18 | interface WeatherForecast { 19 | date: string; 20 | temperatureC: number; 21 | temperatureF: number; 22 | summary: string; 23 | } 24 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.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 | apiBaseUrl: "https://localhost:44343" 8 | }; 9 | 10 | /* 11 | * In development mode, to ignore zone related error stack frames such as 12 | * `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can 13 | * import the following file, but please comment it out in production mode 14 | * because it will have performance impact when throw error 15 | */ 16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /CaWorkshop.Application/Common/Models/Result.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace CaWorkshop.Application.Common.Models 5 | { 6 | public class Result 7 | { 8 | internal Result(bool succeeded, IEnumerable errors) 9 | { 10 | Succeeded = succeeded; 11 | Errors = errors.ToArray(); 12 | } 13 | 14 | public bool Succeeded { get; set; } 15 | 16 | public string[] Errors { get; set; } 17 | 18 | public static Result Success() 19 | { 20 | return new Result(true, new string[] { }); 21 | } 22 | 23 | public static Result Failure(IEnumerable errors) 24 | { 25 | return new Result(false, errors); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/api-authorization/login/login.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } 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(async(() => { 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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/api-authorization/logout/logout.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } 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(async(() => { 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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:50373", 7 | "sslPort": 44343 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | } 17 | }, 18 | "CaWorkshop.WebUI": { 19 | "commandName": "Project", 20 | "launchBrowser": true, 21 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 22 | "environmentVariables": { 23 | "ASPNETCORE_ENVIRONMENT": "Development" 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/api-authorization/login-menu/login-menu.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } 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(async(() => { 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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/api-authorization/login-menu/login-menu.component.html: -------------------------------------------------------------------------------- 1 | 9 | 17 | -------------------------------------------------------------------------------- /CaWorkshop.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.css'] 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 | -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoLists/Queries/GetTodoLists/TodosVm.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Domain.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace CaWorkshop.Application.TodoLists.Queries.GetTodoLists 7 | { 8 | public class TodosVm 9 | { 10 | public List PriorityLevels 11 | { 12 | get 13 | { 14 | return Enum.GetValues(typeof(PriorityLevel)) 15 | .Cast() 16 | .Select(p => new PriorityLevelDto 17 | { 18 | Value = (int)p, 19 | Name = p.ToString() 20 | }) 21 | .ToList(); 22 | } 23 | } 24 | 25 | public List Lists { get; set; } 26 | } 27 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoLists/Queries/GetTodoLists/TodoItemDto.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using CaWorkshop.Application.Common.Mappings; 3 | using CaWorkshop.Domain.Entities; 4 | 5 | namespace CaWorkshop.Application.TodoLists.Queries.GetTodoLists 6 | { 7 | public class TodoItemDto : IMapFrom 8 | { 9 | public long 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 => 25 | opt.MapFrom(s => (int)s.Priority)); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.Application/CaWorkshop.Application.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | netstandard2.1 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Pages/Error.cshtml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Microsoft.AspNetCore.Mvc.RazorPages; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace CaWorkshop.WebUI.Pages 11 | { 12 | [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] 13 | public class ErrorModel : PageModel 14 | { 15 | private readonly ILogger _logger; 16 | 17 | public ErrorModel(ILogger logger) 18 | { 19 | _logger = logger; 20 | } 21 | 22 | public string RequestId { get; set; } 23 | 24 | public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); 25 | 26 | public void OnGet() 27 | { 28 | RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.Application.UnitTests/CaWorkshop.Application.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Controllers/OidcConfigurationController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.ApiAuthorization.IdentityServer; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.Logging; 4 | 5 | namespace CaWorkshop.WebUI.Controllers 6 | { 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 | } 27 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/README.md: -------------------------------------------------------------------------------- 1 | # CaWorkshop.WebUI 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.0.0. 4 | 5 | ## Development server 6 | 7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 8 | 9 | ## Code scaffolding 10 | 11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 12 | 13 | ## Build 14 | 15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | 25 | ## Further help 26 | 27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 28 | -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoLists/Commands/CreateTodoList/CreateTodoListCommandValidator.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Interfaces; 2 | using FluentValidation; 3 | using Microsoft.EntityFrameworkCore; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace CaWorkshop.Application.TodoLists.Commands.CreateTodoList 8 | { 9 | public class CreateTodoListCommandValidator 10 | : AbstractValidator 11 | { 12 | private IApplicationDbContext _context; 13 | 14 | public CreateTodoListCommandValidator( 15 | IApplicationDbContext context) 16 | { 17 | _context = context; 18 | 19 | RuleFor(v => v.Title) 20 | .MaximumLength(240) 21 | .NotEmpty() 22 | .MustAsync(BeUniqueTitle) 23 | .WithMessage("The specified title already exists."); 24 | } 25 | 26 | public async Task BeUniqueTitle(string title, 27 | CancellationToken cancellationToken) 28 | { 29 | return await _context.TodoLists 30 | .AllAsync(l => l.Title != title); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/Common/Mappings/MappingProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using System; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | namespace CaWorkshop.Application.Common.Mappings 7 | { 8 | public class MappingProfile : Profile 9 | { 10 | public MappingProfile() 11 | { 12 | ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly()); 13 | } 14 | 15 | private void ApplyMappingsFromAssembly(Assembly assembly) 16 | { 17 | var types = assembly.GetExportedTypes() 18 | .Where(t => t.GetInterfaces().Any(i => 19 | i.IsGenericType && 20 | i.GetGenericTypeDefinition() == typeof(IMapFrom<>))) 21 | .ToList(); 22 | 23 | foreach (var type in types) 24 | { 25 | var method = type.GetMethod("Mapping") ?? 26 | type.GetInterface("IMapFrom`1") 27 | .GetMethod("Mapping"); 28 | 29 | var instance = Activator.CreateInstance(type); 30 | 31 | method?.Invoke(instance, new object[] { this }); 32 | } 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /CaWorkshop.Application.UnitTests/Common/Mappings/MappingTests.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using CaWorkshop.Application.TodoLists.Queries.GetTodoLists; 3 | using CaWorkshop.Domain.Entities; 4 | using System; 5 | using Xunit; 6 | 7 | namespace CaWorkshop.Application.UnitTests.Common.Mapping 8 | { 9 | public class MappingTests : IClassFixture 10 | { 11 | private readonly IMapper _mapper; 12 | 13 | public MappingTests(MappingFixture fixture) 14 | { 15 | _mapper = fixture.Mapper; 16 | } 17 | 18 | [Fact] 19 | public void ShouldHaveValidConfiguration() 20 | { 21 | _mapper 22 | .ConfigurationProvider 23 | .AssertConfigurationIsValid(); 24 | } 25 | 26 | [Theory] 27 | [InlineData(typeof(TodoList), typeof(TodoListDto))] 28 | [InlineData(typeof(TodoItem), typeof(TodoItemDto))] 29 | public void ShouldSupportMappingFromSourceToDestination 30 | (Type source, Type destination) 31 | { 32 | var instance = Activator.CreateInstance(source); 33 | 34 | _mapper.Map(instance, source, destination); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/Common/Exceptions/ValidationException.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation.Results; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace CaWorkshop.Application.Common.Exceptions 7 | { 8 | public class ValidationException : Exception 9 | { 10 | public ValidationException() 11 | : base("One or more validation errors occurred.") 12 | { 13 | Errors = new Dictionary(); 14 | } 15 | 16 | public ValidationException(List failures) 17 | : this() 18 | { 19 | var propertyNames = failures 20 | .Select(e => e.PropertyName) 21 | .Distinct(); 22 | 23 | foreach (var propertyName in propertyNames) 24 | { 25 | var propertyFailures = failures 26 | .Where(e => e.PropertyName == propertyName) 27 | .Select(e => e.ErrorMessage) 28 | .ToArray(); 29 | 30 | Errors.Add(propertyName, propertyFailures); 31 | } 32 | } 33 | 34 | public IDictionary Errors { get; } 35 | } 36 | } -------------------------------------------------------------------------------- /CaWorkshop.Application.UnitTests/TodoLists/Commands/CreateTodoLists/CreateTodoListCommandTests.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.TodoLists.Commands.CreateTodoList; 2 | using CaWorkshop.Infrastructure.Persistence; 3 | using Shouldly; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using Xunit; 7 | 8 | namespace CaWorkshop.Application.UnitTests.TodoLists.Commands.CreateTodoList 9 | { 10 | 11 | public class CreateTodoListCommandTests : TestBase 12 | { 13 | private readonly ApplicationDbContext _context; 14 | 15 | public CreateTodoListCommandTests() 16 | { 17 | _context = Context; 18 | } 19 | 20 | [Fact] 21 | public async Task Handle_ShouldPersistTodoList() 22 | { 23 | var command = new CreateTodoListCommand 24 | { 25 | Title = "Bucket List" 26 | }; 27 | 28 | var handler = new CreateTodoListCommandHandler(_context); 29 | 30 | var result = await handler.Handle(command, 31 | CancellationToken.None); 32 | 33 | var entity = _context.TodoLists.Find(result); 34 | 35 | entity.ShouldNotBeNull(); 36 | entity.Title.ShouldBe(command.Title); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoLists/Commands/CreateTodoList/CreateTodoListCommand.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Interfaces; 2 | using CaWorkshop.Domain.Entities; 3 | using MediatR; 4 | using System.ComponentModel.DataAnnotations; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace CaWorkshop.Application.TodoLists.Commands.CreateTodoList 9 | { 10 | public class CreateTodoListCommand : IRequest 11 | { 12 | public string Title { get; set; } 13 | } 14 | 15 | 16 | public class CreateTodoListCommandHandler 17 | : IRequestHandler 18 | { 19 | private readonly IApplicationDbContext _context; 20 | 21 | public CreateTodoListCommandHandler(IApplicationDbContext context) 22 | { 23 | _context = context; 24 | } 25 | 26 | public async Task Handle(CreateTodoListCommand request, 27 | CancellationToken cancellationToken) 28 | { 29 | var entity = new TodoList(); 30 | 31 | entity.Title = request.Title; 32 | 33 | _context.TodoLists.Add(entity); 34 | 35 | await _context.SaveChangesAsync(cancellationToken); 36 | 37 | return entity.Id; 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoLists/Queries/GetTodoLists/GetTodoListsQuery.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using AutoMapper.QueryableExtensions; 3 | using CaWorkshop.Application.Common.Interfaces; 4 | using MediatR; 5 | using Microsoft.EntityFrameworkCore; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace CaWorkshop.Application.TodoLists.Queries.GetTodoLists 10 | { 11 | public class GetTodoListsQuery : IRequest 12 | { 13 | } 14 | 15 | public class GetTodoListsQueryHandler 16 | : IRequestHandler 17 | { 18 | private readonly IApplicationDbContext _context; 19 | private readonly IMapper _mapper; 20 | 21 | public GetTodoListsQueryHandler(IApplicationDbContext context, IMapper mapper) 22 | { 23 | _context = context; 24 | _mapper = mapper; 25 | } 26 | 27 | public async Task Handle( 28 | GetTodoListsQuery request, 29 | CancellationToken cancellationToken) 30 | { 31 | var vm = new TodosVm(); 32 | 33 | vm.Lists = await _context.TodoLists 34 | .ProjectTo(_mapper.ConfigurationProvider) 35 | .ToListAsync(cancellationToken); 36 | 37 | return vm; 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoLists/Queries/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "requires": true, 3 | "lockfileVersion": 1, 4 | "dependencies": { 5 | "@fortawesome/fontawesome-common-types": { 6 | "version": "0.2.27", 7 | "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-0.2.27.tgz", 8 | "integrity": "sha512-97GaByGaXDGMkzcJX7VmR/jRJd8h1mfhtA7RsxDBN61GnWE/PPCZhOdwG/8OZYktiRUF0CvFOr+VgRkJrt6TWg==" 9 | }, 10 | "@fortawesome/fontawesome-svg-core": { 11 | "version": "1.2.27", 12 | "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-1.2.27.tgz", 13 | "integrity": "sha512-sOD3DKynocnHYpuw2sLPnTunDj7rLk91LYhi2axUYwuGe9cPCw7Bsu9EWtVdNJP+IYgTCZIbyARKXuy5K/nv+Q==", 14 | "requires": { 15 | "@fortawesome/fontawesome-common-types": "^0.2.27" 16 | } 17 | }, 18 | "@fortawesome/free-solid-svg-icons": { 19 | "version": "5.12.1", 20 | "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-5.12.1.tgz", 21 | "integrity": "sha512-k3MwRFFUhyL4cuCJSaHDA0YNYMELDXX0h8JKtWYxO5XD3Dn+maXOMrVAAiNGooUyM2v/wz/TOaM0jxYVKeXX7g==", 22 | "requires": { 23 | "@fortawesome/fontawesome-common-types": "^0.2.27" 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/app/counter/counter.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } 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(async(() => { 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', async(() => { 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', async(() => { 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 | -------------------------------------------------------------------------------- /CaWorkshop.Application.UnitTests/TodoLists/Queries/GetTodoLists/GetTodoListsQueryTests.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using CaWorkshop.Application.TodoLists.Queries.GetTodoLists; 3 | using CaWorkshop.Infrastructure.Persistence; 4 | using Shouldly; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | 9 | namespace CaWorkshop.Application.UnitTests.TodoLists.Queries.GetTodoLists 10 | { 11 | [Collection("QueryTests")] 12 | public class GetTodoListsQueryTests 13 | { 14 | private readonly ApplicationDbContext _context; 15 | private readonly IMapper _mapper; 16 | 17 | public GetTodoListsQueryTests(TestBase testBase) 18 | { 19 | _context = testBase.Context; 20 | _mapper = testBase.Mapper; 21 | } 22 | 23 | [Fact] 24 | public async Task Handle_ReturnsCorrectVmAndListCount() 25 | { 26 | // Arrange 27 | var query = new GetTodoListsQuery(); 28 | var handler = new GetTodoListsQueryHandler(_context, _mapper); 29 | 30 | // Act 31 | var result = await handler.Handle(query, CancellationToken.None); 32 | 33 | // Assert 34 | result.ShouldBeOfType(); 35 | result.Lists.Count.ShouldBe(1); 36 | result.Lists[0].Items.Count.ShouldBe(5); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoItems/Commands/CreateTodoItem/CreateTodoItemCommand.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Interfaces; 2 | using CaWorkshop.Domain.Entities; 3 | using MediatR; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace CaWorkshop.Application.TodoItems.Commands.CreateTodoItem 8 | { 9 | public class CreateTodoItemCommand : IRequest 10 | { 11 | public int ListId { get; set; } 12 | 13 | public string Title { get; set; } 14 | } 15 | 16 | public class CreateTodoItemCommandHandler 17 | : IRequestHandler 18 | { 19 | private readonly IApplicationDbContext _context; 20 | 21 | public CreateTodoItemCommandHandler(IApplicationDbContext context) 22 | { 23 | _context = context; 24 | } 25 | 26 | public async Task Handle(CreateTodoItemCommand request, 27 | CancellationToken cancellationToken) 28 | { 29 | var entity = new TodoItem 30 | { 31 | ListId = request.ListId, 32 | Title = request.Title, 33 | Done = false 34 | }; 35 | 36 | _context.TodoItems.Add(entity); 37 | 38 | await _context.SaveChangesAsync(cancellationToken); 39 | 40 | return entity.Id; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoItems/Commands/DeleteTodoItem/DeleteTodoItemCommand.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Exceptions; 2 | using CaWorkshop.Application.Common.Interfaces; 3 | using CaWorkshop.Domain.Entities; 4 | using MediatR; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace CaWorkshop.Application.TodoItems.Commands.DeleteTodoItem 9 | { 10 | public class DeleteTodoItemCommand : IRequest 11 | { 12 | public long Id { get; set; } 13 | } 14 | 15 | public class DeleteTodoItemCommandHandler 16 | : IRequestHandler 17 | { 18 | private readonly IApplicationDbContext _context; 19 | 20 | public DeleteTodoItemCommandHandler(IApplicationDbContext context) 21 | { 22 | _context = context; 23 | } 24 | 25 | public async Task Handle(DeleteTodoItemCommand request, 26 | CancellationToken cancellationToken) 27 | { 28 | var entity = await _context.TodoItems.FindAsync(request.Id); 29 | 30 | if (entity == null) 31 | { 32 | throw new NotFoundException(nameof(TodoItem), request.Id); 33 | } 34 | 35 | _context.TodoItems.Remove(entity); 36 | 37 | await _context.SaveChangesAsync(cancellationToken); 38 | 39 | return Unit.Value; 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Authorization; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace CaWorkshop.WebUI.Controllers 10 | { 11 | [Authorize] 12 | [ApiController] 13 | [Route("[controller]")] 14 | public class WeatherForecastController : ControllerBase 15 | { 16 | private static readonly string[] Summaries = new[] 17 | { 18 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 19 | }; 20 | 21 | private readonly ILogger _logger; 22 | 23 | public WeatherForecastController(ILogger logger) 24 | { 25 | _logger = logger; 26 | } 27 | 28 | [HttpGet] 29 | public IEnumerable Get() 30 | { 31 | var rng = new Random(); 32 | return Enumerable.Range(1, 10).Select(index => new WeatherForecast 33 | { 34 | Date = DateTime.Now.AddDays(index), 35 | TemperatureC = rng.Next(-20, 55), 36 | Summary = Summaries[rng.Next(Summaries.Length)] 37 | }) 38 | .ToArray(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Pages/Shared/_LoginPartial.cshtml: -------------------------------------------------------------------------------- 1 | @using Microsoft.AspNetCore.Identity 2 | @using CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.Infrastructure/DependencyInjection.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Interfaces; 2 | using CaWorkshop.Infrastructure.Identity; 3 | using CaWorkshop.Infrastructure.Persistence; 4 | using Microsoft.AspNetCore.Authentication; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.DependencyInjection; 8 | 9 | namespace CaWorkshop.Infrastructure 10 | { 11 | public static class DependencyInjection 12 | { 13 | public static IServiceCollection AddInfrastructure( 14 | this IServiceCollection services, 15 | IConfiguration configuration) 16 | { 17 | services.AddDbContext(options => 18 | options.UseSqlServer( 19 | configuration.GetConnectionString("DefaultConnection"))); 20 | 21 | services.AddScoped(); 22 | 23 | services.AddScoped(provider => provider.GetService()); 24 | 25 | services.AddDefaultIdentity() 26 | .AddEntityFrameworkStores(); 27 | 28 | services.AddIdentityServer() 29 | .AddApiAuthorization(); 30 | 31 | services.AddAuthentication() 32 | .AddIdentityServerJwt(); 33 | 34 | return services; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/Common/Behaviours/RequestLoggerBehaviour.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Interfaces; 2 | using MediatR.Pipeline; 3 | using Microsoft.Extensions.Logging; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace CaWorkshop.Application.Common.Behaviours 8 | { 9 | public class RequestLoggerBehaviour 10 | : IRequestPreProcessor 11 | { 12 | private readonly ILogger _logger; 13 | private readonly ICurrentUserService _currentUserService; 14 | private readonly IIdentityService _identityService; 15 | 16 | public RequestLoggerBehaviour( 17 | ILogger logger, 18 | ICurrentUserService currentUserService, 19 | IIdentityService identityService) 20 | { 21 | _logger = logger; 22 | _currentUserService = currentUserService; 23 | _identityService = identityService; 24 | } 25 | 26 | public async Task Process( 27 | TRequest request, 28 | CancellationToken cancellationToken) 29 | { 30 | var requestName = typeof(TRequest).Name; 31 | var userId = _currentUserService.UserId; 32 | var userName = await _identityService.GetUserNameAsync(userId); 33 | 34 | _logger.LogInformation( 35 | "CaWorkshop Request: {Name} {@UserId} {@UserName} {@Request}", 36 | requestName, userId, userName, request); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.Application.UnitTests/TodoList/Commands/CreateTodoList/CreateTodoListValidatorTests.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.TodoLists.Commands.CreateTodoList; 2 | using CaWorkshop.Infrastructure.Persistence; 3 | using Shouldly; 4 | using Xunit; 5 | 6 | namespace CaWorkshop.Application.UnitTests.TodoLists.Commands.CreateTodoList 7 | { 8 | public class CreateTodoListCommandValidatorTests : TestBase 9 | { 10 | private readonly ApplicationDbContext _context; 11 | 12 | public CreateTodoListCommandValidatorTests() 13 | { 14 | _context = Context; 15 | } 16 | 17 | [Fact] 18 | public void IsValid_ShouldBeTrue_WhenListTitleIsUnique() 19 | { 20 | var command = new CreateTodoListCommand 21 | { 22 | Title = "Bucket List" 23 | }; 24 | 25 | var validator = new CreateTodoListCommandValidator(_context); 26 | 27 | var result = validator.Validate(command); 28 | 29 | result.IsValid.ShouldBe(true); 30 | } 31 | 32 | [Fact] 33 | public void IsValid_ShouldBeFalse_WhenListTitleIsNotUnique() 34 | { 35 | var command = new CreateTodoListCommand 36 | { 37 | Title = "Death List Five" 38 | }; 39 | 40 | var validator = new CreateTodoListCommandValidator(_context); 41 | 42 | var result = validator.Validate(command); 43 | 44 | result.IsValid.ShouldBe(false); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/Common/Behaviours/RequestValidationBehaviour.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using MediatR; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using ValidationException = 8 | CaWorkshop.Application.Common.Exceptions.ValidationException; 9 | 10 | namespace CaWorkshop.Application.Common.Behaviours 11 | { 12 | public class RequestValidationBehavior 13 | : IPipelineBehavior 14 | where TRequest : IRequest 15 | { 16 | private readonly IEnumerable> _validators; 17 | 18 | public RequestValidationBehavior( 19 | IEnumerable> validators) 20 | { 21 | _validators = validators; 22 | } 23 | 24 | public Task Handle(TRequest request, 25 | CancellationToken cancellationToken, 26 | RequestHandlerDelegate next) 27 | { 28 | var context = new ValidationContext(request); 29 | 30 | var failures = _validators 31 | .Select(v => v.Validate(context)) 32 | .SelectMany(result => result.Errors) 33 | .Where(f => f != null) 34 | .ToList(); 35 | 36 | if (failures.Count != 0) 37 | { 38 | throw new ValidationException(failures); 39 | } 40 | 41 | return next(); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoLists/Commands/DeleteTodoList/DeleteTodoListCommand.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Exceptions; 2 | using CaWorkshop.Application.Common.Interfaces; 3 | using CaWorkshop.Domain.Entities; 4 | using MediatR; 5 | using Microsoft.EntityFrameworkCore; 6 | using System.Linq; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace CaWorkshop.Application.TodoLists.Commands.DeleteTodoList 11 | { 12 | public class DeleteTodoListCommand : IRequest 13 | { 14 | public int Id { get; set; } 15 | } 16 | 17 | public class DeleteTodoListCommandHandler 18 | : IRequestHandler 19 | { 20 | private readonly IApplicationDbContext _context; 21 | 22 | public DeleteTodoListCommandHandler(IApplicationDbContext context) 23 | { 24 | _context = context; 25 | } 26 | 27 | public async Task Handle(DeleteTodoListCommand request, 28 | CancellationToken cancellationToken) 29 | { 30 | var entity = await _context.TodoLists 31 | .Where(l => l.Id == request.Id) 32 | .SingleOrDefaultAsync(cancellationToken); 33 | 34 | if (entity == null) 35 | { 36 | throw new NotFoundException(nameof(TodoList), request.Id); 37 | } 38 | 39 | _context.TodoLists.Remove(entity); 40 | 41 | await _context.SaveChangesAsync(cancellationToken); 42 | 43 | return Unit.Value; 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoLists/Commands/UpdateTodoList/UpdateTodoListCommand.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Exceptions; 2 | using CaWorkshop.Application.Common.Interfaces; 3 | using CaWorkshop.Domain.Entities; 4 | using MediatR; 5 | using System.ComponentModel.DataAnnotations; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace CaWorkshop.Application.TodoLists.Commands.UpdateTodoList 10 | { 11 | public class UpdateTodoListCommand : IRequest 12 | { 13 | public int Id { get; set; } 14 | 15 | [Required] 16 | [StringLength(240)] 17 | public string Title { get; set; } 18 | } 19 | 20 | public class UpdateTodoListCommandHandler 21 | : IRequestHandler 22 | { 23 | private readonly IApplicationDbContext _context; 24 | 25 | public UpdateTodoListCommandHandler(IApplicationDbContext context) 26 | { 27 | _context = context; 28 | } 29 | 30 | public async Task Handle(UpdateTodoListCommand request, 31 | CancellationToken cancellationToken) 32 | { 33 | var entity = await _context.TodoLists.FindAsync(request.Id); 34 | 35 | if (entity == null) 36 | { 37 | throw new NotFoundException(nameof(TodoList), request.Id); 38 | } 39 | 40 | entity.Title = request.Title; 41 | 42 | await _context.SaveChangesAsync(cancellationToken); 43 | 44 | return Unit.Value; 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Program.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Infrastructure.Persistence; 2 | using Microsoft.AspNetCore; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Logging; 7 | using System; 8 | 9 | namespace CaWorkshop.WebUI 10 | { 11 | public class Program 12 | { 13 | public static void Main(string[] args) 14 | { 15 | var host = CreateWebHostBuilder(args).Build(); 16 | 17 | using (var scope = host.Services.CreateScope()) 18 | { 19 | var services = scope.ServiceProvider; 20 | 21 | try 22 | { 23 | var context = services 24 | .GetRequiredService(); 25 | 26 | context.Database.Migrate(); 27 | 28 | ApplicationDbContextSeeder.Seed(context); 29 | } 30 | catch (Exception ex) 31 | { 32 | var logger = services 33 | .GetRequiredService>(); 34 | 35 | logger.LogError(ex, "An error occurred while " + 36 | "migrating or initializing the database."); 37 | } 38 | } 39 | 40 | host.Run(); 41 | } 42 | 43 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 44 | WebHost.CreateDefaultBuilder(args) 45 | .UseStartup(); 46 | } 47 | } -------------------------------------------------------------------------------- /CaWorkshop.Application.UnitTests/DbContextFactory.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Interfaces; 2 | using CaWorkshop.Infrastructure.Persistence; 3 | using IdentityServer4.EntityFramework.Options; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.Extensions.Options; 6 | using Moq; 7 | using System; 8 | 9 | namespace CaWorkshop.Application.UnitTests 10 | { 11 | public static class DbContextFactory 12 | { 13 | public static ApplicationDbContext Create() 14 | { 15 | var options = new DbContextOptionsBuilder() 16 | .UseInMemoryDatabase(Guid.NewGuid().ToString()) 17 | .Options; 18 | 19 | var operationalStoreOptions = Options.Create( 20 | new OperationalStoreOptions 21 | { 22 | DeviceFlowCodes = 23 | new TableConfiguration("DeviceCodes"), 24 | PersistedGrants = 25 | new TableConfiguration("PersistedGrants") 26 | }); 27 | 28 | var currentUserServiceMock = new Mock(); 29 | currentUserServiceMock.Setup(m => m.UserId) 30 | .Returns("00000000-0000-0000-0000-000000000000"); 31 | 32 | var context = new ApplicationDbContext( 33 | options, operationalStoreOptions, 34 | currentUserServiceMock.Object); 35 | 36 | ApplicationDbContextSeeder.Seed(context); 37 | 38 | return context; 39 | } 40 | 41 | public static void Destroy(ApplicationDbContext context) 42 | { 43 | context.Database.EnsureDeleted(); 44 | context.Dispose(); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /CaWorkshop.Infrastructure/Persistence/ApplicationDbContextSeeder.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Domain.Entities; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace CaWorkshop.Infrastructure.Persistence 6 | { 7 | public static class ApplicationDbContextSeeder 8 | { 9 | public static void Seed(ApplicationDbContext context) 10 | { 11 | if (context.TodoLists.Any()) 12 | { 13 | return; 14 | } 15 | 16 | context.TodoLists.Add( 17 | new TodoList 18 | { 19 | Title = "Death List Five", 20 | Items = new List 21 | { 22 | new TodoItem 23 | { 24 | Title = "O-Ren Ishii", 25 | Done = true 26 | }, 27 | new TodoItem 28 | { 29 | Title = "Vernita Green", 30 | Done = true 31 | }, 32 | new TodoItem 33 | { 34 | Title = "Budd", 35 | Done = true 36 | }, 37 | new TodoItem 38 | { 39 | Title = "Ellie Driver" 40 | }, 41 | new TodoItem 42 | { 43 | Title = "Bill" 44 | } 45 | } 46 | } 47 | ); 48 | 49 | context.SaveChanges(); 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Controllers/TodoItemsController.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.TodoItems.Commands.CreateTodoItem; 2 | using CaWorkshop.Application.TodoItems.Commands.DeleteTodoItem; 3 | using CaWorkshop.Application.TodoItems.Commands.UpdateTodoItem; 4 | using MediatR; 5 | using Microsoft.AspNetCore.Mvc; 6 | using System.Threading.Tasks; 7 | using Microsoft.AspNetCore.Authorization; 8 | using Microsoft.AspNetCore.Http; 9 | 10 | namespace CaWorkshop.WebUI.Controllers 11 | { 12 | [Authorize] 13 | [Route("api/[controller]")] 14 | [ApiController] 15 | public class TodoItemsController : ControllerBase 16 | { 17 | private readonly IMediator _mediator; 18 | 19 | public TodoItemsController(IMediator mediator) 20 | { 21 | _mediator = mediator; 22 | } 23 | 24 | // POST: api/TodoItems 25 | [HttpPost] 26 | public async Task> PostTodoItem( 27 | CreateTodoItemCommand command) 28 | { 29 | return await _mediator.Send(command); 30 | } 31 | 32 | // PUT: api/TodoItems/5 33 | [HttpPut("{id}")] 34 | public async Task PutTodoItem(long id, 35 | UpdateTodoItemCommand 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 | // DELETE: api/TodoItems/5 48 | [HttpDelete("{id}")] 49 | [ProducesResponseType(StatusCodes.Status204NoContent)] 50 | public async Task DeleteTodoItem(long id) 51 | { 52 | await _mediator.Send(new DeleteTodoItemCommand { Id = id }); 53 | 54 | return NoContent(); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /CaWorkshop.Application/TodoItems/Commands/UpdateTodoItem/UpdateTodoItemCommand.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Exceptions; 2 | using CaWorkshop.Application.Common.Interfaces; 3 | using CaWorkshop.Domain.Entities; 4 | using MediatR; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace CaWorkshop.Application.TodoItems.Commands.UpdateTodoItem 9 | { 10 | public partial class UpdateTodoItemCommand : IRequest 11 | { 12 | public long Id { get; set; } 13 | 14 | public int ListId { get; set; } 15 | 16 | public string Title { get; set; } 17 | 18 | public bool Done { get; set; } 19 | 20 | public int Priority { get; set; } 21 | 22 | public string Note { get; set; } 23 | } 24 | 25 | public class UpdateTodoItemCommandHandler 26 | : IRequestHandler 27 | { 28 | private readonly IApplicationDbContext _context; 29 | 30 | public UpdateTodoItemCommandHandler(IApplicationDbContext context) 31 | { 32 | _context = context; 33 | } 34 | 35 | public async Task Handle(UpdateTodoItemCommand request, 36 | CancellationToken cancellationToken) 37 | { 38 | var entity = await _context.TodoItems.FindAsync(request.Id); 39 | 40 | if (entity == null) 41 | { 42 | throw new NotFoundException(nameof(TodoItem), request.Id); 43 | } 44 | 45 | entity.ListId = request.ListId; 46 | entity.Title = request.Title; 47 | entity.Done = request.Done; 48 | entity.Priority = (PriorityLevel)request.Priority; 49 | entity.Note = request.Note; 50 | 51 | await _context.SaveChangesAsync(cancellationToken); 52 | 53 | return Unit.Value; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Controllers/TodoListsController.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.TodoLists.Commands.CreateTodoList; 2 | using CaWorkshop.Application.TodoLists.Commands.DeleteTodoList; 3 | using CaWorkshop.Application.TodoLists.Commands.UpdateTodoList; 4 | using CaWorkshop.Application.TodoLists.Queries.GetTodoLists; 5 | using MediatR; 6 | using Microsoft.AspNetCore.Authorization; 7 | using Microsoft.AspNetCore.Mvc; 8 | using System.Threading.Tasks; 9 | 10 | namespace CaWorkshop.WebUI.Controllers 11 | { 12 | [Authorize] 13 | [Route("api/[controller]")] 14 | [ApiController] 15 | public class TodoListsController : ControllerBase 16 | { 17 | private readonly IMediator _mediator; 18 | 19 | public TodoListsController(IMediator mediator) 20 | { 21 | _mediator = mediator; 22 | } 23 | 24 | // GET: api/TodoLists 25 | [HttpGet] 26 | public async Task> GetTodoLists() 27 | { 28 | return await _mediator.Send(new GetTodoListsQuery()); 29 | 30 | } 31 | 32 | // POST: api/TodoLists 33 | [HttpPost] 34 | public async Task> PostTodoList( 35 | CreateTodoListCommand command) 36 | { 37 | return await _mediator.Send(command); 38 | } 39 | 40 | // PUT: api/TodoLists/5 41 | [HttpPut("{id}")] 42 | public async Task PutTodoList(int id, 43 | UpdateTodoListCommand command) 44 | { 45 | if (id != command.Id) 46 | { 47 | return BadRequest(); 48 | } 49 | 50 | await _mediator.Send(command); 51 | 52 | return NoContent(); 53 | } 54 | 55 | // DELETE: api/TodoLists/5 56 | [HttpDelete("{id}")] 57 | public async Task DeleteTodoList(int id) 58 | { 59 | await _mediator.Send(new DeleteTodoListCommand { Id = id }); 60 | 61 | return NoContent(); 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/app/nav-menu/nav-menu.component.html: -------------------------------------------------------------------------------- 1 |
2 | 53 |
54 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "caworkshop.webui", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "build:ssr": "ng run CaWorkshop.WebUI:server:dev", 9 | "test": "ng test", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/animations": "8.2.12", 16 | "@angular/common": "8.2.12", 17 | "@angular/compiler": "8.2.12", 18 | "@angular/core": "8.2.12", 19 | "@angular/forms": "8.2.12", 20 | "@angular/platform-browser": "8.2.12", 21 | "@angular/platform-browser-dynamic": "8.2.12", 22 | "@angular/platform-server": "8.2.12", 23 | "@angular/router": "8.2.12", 24 | "@fortawesome/angular-fontawesome": "^0.6.0", 25 | "@fortawesome/fontawesome-svg-core": "^1.2.27", 26 | "@fortawesome/free-solid-svg-icons": "^5.12.1", 27 | "@nguniversal/module-map-ngfactory-loader": "8.1.1", 28 | "aspnet-prerendering": "^3.0.1", 29 | "bootstrap": "^4.3.1", 30 | "core-js": "^3.3.3", 31 | "jquery": "3.4.1", 32 | "ngx-bootstrap": "^5.3.2", 33 | "oidc-client": "^1.9.1", 34 | "popper.js": "^1.16.0", 35 | "rxjs": "^6.5.3", 36 | "zone.js": "0.9.1" 37 | }, 38 | "devDependencies": { 39 | "@angular-devkit/build-angular": "^0.803.14", 40 | "@angular/cli": "8.3.14", 41 | "@angular/compiler-cli": "8.2.12", 42 | "@angular/language-service": "8.2.12", 43 | "@types/jasmine": "~3.4.4", 44 | "@types/jasminewd2": "~2.0.8", 45 | "@types/node": "~12.11.6", 46 | "codelyzer": "^5.2.0", 47 | "jasmine-core": "~3.5.0", 48 | "jasmine-spec-reporter": "~4.2.1", 49 | "karma": "^4.4.1", 50 | "karma-chrome-launcher": "~3.1.0", 51 | "karma-coverage-istanbul-reporter": "~2.1.0", 52 | "karma-jasmine": "~2.0.1", 53 | "karma-jasmine-html-reporter": "^1.4.2", 54 | "typescript": "3.5.3" 55 | }, 56 | "optionalDependencies": { 57 | "node-sass": "^4.12.0", 58 | "protractor": "~5.4.2", 59 | "ts-node": "~8.4.1", 60 | "tslint": "~5.20.0" 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /CaWorkshop.Application/Common/Behaviours/RequestPerformanceBehaviour.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Interfaces; 2 | using MediatR; 3 | using Microsoft.Extensions.Logging; 4 | using System.Diagnostics; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace CaWorkshop.Application.Common.Behaviours 9 | { 10 | public class RequestPerformanceBehaviour 11 | : IPipelineBehavior 12 | { 13 | private readonly Stopwatch _timer; 14 | private readonly ILogger _logger; 15 | private readonly ICurrentUserService _currentUserService; 16 | private readonly IIdentityService _identityService; 17 | 18 | public RequestPerformanceBehaviour( 19 | ILogger logger, 20 | ICurrentUserService currentUserService, 21 | IIdentityService identityService) 22 | { 23 | _timer = new Stopwatch(); 24 | 25 | _logger = logger; 26 | _currentUserService = currentUserService; 27 | _identityService = identityService; 28 | } 29 | 30 | public async Task Handle( 31 | TRequest request, CancellationToken 32 | cancellationToken, 33 | RequestHandlerDelegate next) 34 | { 35 | _timer.Start(); 36 | 37 | var response = await next(); 38 | 39 | _timer.Stop(); 40 | 41 | var elapsedMilliseconds = _timer.ElapsedMilliseconds; 42 | 43 | if (elapsedMilliseconds > 500) 44 | { 45 | var requestName = typeof(TRequest).Name; 46 | var userId = _currentUserService.UserId; 47 | var userName = 48 | await _identityService.GetUserNameAsync(userId); 49 | 50 | _logger.LogWarning( 51 | "CaWorkshop Long Running Request: {Name} " + 52 | "({ElapsedMilliseconds} milliseconds) {@UserId} " + 53 | "{@Request}", 54 | requestName, elapsedMilliseconds, 55 | userId, userName, request); 56 | } 57 | 58 | return response; 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /CaWorkshop.Infrastructure/Identity/IdentityService.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Interfaces; 2 | using CaWorkshop.Application.Common.Models; 3 | using Microsoft.AspNetCore.Identity; 4 | using Microsoft.EntityFrameworkCore; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace CaWorkshop.Infrastructure.Identity 9 | { 10 | public class IdentityService : IIdentityService 11 | { 12 | private readonly UserManager _userManager; 13 | 14 | public IdentityService(UserManager userManager) 15 | { 16 | _userManager = userManager; 17 | } 18 | 19 | public async Task GetUserNameAsync(string userId) 20 | { 21 | var user = await _userManager.Users.FirstAsync(u => 22 | u.Id == userId); 23 | 24 | return user.UserName; 25 | } 26 | 27 | public async Task<(Result Result, string UserId)> CreateUserAsync( 28 | string userName, string password) 29 | { 30 | var user = new ApplicationUser 31 | { 32 | UserName = userName, 33 | Email = userName, 34 | }; 35 | 36 | var result = await _userManager.CreateAsync(user, password); 37 | 38 | return (result.ToApplicationResult(), user.Id); 39 | } 40 | 41 | public async Task DeleteUserAsync(string userId) 42 | { 43 | var user = _userManager.Users.SingleOrDefault(u => 44 | u.Id == userId); 45 | 46 | if (user != null) 47 | { 48 | return await DeleteUserAsync(user); 49 | } 50 | 51 | return Result.Success(); 52 | } 53 | 54 | public async Task DeleteUserAsync(ApplicationUser user) 55 | { 56 | var result = await _userManager.DeleteAsync(user); 57 | 58 | return result.ToApplicationResult(); 59 | } 60 | } 61 | 62 | public static class IdentityResultExtensions 63 | { 64 | public static Result ToApplicationResult(this IdentityResult result) 65 | { 66 | return result.Succeeded 67 | ? Result.Success() 68 | : Result.Failure(result.Errors.Select(e => e.Description)); 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Common/CustomExceptionHandlerMiddleware.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Exceptions; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Http; 4 | using Newtonsoft.Json; 5 | using System; 6 | using System.Net; 7 | using System.Threading.Tasks; 8 | 9 | namespace CleanArchitecture.WebUI.Common 10 | { 11 | public class CustomExceptionHandlerMiddleware 12 | { 13 | private readonly RequestDelegate _next; 14 | 15 | public CustomExceptionHandlerMiddleware(RequestDelegate next) 16 | { 17 | _next = next; 18 | } 19 | 20 | public async Task Invoke(HttpContext context) 21 | { 22 | try 23 | { 24 | await _next(context); 25 | } 26 | catch (Exception ex) 27 | { 28 | await HandleExceptionAsync(context, ex); 29 | } 30 | } 31 | 32 | private Task HandleExceptionAsync( 33 | HttpContext context, Exception exception) 34 | { 35 | var code = HttpStatusCode.InternalServerError; 36 | 37 | var result = string.Empty; 38 | 39 | switch (exception) 40 | { 41 | case ValidationException validationException: 42 | code = HttpStatusCode.BadRequest; 43 | result = JsonConvert.SerializeObject( 44 | validationException.Errors); 45 | break; 46 | case NotFoundException _: 47 | code = HttpStatusCode.NotFound; 48 | break; 49 | } 50 | 51 | context.Response.ContentType = "application/json"; 52 | context.Response.StatusCode = (int)code; 53 | 54 | if (string.IsNullOrEmpty(result)) 55 | { 56 | result = JsonConvert.SerializeObject( 57 | new { error = exception.Message }); 58 | } 59 | 60 | return context.Response.WriteAsync(result); 61 | } 62 | } 63 | 64 | public static class CustomExceptionHandlerMiddlewareExtensions 65 | { 66 | public static IApplicationBuilder UseCustomExceptionHandler( 67 | this IApplicationBuilder builder) 68 | { 69 | return builder.UseMiddleware(); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /CaWorkshop.Application/DependencyInjection.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using CaWorkshop.Application.Common.Behaviours; 3 | using FluentValidation; 4 | using MediatR; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using System.Linq; 8 | using System.Reflection; 9 | 10 | namespace CaWorkshop.Application 11 | { 12 | public static class DependencyInjection 13 | { 14 | public static IServiceCollection AddApplication( 15 | this IServiceCollection services, 16 | IConfiguration configuration) 17 | { 18 | services.AddMediatR(Assembly.GetExecutingAssembly()); 19 | services.AddAutoMapper(Assembly.GetExecutingAssembly()); 20 | 21 | services.AddTransient(typeof(IPipelineBehavior<,>), 22 | typeof(RequestValidationBehavior<,>)); 23 | 24 | services.AddTransient(typeof(IPipelineBehavior<,>), 25 | typeof(RequestPerformanceBehaviour<,>)); 26 | 27 | services.AddAllRequestValidators(); 28 | 29 | return services; 30 | } 31 | 32 | // NOTE: My apologies! If I had more time, 33 | // I would have created a shorter method. ;) 34 | private static IServiceCollection AddAllRequestValidators( 35 | this IServiceCollection services) 36 | { 37 | var validatorType = typeof(IValidator<>); 38 | 39 | var validatorTypes = Assembly.GetExecutingAssembly() 40 | .GetExportedTypes() 41 | .Where(t => t.GetInterfaces().Any(i => 42 | i.IsGenericType && 43 | i.GetGenericTypeDefinition() == validatorType)) 44 | .ToList(); 45 | 46 | foreach (var validator in validatorTypes) 47 | { 48 | var requestType = validator.GetInterfaces() 49 | .Where(i => i.IsGenericType && 50 | i.GetGenericTypeDefinition() == typeof(IValidator<>)) 51 | .Select(i => i.GetGenericArguments()[0]) 52 | .First(); 53 | 54 | var validatorInterface = validatorType 55 | .MakeGenericType(requestType); 56 | 57 | services.AddTransient(validatorInterface, validator); 58 | } 59 | 60 | return services; 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /CaWorkshop.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 { RouterModule } from "@angular/router"; 6 | import { FontAwesomeModule } from "@fortawesome/angular-fontawesome"; 7 | import { API_BASE_URL } from "./services/ca-workshop-api.service"; 8 | import { environment } from "src/environments/environment"; 9 | import { TodoComponent } from "./todo/todo.component"; 10 | 11 | import { AppComponent } from "./app.component"; 12 | import { NavMenuComponent } from "./nav-menu/nav-menu.component"; 13 | import { HomeComponent } from "./home/home.component"; 14 | import { CounterComponent } from "./counter/counter.component"; 15 | import { FetchDataComponent } from "./fetch-data/fetch-data.component"; 16 | import { ApiAuthorizationModule } from "src/api-authorization/api-authorization.module"; 17 | import { AuthorizeGuard } from "src/api-authorization/authorize.guard"; 18 | import { AuthorizeInterceptor } from "src/api-authorization/authorize.interceptor"; 19 | import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; 20 | import { ModalModule } from "ngx-bootstrap/modal"; 21 | 22 | @NgModule({ 23 | declarations: [ 24 | AppComponent, 25 | NavMenuComponent, 26 | HomeComponent, 27 | CounterComponent, 28 | FetchDataComponent, 29 | TodoComponent 30 | ], 31 | imports: [ 32 | BrowserModule.withServerTransition({ appId: "ng-cli-universal" }), 33 | HttpClientModule, 34 | FormsModule, 35 | ApiAuthorizationModule, 36 | FontAwesomeModule, 37 | RouterModule.forRoot([ 38 | { path: "", component: HomeComponent, pathMatch: "full" }, 39 | { path: "counter", component: CounterComponent }, 40 | { 41 | path: "fetch-data", 42 | component: FetchDataComponent, 43 | canActivate: [AuthorizeGuard] 44 | }, 45 | { path: "todo", component: TodoComponent, canActivate: [AuthorizeGuard] } 46 | ]), 47 | BrowserAnimationsModule, 48 | ModalModule.forRoot() 49 | ], 50 | providers: [ 51 | { provide: HTTP_INTERCEPTORS, useClass: AuthorizeInterceptor, multi: true }, 52 | { provide: API_BASE_URL, useValue: environment.apiBaseUrl } 53 | ], 54 | bootstrap: [AppComponent] 55 | }) 56 | export class AppModule {} 57 | -------------------------------------------------------------------------------- /CaWorkshop.Infrastructure/Persistence/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application.Common.Interfaces; 2 | using CaWorkshop.Domain.Common; 3 | using CaWorkshop.Domain.Entities; 4 | using CaWorkshop.Infrastructure.Identity; 5 | using IdentityServer4.EntityFramework.Options; 6 | using Microsoft.AspNetCore.ApiAuthorization.IdentityServer; 7 | using Microsoft.EntityFrameworkCore; 8 | using Microsoft.Extensions.Options; 9 | using System; 10 | using System.Reflection; 11 | using System.Threading; 12 | using System.Threading.Tasks; 13 | 14 | namespace CaWorkshop.Infrastructure.Persistence 15 | { 16 | public class ApplicationDbContext 17 | : ApiAuthorizationDbContext, IApplicationDbContext 18 | { 19 | private readonly ICurrentUserService _currentUserService; 20 | 21 | public ApplicationDbContext( 22 | DbContextOptions options, 23 | IOptions operationalStoreOptions, 24 | ICurrentUserService currentUserService) 25 | : base(options, operationalStoreOptions) 26 | { 27 | _currentUserService = currentUserService; 28 | } 29 | 30 | public DbSet TodoItems { get; set; } 31 | 32 | public DbSet TodoLists { get; set; } 33 | 34 | public override Task SaveChangesAsync( 35 | 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 43 | = _currentUserService.UserId; 44 | entry.Entity.CreatedUtc 45 | = DateTime.UtcNow; 46 | break; 47 | case EntityState.Modified: 48 | entry.Entity.LastModifiedBy 49 | = _currentUserService.UserId; 50 | entry.Entity.LastModifiedUtc 51 | = DateTime.UtcNow; 52 | break; 53 | } 54 | } 55 | 56 | return base.SaveChangesAsync(cancellationToken); 57 | } 58 | 59 | protected override void OnModelCreating(ModelBuilder builder) 60 | { 61 | builder.ApplyConfigurationsFromAssembly( 62 | Assembly.GetExecutingAssembly()); 63 | 64 | base.OnModelCreating(builder); 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /CaWorkshop.Infrastructure/Persistence/Migrations/20200225000904_Todo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace CaWorkshop.Infrastructure.Persistence.Migrations 5 | { 6 | public partial class Todo : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "TodoLists", 12 | columns: table => new 13 | { 14 | Id = table.Column(nullable: false) 15 | .Annotation("SqlServer:Identity", "1, 1"), 16 | Title = table.Column(maxLength: 280, nullable: false), 17 | Colour = table.Column(nullable: true) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PK_TodoLists", x => x.Id); 22 | }); 23 | 24 | migrationBuilder.CreateTable( 25 | name: "TodoItems", 26 | columns: table => new 27 | { 28 | Id = table.Column(nullable: false) 29 | .Annotation("SqlServer:Identity", "1, 1"), 30 | ListId = table.Column(nullable: false), 31 | Title = table.Column(maxLength: 280, nullable: false), 32 | Note = table.Column(maxLength: 4000, nullable: true), 33 | Done = table.Column(nullable: false), 34 | Reminder = table.Column(nullable: true), 35 | Priority = table.Column(nullable: false) 36 | }, 37 | constraints: table => 38 | { 39 | table.PrimaryKey("PK_TodoItems", x => x.Id); 40 | table.ForeignKey( 41 | name: "FK_TodoItems_TodoLists_ListId", 42 | column: x => x.ListId, 43 | principalTable: "TodoLists", 44 | principalColumn: "Id", 45 | onDelete: ReferentialAction.Cascade); 46 | }); 47 | 48 | migrationBuilder.CreateIndex( 49 | name: "IX_TodoItems_ListId", 50 | table: "TodoItems", 51 | column: "ListId"); 52 | } 53 | 54 | protected override void Down(MigrationBuilder migrationBuilder) 55 | { 56 | migrationBuilder.DropTable( 57 | name: "TodoItems"); 58 | 59 | migrationBuilder.DropTable( 60 | name: "TodoLists"); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /CaWorkshop.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/dist/zone'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /CaWorkshop.Infrastructure/Persistence/Migrations/20200225061624_Audit Todos.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace CaWorkshop.Infrastructure.Persistence.Migrations 5 | { 6 | public partial class AuditTodos : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.AddColumn( 11 | name: "CreatedBy", 12 | table: "TodoLists", 13 | nullable: true); 14 | 15 | migrationBuilder.AddColumn( 16 | name: "CreatedUtc", 17 | table: "TodoLists", 18 | nullable: false, 19 | defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); 20 | 21 | migrationBuilder.AddColumn( 22 | name: "LastModifiedBy", 23 | table: "TodoLists", 24 | nullable: true); 25 | 26 | migrationBuilder.AddColumn( 27 | name: "LastModifiedUtc", 28 | table: "TodoLists", 29 | nullable: true); 30 | 31 | migrationBuilder.AddColumn( 32 | name: "CreatedBy", 33 | table: "TodoItems", 34 | nullable: true); 35 | 36 | migrationBuilder.AddColumn( 37 | name: "CreatedUtc", 38 | table: "TodoItems", 39 | nullable: false, 40 | defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); 41 | 42 | migrationBuilder.AddColumn( 43 | name: "LastModifiedBy", 44 | table: "TodoItems", 45 | nullable: true); 46 | 47 | migrationBuilder.AddColumn( 48 | name: "LastModifiedUtc", 49 | table: "TodoItems", 50 | nullable: true); 51 | } 52 | 53 | protected override void Down(MigrationBuilder migrationBuilder) 54 | { 55 | migrationBuilder.DropColumn( 56 | name: "CreatedBy", 57 | table: "TodoLists"); 58 | 59 | migrationBuilder.DropColumn( 60 | name: "CreatedUtc", 61 | table: "TodoLists"); 62 | 63 | migrationBuilder.DropColumn( 64 | name: "LastModifiedBy", 65 | table: "TodoLists"); 66 | 67 | migrationBuilder.DropColumn( 68 | name: "LastModifiedUtc", 69 | table: "TodoLists"); 70 | 71 | migrationBuilder.DropColumn( 72 | name: "CreatedBy", 73 | table: "TodoItems"); 74 | 75 | migrationBuilder.DropColumn( 76 | name: "CreatedUtc", 77 | table: "TodoItems"); 78 | 79 | migrationBuilder.DropColumn( 80 | name: "LastModifiedBy", 81 | table: "TodoItems"); 82 | 83 | migrationBuilder.DropColumn( 84 | name: "LastModifiedUtc", 85 | table: "TodoItems"); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/api-authorization/api-authorization.constants.ts: -------------------------------------------------------------------------------- 1 | export const ApplicationName = 'CaWorkshop.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 | -------------------------------------------------------------------------------- /CaWorkshop.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29806.167 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaWorkshop.WebUI", "CaWorkshop.WebUI\CaWorkshop.WebUI.csproj", "{5AF23B36-16A2-40F4-8FD1-14CB7A444B6E}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaWorkshop.Domain", "CaWorkshop.Domain\CaWorkshop.Domain.csproj", "{881C86B6-B9A5-428E-8D0E-DAC62736DE82}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaWorkshop.Application", "CaWorkshop.Application\CaWorkshop.Application.csproj", "{CE9BF19D-0C7B-4CA3-A9DF-23F5993D8B54}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaWorkshop.Infrastructure", "CaWorkshop.Infrastructure\CaWorkshop.Infrastructure.csproj", "{80EF17AC-3D6B-47DB-A342-7566FBDDD08B}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaWorkshop.Application.UnitTests", "CaWorkshop.Application.UnitTests\CaWorkshop.Application.UnitTests.csproj", "{EE46A9D5-2090-4B19-A902-DA6F35F46B56}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {5AF23B36-16A2-40F4-8FD1-14CB7A444B6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {5AF23B36-16A2-40F4-8FD1-14CB7A444B6E}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {5AF23B36-16A2-40F4-8FD1-14CB7A444B6E}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {5AF23B36-16A2-40F4-8FD1-14CB7A444B6E}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {881C86B6-B9A5-428E-8D0E-DAC62736DE82}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {881C86B6-B9A5-428E-8D0E-DAC62736DE82}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {881C86B6-B9A5-428E-8D0E-DAC62736DE82}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {881C86B6-B9A5-428E-8D0E-DAC62736DE82}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {CE9BF19D-0C7B-4CA3-A9DF-23F5993D8B54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {CE9BF19D-0C7B-4CA3-A9DF-23F5993D8B54}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {CE9BF19D-0C7B-4CA3-A9DF-23F5993D8B54}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {CE9BF19D-0C7B-4CA3-A9DF-23F5993D8B54}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {80EF17AC-3D6B-47DB-A342-7566FBDDD08B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {80EF17AC-3D6B-47DB-A342-7566FBDDD08B}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {80EF17AC-3D6B-47DB-A342-7566FBDDD08B}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {80EF17AC-3D6B-47DB-A342-7566FBDDD08B}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {EE46A9D5-2090-4B19-A902-DA6F35F46B56}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {EE46A9D5-2090-4B19-A902-DA6F35F46B56}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {EE46A9D5-2090-4B19-A902-DA6F35F46B56}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {EE46A9D5-2090-4B19-A902-DA6F35F46B56}.Release|Any CPU.Build.0 = Release|Any CPU 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | GlobalSection(ExtensibilityGlobals) = postSolution 47 | SolutionGuid = {A4A5688A-A349-4A76-9F22-81383E7137EE} 48 | EndGlobalSection 49 | EndGlobal 50 | -------------------------------------------------------------------------------- /CaWorkshop.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-use-before-declare": true, 76 | "no-var-keyword": true, 77 | "object-literal-sort-keys": false, 78 | "one-line": [ 79 | true, 80 | "check-open-brace", 81 | "check-catch", 82 | "check-else", 83 | "check-whitespace" 84 | ], 85 | "prefer-const": true, 86 | "quotemark": [ 87 | true, 88 | "single" 89 | ], 90 | "radix": true, 91 | "semicolon": [ 92 | true, 93 | "always" 94 | ], 95 | "triple-equals": [ 96 | true, 97 | "allow-null-check" 98 | ], 99 | "typedef-whitespace": [ 100 | true, 101 | { 102 | "call-signature": "nospace", 103 | "index-signature": "nospace", 104 | "parameter": "nospace", 105 | "property-declaration": "nospace", 106 | "variable-declaration": "nospace" 107 | } 108 | ], 109 | "unified-signatures": true, 110 | "variable-name": false, 111 | "whitespace": [ 112 | true, 113 | "check-branch", 114 | "check-decl", 115 | "check-operator", 116 | "check-separator", 117 | "check-type" 118 | ], 119 | "no-output-on-prefix": true, 120 | "no-inputs-metadata-property": true, 121 | "no-outputs-metadata-property": true, 122 | "no-host-metadata-property": true, 123 | "no-input-rename": true, 124 | "no-output-rename": true, 125 | "use-lifecycle-interface": true, 126 | "use-pipe-transform-interface": true, 127 | "component-class-suffix": true, 128 | "directive-class-suffix": true 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/Startup.cs: -------------------------------------------------------------------------------- 1 | using CaWorkshop.Application; 2 | using CaWorkshop.Application.Common.Interfaces; 3 | using CaWorkshop.Infrastructure; 4 | using CleanArchitecture.WebUI.Common; 5 | using CleanArchitecture.WebUI.Services; 6 | using Microsoft.AspNetCore.Builder; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.Hosting; 11 | 12 | namespace CaWorkshop.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.AddInfrastructure(Configuration); 27 | services.AddApplication(Configuration); 28 | services.AddHttpContextAccessor(); 29 | services.AddScoped(); 30 | 31 | services.AddControllersWithViews(); 32 | 33 | services.AddRazorPages(); 34 | // In production, the Angular files will be served from this directory 35 | services.AddSpaStaticFiles(configuration => 36 | { 37 | configuration.RootPath = "ClientApp/dist"; 38 | }); 39 | 40 | services.AddOpenApiDocument(configure => 41 | { 42 | configure.Title = "CaWorkshop API"; 43 | }); 44 | } 45 | 46 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 47 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 48 | { 49 | if (env.IsDevelopment()) 50 | { 51 | app.UseDeveloperExceptionPage(); 52 | app.UseDatabaseErrorPage(); 53 | } 54 | else 55 | { 56 | app.UseExceptionHandler("/Error"); 57 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 58 | app.UseHsts(); 59 | } 60 | 61 | app.UseCustomExceptionHandler(); 62 | app.UseHttpsRedirection(); 63 | app.UseStaticFiles(); 64 | if (!env.IsDevelopment()) 65 | { 66 | app.UseSpaStaticFiles(); 67 | } 68 | 69 | app.UseSwaggerUi3(settings => 70 | { 71 | settings.DocumentPath = "/api/specification.json"; 72 | }); 73 | app.UseRouting(); 74 | 75 | app.UseAuthentication(); 76 | app.UseIdentityServer(); 77 | app.UseAuthorization(); 78 | app.UseEndpoints(endpoints => 79 | { 80 | endpoints.MapControllerRoute( 81 | name: "default", 82 | pattern: "{controller}/{action=Index}/{id?}"); 83 | endpoints.MapRazorPages(); 84 | }); 85 | 86 | app.UseSpa(spa => 87 | { 88 | // To learn more about options for serving an Angular SPA from ASP.NET Core, 89 | // see https://go.microsoft.com/fwlink/?linkid=864501 90 | 91 | spa.Options.SourcePath = "ClientApp"; 92 | 93 | if (env.IsDevelopment()) 94 | { 95 | // spa.UseAngularCliServer(npmScript: "start"); 96 | spa.UseProxyToSpaDevelopmentServer("http://localhost:4200"); 97 | } 98 | }); 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/openapi.nswag: -------------------------------------------------------------------------------- 1 | { 2 | "runtime": "NetCore30", 3 | "defaultVariables": null, 4 | "documentGenerator": { 5 | "aspNetCoreToOpenApi": { 6 | "project": "CaWorkshop.WebUI.csproj", 7 | "msBuildProjectExtensionsPath": null, 8 | "configuration": null, 9 | "runtime": null, 10 | "targetFramework": null, 11 | "noBuild": true, 12 | "verbose": true, 13 | "workingDirectory": null, 14 | "requireParametersWithoutDefault": false, 15 | "apiGroupNames": null, 16 | "defaultPropertyNameHandling": "Default", 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": "My Title", 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": "Swagger2", 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 | "useSingletonProvider": true, 67 | "injectionTokenType": "InjectionToken", 68 | "rxJsVersion": 6.0, 69 | "dateTimeType": "Date", 70 | "nullValue": "Undefined", 71 | "generateClientClasses": true, 72 | "generateClientInterfaces": true, 73 | "generateOptionalParameters": false, 74 | "exportTypes": true, 75 | "wrapDtoExceptions": false, 76 | "exceptionClass": "ApiException", 77 | "clientBaseClass": null, 78 | "wrapResponses": false, 79 | "wrapResponseMethods": [], 80 | "generateResponseClasses": true, 81 | "responseClass": "SwaggerResponse", 82 | "protectedMethods": [], 83 | "configurationClass": null, 84 | "useTransformOptionsMethod": false, 85 | "useTransformResultMethod": false, 86 | "generateDtoTypes": true, 87 | "operationGenerationMode": "MultipleClientsFromOperationId", 88 | "markOptionalProperties": true, 89 | "generateCloneMethod": false, 90 | "typeStyle": "Class", 91 | "classTypes": [], 92 | "extendedClasses": [], 93 | "extensionCode": null, 94 | "generateDefaultValues": true, 95 | "excludedTypeNames": [], 96 | "excludedParameterNames": [], 97 | "handleReferences": false, 98 | "generateConstructorInterface": true, 99 | "convertConstructorInterfaceData": false, 100 | "importRequiredTypes": true, 101 | "useGetBaseUrlMethod": false, 102 | "baseUrlTokenName": "API_BASE_URL", 103 | "queryNullValue": "", 104 | "inlineNamedDictionaries": false, 105 | "inlineNamedAny": false, 106 | "templateDirectory": null, 107 | "typeNameGeneratorType": null, 108 | "propertyNameGeneratorType": null, 109 | "enumNameGeneratorType": null, 110 | "serviceHost": null, 111 | "serviceSchemes": null, 112 | "output": "ClientApp/src/app/services/ca-workshop-api.service.ts" 113 | } 114 | } 115 | } -------------------------------------------------------------------------------- /CaWorkshop.WebUI/CaWorkshop.WebUI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | true 6 | Latest 7 | false 8 | ClientApp\ 9 | $(DefaultItemExcludes);$(SpaRoot)node_modules\** 10 | 11 | 12 | false 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | all 29 | runtime; build; native; contentfiles; analyzers; buildtransitive 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | %(DistFiles.Identity) 73 | PreserveNewest 74 | true 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /CaWorkshop.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.css'] 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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/.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 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | *_i.c 44 | *_p.c 45 | *_i.h 46 | *.ilk 47 | *.meta 48 | *.obj 49 | *.pch 50 | *.pdb 51 | *.pgc 52 | *.pgd 53 | *.rsp 54 | *.sbr 55 | *.tlb 56 | *.tli 57 | *.tlh 58 | *.tmp 59 | *.tmp_proj 60 | *.log 61 | *.vspscc 62 | *.vssscc 63 | .builds 64 | *.pidb 65 | *.svclog 66 | *.scc 67 | 68 | # Chutzpah Test files 69 | _Chutzpah* 70 | 71 | # Visual C++ cache files 72 | ipch/ 73 | *.aps 74 | *.ncb 75 | *.opendb 76 | *.opensdf 77 | *.sdf 78 | *.cachefile 79 | 80 | # Visual Studio profiler 81 | *.psess 82 | *.vsp 83 | *.vspx 84 | *.sap 85 | 86 | # TFS 2012 Local Workspace 87 | $tf/ 88 | 89 | # Guidance Automation Toolkit 90 | *.gpState 91 | 92 | # ReSharper is a .NET coding add-in 93 | _ReSharper*/ 94 | *.[Rr]e[Ss]harper 95 | *.DotSettings.user 96 | 97 | # JustCode is a .NET coding add-in 98 | .JustCode 99 | 100 | # TeamCity is a build add-in 101 | _TeamCity* 102 | 103 | # DotCover is a Code Coverage Tool 104 | *.dotCover 105 | 106 | # NCrunch 107 | _NCrunch_* 108 | .*crunch*.local.xml 109 | nCrunchTemp_* 110 | 111 | # MightyMoose 112 | *.mm.* 113 | AutoTest.Net/ 114 | 115 | # Web workbench (sass) 116 | .sass-cache/ 117 | 118 | # Installshield output folder 119 | [Ee]xpress/ 120 | 121 | # DocProject is a documentation generator add-in 122 | DocProject/buildhelp/ 123 | DocProject/Help/*.HxT 124 | DocProject/Help/*.HxC 125 | DocProject/Help/*.hhc 126 | DocProject/Help/*.hhk 127 | DocProject/Help/*.hhp 128 | DocProject/Help/Html2 129 | DocProject/Help/html 130 | 131 | # Click-Once directory 132 | publish/ 133 | 134 | # Publish Web Output 135 | *.[Pp]ublish.xml 136 | *.azurePubxml 137 | # TODO: Comment the next line if you want to checkin your web deploy settings 138 | # but database connection strings (with potential passwords) will be unencrypted 139 | *.pubxml 140 | *.publishproj 141 | 142 | # NuGet Packages 143 | *.nupkg 144 | # The packages folder can be ignored because of Package Restore 145 | **/packages/* 146 | # except build/, which is used as an MSBuild target. 147 | !**/packages/build/ 148 | # Uncomment if necessary however generally it will be regenerated when needed 149 | #!**/packages/repositories.config 150 | 151 | # Microsoft Azure Build Output 152 | csx/ 153 | *.build.csdef 154 | 155 | # Microsoft Azure Emulator 156 | ecf/ 157 | rcf/ 158 | 159 | # Microsoft Azure ApplicationInsights config file 160 | ApplicationInsights.config 161 | 162 | # Windows Store app package directory 163 | AppPackages/ 164 | BundleArtifacts/ 165 | 166 | # Visual Studio cache files 167 | # files ending in .cache can be ignored 168 | *.[Cc]ache 169 | # but keep track of directories ending in .cache 170 | !*.[Cc]ache/ 171 | 172 | # Others 173 | ClientBin/ 174 | ~$* 175 | *~ 176 | *.dbmdl 177 | *.dbproj.schemaview 178 | *.pfx 179 | *.publishsettings 180 | orleans.codegen.cs 181 | 182 | /node_modules 183 | 184 | # RIA/Silverlight projects 185 | Generated_Code/ 186 | 187 | # Backup & report files from converting an old project file 188 | # to a newer Visual Studio version. Backup files are not needed, 189 | # because we have git ;-) 190 | _UpgradeReport_Files/ 191 | Backup*/ 192 | UpgradeLog*.XML 193 | UpgradeLog*.htm 194 | 195 | # SQL Server files 196 | *.mdf 197 | *.ldf 198 | 199 | # Business Intelligence projects 200 | *.rdl.data 201 | *.bim.layout 202 | *.bim_*.settings 203 | 204 | # Microsoft Fakes 205 | FakesAssemblies/ 206 | 207 | # GhostDoc plugin setting file 208 | *.GhostDoc.xml 209 | 210 | # Node.js Tools for Visual Studio 211 | .ntvs_analysis.dat 212 | 213 | # Visual Studio 6 build log 214 | *.plg 215 | 216 | # Visual Studio 6 workspace options file 217 | *.opt 218 | 219 | # Visual Studio LightSwitch build output 220 | **/*.HTMLClient/GeneratedArtifacts 221 | **/*.DesktopClient/GeneratedArtifacts 222 | **/*.DesktopClient/ModelManifest.xml 223 | **/*.Server/GeneratedArtifacts 224 | **/*.Server/ModelManifest.xml 225 | _Pvt_Extensions 226 | 227 | # Paket dependency manager 228 | .paket/paket.exe 229 | 230 | # FAKE - F# Make 231 | .fake/ 232 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "CaWorkshop.WebUI": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "prefix": "app", 11 | "schematics": {}, 12 | "architect": { 13 | "build": { 14 | "builder": "@angular-devkit/build-angular:browser", 15 | "options": { 16 | "progress": false, 17 | "extractCss": true, 18 | "outputPath": "dist", 19 | "index": "src/index.html", 20 | "main": "src/main.ts", 21 | "polyfills": "src/polyfills.ts", 22 | "tsConfig": "src/tsconfig.app.json", 23 | "assets": ["src/assets"], 24 | "styles": [ 25 | "./node_modules/bootstrap/dist/css/bootstrap.min.css", 26 | "./node_modules/ngx-bootstrap/datepicker/bs-datepicker.css", 27 | "src/styles.css" 28 | ], 29 | "scripts": [] 30 | }, 31 | "configurations": { 32 | "production": { 33 | "fileReplacements": [ 34 | { 35 | "replace": "src/environments/environment.ts", 36 | "with": "src/environments/environment.prod.ts" 37 | } 38 | ], 39 | "optimization": true, 40 | "outputHashing": "all", 41 | "sourceMap": false, 42 | "extractCss": true, 43 | "namedChunks": false, 44 | "aot": true, 45 | "extractLicenses": true, 46 | "vendorChunk": false, 47 | "buildOptimizer": true 48 | } 49 | } 50 | }, 51 | "serve": { 52 | "builder": "@angular-devkit/build-angular:dev-server", 53 | "options": { 54 | "browserTarget": "CaWorkshop.WebUI:build" 55 | }, 56 | "configurations": { 57 | "production": { 58 | "browserTarget": "CaWorkshop.WebUI:build:production" 59 | } 60 | } 61 | }, 62 | "extract-i18n": { 63 | "builder": "@angular-devkit/build-angular:extract-i18n", 64 | "options": { 65 | "browserTarget": "CaWorkshop.WebUI:build" 66 | } 67 | }, 68 | "test": { 69 | "builder": "@angular-devkit/build-angular:karma", 70 | "options": { 71 | "main": "src/test.ts", 72 | "polyfills": "src/polyfills.ts", 73 | "tsConfig": "src/tsconfig.spec.json", 74 | "karmaConfig": "src/karma.conf.js", 75 | "styles": [ 76 | "./node_modules/bootstrap/dist/css/bootstrap.min.css", 77 | "./node_modules/ngx-bootstrap/datepicker/bs-datepicker.css", 78 | "src/styles.css" 79 | ], 80 | "scripts": [], 81 | "assets": ["src/assets"] 82 | } 83 | }, 84 | "lint": { 85 | "builder": "@angular-devkit/build-angular:tslint", 86 | "options": { 87 | "tsConfig": ["src/tsconfig.app.json", "src/tsconfig.spec.json"], 88 | "exclude": ["**/node_modules/**"] 89 | } 90 | }, 91 | "server": { 92 | "builder": "@angular-devkit/build-angular:server", 93 | "options": { 94 | "outputPath": "dist-server", 95 | "main": "src/main.ts", 96 | "tsConfig": "src/tsconfig.server.json" 97 | }, 98 | "configurations": { 99 | "dev": { 100 | "optimization": true, 101 | "outputHashing": "all", 102 | "sourceMap": false, 103 | "namedChunks": false, 104 | "extractLicenses": true, 105 | "vendorChunk": true 106 | }, 107 | "production": { 108 | "optimization": true, 109 | "outputHashing": "all", 110 | "sourceMap": false, 111 | "namedChunks": false, 112 | "extractLicenses": true, 113 | "vendorChunk": false 114 | } 115 | } 116 | } 117 | } 118 | }, 119 | "CaWorkshop.WebUI-e2e": { 120 | "root": "e2e/", 121 | "projectType": "application", 122 | "architect": { 123 | "e2e": { 124 | "builder": "@angular-devkit/build-angular:protractor", 125 | "options": { 126 | "protractorConfig": "e2e/protractor.conf.js", 127 | "devServerTarget": "CaWorkshop.WebUI:serve" 128 | } 129 | }, 130 | "lint": { 131 | "builder": "@angular-devkit/build-angular:tslint", 132 | "options": { 133 | "tsConfig": "e2e/tsconfig.e2e.json", 134 | "exclude": ["**/node_modules/**"] 135 | } 136 | } 137 | } 138 | } 139 | }, 140 | "defaultProject": "CaWorkshop.WebUI" 141 | } 142 | -------------------------------------------------------------------------------- /CaWorkshop.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.css'] 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 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/app/todo/todo.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, TemplateRef, OnInit } from "@angular/core"; 2 | import { faPlus, faEllipsisH } from "@fortawesome/free-solid-svg-icons"; 3 | import { BsModalService, BsModalRef } from "ngx-bootstrap/modal"; 4 | import { 5 | TodoListsClient, 6 | TodoItemsClient, 7 | TodoListDto, 8 | TodoItemDto, 9 | PriorityLevelDto, 10 | CreateTodoListCommand, 11 | UpdateTodoListCommand, 12 | CreateTodoItemCommand, 13 | UpdateTodoItemCommand 14 | } from "../services/ca-workshop-api.service"; 15 | 16 | @Component({ 17 | selector: "app-todo-component", 18 | templateUrl: "./todo.component.html", 19 | styleUrls: ["./todo.component.css"] 20 | }) 21 | export class TodoComponent implements OnInit { 22 | debug = false; 23 | lists: TodoListDto[]; 24 | priorityLevels: PriorityLevelDto[]; 25 | selectedList: TodoListDto; 26 | selectedItem: TodoItemDto; 27 | newListEditor: any = {}; 28 | listOptionsEditor: any = {}; 29 | itemDetailsEditor: any = {}; 30 | newListModalRef: BsModalRef; 31 | listOptionsModalRef: BsModalRef; 32 | deleteListModalRef: BsModalRef; 33 | itemDetailsModalRef: BsModalRef; 34 | faPlus = faPlus; 35 | faEllipsisH = faEllipsisH; 36 | 37 | constructor( 38 | private listsClient: TodoListsClient, 39 | private itemsClient: TodoItemsClient, 40 | private modalService: BsModalService 41 | ) {} 42 | 43 | ngOnInit(): void { 44 | this.listsClient.getTodoLists().subscribe( 45 | result => { 46 | this.lists = result.lists; 47 | this.priorityLevels = result.priorityLevels; 48 | if (this.lists.length) { 49 | this.selectedList = this.lists[0]; 50 | } 51 | }, 52 | error => console.error(error) 53 | ); 54 | } 55 | 56 | // Lists 57 | remainingItems(list: TodoListDto): number { 58 | return list.items.filter(t => !t.done).length; 59 | } 60 | 61 | showNewListModal(template: TemplateRef): void { 62 | this.newListModalRef = this.modalService.show(template); 63 | setTimeout(() => document.getElementById("title").focus(), 250); 64 | } 65 | 66 | newListCancelled(): void { 67 | this.newListModalRef.hide(); 68 | this.newListEditor = {}; 69 | } 70 | 71 | addList(): void { 72 | const list = { 73 | id: 0, 74 | title: this.newListEditor.title, 75 | items: [] 76 | } as TodoListDto; 77 | 78 | this.listsClient.postTodoList(list).subscribe( 79 | result => { 80 | list.id = result; 81 | this.lists.push(list); 82 | this.selectedList = list; 83 | this.newListModalRef.hide(); 84 | this.newListEditor = {}; 85 | }, 86 | error => { 87 | const errors = JSON.parse(error.response); 88 | 89 | if (errors && errors.Title) { 90 | this.newListEditor.error = errors.Title[0]; 91 | } 92 | 93 | setTimeout(() => document.getElementById("title").focus(), 250); 94 | } 95 | ); 96 | } 97 | 98 | showListOptionsModal(template: TemplateRef) { 99 | this.listOptionsEditor = { 100 | id: this.selectedList.id, 101 | title: this.selectedList.title 102 | }; 103 | 104 | this.listOptionsModalRef = this.modalService.show(template); 105 | } 106 | 107 | updateListOptions() { 108 | const list = this.listOptionsEditor as UpdateTodoListCommand; 109 | this.listsClient.putTodoList(this.selectedList.id, list).subscribe( 110 | () => { 111 | (this.selectedList.title = this.listOptionsEditor.title), 112 | this.listOptionsModalRef.hide(); 113 | this.listOptionsEditor = {}; 114 | }, 115 | error => console.error(error) 116 | ); 117 | } 118 | 119 | confirmDeleteList(template: TemplateRef) { 120 | this.listOptionsModalRef.hide(); 121 | this.deleteListModalRef = this.modalService.show(template); 122 | } 123 | 124 | deleteListConfirmed(): void { 125 | this.listsClient.deleteTodoList(this.selectedList.id).subscribe( 126 | () => { 127 | this.deleteListModalRef.hide(); 128 | this.lists = this.lists.filter(t => t.id !== this.selectedList.id); 129 | this.selectedList = this.lists.length ? this.lists[0] : null; 130 | }, 131 | error => console.error(error) 132 | ); 133 | } 134 | 135 | // Items 136 | showItemDetailsModal(template: TemplateRef, item: TodoItemDto): void { 137 | this.selectedItem = item; 138 | this.itemDetailsEditor = { 139 | ...this.selectedItem 140 | }; 141 | 142 | this.itemDetailsModalRef = this.modalService.show(template); 143 | } 144 | 145 | updateItemDetails(): void { 146 | const item = this.itemDetailsEditor as UpdateTodoItemCommand; 147 | this.itemsClient.putTodoItem(this.selectedItem.id, item).subscribe( 148 | () => { 149 | if (this.selectedItem.listId !== this.itemDetailsEditor.listId) { 150 | this.selectedList.items = this.selectedList.items.filter( 151 | i => i.id !== this.selectedItem.id 152 | ); 153 | const listIndex = this.lists.findIndex( 154 | l => l.id === this.itemDetailsEditor.listId 155 | ); 156 | this.selectedItem.listId = this.itemDetailsEditor.listId; 157 | this.lists[listIndex].items.push(this.selectedItem); 158 | } 159 | 160 | this.selectedItem.priority = this.itemDetailsEditor.priority; 161 | this.selectedItem.note = this.itemDetailsEditor.note; 162 | this.itemDetailsModalRef.hide(); 163 | this.itemDetailsEditor = {}; 164 | }, 165 | error => console.error(error) 166 | ); 167 | } 168 | 169 | addItem() { 170 | const item = { 171 | id: 0, 172 | listId: this.selectedList.id, 173 | priority: this.priorityLevels[0].value, 174 | title: "", 175 | done: false 176 | } as TodoItemDto; 177 | 178 | this.selectedList.items.push(item); 179 | const index = this.selectedList.items.length - 1; 180 | this.editItem(item, "itemTitle" + index); 181 | } 182 | 183 | editItem(item: TodoItemDto, inputId: string): void { 184 | this.selectedItem = item; 185 | setTimeout(() => document.getElementById(inputId).focus(), 100); 186 | } 187 | 188 | updateItem(item: TodoItemDto, pressedEnter: boolean = false): void { 189 | const isNewItem = item.id === 0; 190 | 191 | if (!item.title.trim()) { 192 | this.deleteItem(item); 193 | return; 194 | } 195 | 196 | if (item.id === 0) { 197 | this.itemsClient 198 | .postTodoItem({ 199 | ...item, 200 | listId: this.selectedList.id 201 | } as CreateTodoItemCommand) 202 | .subscribe( 203 | result => { 204 | item.id = result; 205 | }, 206 | error => console.error(error) 207 | ); 208 | } else { 209 | this.itemsClient.putTodoItem(item.id, item).subscribe( 210 | () => console.log("Update succeeded."), 211 | error => console.error(error) 212 | ); 213 | } 214 | 215 | this.selectedItem = null; 216 | 217 | if (isNewItem && pressedEnter) { 218 | setTimeout(() => this.addItem(), 250); 219 | } 220 | } 221 | 222 | deleteItem(item: TodoItemDto) { 223 | if (this.itemDetailsModalRef) { 224 | this.itemDetailsModalRef.hide(); 225 | } 226 | 227 | if (item.id === 0) { 228 | const itemIndex = this.selectedList.items.indexOf(this.selectedItem); 229 | this.selectedList.items.splice(itemIndex, 1); 230 | } else { 231 | this.itemsClient.deleteTodoItem(item.id).subscribe( 232 | () => 233 | (this.selectedList.items = this.selectedList.items.filter( 234 | t => t.id !== item.id 235 | )), 236 | error => console.error(error) 237 | ); 238 | } 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/api-authorization/authorize.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { User, UserManager, WebStorageStateStore } from 'oidc-client'; 3 | import { BehaviorSubject, concat, from, Observable } from 'rxjs'; 4 | import { filter, map, mergeMap, take, tap } from 'rxjs/operators'; 5 | import { ApplicationPaths, ApplicationName } from './api-authorization.constants'; 6 | 7 | export type IAuthenticationResult = 8 | SuccessAuthenticationResult | 9 | FailureAuthenticationResult | 10 | RedirectAuthenticationResult; 11 | 12 | export interface SuccessAuthenticationResult { 13 | status: AuthenticationResultStatus.Success; 14 | state: any; 15 | } 16 | 17 | export interface FailureAuthenticationResult { 18 | status: AuthenticationResultStatus.Fail; 19 | message: string; 20 | } 21 | 22 | export interface RedirectAuthenticationResult { 23 | status: AuthenticationResultStatus.Redirect; 24 | } 25 | 26 | export enum AuthenticationResultStatus { 27 | Success, 28 | Redirect, 29 | Fail 30 | } 31 | 32 | export interface IUser { 33 | name: string; 34 | } 35 | 36 | @Injectable({ 37 | providedIn: 'root' 38 | }) 39 | export class AuthorizeService { 40 | // By default pop ups are disabled because they don't work properly on Edge. 41 | // If you want to enable pop up authentication simply set this flag to false. 42 | 43 | private popUpDisabled = true; 44 | private userManager: UserManager; 45 | private userSubject: BehaviorSubject = new BehaviorSubject(null); 46 | 47 | public isAuthenticated(): Observable { 48 | return this.getUser().pipe(map(u => !!u)); 49 | } 50 | 51 | public getUser(): Observable { 52 | return concat( 53 | this.userSubject.pipe(take(1), filter(u => !!u)), 54 | this.getUserFromStorage().pipe(filter(u => !!u), tap(u => this.userSubject.next(u))), 55 | this.userSubject.asObservable()); 56 | } 57 | 58 | public getAccessToken(): Observable { 59 | return from(this.ensureUserManagerInitialized()) 60 | .pipe(mergeMap(() => from(this.userManager.getUser())), 61 | map(user => user && user.access_token)); 62 | } 63 | 64 | // We try to authenticate the user in three different ways: 65 | // 1) We try to see if we can authenticate the user silently. This happens 66 | // when the user is already logged in on the IdP and is done using a hidden iframe 67 | // on the client. 68 | // 2) We try to authenticate the user using a PopUp Window. This might fail if there is a 69 | // Pop-Up blocker or the user has disabled PopUps. 70 | // 3) If the two methods above fail, we redirect the browser to the IdP to perform a traditional 71 | // redirect flow. 72 | public async signIn(state: any): Promise { 73 | await this.ensureUserManagerInitialized(); 74 | let user: User = null; 75 | try { 76 | user = await this.userManager.signinSilent(this.createArguments()); 77 | this.userSubject.next(user.profile); 78 | return this.success(state); 79 | } catch (silentError) { 80 | // User might not be authenticated, fallback to popup authentication 81 | console.log('Silent authentication error: ', silentError); 82 | 83 | try { 84 | if (this.popUpDisabled) { 85 | throw new Error('Popup disabled. Change \'authorize.service.ts:AuthorizeService.popupDisabled\' to false to enable it.'); 86 | } 87 | user = await this.userManager.signinPopup(this.createArguments()); 88 | this.userSubject.next(user.profile); 89 | return this.success(state); 90 | } catch (popupError) { 91 | if (popupError.message === 'Popup window closed') { 92 | // The user explicitly cancelled the login action by closing an opened popup. 93 | return this.error('The user closed the window.'); 94 | } else if (!this.popUpDisabled) { 95 | console.log('Popup authentication error: ', popupError); 96 | } 97 | 98 | // PopUps might be blocked by the user, fallback to redirect 99 | try { 100 | await this.userManager.signinRedirect(this.createArguments(state)); 101 | return this.redirect(); 102 | } catch (redirectError) { 103 | console.log('Redirect authentication error: ', redirectError); 104 | return this.error(redirectError); 105 | } 106 | } 107 | } 108 | } 109 | 110 | public async completeSignIn(url: string): Promise { 111 | try { 112 | await this.ensureUserManagerInitialized(); 113 | const user = await this.userManager.signinCallback(url); 114 | this.userSubject.next(user && user.profile); 115 | return this.success(user && user.state); 116 | } catch (error) { 117 | console.log('There was an error signing in: ', error); 118 | return this.error('There was an error signing in.'); 119 | } 120 | } 121 | 122 | public async signOut(state: any): Promise { 123 | try { 124 | if (this.popUpDisabled) { 125 | throw new Error('Popup disabled. Change \'authorize.service.ts:AuthorizeService.popupDisabled\' to false to enable it.'); 126 | } 127 | 128 | await this.ensureUserManagerInitialized(); 129 | await this.userManager.signoutPopup(this.createArguments()); 130 | this.userSubject.next(null); 131 | return this.success(state); 132 | } catch (popupSignOutError) { 133 | console.log('Popup signout error: ', popupSignOutError); 134 | try { 135 | await this.userManager.signoutRedirect(this.createArguments(state)); 136 | return this.redirect(); 137 | } catch (redirectSignOutError) { 138 | console.log('Redirect signout error: ', popupSignOutError); 139 | return this.error(redirectSignOutError); 140 | } 141 | } 142 | } 143 | 144 | public async completeSignOut(url: string): Promise { 145 | await this.ensureUserManagerInitialized(); 146 | try { 147 | const state = await this.userManager.signoutCallback(url); 148 | this.userSubject.next(null); 149 | return this.success(state && state.data); 150 | } catch (error) { 151 | console.log(`There was an error trying to log out '${error}'.`); 152 | return this.error(error); 153 | } 154 | } 155 | 156 | private createArguments(state?: any): any { 157 | return { useReplaceToNavigate: true, data: state }; 158 | } 159 | 160 | private error(message: string): IAuthenticationResult { 161 | return { status: AuthenticationResultStatus.Fail, message }; 162 | } 163 | 164 | private success(state: any): IAuthenticationResult { 165 | return { status: AuthenticationResultStatus.Success, state }; 166 | } 167 | 168 | private redirect(): IAuthenticationResult { 169 | return { status: AuthenticationResultStatus.Redirect }; 170 | } 171 | 172 | private async ensureUserManagerInitialized(): Promise { 173 | if (this.userManager !== undefined) { 174 | return; 175 | } 176 | 177 | const response = await fetch(ApplicationPaths.ApiAuthorizationClientConfigurationUrl); 178 | if (!response.ok) { 179 | throw new Error(`Could not load settings for '${ApplicationName}'`); 180 | } 181 | 182 | const settings: any = await response.json(); 183 | settings.automaticSilentRenew = true; 184 | settings.includeIdTokenInSilentRenew = true; 185 | this.userManager = new UserManager(settings); 186 | 187 | this.userManager.events.addUserSignedOut(async () => { 188 | await this.userManager.removeUser(); 189 | this.userSubject.next(null); 190 | }); 191 | } 192 | 193 | private getUserFromStorage(): Observable { 194 | return from(this.ensureUserManagerInitialized()) 195 | .pipe( 196 | mergeMap(() => this.userManager.getUser()), 197 | map(u => u && u.profile)); 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | 33 | # Visual Studio 2015/2017 cache/options directory 34 | .vs/ 35 | # Uncomment if you have tasks that create the project's static files in wwwroot 36 | #wwwroot/ 37 | 38 | # Visual Studio 2017 auto generated files 39 | Generated\ Files/ 40 | 41 | # MSTest test Results 42 | [Tt]est[Rr]esult*/ 43 | [Bb]uild[Ll]og.* 44 | 45 | # NUNIT 46 | *.VisualState.xml 47 | TestResult.xml 48 | 49 | # Build Results of an ATL Project 50 | [Dd]ebugPS/ 51 | [Rr]eleasePS/ 52 | dlldata.c 53 | 54 | # Benchmark Results 55 | BenchmarkDotNet.Artifacts/ 56 | 57 | # .NET Core 58 | project.lock.json 59 | project.fragment.lock.json 60 | artifacts/ 61 | 62 | # StyleCop 63 | StyleCopReport.xml 64 | 65 | # Files built by Visual Studio 66 | *_i.c 67 | *_p.c 68 | *_h.h 69 | *.ilk 70 | *.meta 71 | *.obj 72 | *.iobj 73 | *.pch 74 | *.pdb 75 | *.ipdb 76 | *.pgc 77 | *.pgd 78 | *.rsp 79 | *.sbr 80 | *.tlb 81 | *.tli 82 | *.tlh 83 | *.tmp 84 | *.tmp_proj 85 | *_wpftmp.csproj 86 | *.log 87 | *.vspscc 88 | *.vssscc 89 | .builds 90 | *.pidb 91 | *.svclog 92 | *.scc 93 | 94 | # Chutzpah Test files 95 | _Chutzpah* 96 | 97 | # Visual C++ cache files 98 | ipch/ 99 | *.aps 100 | *.ncb 101 | *.opendb 102 | *.opensdf 103 | *.sdf 104 | *.cachefile 105 | *.VC.db 106 | *.VC.VC.opendb 107 | 108 | # Visual Studio profiler 109 | *.psess 110 | *.vsp 111 | *.vspx 112 | *.sap 113 | 114 | # Visual Studio Trace Files 115 | *.e2e 116 | 117 | # TFS 2012 Local Workspace 118 | $tf/ 119 | 120 | # Guidance Automation Toolkit 121 | *.gpState 122 | 123 | # ReSharper is a .NET coding add-in 124 | _ReSharper*/ 125 | *.[Rr]e[Ss]harper 126 | *.DotSettings.user 127 | 128 | # JustCode is a .NET coding add-in 129 | .JustCode 130 | 131 | # TeamCity is a build add-in 132 | _TeamCity* 133 | 134 | # DotCover is a Code Coverage Tool 135 | *.dotCover 136 | 137 | # AxoCover is a Code Coverage Tool 138 | .axoCover/* 139 | !.axoCover/settings.json 140 | 141 | # Visual Studio code coverage results 142 | *.coverage 143 | *.coveragexml 144 | 145 | # NCrunch 146 | _NCrunch_* 147 | .*crunch*.local.xml 148 | nCrunchTemp_* 149 | 150 | # MightyMoose 151 | *.mm.* 152 | AutoTest.Net/ 153 | 154 | # Web workbench (sass) 155 | .sass-cache/ 156 | 157 | # Installshield output folder 158 | [Ee]xpress/ 159 | 160 | # DocProject is a documentation generator add-in 161 | DocProject/buildhelp/ 162 | DocProject/Help/*.HxT 163 | DocProject/Help/*.HxC 164 | DocProject/Help/*.hhc 165 | DocProject/Help/*.hhk 166 | DocProject/Help/*.hhp 167 | DocProject/Help/Html2 168 | DocProject/Help/html 169 | 170 | # Click-Once directory 171 | publish/ 172 | 173 | # Publish Web Output 174 | *.[Pp]ublish.xml 175 | *.azurePubxml 176 | # Note: Comment the next line if you want to checkin your web deploy settings, 177 | # but database connection strings (with potential passwords) will be unencrypted 178 | *.pubxml 179 | *.publishproj 180 | 181 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 182 | # checkin your Azure Web App publish settings, but sensitive information contained 183 | # in these scripts will be unencrypted 184 | PublishScripts/ 185 | 186 | # NuGet Packages 187 | *.nupkg 188 | # The packages folder can be ignored because of Package Restore 189 | **/[Pp]ackages/* 190 | # except build/, which is used as an MSBuild target. 191 | !**/[Pp]ackages/build/ 192 | # Uncomment if necessary however generally it will be regenerated when needed 193 | #!**/[Pp]ackages/repositories.config 194 | # NuGet v3's project.json files produces more ignorable files 195 | *.nuget.props 196 | *.nuget.targets 197 | 198 | # Microsoft Azure Build Output 199 | csx/ 200 | *.build.csdef 201 | 202 | # Microsoft Azure Emulator 203 | ecf/ 204 | rcf/ 205 | 206 | # Windows Store app package directories and files 207 | AppPackages/ 208 | BundleArtifacts/ 209 | Package.StoreAssociation.xml 210 | _pkginfo.txt 211 | *.appx 212 | *.appxbundle 213 | *.appxupload 214 | 215 | # Visual Studio cache files 216 | # files ending in .cache can be ignored 217 | *.[Cc]ache 218 | # but keep track of directories ending in .cache 219 | !?*.[Cc]ache/ 220 | 221 | # Others 222 | ClientBin/ 223 | ~$* 224 | *~ 225 | *.dbmdl 226 | *.dbproj.schemaview 227 | *.jfm 228 | *.pfx 229 | *.publishsettings 230 | orleans.codegen.cs 231 | 232 | # Including strong name files can present a security risk 233 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 234 | #*.snk 235 | 236 | # Since there are multiple workflows, uncomment next line to ignore bower_components 237 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 238 | #bower_components/ 239 | 240 | # RIA/Silverlight projects 241 | Generated_Code/ 242 | 243 | # Backup & report files from converting an old project file 244 | # to a newer Visual Studio version. Backup files are not needed, 245 | # because we have git ;-) 246 | _UpgradeReport_Files/ 247 | Backup*/ 248 | UpgradeLog*.XML 249 | UpgradeLog*.htm 250 | ServiceFabricBackup/ 251 | *.rptproj.bak 252 | 253 | # SQL Server files 254 | *.mdf 255 | *.ldf 256 | *.ndf 257 | 258 | # Business Intelligence projects 259 | *.rdl.data 260 | *.bim.layout 261 | *.bim_*.settings 262 | *.rptproj.rsuser 263 | *- Backup*.rdl 264 | 265 | # Microsoft Fakes 266 | FakesAssemblies/ 267 | 268 | # GhostDoc plugin setting file 269 | *.GhostDoc.xml 270 | 271 | # Node.js Tools for Visual Studio 272 | .ntvs_analysis.dat 273 | node_modules/ 274 | 275 | # Visual Studio 6 build log 276 | *.plg 277 | 278 | # Visual Studio 6 workspace options file 279 | *.opt 280 | 281 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 282 | *.vbw 283 | 284 | # Visual Studio LightSwitch build output 285 | **/*.HTMLClient/GeneratedArtifacts 286 | **/*.DesktopClient/GeneratedArtifacts 287 | **/*.DesktopClient/ModelManifest.xml 288 | **/*.Server/GeneratedArtifacts 289 | **/*.Server/ModelManifest.xml 290 | _Pvt_Extensions 291 | 292 | # Paket dependency manager 293 | .paket/paket.exe 294 | paket-files/ 295 | 296 | # FAKE - F# Make 297 | .fake/ 298 | 299 | # CodeRush personal settings 300 | .cr/personal 301 | 302 | # Python Tools for Visual Studio (PTVS) 303 | __pycache__/ 304 | *.pyc 305 | 306 | # Cake - Uncomment if you are using it 307 | # tools/** 308 | # !tools/packages.config 309 | 310 | # Tabs Studio 311 | *.tss 312 | 313 | # Telerik's JustMock configuration file 314 | *.jmconfig 315 | 316 | # BizTalk build output 317 | *.btp.cs 318 | *.btm.cs 319 | *.odx.cs 320 | *.xsd.cs 321 | 322 | # OpenCover UI analysis results 323 | OpenCover/ 324 | 325 | # Azure Stream Analytics local run output 326 | ASALocalRun/ 327 | 328 | # MSBuild Binary and Structured Log 329 | *.binlog 330 | 331 | # NVidia Nsight GPU debugger configuration file 332 | *.nvuser 333 | 334 | # MFractors (Xamarin productivity tool) working folder 335 | .mfractor/ 336 | 337 | # Local History for Visual Studio 338 | .localhistory/ 339 | 340 | # BeatPulse healthcheck temp database 341 | healthchecksdb 342 | 343 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 344 | MigrationBackup/ 345 | 346 | ## 347 | ## Visual studio for Mac 348 | ## 349 | 350 | 351 | # globs 352 | Makefile.in 353 | *.userprefs 354 | *.usertasks 355 | config.make 356 | config.status 357 | aclocal.m4 358 | install-sh 359 | autom4te.cache/ 360 | *.tar.gz 361 | tarballs/ 362 | test-results/ 363 | 364 | # Mac bundle stuff 365 | *.dmg 366 | *.app 367 | 368 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 369 | # General 370 | .DS_Store 371 | .AppleDouble 372 | .LSOverride 373 | 374 | # Icon must end with two \r 375 | Icon 376 | 377 | 378 | # Thumbnails 379 | ._* 380 | 381 | # Files that might appear in the root of a volume 382 | .DocumentRevisions-V100 383 | .fseventsd 384 | .Spotlight-V100 385 | .TemporaryItems 386 | .Trashes 387 | .VolumeIcon.icns 388 | .com.apple.timemachine.donotpresent 389 | 390 | # Directories potentially created on remote AFP share 391 | .AppleDB 392 | .AppleDesktop 393 | Network Trash Folder 394 | Temporary Items 395 | .apdisk 396 | 397 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 398 | # Windows thumbnail cache files 399 | Thumbs.db 400 | ehthumbs.db 401 | ehthumbs_vista.db 402 | 403 | # Dump file 404 | *.stackdump 405 | 406 | # Folder config file 407 | [Dd]esktop.ini 408 | 409 | # Recycle Bin used on file shares 410 | $RECYCLE.BIN/ 411 | 412 | # Windows Installer files 413 | *.cab 414 | *.msi 415 | *.msix 416 | *.msm 417 | *.msp 418 | 419 | # Windows shortcuts 420 | *.lnk 421 | 422 | # JetBrains Rider 423 | .idea/ 424 | *.sln.iml 425 | 426 | ## 427 | ## Visual Studio Code 428 | ## 429 | .vscode/* 430 | !.vscode/settings.json 431 | !.vscode/tasks.json 432 | !.vscode/launch.json 433 | !.vscode/extensions.json 434 | -------------------------------------------------------------------------------- /CaWorkshop.WebUI/ClientApp/src/app/todo/todo.component.html: -------------------------------------------------------------------------------- 1 |

Todo

2 | 3 |

This is a complex todo list component.

4 | 5 |

Loading...

6 | 7 |
8 |
9 |
10 |
11 |

Lists

12 | 19 |
20 |
    21 |
  • 27 |
    28 |
    29 | {{ list.title }} 30 |
    31 |
    32 | {{ remainingItems(list) }} 33 |
    34 |
    35 |
  • 36 |
37 |
38 |
39 |
40 |

{{ selectedList.title }}

41 | 49 |
50 |
    51 |
  • 55 |
    56 |
    57 | 62 |
    63 |
    64 | 74 |
    81 | {{ item.title }} 82 |
    83 |
    84 |
    85 | 93 |
    94 |
    95 |
  • 96 |
  • 97 | 98 |
  • 99 |
100 |
101 |
102 |
103 | 104 |
105 |
{{ lists | json }}
106 |
107 | 108 | 109 | 120 | 136 | 156 | 157 | 158 | 159 | 170 | 204 | 224 | 225 | 226 | 227 | 238 | 244 | 262 | 263 | 264 | 265 | 276 | 296 | 304 | 305 | -------------------------------------------------------------------------------- /CaWorkshop.Infrastructure/Persistence/Migrations/00000000000000_CreateIdentitySchema.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace CaWorkshop.Infrastructure.Persistence.Migrations 5 | { 6 | public partial class CreateIdentitySchema : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "AspNetRoles", 12 | columns: table => new 13 | { 14 | Id = table.Column(nullable: false), 15 | Name = table.Column(maxLength: 256, nullable: true), 16 | NormalizedName = table.Column(maxLength: 256, nullable: true), 17 | ConcurrencyStamp = table.Column(nullable: true) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PK_AspNetRoles", x => x.Id); 22 | }); 23 | 24 | migrationBuilder.CreateTable( 25 | name: "AspNetUsers", 26 | columns: table => new 27 | { 28 | Id = table.Column(nullable: false), 29 | UserName = table.Column(maxLength: 256, nullable: true), 30 | NormalizedUserName = table.Column(maxLength: 256, nullable: true), 31 | Email = table.Column(maxLength: 256, nullable: true), 32 | NormalizedEmail = table.Column(maxLength: 256, nullable: true), 33 | EmailConfirmed = table.Column(nullable: false), 34 | PasswordHash = table.Column(nullable: true), 35 | SecurityStamp = table.Column(nullable: true), 36 | ConcurrencyStamp = table.Column(nullable: true), 37 | PhoneNumber = table.Column(nullable: true), 38 | PhoneNumberConfirmed = table.Column(nullable: false), 39 | TwoFactorEnabled = table.Column(nullable: false), 40 | LockoutEnd = table.Column(nullable: true), 41 | LockoutEnabled = table.Column(nullable: false), 42 | AccessFailedCount = table.Column(nullable: false) 43 | }, 44 | constraints: table => 45 | { 46 | table.PrimaryKey("PK_AspNetUsers", x => x.Id); 47 | }); 48 | 49 | migrationBuilder.CreateTable( 50 | name: "DeviceCodes", 51 | columns: table => new 52 | { 53 | UserCode = table.Column(maxLength: 200, nullable: false), 54 | DeviceCode = table.Column(maxLength: 200, nullable: false), 55 | SubjectId = table.Column(maxLength: 200, nullable: true), 56 | ClientId = table.Column(maxLength: 200, nullable: false), 57 | CreationTime = table.Column(nullable: false), 58 | Expiration = table.Column(nullable: false), 59 | Data = table.Column(maxLength: 50000, nullable: false) 60 | }, 61 | constraints: table => 62 | { 63 | table.PrimaryKey("PK_DeviceCodes", x => x.UserCode); 64 | }); 65 | 66 | migrationBuilder.CreateTable( 67 | name: "PersistedGrants", 68 | columns: table => new 69 | { 70 | Key = table.Column(maxLength: 200, nullable: false), 71 | Type = table.Column(maxLength: 50, nullable: false), 72 | SubjectId = table.Column(maxLength: 200, nullable: true), 73 | ClientId = table.Column(maxLength: 200, nullable: false), 74 | CreationTime = table.Column(nullable: false), 75 | Expiration = table.Column(nullable: true), 76 | Data = table.Column(maxLength: 50000, nullable: false) 77 | }, 78 | constraints: table => 79 | { 80 | table.PrimaryKey("PK_PersistedGrants", x => x.Key); 81 | }); 82 | 83 | migrationBuilder.CreateTable( 84 | name: "AspNetRoleClaims", 85 | columns: table => new 86 | { 87 | Id = table.Column(nullable: false) 88 | .Annotation("SqlServer:Identity", "1, 1"), 89 | RoleId = table.Column(nullable: false), 90 | ClaimType = table.Column(nullable: true), 91 | ClaimValue = table.Column(nullable: true) 92 | }, 93 | constraints: table => 94 | { 95 | table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); 96 | table.ForeignKey( 97 | name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", 98 | column: x => x.RoleId, 99 | principalTable: "AspNetRoles", 100 | principalColumn: "Id", 101 | onDelete: ReferentialAction.Cascade); 102 | }); 103 | 104 | migrationBuilder.CreateTable( 105 | name: "AspNetUserClaims", 106 | columns: table => new 107 | { 108 | Id = table.Column(nullable: false) 109 | .Annotation("SqlServer:Identity", "1, 1"), 110 | UserId = table.Column(nullable: false), 111 | ClaimType = table.Column(nullable: true), 112 | ClaimValue = table.Column(nullable: true) 113 | }, 114 | constraints: table => 115 | { 116 | table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); 117 | table.ForeignKey( 118 | name: "FK_AspNetUserClaims_AspNetUsers_UserId", 119 | column: x => x.UserId, 120 | principalTable: "AspNetUsers", 121 | principalColumn: "Id", 122 | onDelete: ReferentialAction.Cascade); 123 | }); 124 | 125 | migrationBuilder.CreateTable( 126 | name: "AspNetUserLogins", 127 | columns: table => new 128 | { 129 | LoginProvider = table.Column(maxLength: 128, nullable: false), 130 | ProviderKey = table.Column(maxLength: 128, nullable: false), 131 | ProviderDisplayName = table.Column(nullable: true), 132 | UserId = table.Column(nullable: false) 133 | }, 134 | constraints: table => 135 | { 136 | table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); 137 | table.ForeignKey( 138 | name: "FK_AspNetUserLogins_AspNetUsers_UserId", 139 | column: x => x.UserId, 140 | principalTable: "AspNetUsers", 141 | principalColumn: "Id", 142 | onDelete: ReferentialAction.Cascade); 143 | }); 144 | 145 | migrationBuilder.CreateTable( 146 | name: "AspNetUserRoles", 147 | columns: table => new 148 | { 149 | UserId = table.Column(nullable: false), 150 | RoleId = table.Column(nullable: false) 151 | }, 152 | constraints: table => 153 | { 154 | table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); 155 | table.ForeignKey( 156 | name: "FK_AspNetUserRoles_AspNetRoles_RoleId", 157 | column: x => x.RoleId, 158 | principalTable: "AspNetRoles", 159 | principalColumn: "Id", 160 | onDelete: ReferentialAction.Cascade); 161 | table.ForeignKey( 162 | name: "FK_AspNetUserRoles_AspNetUsers_UserId", 163 | column: x => x.UserId, 164 | principalTable: "AspNetUsers", 165 | principalColumn: "Id", 166 | onDelete: ReferentialAction.Cascade); 167 | }); 168 | 169 | migrationBuilder.CreateTable( 170 | name: "AspNetUserTokens", 171 | columns: table => new 172 | { 173 | UserId = table.Column(nullable: false), 174 | LoginProvider = table.Column(maxLength: 128, nullable: false), 175 | Name = table.Column(maxLength: 128, nullable: false), 176 | Value = table.Column(nullable: true) 177 | }, 178 | constraints: table => 179 | { 180 | table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); 181 | table.ForeignKey( 182 | name: "FK_AspNetUserTokens_AspNetUsers_UserId", 183 | column: x => x.UserId, 184 | principalTable: "AspNetUsers", 185 | principalColumn: "Id", 186 | onDelete: ReferentialAction.Cascade); 187 | }); 188 | 189 | migrationBuilder.CreateIndex( 190 | name: "IX_AspNetRoleClaims_RoleId", 191 | table: "AspNetRoleClaims", 192 | column: "RoleId"); 193 | 194 | migrationBuilder.CreateIndex( 195 | name: "RoleNameIndex", 196 | table: "AspNetRoles", 197 | column: "NormalizedName", 198 | unique: true, 199 | filter: "[NormalizedName] IS NOT NULL"); 200 | 201 | migrationBuilder.CreateIndex( 202 | name: "IX_AspNetUserClaims_UserId", 203 | table: "AspNetUserClaims", 204 | column: "UserId"); 205 | 206 | migrationBuilder.CreateIndex( 207 | name: "IX_AspNetUserLogins_UserId", 208 | table: "AspNetUserLogins", 209 | column: "UserId"); 210 | 211 | migrationBuilder.CreateIndex( 212 | name: "IX_AspNetUserRoles_RoleId", 213 | table: "AspNetUserRoles", 214 | column: "RoleId"); 215 | 216 | migrationBuilder.CreateIndex( 217 | name: "EmailIndex", 218 | table: "AspNetUsers", 219 | column: "NormalizedEmail"); 220 | 221 | migrationBuilder.CreateIndex( 222 | name: "UserNameIndex", 223 | table: "AspNetUsers", 224 | column: "NormalizedUserName", 225 | unique: true, 226 | filter: "[NormalizedUserName] IS NOT NULL"); 227 | 228 | migrationBuilder.CreateIndex( 229 | name: "IX_DeviceCodes_DeviceCode", 230 | table: "DeviceCodes", 231 | column: "DeviceCode", 232 | unique: true); 233 | 234 | migrationBuilder.CreateIndex( 235 | name: "IX_DeviceCodes_Expiration", 236 | table: "DeviceCodes", 237 | column: "Expiration"); 238 | 239 | migrationBuilder.CreateIndex( 240 | name: "IX_PersistedGrants_Expiration", 241 | table: "PersistedGrants", 242 | column: "Expiration"); 243 | 244 | migrationBuilder.CreateIndex( 245 | name: "IX_PersistedGrants_SubjectId_ClientId_Type", 246 | table: "PersistedGrants", 247 | columns: new[] { "SubjectId", "ClientId", "Type" }); 248 | } 249 | 250 | protected override void Down(MigrationBuilder migrationBuilder) 251 | { 252 | migrationBuilder.DropTable( 253 | name: "AspNetRoleClaims"); 254 | 255 | migrationBuilder.DropTable( 256 | name: "AspNetUserClaims"); 257 | 258 | migrationBuilder.DropTable( 259 | name: "AspNetUserLogins"); 260 | 261 | migrationBuilder.DropTable( 262 | name: "AspNetUserRoles"); 263 | 264 | migrationBuilder.DropTable( 265 | name: "AspNetUserTokens"); 266 | 267 | migrationBuilder.DropTable( 268 | name: "DeviceCodes"); 269 | 270 | migrationBuilder.DropTable( 271 | name: "PersistedGrants"); 272 | 273 | migrationBuilder.DropTable( 274 | name: "AspNetRoles"); 275 | 276 | migrationBuilder.DropTable( 277 | name: "AspNetUsers"); 278 | } 279 | } 280 | } 281 | --------------------------------------------------------------------------------