diff --git a/src/Identity.API/Configuration/Config.cs b/src/Identity.API/Configuration/Config.cs index f1d41a67a..785bedfbb 100644 --- a/src/Identity.API/Configuration/Config.cs +++ b/src/Identity.API/Configuration/Config.cs @@ -1,192 +1,191 @@ -namespace eShop.Identity.API.Configuration +namespace eShop.Identity.API.Configuration; + +public class Config { - public class Config + // ApiResources define the apis in your system + public static IEnumerable GetApis() { - // ApiResources define the apis in your system - public static IEnumerable GetApis() + return new List { - return new List - { - new ApiResource("orders", "Orders Service"), - new ApiResource("basket", "Basket Service"), - new ApiResource("webhooks", "Webhooks registration Service"), - }; - } + new ApiResource("orders", "Orders Service"), + new ApiResource("basket", "Basket Service"), + new ApiResource("webhooks", "Webhooks registration Service"), + }; + } - // ApiScope is used to protect the API - //The effect is the same as that of API resources in IdentityServer 3.x - public static IEnumerable GetApiScopes() + // ApiScope is used to protect the API + //The effect is the same as that of API resources in IdentityServer 3.x + public static IEnumerable GetApiScopes() + { + return new List { - return new List - { - new ApiScope("orders", "Orders Service"), - new ApiScope("basket", "Basket Service"), - new ApiScope("webhooks", "Webhooks registration Service"), - }; - } + new ApiScope("orders", "Orders Service"), + new ApiScope("basket", "Basket Service"), + new ApiScope("webhooks", "Webhooks registration Service"), + }; + } - // Identity resources are data like user ID, name, or email address of a user - // see: http://docs.identityserver.io/en/release/configuration/resources.html - public static IEnumerable GetResources() + // Identity resources are data like user ID, name, or email address of a user + // see: http://docs.identityserver.io/en/release/configuration/resources.html + public static IEnumerable GetResources() + { + return new List { - return new List - { - new IdentityResources.OpenId(), - new IdentityResources.Profile() - }; - } + new IdentityResources.OpenId(), + new IdentityResources.Profile() + }; + } - // client want to access resources (aka scopes) - public static IEnumerable GetClients(IConfiguration configuration) + // client want to access resources (aka scopes) + public static IEnumerable GetClients(IConfiguration configuration) + { + return new List { - return new List + new Client + { + ClientId = "maui", + ClientName = "eShop MAUI OpenId Client", + AllowedGrantTypes = GrantTypes.Code, + //Used to retrieve the access token on the back channel. + ClientSecrets = + { + new Secret("secret".Sha256()) + }, + RedirectUris = { configuration["MauiCallback"] }, + RequireConsent = false, + RequirePkce = true, + PostLogoutRedirectUris = { $"{configuration["MauiCallback"]}/Account/Redirecting" }, + //AllowedCorsOrigins = { "http://eshopxamarin" }, + AllowedScopes = new List + { + IdentityServerConstants.StandardScopes.OpenId, + IdentityServerConstants.StandardScopes.Profile, + IdentityServerConstants.StandardScopes.OfflineAccess, + "orders", + "basket", + "mobileshoppingagg", + "webhooks" + }, + //Allow requesting refresh tokens for long lived API access + AllowOfflineAccess = true, + AllowAccessTokensViaBrowser = true, + AlwaysIncludeUserClaimsInIdToken = true, + AccessTokenLifetime = 60*60*2, // 2 hours + IdentityTokenLifetime= 60*60*2 // 2 hours + }, + new Client { - new Client + ClientId = "webapp", + ClientName = "WebApp Client", + ClientSecrets = new List { - ClientId = "maui", - ClientName = "eShop MAUI OpenId Client", - AllowedGrantTypes = GrantTypes.Code, - //Used to retrieve the access token on the back channel. - ClientSecrets = - { - new Secret("secret".Sha256()) - }, - RedirectUris = { configuration["MauiCallback"] }, - RequireConsent = false, - RequirePkce = true, - PostLogoutRedirectUris = { $"{configuration["MauiCallback"]}/Account/Redirecting" }, - //AllowedCorsOrigins = { "http://eshopxamarin" }, - AllowedScopes = new List - { - IdentityServerConstants.StandardScopes.OpenId, - IdentityServerConstants.StandardScopes.Profile, - IdentityServerConstants.StandardScopes.OfflineAccess, - "orders", - "basket", - "mobileshoppingagg", - "webhooks" - }, - //Allow requesting refresh tokens for long lived API access - AllowOfflineAccess = true, - AllowAccessTokensViaBrowser = true, - AlwaysIncludeUserClaimsInIdToken = true, - AccessTokenLifetime = 60*60*2, // 2 hours - IdentityTokenLifetime= 60*60*2 // 2 hours + new Secret("secret".Sha256()) }, - new Client + ClientUri = $"{configuration["WebAppClient"]}", // public uri of the client + AllowedGrantTypes = GrantTypes.Code, + AllowAccessTokensViaBrowser = false, + RequireConsent = false, + AllowOfflineAccess = true, + AlwaysIncludeUserClaimsInIdToken = true, + RequirePkce = false, + RedirectUris = new List { - ClientId = "webapp", - ClientName = "WebApp Client", - ClientSecrets = new List - { - new Secret("secret".Sha256()) - }, - ClientUri = $"{configuration["WebAppClient"]}", // public uri of the client - AllowedGrantTypes = GrantTypes.Code, - AllowAccessTokensViaBrowser = false, - RequireConsent = false, - AllowOfflineAccess = true, - AlwaysIncludeUserClaimsInIdToken = true, - RequirePkce = false, - RedirectUris = new List - { - $"{configuration["WebAppClient"]}/signin-oidc" - }, - PostLogoutRedirectUris = new List - { - $"{configuration["WebAppClient"]}/signout-callback-oidc" - }, - AllowedScopes = new List - { - IdentityServerConstants.StandardScopes.OpenId, - IdentityServerConstants.StandardScopes.Profile, - IdentityServerConstants.StandardScopes.OfflineAccess, - "orders", - "basket", - "webshoppingagg", - "webhooks" - }, - AccessTokenLifetime = 60*60*2, // 2 hours - IdentityTokenLifetime= 60*60*2 // 2 hours + $"{configuration["WebAppClient"]}/signin-oidc" }, - new Client + PostLogoutRedirectUris = new List { - ClientId = "webhooksclient", - ClientName = "Webhooks Client", - ClientSecrets = new List - { - new Secret("secret".Sha256()) - }, - ClientUri = $"{configuration["WebhooksWebClient"]}", // public uri of the client - AllowedGrantTypes = GrantTypes.Code, - AllowAccessTokensViaBrowser = false, - RequireConsent = false, - AllowOfflineAccess = true, - AlwaysIncludeUserClaimsInIdToken = true, - RedirectUris = new List - { - $"{configuration["WebhooksWebClient"]}/signin-oidc" - }, - PostLogoutRedirectUris = new List - { - $"{configuration["WebhooksWebClient"]}/signout-callback-oidc" - }, - AllowedScopes = new List - { - IdentityServerConstants.StandardScopes.OpenId, - IdentityServerConstants.StandardScopes.Profile, - IdentityServerConstants.StandardScopes.OfflineAccess, - "webhooks" - }, - AccessTokenLifetime = 60*60*2, // 2 hours - IdentityTokenLifetime= 60*60*2 // 2 hours + $"{configuration["WebAppClient"]}/signout-callback-oidc" }, - new Client + AllowedScopes = new List { - ClientId = "basketswaggerui", - ClientName = "Basket Swagger UI", - AllowedGrantTypes = GrantTypes.Implicit, - AllowAccessTokensViaBrowser = true, + IdentityServerConstants.StandardScopes.OpenId, + IdentityServerConstants.StandardScopes.Profile, + IdentityServerConstants.StandardScopes.OfflineAccess, + "orders", + "basket", + "webshoppingagg", + "webhooks" + }, + AccessTokenLifetime = 60*60*2, // 2 hours + IdentityTokenLifetime= 60*60*2 // 2 hours + }, + new Client + { + ClientId = "webhooksclient", + ClientName = "Webhooks Client", + ClientSecrets = new List + { + new Secret("secret".Sha256()) + }, + ClientUri = $"{configuration["WebhooksWebClient"]}", // public uri of the client + AllowedGrantTypes = GrantTypes.Code, + AllowAccessTokensViaBrowser = false, + RequireConsent = false, + AllowOfflineAccess = true, + AlwaysIncludeUserClaimsInIdToken = true, + RedirectUris = new List + { + $"{configuration["WebhooksWebClient"]}/signin-oidc" + }, + PostLogoutRedirectUris = new List + { + $"{configuration["WebhooksWebClient"]}/signout-callback-oidc" + }, + AllowedScopes = new List + { + IdentityServerConstants.StandardScopes.OpenId, + IdentityServerConstants.StandardScopes.Profile, + IdentityServerConstants.StandardScopes.OfflineAccess, + "webhooks" + }, + AccessTokenLifetime = 60*60*2, // 2 hours + IdentityTokenLifetime= 60*60*2 // 2 hours + }, + new Client + { + ClientId = "basketswaggerui", + ClientName = "Basket Swagger UI", + AllowedGrantTypes = GrantTypes.Implicit, + AllowAccessTokensViaBrowser = true, - RedirectUris = { $"{configuration["BasketApiClient"]}/swagger/oauth2-redirect.html" }, - PostLogoutRedirectUris = { $"{configuration["BasketApiClient"]}/swagger/" }, + RedirectUris = { $"{configuration["BasketApiClient"]}/swagger/oauth2-redirect.html" }, + PostLogoutRedirectUris = { $"{configuration["BasketApiClient"]}/swagger/" }, - AllowedScopes = - { - "basket" - } - }, - new Client + AllowedScopes = { - ClientId = "orderingswaggerui", - ClientName = "Ordering Swagger UI", - AllowedGrantTypes = GrantTypes.Implicit, - AllowAccessTokensViaBrowser = true, + "basket" + } + }, + new Client + { + ClientId = "orderingswaggerui", + ClientName = "Ordering Swagger UI", + AllowedGrantTypes = GrantTypes.Implicit, + AllowAccessTokensViaBrowser = true, - RedirectUris = { $"{configuration["OrderingApiClient"]}/swagger/oauth2-redirect.html" }, - PostLogoutRedirectUris = { $"{configuration["OrderingApiClient"]}/swagger/" }, + RedirectUris = { $"{configuration["OrderingApiClient"]}/swagger/oauth2-redirect.html" }, + PostLogoutRedirectUris = { $"{configuration["OrderingApiClient"]}/swagger/" }, - AllowedScopes = - { - "orders" - } - }, - new Client + AllowedScopes = { - ClientId = "webhooksswaggerui", - ClientName = "WebHooks Service Swagger UI", - AllowedGrantTypes = GrantTypes.Implicit, - AllowAccessTokensViaBrowser = true, + "orders" + } + }, + new Client + { + ClientId = "webhooksswaggerui", + ClientName = "WebHooks Service Swagger UI", + AllowedGrantTypes = GrantTypes.Implicit, + AllowAccessTokensViaBrowser = true, - RedirectUris = { $"{configuration["WebhooksApiClient"]}/swagger/oauth2-redirect.html" }, - PostLogoutRedirectUris = { $"{configuration["WebhooksApiClient"]}/swagger/" }, + RedirectUris = { $"{configuration["WebhooksApiClient"]}/swagger/oauth2-redirect.html" }, + PostLogoutRedirectUris = { $"{configuration["WebhooksApiClient"]}/swagger/" }, - AllowedScopes = - { - "webhooks" - } + AllowedScopes = + { + "webhooks" } - }; - } + } + }; } } diff --git a/src/Identity.API/Models/AccountViewModels/ForgotPasswordViewModel.cs b/src/Identity.API/Models/AccountViewModels/ForgotPasswordViewModel.cs index 5f782728f..98f5035f3 100644 --- a/src/Identity.API/Models/AccountViewModels/ForgotPasswordViewModel.cs +++ b/src/Identity.API/Models/AccountViewModels/ForgotPasswordViewModel.cs @@ -1,9 +1,8 @@ -namespace eShop.Identity.API.Models.AccountViewModels +namespace eShop.Identity.API.Models.AccountViewModels; + +public record ForgotPasswordViewModel { - public record ForgotPasswordViewModel - { - [Required] - [EmailAddress] - public string Email { get; init; } - } + [Required] + [EmailAddress] + public string Email { get; init; } } diff --git a/src/Identity.API/Models/AccountViewModels/LoggedOutViewModel.cs b/src/Identity.API/Models/AccountViewModels/LoggedOutViewModel.cs index 63d60cea2..65cddfb24 100644 --- a/src/Identity.API/Models/AccountViewModels/LoggedOutViewModel.cs +++ b/src/Identity.API/Models/AccountViewModels/LoggedOutViewModel.cs @@ -1,9 +1,8 @@ -namespace eShop.Identity.API.Models.AccountViewModels +namespace eShop.Identity.API.Models.AccountViewModels; + +public record LoggedOutViewModel { - public record LoggedOutViewModel - { - public string PostLogoutRedirectUri { get; init; } - public string ClientName { get; init; } - public string SignOutIframeUrl { get; init; } - } + public string PostLogoutRedirectUri { get; init; } + public string ClientName { get; init; } + public string SignOutIframeUrl { get; init; } } diff --git a/src/Identity.API/Models/AccountViewModels/LoginViewModel.cs b/src/Identity.API/Models/AccountViewModels/LoginViewModel.cs index 04674179c..33e6fc32f 100644 --- a/src/Identity.API/Models/AccountViewModels/LoginViewModel.cs +++ b/src/Identity.API/Models/AccountViewModels/LoginViewModel.cs @@ -1,17 +1,16 @@ -namespace eShop.Identity.API.Models.AccountViewModels +namespace eShop.Identity.API.Models.AccountViewModels; + +public record LoginViewModel { - public record LoginViewModel - { - [Required] - [EmailAddress] - public string Email { get; set; } + [Required] + [EmailAddress] + public string Email { get; set; } - [Required] - [DataType(DataType.Password)] - public string Password { get; set; } + [Required] + [DataType(DataType.Password)] + public string Password { get; set; } - [Display(Name = "Remember me?")] - public bool RememberMe { get; set; } - public string ReturnUrl { get; set; } - } + [Display(Name = "Remember me?")] + public bool RememberMe { get; set; } + public string ReturnUrl { get; set; } } diff --git a/src/Identity.API/Models/AccountViewModels/LogoutViewModel.cs b/src/Identity.API/Models/AccountViewModels/LogoutViewModel.cs index d202bef42..8fbbfe2ed 100644 --- a/src/Identity.API/Models/AccountViewModels/LogoutViewModel.cs +++ b/src/Identity.API/Models/AccountViewModels/LogoutViewModel.cs @@ -1,7 +1,6 @@ -namespace eShop.Identity.API.Models.AccountViewModels +namespace eShop.Identity.API.Models.AccountViewModels; + +public record LogoutViewModel { - public record LogoutViewModel - { - public string LogoutId { get; set; } - } + public string LogoutId { get; set; } } diff --git a/src/Identity.API/Models/AccountViewModels/RedirectViewModel.cs b/src/Identity.API/Models/AccountViewModels/RedirectViewModel.cs index 4da3be9e6..3bdd78272 100644 --- a/src/Identity.API/Models/AccountViewModels/RedirectViewModel.cs +++ b/src/Identity.API/Models/AccountViewModels/RedirectViewModel.cs @@ -1,7 +1,6 @@ -namespace eShop.Identity.API.Models.AccountViewModels +namespace eShop.Identity.API.Models.AccountViewModels; + +public class RedirectViewModel { - public class RedirectViewModel - { - public string RedirectUrl { get; set; } - } + public string RedirectUrl { get; set; } } diff --git a/src/Identity.API/Models/AccountViewModels/RegisterViewModel.cs b/src/Identity.API/Models/AccountViewModels/RegisterViewModel.cs index 9c47f79e7..976b2c07e 100644 --- a/src/Identity.API/Models/AccountViewModels/RegisterViewModel.cs +++ b/src/Identity.API/Models/AccountViewModels/RegisterViewModel.cs @@ -1,23 +1,22 @@ -namespace eShop.Identity.API.Models.AccountViewModels +namespace eShop.Identity.API.Models.AccountViewModels; + +public record RegisterViewModel { - public record RegisterViewModel - { - [Required] - [EmailAddress] - [Display(Name = "Email")] - public string Email { get; init; } + [Required] + [EmailAddress] + [Display(Name = "Email")] + public string Email { get; init; } - [Required] - [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; init; } + [Required] + [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Password)] + [Display(Name = "Password")] + public string Password { get; init; } - [DataType(DataType.Password)] - [Display(Name = "Confirm password")] - [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] - public string ConfirmPassword { get; init; } + [DataType(DataType.Password)] + [Display(Name = "Confirm password")] + [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] + public string ConfirmPassword { get; init; } - public ApplicationUser User { get; init; } - } + public ApplicationUser User { get; init; } } diff --git a/src/Identity.API/Models/AccountViewModels/ResetPasswordViewModel.cs b/src/Identity.API/Models/AccountViewModels/ResetPasswordViewModel.cs index ced1c9caf..bbab681c1 100644 --- a/src/Identity.API/Models/AccountViewModels/ResetPasswordViewModel.cs +++ b/src/Identity.API/Models/AccountViewModels/ResetPasswordViewModel.cs @@ -1,21 +1,20 @@ -namespace eShop.Identity.API.Models.AccountViewModels +namespace eShop.Identity.API.Models.AccountViewModels; + +public record ResetPasswordViewModel { - public record ResetPasswordViewModel - { - [Required] - [EmailAddress] - public string Email { get; init; } + [Required] + [EmailAddress] + public string Email { get; init; } - [Required] - [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] - [DataType(DataType.Password)] - public string Password { get; init; } + [Required] + [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Password)] + public string Password { get; init; } - [DataType(DataType.Password)] - [Display(Name = "Confirm password")] - [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] - public string ConfirmPassword { get; init; } + [DataType(DataType.Password)] + [Display(Name = "Confirm password")] + [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] + public string ConfirmPassword { get; init; } - public string Code { get; init; } - } + public string Code { get; init; } } diff --git a/src/Identity.API/Models/AccountViewModels/SendCodeViewModel.cs b/src/Identity.API/Models/AccountViewModels/SendCodeViewModel.cs index 195ac1dbf..4363a6f63 100644 --- a/src/Identity.API/Models/AccountViewModels/SendCodeViewModel.cs +++ b/src/Identity.API/Models/AccountViewModels/SendCodeViewModel.cs @@ -1,13 +1,12 @@ -namespace eShop.Identity.API.Models.AccountViewModels +namespace eShop.Identity.API.Models.AccountViewModels; + +public record SendCodeViewModel { - public record SendCodeViewModel - { - public string SelectedProvider { get; init; } + public string SelectedProvider { get; init; } - public ICollection Providers { get; init; } + public ICollection Providers { get; init; } - public string ReturnUrl { get; init; } + public string ReturnUrl { get; init; } - public bool RememberMe { get; init; } - } + public bool RememberMe { get; init; } } diff --git a/src/Identity.API/Models/AccountViewModels/VerifyCodeViewModel.cs b/src/Identity.API/Models/AccountViewModels/VerifyCodeViewModel.cs index f2073800c..68f007507 100644 --- a/src/Identity.API/Models/AccountViewModels/VerifyCodeViewModel.cs +++ b/src/Identity.API/Models/AccountViewModels/VerifyCodeViewModel.cs @@ -1,19 +1,18 @@ -namespace eShop.Identity.API.Models.AccountViewModels +namespace eShop.Identity.API.Models.AccountViewModels; + +public record VerifyCodeViewModel { - public record VerifyCodeViewModel - { - [Required] - public string Provider { get; init; } + [Required] + public string Provider { get; init; } - [Required] - public string Code { get; init; } + [Required] + public string Code { get; init; } - public string ReturnUrl { get; init; } + public string ReturnUrl { get; init; } - [Display(Name = "Remember this browser?")] - public bool RememberBrowser { get; init; } + [Display(Name = "Remember this browser?")] + public bool RememberBrowser { get; init; } - [Display(Name = "Remember me?")] - public bool RememberMe { get; init; } - } + [Display(Name = "Remember me?")] + public bool RememberMe { get; init; } } diff --git a/src/Identity.API/Models/ApplicationUser.cs b/src/Identity.API/Models/ApplicationUser.cs index 11a151a1f..b4c405a74 100644 --- a/src/Identity.API/Models/ApplicationUser.cs +++ b/src/Identity.API/Models/ApplicationUser.cs @@ -1,31 +1,30 @@ -namespace eShop.Identity.API.Models +namespace eShop.Identity.API.Models; + +// Add profile data for application users by adding properties to the ApplicationUser class +public class ApplicationUser : IdentityUser { - // Add profile data for application users by adding properties to the ApplicationUser class - public class ApplicationUser : IdentityUser - { - [Required] - public string CardNumber { get; set; } - [Required] - public string SecurityNumber { get; set; } - [Required] - [RegularExpression(@"(0[1-9]|1[0-2])\/[0-9]{2}", ErrorMessage = "Expiration should match a valid MM/YY value")] - public string Expiration { get; set; } - [Required] - public string CardHolderName { get; set; } - public int CardType { get; set; } - [Required] - public string Street { get; set; } - [Required] - public string City { get; set; } - [Required] - public string State { get; set; } - [Required] - public string Country { get; set; } - [Required] - public string ZipCode { get; set; } - [Required] - public string Name { get; set; } - [Required] - public string LastName { get; set; } - } + [Required] + public string CardNumber { get; set; } + [Required] + public string SecurityNumber { get; set; } + [Required] + [RegularExpression(@"(0[1-9]|1[0-2])\/[0-9]{2}", ErrorMessage = "Expiration should match a valid MM/YY value")] + public string Expiration { get; set; } + [Required] + public string CardHolderName { get; set; } + public int CardType { get; set; } + [Required] + public string Street { get; set; } + [Required] + public string City { get; set; } + [Required] + public string State { get; set; } + [Required] + public string Country { get; set; } + [Required] + public string ZipCode { get; set; } + [Required] + public string Name { get; set; } + [Required] + public string LastName { get; set; } } diff --git a/src/Identity.API/Models/ConsentViewModels/ConsentInputModel.cs b/src/Identity.API/Models/ConsentViewModels/ConsentInputModel.cs index 7edde46a8..5568ccd87 100644 --- a/src/Identity.API/Models/ConsentViewModels/ConsentInputModel.cs +++ b/src/Identity.API/Models/ConsentViewModels/ConsentInputModel.cs @@ -1,11 +1,10 @@ -namespace eShop.Identity.API.Models.ConsentViewModels +namespace eShop.Identity.API.Models.ConsentViewModels; + +public class ConsentInputModel { - public class ConsentInputModel - { - public string Button { get; set; } - public IEnumerable ScopesConsented { get; set; } - public bool RememberConsent { get; set; } - public string ReturnUrl { get; set; } - public string Description { get; set; } - } + public string Button { get; set; } + public IEnumerable ScopesConsented { get; set; } + public bool RememberConsent { get; set; } + public string ReturnUrl { get; set; } + public string Description { get; set; } } diff --git a/src/Identity.API/Models/ConsentViewModels/ConsentOptions.cs b/src/Identity.API/Models/ConsentViewModels/ConsentOptions.cs index 765c3545c..4f3295a32 100644 --- a/src/Identity.API/Models/ConsentViewModels/ConsentOptions.cs +++ b/src/Identity.API/Models/ConsentViewModels/ConsentOptions.cs @@ -1,12 +1,11 @@ -namespace eShop.Identity.API.Models.ConsentViewModels +namespace eShop.Identity.API.Models.ConsentViewModels; + +public class ConsentOptions { - public class ConsentOptions - { - public static bool EnableOfflineAccess = true; - public static string OfflineAccessDisplayName = "Offline Access"; - public static string OfflineAccessDescription = "Access to your applications and resources, even when you are offline"; + public static bool EnableOfflineAccess = true; + public static string OfflineAccessDisplayName = "Offline Access"; + public static string OfflineAccessDescription = "Access to your applications and resources, even when you are offline"; - public static readonly string MustChooseOneErrorMessage = "You must pick at least one permission"; - public static readonly string InvalidSelectionErrorMessage = "Invalid selection"; - } + public static readonly string MustChooseOneErrorMessage = "You must pick at least one permission"; + public static readonly string InvalidSelectionErrorMessage = "Invalid selection"; } diff --git a/src/Identity.API/Models/ConsentViewModels/ConsentViewModel.cs b/src/Identity.API/Models/ConsentViewModels/ConsentViewModel.cs index 07cc70640..1801dc02c 100644 --- a/src/Identity.API/Models/ConsentViewModels/ConsentViewModel.cs +++ b/src/Identity.API/Models/ConsentViewModels/ConsentViewModel.cs @@ -1,13 +1,12 @@ -namespace eShop.Identity.API.Models.ConsentViewModels +namespace eShop.Identity.API.Models.ConsentViewModels; + +public class ConsentViewModel : ConsentInputModel { - public class ConsentViewModel : ConsentInputModel - { - public string ClientName { get; set; } - public string ClientUrl { get; set; } - public string ClientLogoUrl { get; set; } - public bool AllowRememberConsent { get; set; } + public string ClientName { get; set; } + public string ClientUrl { get; set; } + public string ClientLogoUrl { get; set; } + public bool AllowRememberConsent { get; set; } - public IEnumerable IdentityScopes { get; set; } - public IEnumerable ApiScopes { get; set; } - } + public IEnumerable IdentityScopes { get; set; } + public IEnumerable ApiScopes { get; set; } } diff --git a/src/Identity.API/Models/ConsentViewModels/ProcessConsentResult.cs b/src/Identity.API/Models/ConsentViewModels/ProcessConsentResult.cs index 44d0fa825..5202e810c 100644 --- a/src/Identity.API/Models/ConsentViewModels/ProcessConsentResult.cs +++ b/src/Identity.API/Models/ConsentViewModels/ProcessConsentResult.cs @@ -1,15 +1,14 @@ -namespace eShop.Identity.API.Models.ConsentViewModels +namespace eShop.Identity.API.Models.ConsentViewModels; + +public class ProcessConsentResult { - public class ProcessConsentResult - { - public bool IsRedirect => RedirectUri != null; - public string RedirectUri { get; set; } - public Client Client { get; set; } + public bool IsRedirect => RedirectUri != null; + public string RedirectUri { get; set; } + public Client Client { get; set; } - public bool ShowView => ViewModel != null; - public ConsentViewModel ViewModel { get; set; } + public bool ShowView => ViewModel != null; + public ConsentViewModel ViewModel { get; set; } - public bool HasValidationError => ValidationError != null; - public string ValidationError { get; set; } - } + public bool HasValidationError => ValidationError != null; + public string ValidationError { get; set; } } diff --git a/src/Identity.API/Models/ConsentViewModels/ScopeViewModel.cs b/src/Identity.API/Models/ConsentViewModels/ScopeViewModel.cs index 9ca82601b..4071d84ed 100644 --- a/src/Identity.API/Models/ConsentViewModels/ScopeViewModel.cs +++ b/src/Identity.API/Models/ConsentViewModels/ScopeViewModel.cs @@ -1,12 +1,11 @@ -namespace eShop.Identity.API.Models.ConsentViewModels +namespace eShop.Identity.API.Models.ConsentViewModels; + +public class ScopeViewModel { - public class ScopeViewModel - { - public string Value { get; set; } - public string DisplayName { get; set; } - public string Description { get; set; } - public bool Emphasize { get; set; } - public bool Required { get; set; } - public bool Checked { get; set; } - } + public string Value { get; set; } + public string DisplayName { get; set; } + public string Description { get; set; } + public bool Emphasize { get; set; } + public bool Required { get; set; } + public bool Checked { get; set; } } diff --git a/src/Identity.API/Models/ErrorViewModel.cs b/src/Identity.API/Models/ErrorViewModel.cs index 0cf0caa7a..1ea3a5eb9 100644 --- a/src/Identity.API/Models/ErrorViewModel.cs +++ b/src/Identity.API/Models/ErrorViewModel.cs @@ -1,9 +1,8 @@ // Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. -namespace eShop.Identity.API.Models +namespace eShop.Identity.API.Models; + +public record ErrorViewModel { - public record ErrorViewModel - { - public ErrorMessage Error { get; set; } - } + public ErrorMessage Error { get; set; } } diff --git a/src/Identity.API/Models/ManageViewModels/AddPhoneNumberViewModel.cs b/src/Identity.API/Models/ManageViewModels/AddPhoneNumberViewModel.cs index fc3bf7f05..34af0b788 100644 --- a/src/Identity.API/Models/ManageViewModels/AddPhoneNumberViewModel.cs +++ b/src/Identity.API/Models/ManageViewModels/AddPhoneNumberViewModel.cs @@ -1,10 +1,9 @@ -namespace eShop.Identity.API.Models.ManageViewModels +namespace eShop.Identity.API.Models.ManageViewModels; + +public record AddPhoneNumberViewModel { - public record AddPhoneNumberViewModel - { - [Required] - [Phone] - [Display(Name = "Phone number")] - public string PhoneNumber { get; init; } - } + [Required] + [Phone] + [Display(Name = "Phone number")] + public string PhoneNumber { get; init; } } diff --git a/src/Identity.API/Models/ManageViewModels/ChangePasswordViewModel.cs b/src/Identity.API/Models/ManageViewModels/ChangePasswordViewModel.cs index f7a909b1b..d98d38c5f 100644 --- a/src/Identity.API/Models/ManageViewModels/ChangePasswordViewModel.cs +++ b/src/Identity.API/Models/ManageViewModels/ChangePasswordViewModel.cs @@ -1,21 +1,20 @@ -namespace eShop.Identity.API.Models.ManageViewModels +namespace eShop.Identity.API.Models.ManageViewModels; + +public record ChangePasswordViewModel { - public record ChangePasswordViewModel - { - [Required] - [DataType(DataType.Password)] - [Display(Name = "Current password")] - public string OldPassword { get; init; } + [Required] + [DataType(DataType.Password)] + [Display(Name = "Current password")] + public string OldPassword { get; init; } - [Required] - [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "New password")] - public string NewPassword { get; init; } + [Required] + [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Password)] + [Display(Name = "New password")] + public string NewPassword { get; init; } - [DataType(DataType.Password)] - [Display(Name = "Confirm new password")] - [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] - public string ConfirmPassword { get; init; } - } + [DataType(DataType.Password)] + [Display(Name = "Confirm new password")] + [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] + public string ConfirmPassword { get; init; } } diff --git a/src/Identity.API/Models/ManageViewModels/ConfigureTwoFactorViewModel.cs b/src/Identity.API/Models/ManageViewModels/ConfigureTwoFactorViewModel.cs index bdc4ce7fe..009716e73 100644 --- a/src/Identity.API/Models/ManageViewModels/ConfigureTwoFactorViewModel.cs +++ b/src/Identity.API/Models/ManageViewModels/ConfigureTwoFactorViewModel.cs @@ -1,9 +1,8 @@ -namespace eShop.Identity.API.Models.ManageViewModels +namespace eShop.Identity.API.Models.ManageViewModels; + +public record ConfigureTwoFactorViewModel { - public record ConfigureTwoFactorViewModel - { - public string SelectedProvider { get; init; } + public string SelectedProvider { get; init; } - public ICollection Providers { get; init; } - } + public ICollection Providers { get; init; } } diff --git a/src/Identity.API/Models/ManageViewModels/FactorViewModel.cs b/src/Identity.API/Models/ManageViewModels/FactorViewModel.cs index f181b8099..f33a01f8f 100644 --- a/src/Identity.API/Models/ManageViewModels/FactorViewModel.cs +++ b/src/Identity.API/Models/ManageViewModels/FactorViewModel.cs @@ -1,7 +1,6 @@ -namespace eShop.Identity.API.Models.ManageViewModels +namespace eShop.Identity.API.Models.ManageViewModels; + +public record FactorViewModel { - public record FactorViewModel - { - public string Purpose { get; init; } - } + public string Purpose { get; init; } } diff --git a/src/Identity.API/Models/ManageViewModels/IndexViewModel.cs b/src/Identity.API/Models/ManageViewModels/IndexViewModel.cs index e107f3342..14ab4fef3 100644 --- a/src/Identity.API/Models/ManageViewModels/IndexViewModel.cs +++ b/src/Identity.API/Models/ManageViewModels/IndexViewModel.cs @@ -1,15 +1,14 @@ -namespace eShop.Identity.API.Models.ManageViewModels +namespace eShop.Identity.API.Models.ManageViewModels; + +public record IndexViewModel { - public record IndexViewModel - { - public bool HasPassword { get; init; } + public bool HasPassword { get; init; } - public IList Logins { get; init; } + public IList Logins { get; init; } - public string PhoneNumber { get; init; } + public string PhoneNumber { get; init; } - public bool TwoFactor { get; init; } + public bool TwoFactor { get; init; } - public bool BrowserRemembered { get; init; } - } + public bool BrowserRemembered { get; init; } } diff --git a/src/Identity.API/Models/ManageViewModels/SetPasswordViewModel.cs b/src/Identity.API/Models/ManageViewModels/SetPasswordViewModel.cs index 893f7b8af..3cb30c769 100644 --- a/src/Identity.API/Models/ManageViewModels/SetPasswordViewModel.cs +++ b/src/Identity.API/Models/ManageViewModels/SetPasswordViewModel.cs @@ -1,16 +1,15 @@ -namespace eShop.Identity.API.Models.ManageViewModels +namespace eShop.Identity.API.Models.ManageViewModels; + +public record SetPasswordViewModel { - public record SetPasswordViewModel - { - [Required] - [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "New password")] - public string NewPassword { get; init; } + [Required] + [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Password)] + [Display(Name = "New password")] + public string NewPassword { get; init; } - [DataType(DataType.Password)] - [Display(Name = "Confirm new password")] - [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] - public string ConfirmPassword { get; init; } - } + [DataType(DataType.Password)] + [Display(Name = "Confirm new password")] + [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] + public string ConfirmPassword { get; init; } } diff --git a/src/Identity.API/Models/ManageViewModels/VerifyPhoneNumberViewModel.cs b/src/Identity.API/Models/ManageViewModels/VerifyPhoneNumberViewModel.cs index 4c9d0477f..1a5b4f554 100644 --- a/src/Identity.API/Models/ManageViewModels/VerifyPhoneNumberViewModel.cs +++ b/src/Identity.API/Models/ManageViewModels/VerifyPhoneNumberViewModel.cs @@ -1,13 +1,12 @@ -namespace eShop.Identity.API.Models.ManageViewModels +namespace eShop.Identity.API.Models.ManageViewModels; + +public record VerifyPhoneNumberViewModel { - public record VerifyPhoneNumberViewModel - { - [Required] - public string Code { get; init; } + [Required] + public string Code { get; init; } - [Required] - [Phone] - [Display(Name = "Phone number")] - public string PhoneNumber { get; init; } - } + [Required] + [Phone] + [Display(Name = "Phone number")] + public string PhoneNumber { get; init; } } diff --git a/src/Identity.API/Quickstart/Account/AccountController.cs b/src/Identity.API/Quickstart/Account/AccountController.cs index e0aef7b95..4c1405b3d 100644 --- a/src/Identity.API/Quickstart/Account/AccountController.cs +++ b/src/Identity.API/Quickstart/Account/AccountController.cs @@ -1,79 +1,105 @@ // Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. -namespace IdentityServerHost.Quickstart.UI +namespace IdentityServerHost.Quickstart.UI; + +[SecurityHeaders] +[AllowAnonymous] +public class AccountController : Controller { - [SecurityHeaders] - [AllowAnonymous] - public class AccountController : Controller + private readonly UserManager _userManager; + private readonly SignInManager _signInManager; + private readonly IIdentityServerInteractionService _interaction; + private readonly IClientStore _clientStore; + private readonly IAuthenticationSchemeProvider _schemeProvider; + private readonly IAuthenticationHandlerProvider _handlerProvider; + private readonly IEventService _events; + + public AccountController( + UserManager userManager, + SignInManager signInManager, + IIdentityServerInteractionService interaction, + IClientStore clientStore, + IAuthenticationSchemeProvider schemeProvider, + IAuthenticationHandlerProvider handlerProvider, + IEventService events) + { + _userManager = userManager; + _signInManager = signInManager; + _interaction = interaction; + _clientStore = clientStore; + _schemeProvider = schemeProvider; + _handlerProvider = handlerProvider; + _events = events; + } + + /// + /// Entry point into the login workflow + /// + [HttpGet] + public async Task Login(string returnUrl) { - private readonly UserManager _userManager; - private readonly SignInManager _signInManager; - private readonly IIdentityServerInteractionService _interaction; - private readonly IClientStore _clientStore; - private readonly IAuthenticationSchemeProvider _schemeProvider; - private readonly IAuthenticationHandlerProvider _handlerProvider; - private readonly IEventService _events; - - public AccountController( - UserManager userManager, - SignInManager signInManager, - IIdentityServerInteractionService interaction, - IClientStore clientStore, - IAuthenticationSchemeProvider schemeProvider, - IAuthenticationHandlerProvider handlerProvider, - IEventService events) + // build a model so we know what to show on the login page + var vm = await BuildLoginViewModelAsync(returnUrl); + + ViewData["ReturnUrl"] = returnUrl; + + if (vm.IsExternalLoginOnly) { - _userManager = userManager; - _signInManager = signInManager; - _interaction = interaction; - _clientStore = clientStore; - _schemeProvider = schemeProvider; - _handlerProvider = handlerProvider; - _events = events; + // we only have one option for logging in and it's an external provider + return RedirectToAction("Challenge", "External", new { scheme = vm.ExternalLoginScheme, returnUrl }); } - /// - /// Entry point into the login workflow - /// - [HttpGet] - public async Task Login(string returnUrl) + return View(vm); + } + + /// + /// Handle postback from username/password login + /// + [HttpPost] + [ValidateAntiForgeryToken] + public async Task Login(LoginInputModel model, string button) + { + // check if we are in the context of an authorization request + var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); + + // the user clicked the "cancel" button + if (button != "login") { - // build a model so we know what to show on the login page - var vm = await BuildLoginViewModelAsync(returnUrl); + if (context != null) + { + // if the user cancels, send a result back into IdentityServer as if they + // denied the consent (even if this client does not require consent). + // this will send back an access denied OIDC error response to the client. + await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied); - ViewData["ReturnUrl"] = returnUrl; + // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null + if (context.IsNativeClient()) + { + // The client is native, so this change in how to + // return the response is for better UX for the end user. + return this.LoadingPage("Redirect", model.ReturnUrl); + } - if (vm.IsExternalLoginOnly) + return Redirect(model.ReturnUrl); + } + else { - // we only have one option for logging in and it's an external provider - return RedirectToAction("Challenge", "External", new { scheme = vm.ExternalLoginScheme, returnUrl }); + // since we don't have a valid context, then we just go back to the home page + return Redirect("~/"); } - - return View(vm); } - /// - /// Handle postback from username/password login - /// - [HttpPost] - [ValidateAntiForgeryToken] - public async Task Login(LoginInputModel model, string button) + if (ModelState.IsValid) { - // check if we are in the context of an authorization request - var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); - - // the user clicked the "cancel" button - if (button != "login") + var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure: true); + if (result.Succeeded) { + var user = await _userManager.FindByNameAsync(model.Username); + await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId: context?.Client.ClientId)); + if (context != null) { - // if the user cancels, send a result back into IdentityServer as if they - // denied the consent (even if this client does not require consent). - // this will send back an access denied OIDC error response to the client. - await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied); - - // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (context.IsNativeClient()) { // The client is native, so this change in how to @@ -81,254 +107,227 @@ public async Task Login(LoginInputModel model, string button) return this.LoadingPage("Redirect", model.ReturnUrl); } + // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null return Redirect(model.ReturnUrl); } - else + + // request for a local page + if (Url.IsLocalUrl(model.ReturnUrl)) + { + return Redirect(model.ReturnUrl); + } + else if (string.IsNullOrEmpty(model.ReturnUrl)) { - // since we don't have a valid context, then we just go back to the home page return Redirect("~/"); } + else + { + // user might have clicked on a malicious link - should be logged + throw new Exception("invalid return URL"); + } } - if (ModelState.IsValid) - { - var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure: true); - if (result.Succeeded) - { - var user = await _userManager.FindByNameAsync(model.Username); - await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId: context?.Client.ClientId)); + await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId: context?.Client.ClientId)); + ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage); + } - if (context != null) - { - if (context.IsNativeClient()) - { - // The client is native, so this change in how to - // return the response is for better UX for the end user. - return this.LoadingPage("Redirect", model.ReturnUrl); - } - - // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null - return Redirect(model.ReturnUrl); - } + // something went wrong, show form with error + var vm = await BuildLoginViewModelAsync(model); - // request for a local page - if (Url.IsLocalUrl(model.ReturnUrl)) - { - return Redirect(model.ReturnUrl); - } - else if (string.IsNullOrEmpty(model.ReturnUrl)) - { - return Redirect("~/"); - } - else - { - // user might have clicked on a malicious link - should be logged - throw new Exception("invalid return URL"); - } - } + ViewData["ReturnUrl"] = model.ReturnUrl; - await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId: context?.Client.ClientId)); - ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage); - } + return View(vm); + } - // something went wrong, show form with error - var vm = await BuildLoginViewModelAsync(model); - ViewData["ReturnUrl"] = model.ReturnUrl; + /// + /// Show logout page + /// + [HttpGet] + public async Task Logout(string logoutId) + { + // build a model so the logout page knows what to display + var vm = await BuildLogoutViewModelAsync(logoutId); - return View(vm); + if (vm.ShowLogoutPrompt == false) + { + // if the request for logout was properly authenticated from IdentityServer, then + // we don't need to show the prompt and can just log the user out directly. + return await Logout(vm); } + return View(vm); + } - /// - /// Show logout page - /// - [HttpGet] - public async Task Logout(string logoutId) - { - // build a model so the logout page knows what to display - var vm = await BuildLogoutViewModelAsync(logoutId); + /// + /// Handle logout page postback + /// + [HttpPost] + [ValidateAntiForgeryToken] + public async Task Logout(LogoutInputModel model) + { + // build a model so the logged out page knows what to display + var vm = await BuildLoggedOutViewModelAsync(model.LogoutId); - if (vm.ShowLogoutPrompt == false) - { - // if the request for logout was properly authenticated from IdentityServer, then - // we don't need to show the prompt and can just log the user out directly. - return await Logout(vm); - } + if (User?.Identity.IsAuthenticated == true) + { + // delete local authentication cookie + await _signInManager.SignOutAsync(); - return View(vm); + // raise the logout event + await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName())); } - /// - /// Handle logout page postback - /// - [HttpPost] - [ValidateAntiForgeryToken] - public async Task Logout(LogoutInputModel model) + // check if we need to trigger sign-out at an upstream identity provider + if (vm.TriggerExternalSignout) { - // build a model so the logged out page knows what to display - var vm = await BuildLoggedOutViewModelAsync(model.LogoutId); + // build a return URL so the upstream provider will redirect back + // to us after the user has logged out. this allows us to then + // complete our single sign-out processing. + string url = Url.Action("Logout", new { logoutId = vm.LogoutId }); - if (User?.Identity.IsAuthenticated == true) - { - // delete local authentication cookie - await _signInManager.SignOutAsync(); + // this triggers a redirect to the external provider for sign-out + return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme); + } - // raise the logout event - await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName())); - } + return View("LoggedOut", vm); + } + + [HttpGet] + public IActionResult AccessDenied() + { + return View(); + } - // check if we need to trigger sign-out at an upstream identity provider - if (vm.TriggerExternalSignout) + + /*****************************************/ + /* helper APIs for the AccountController */ + /*****************************************/ + private async Task BuildLoginViewModelAsync(string returnUrl) + { + var context = await _interaction.GetAuthorizationContextAsync(returnUrl); + if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null) + { + var local = context.IdP == IdentityServerConstants.LocalIdentityProvider; + + // this is meant to short circuit the UI and only trigger the one external IdP + var vm = new LoginViewModel { - // build a return URL so the upstream provider will redirect back - // to us after the user has logged out. this allows us to then - // complete our single sign-out processing. - string url = Url.Action("Logout", new { logoutId = vm.LogoutId }); + EnableLocalLogin = local, + ReturnUrl = returnUrl, + Username = context?.LoginHint, + }; - // this triggers a redirect to the external provider for sign-out - return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme); + if (!local) + { + vm.ExternalProviders = new[] { new ExternalProvider { AuthenticationScheme = context.IdP } }; } - return View("LoggedOut", vm); + return vm; } - [HttpGet] - public IActionResult AccessDenied() - { - return View(); - } + var schemes = await _schemeProvider.GetAllSchemesAsync(); + var providers = schemes + .Where(x => x.DisplayName != null) + .Select(x => new ExternalProvider + { + DisplayName = x.DisplayName ?? x.Name, + AuthenticationScheme = x.Name + }).ToList(); - /*****************************************/ - /* helper APIs for the AccountController */ - /*****************************************/ - private async Task BuildLoginViewModelAsync(string returnUrl) + var allowLocal = true; + if (context?.Client.ClientId != null) { - var context = await _interaction.GetAuthorizationContextAsync(returnUrl); - if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null) + var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId); + if (client != null) { - var local = context.IdP == IdentityServerConstants.LocalIdentityProvider; + allowLocal = client.EnableLocalLogin; - // this is meant to short circuit the UI and only trigger the one external IdP - var vm = new LoginViewModel + if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any()) { - EnableLocalLogin = local, - ReturnUrl = returnUrl, - Username = context?.LoginHint, - }; - - if (!local) - { - vm.ExternalProviders = new[] { new ExternalProvider { AuthenticationScheme = context.IdP } }; + providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList(); } - - return vm; } + } - var schemes = await _schemeProvider.GetAllSchemesAsync(); - - var providers = schemes - .Where(x => x.DisplayName != null) - .Select(x => new ExternalProvider - { - DisplayName = x.DisplayName ?? x.Name, - AuthenticationScheme = x.Name - }).ToList(); - - var allowLocal = true; - if (context?.Client.ClientId != null) - { - var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId); - if (client != null) - { - allowLocal = client.EnableLocalLogin; + return new LoginViewModel + { + AllowRememberLogin = AccountOptions.AllowRememberLogin, + EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin, + ReturnUrl = returnUrl, + Username = context?.LoginHint, + ExternalProviders = providers.ToArray() + }; + } - if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any()) - { - providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList(); - } - } - } + private async Task BuildLoginViewModelAsync(LoginInputModel model) + { + var vm = await BuildLoginViewModelAsync(model.ReturnUrl); + vm.Username = model.Username; + vm.RememberLogin = model.RememberLogin; + return vm; + } - return new LoginViewModel - { - AllowRememberLogin = AccountOptions.AllowRememberLogin, - EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin, - ReturnUrl = returnUrl, - Username = context?.LoginHint, - ExternalProviders = providers.ToArray() - }; - } + private async Task BuildLogoutViewModelAsync(string logoutId) + { + var vm = new LogoutViewModel { LogoutId = logoutId, ShowLogoutPrompt = AccountOptions.ShowLogoutPrompt }; - private async Task BuildLoginViewModelAsync(LoginInputModel model) + if (User?.Identity.IsAuthenticated != true) { - var vm = await BuildLoginViewModelAsync(model.ReturnUrl); - vm.Username = model.Username; - vm.RememberLogin = model.RememberLogin; + // if the user is not authenticated, then just show logged out page + vm.ShowLogoutPrompt = false; return vm; } - private async Task BuildLogoutViewModelAsync(string logoutId) + var context = await _interaction.GetLogoutContextAsync(logoutId); + if (context?.ShowSignoutPrompt == false) { - var vm = new LogoutViewModel { LogoutId = logoutId, ShowLogoutPrompt = AccountOptions.ShowLogoutPrompt }; - - if (User?.Identity.IsAuthenticated != true) - { - // if the user is not authenticated, then just show logged out page - vm.ShowLogoutPrompt = false; - return vm; - } - - var context = await _interaction.GetLogoutContextAsync(logoutId); - if (context?.ShowSignoutPrompt == false) - { - // it's safe to automatically sign-out - vm.ShowLogoutPrompt = false; - return vm; - } - - // show the logout prompt. this prevents attacks where the user - // is automatically signed out by another malicious web page. + // it's safe to automatically sign-out + vm.ShowLogoutPrompt = false; return vm; } - private async Task BuildLoggedOutViewModelAsync(string logoutId) - { - // get context information (client name, post logout redirect URI and iframe for federated signout) - var logout = await _interaction.GetLogoutContextAsync(logoutId); + // show the logout prompt. this prevents attacks where the user + // is automatically signed out by another malicious web page. + return vm; + } - var vm = new LoggedOutViewModel - { - AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut, - PostLogoutRedirectUri = logout?.PostLogoutRedirectUri, - ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName, - SignOutIframeUrl = logout?.SignOutIFrameUrl, - LogoutId = logoutId - }; + private async Task BuildLoggedOutViewModelAsync(string logoutId) + { + // get context information (client name, post logout redirect URI and iframe for federated signout) + var logout = await _interaction.GetLogoutContextAsync(logoutId); - if (User?.Identity.IsAuthenticated == true) + var vm = new LoggedOutViewModel + { + AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut, + PostLogoutRedirectUri = logout?.PostLogoutRedirectUri, + ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName, + SignOutIframeUrl = logout?.SignOutIFrameUrl, + LogoutId = logoutId + }; + + if (User?.Identity.IsAuthenticated == true) + { + var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; + if (idp != null && idp != IdentityServerConstants.LocalIdentityProvider) { - var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value; - if (idp != null && idp != IdentityServerConstants.LocalIdentityProvider) + var handler = await _handlerProvider.GetHandlerAsync(HttpContext, idp); + if (handler is IAuthenticationSignOutHandler) { - var handler = await _handlerProvider.GetHandlerAsync(HttpContext, idp); - if (handler is IAuthenticationSignOutHandler) + if (vm.LogoutId == null) { - if (vm.LogoutId == null) - { - // if there's no current logout context, we need to create one - // this captures necessary info from the current logged in user - // before we signout and redirect away to the external IdP for signout - vm.LogoutId = await _interaction.CreateLogoutContextAsync(); - } - - vm.ExternalAuthenticationScheme = idp; + // if there's no current logout context, we need to create one + // this captures necessary info from the current logged in user + // before we signout and redirect away to the external IdP for signout + vm.LogoutId = await _interaction.CreateLogoutContextAsync(); } + + vm.ExternalAuthenticationScheme = idp; } } - - return vm; } + + return vm; } -} \ No newline at end of file +} diff --git a/src/Identity.API/Quickstart/Home/HomeController.cs b/src/Identity.API/Quickstart/Home/HomeController.cs index 27f4d73cc..bb881b45f 100644 --- a/src/Identity.API/Quickstart/Home/HomeController.cs +++ b/src/Identity.API/Quickstart/Home/HomeController.cs @@ -1,59 +1,58 @@ // Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. -namespace IdentityServerHost.Quickstart.UI +namespace IdentityServerHost.Quickstart.UI; + +[SecurityHeaders] +[AllowAnonymous] +public class HomeController : Controller { - [SecurityHeaders] - [AllowAnonymous] - public class HomeController : Controller + private readonly IIdentityServerInteractionService _interaction; + private readonly IWebHostEnvironment _environment; + private readonly ILogger _logger; + + public HomeController( + IIdentityServerInteractionService interaction, + IWebHostEnvironment environment, + ILogger logger) + { + _interaction = interaction; + _environment = environment; + _logger = logger; + } + + public IActionResult Index() { - private readonly IIdentityServerInteractionService _interaction; - private readonly IWebHostEnvironment _environment; - private readonly ILogger _logger; - - public HomeController( - IIdentityServerInteractionService interaction, - IWebHostEnvironment environment, - ILogger logger) + if (_environment.IsDevelopment()) { - _interaction = interaction; - _environment = environment; - _logger = logger; + // only show in development + return View(); } - public IActionResult Index() - { - if (_environment.IsDevelopment()) - { - // only show in development - return View(); - } + _logger.LogInformation("Homepage is disabled in production. Returning 404."); + return NotFound(); + } - _logger.LogInformation("Homepage is disabled in production. Returning 404."); - return NotFound(); - } + /// + /// Shows the error page + /// + public async Task Error(string errorId) + { + var vm = new ErrorViewModel(); - /// - /// Shows the error page - /// - public async Task Error(string errorId) + // retrieve error details from identityserver + var message = await _interaction.GetErrorContextAsync(errorId); + if (message != null) { - var vm = new ErrorViewModel(); + vm.Error = message; - // retrieve error details from identityserver - var message = await _interaction.GetErrorContextAsync(errorId); - if (message != null) + if (!_environment.IsDevelopment()) { - vm.Error = message; - - if (!_environment.IsDevelopment()) - { - // only show in development - message.ErrorDescription = null; - } + // only show in development + message.ErrorDescription = null; } - - return View("Error", vm); } + + return View("Error", vm); } -} \ No newline at end of file +} diff --git a/src/Identity.API/Services/EFLoginService.cs b/src/Identity.API/Services/EFLoginService.cs index 8aa9eaf0e..bf192a021 100644 --- a/src/Identity.API/Services/EFLoginService.cs +++ b/src/Identity.API/Services/EFLoginService.cs @@ -1,34 +1,33 @@ -namespace eShop.Identity.API.Services +namespace eShop.Identity.API.Services; + +public class EFLoginService : ILoginService { - public class EFLoginService : ILoginService - { - private UserManager _userManager; - private SignInManager _signInManager; + private UserManager _userManager; + private SignInManager _signInManager; - public EFLoginService(UserManager userManager, SignInManager signInManager) - { - _userManager = userManager; - _signInManager = signInManager; - } + public EFLoginService(UserManager userManager, SignInManager signInManager) + { + _userManager = userManager; + _signInManager = signInManager; + } - public async Task FindByUsername(string user) - { - return await _userManager.FindByEmailAsync(user); - } + public async Task FindByUsername(string user) + { + return await _userManager.FindByEmailAsync(user); + } - public async Task ValidateCredentials(ApplicationUser user, string password) - { - return await _userManager.CheckPasswordAsync(user, password); - } + public async Task ValidateCredentials(ApplicationUser user, string password) + { + return await _userManager.CheckPasswordAsync(user, password); + } - public Task SignIn(ApplicationUser user) - { - return _signInManager.SignInAsync(user, true); - } + public Task SignIn(ApplicationUser user) + { + return _signInManager.SignInAsync(user, true); + } - public Task SignInAsync(ApplicationUser user, AuthenticationProperties properties, string authenticationMethod = null) - { - return _signInManager.SignInAsync(user, properties, authenticationMethod); - } + public Task SignInAsync(ApplicationUser user, AuthenticationProperties properties, string authenticationMethod = null) + { + return _signInManager.SignInAsync(user, properties, authenticationMethod); } } diff --git a/src/Identity.API/Services/ILoginService.cs b/src/Identity.API/Services/ILoginService.cs index a39d006e2..62b894c13 100644 --- a/src/Identity.API/Services/ILoginService.cs +++ b/src/Identity.API/Services/ILoginService.cs @@ -1,13 +1,12 @@ -namespace eShop.Identity.API.Services +namespace eShop.Identity.API.Services; + +public interface ILoginService { - public interface ILoginService - { - Task ValidateCredentials(T user, string password); + Task ValidateCredentials(T user, string password); - Task FindByUsername(string user); + Task FindByUsername(string user); - Task SignIn(T user); + Task SignIn(T user); - Task SignInAsync(T user, AuthenticationProperties properties, string authenticationMethod = null); - } + Task SignInAsync(T user, AuthenticationProperties properties, string authenticationMethod = null); } diff --git a/src/Identity.API/Services/IRedirectService.cs b/src/Identity.API/Services/IRedirectService.cs index d4aaf12f3..4356eb42d 100644 --- a/src/Identity.API/Services/IRedirectService.cs +++ b/src/Identity.API/Services/IRedirectService.cs @@ -1,7 +1,6 @@ -namespace eShop.Identity.API.Services +namespace eShop.Identity.API.Services; + +public interface IRedirectService { - public interface IRedirectService - { - string ExtractRedirectUriFromReturnUrl(string url); - } + string ExtractRedirectUriFromReturnUrl(string url); } diff --git a/src/Identity.API/Services/ProfileService.cs b/src/Identity.API/Services/ProfileService.cs index f42a50fad..1391703d6 100644 --- a/src/Identity.API/Services/ProfileService.cs +++ b/src/Identity.API/Services/ProfileService.cs @@ -1,118 +1,117 @@ -namespace eShop.Identity.API.Services +namespace eShop.Identity.API.Services; + +public class ProfileService : IProfileService { - public class ProfileService : IProfileService - { - private readonly UserManager _userManager; + private readonly UserManager _userManager; - public ProfileService(UserManager userManager) - { - _userManager = userManager; - } + public ProfileService(UserManager userManager) + { + _userManager = userManager; + } - public async Task GetProfileDataAsync(ProfileDataRequestContext context) - { - var subject = context.Subject ?? throw new ArgumentNullException(nameof(context.Subject)); + public async Task GetProfileDataAsync(ProfileDataRequestContext context) + { + var subject = context.Subject ?? throw new ArgumentNullException(nameof(context.Subject)); - var subjectId = subject.Claims.Where(x => x.Type == "sub").FirstOrDefault()?.Value; + var subjectId = subject.Claims.Where(x => x.Type == "sub").FirstOrDefault()?.Value; - var user = await _userManager.FindByIdAsync(subjectId); - if (user == null) - throw new ArgumentException("Invalid subject identifier"); + var user = await _userManager.FindByIdAsync(subjectId); + if (user == null) + throw new ArgumentException("Invalid subject identifier"); - var claims = GetClaimsFromUser(user); - context.IssuedClaims = claims.ToList(); - } + var claims = GetClaimsFromUser(user); + context.IssuedClaims = claims.ToList(); + } - public async Task IsActiveAsync(IsActiveContext context) - { - var subject = context.Subject ?? throw new ArgumentNullException(nameof(context.Subject)); + public async Task IsActiveAsync(IsActiveContext context) + { + var subject = context.Subject ?? throw new ArgumentNullException(nameof(context.Subject)); - var subjectId = subject.Claims.Where(x => x.Type == "sub").FirstOrDefault()?.Value; - var user = await _userManager.FindByIdAsync(subjectId); + var subjectId = subject.Claims.Where(x => x.Type == "sub").FirstOrDefault()?.Value; + var user = await _userManager.FindByIdAsync(subjectId); - context.IsActive = false; + context.IsActive = false; - if (user != null) + if (user != null) + { + if (_userManager.SupportsUserSecurityStamp) { - if (_userManager.SupportsUserSecurityStamp) + var security_stamp = subject.Claims.Where(c => c.Type == "security_stamp").Select(c => c.Value).SingleOrDefault(); + if (security_stamp != null) { - var security_stamp = subject.Claims.Where(c => c.Type == "security_stamp").Select(c => c.Value).SingleOrDefault(); - if (security_stamp != null) - { - var db_security_stamp = await _userManager.GetSecurityStampAsync(user); - if (db_security_stamp != security_stamp) - return; - } + var db_security_stamp = await _userManager.GetSecurityStampAsync(user); + if (db_security_stamp != security_stamp) + return; } - - context.IsActive = - !user.LockoutEnabled || - !user.LockoutEnd.HasValue || - user.LockoutEnd <= DateTime.UtcNow; } + + context.IsActive = + !user.LockoutEnabled || + !user.LockoutEnd.HasValue || + user.LockoutEnd <= DateTime.UtcNow; } + } - private IEnumerable GetClaimsFromUser(ApplicationUser user) + private IEnumerable GetClaimsFromUser(ApplicationUser user) + { + var claims = new List { - var claims = new List - { - new Claim(JwtClaimTypes.Subject, user.Id), - new Claim(JwtClaimTypes.PreferredUserName, user.UserName), - new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName) - }; + new Claim(JwtClaimTypes.Subject, user.Id), + new Claim(JwtClaimTypes.PreferredUserName, user.UserName), + new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName) + }; - if (!string.IsNullOrWhiteSpace(user.Name)) - claims.Add(new Claim("name", user.Name)); + if (!string.IsNullOrWhiteSpace(user.Name)) + claims.Add(new Claim("name", user.Name)); - if (!string.IsNullOrWhiteSpace(user.LastName)) - claims.Add(new Claim("last_name", user.LastName)); + if (!string.IsNullOrWhiteSpace(user.LastName)) + claims.Add(new Claim("last_name", user.LastName)); - if (!string.IsNullOrWhiteSpace(user.CardNumber)) - claims.Add(new Claim("card_number", user.CardNumber)); + if (!string.IsNullOrWhiteSpace(user.CardNumber)) + claims.Add(new Claim("card_number", user.CardNumber)); - if (!string.IsNullOrWhiteSpace(user.CardHolderName)) - claims.Add(new Claim("card_holder", user.CardHolderName)); + if (!string.IsNullOrWhiteSpace(user.CardHolderName)) + claims.Add(new Claim("card_holder", user.CardHolderName)); - if (!string.IsNullOrWhiteSpace(user.SecurityNumber)) - claims.Add(new Claim("card_security_number", user.SecurityNumber)); + if (!string.IsNullOrWhiteSpace(user.SecurityNumber)) + claims.Add(new Claim("card_security_number", user.SecurityNumber)); - if (!string.IsNullOrWhiteSpace(user.Expiration)) - claims.Add(new Claim("card_expiration", user.Expiration)); + if (!string.IsNullOrWhiteSpace(user.Expiration)) + claims.Add(new Claim("card_expiration", user.Expiration)); - if (!string.IsNullOrWhiteSpace(user.City)) - claims.Add(new Claim("address_city", user.City)); + if (!string.IsNullOrWhiteSpace(user.City)) + claims.Add(new Claim("address_city", user.City)); - if (!string.IsNullOrWhiteSpace(user.Country)) - claims.Add(new Claim("address_country", user.Country)); + if (!string.IsNullOrWhiteSpace(user.Country)) + claims.Add(new Claim("address_country", user.Country)); - if (!string.IsNullOrWhiteSpace(user.State)) - claims.Add(new Claim("address_state", user.State)); + if (!string.IsNullOrWhiteSpace(user.State)) + claims.Add(new Claim("address_state", user.State)); - if (!string.IsNullOrWhiteSpace(user.Street)) - claims.Add(new Claim("address_street", user.Street)); + if (!string.IsNullOrWhiteSpace(user.Street)) + claims.Add(new Claim("address_street", user.Street)); - if (!string.IsNullOrWhiteSpace(user.ZipCode)) - claims.Add(new Claim("address_zip_code", user.ZipCode)); + if (!string.IsNullOrWhiteSpace(user.ZipCode)) + claims.Add(new Claim("address_zip_code", user.ZipCode)); - if (_userManager.SupportsUserEmail) + if (_userManager.SupportsUserEmail) + { + claims.AddRange(new[] { - claims.AddRange(new[] - { - new Claim(JwtClaimTypes.Email, user.Email), - new Claim(JwtClaimTypes.EmailVerified, user.EmailConfirmed ? "true" : "false", ClaimValueTypes.Boolean) - }); - } + new Claim(JwtClaimTypes.Email, user.Email), + new Claim(JwtClaimTypes.EmailVerified, user.EmailConfirmed ? "true" : "false", ClaimValueTypes.Boolean) + }); + } - if (_userManager.SupportsUserPhoneNumber && !string.IsNullOrWhiteSpace(user.PhoneNumber)) + if (_userManager.SupportsUserPhoneNumber && !string.IsNullOrWhiteSpace(user.PhoneNumber)) + { + claims.AddRange(new[] { - claims.AddRange(new[] - { - new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber), - new Claim(JwtClaimTypes.PhoneNumberVerified, user.PhoneNumberConfirmed ? "true" : "false", ClaimValueTypes.Boolean) - }); - } - - return claims; + new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber), + new Claim(JwtClaimTypes.PhoneNumberVerified, user.PhoneNumberConfirmed ? "true" : "false", ClaimValueTypes.Boolean) + }); } + + return claims; } } diff --git a/src/Identity.API/Services/RedirectService.cs b/src/Identity.API/Services/RedirectService.cs index d3714d0b1..412e74e03 100644 --- a/src/Identity.API/Services/RedirectService.cs +++ b/src/Identity.API/Services/RedirectService.cs @@ -1,29 +1,28 @@ -namespace eShop.Identity.API.Services +namespace eShop.Identity.API.Services; + +public class RedirectService : IRedirectService { - public class RedirectService : IRedirectService + public string ExtractRedirectUriFromReturnUrl(string url) { - public string ExtractRedirectUriFromReturnUrl(string url) - { - var decodedUrl = System.Net.WebUtility.HtmlDecode(url); - var results = Regex.Split(decodedUrl, "redirect_uri="); - if (results.Length < 2) - return ""; + var decodedUrl = System.Net.WebUtility.HtmlDecode(url); + var results = Regex.Split(decodedUrl, "redirect_uri="); + if (results.Length < 2) + return ""; - string result = results[1]; + string result = results[1]; - string splitKey; - if (result.Contains("signin-oidc")) - splitKey = "signin-oidc"; - else - splitKey = "scope"; + string splitKey; + if (result.Contains("signin-oidc")) + splitKey = "signin-oidc"; + else + splitKey = "scope"; - results = Regex.Split(result, splitKey); - if (results.Length < 2) - return ""; + results = Regex.Split(result, splitKey); + if (results.Length < 2) + return ""; - result = results[0]; + result = results[0]; - return result.Replace("%3A", ":").Replace("%2F", "/").Replace("&", ""); - } + return result.Replace("%3A", ":").Replace("%2F", "/").Replace("&", ""); } } diff --git a/src/OrderProcessor/Events/GracePeriodConfirmedIntegrationEvent.cs b/src/OrderProcessor/Events/GracePeriodConfirmedIntegrationEvent.cs index 678d8c375..330340277 100644 --- a/src/OrderProcessor/Events/GracePeriodConfirmedIntegrationEvent.cs +++ b/src/OrderProcessor/Events/GracePeriodConfirmedIntegrationEvent.cs @@ -1,12 +1,11 @@ -namespace eShop.OrderProcessor.Events -{ - using eShop.EventBus.Events; +namespace eShop.OrderProcessor.Events; + +using eShop.EventBus.Events; - public record GracePeriodConfirmedIntegrationEvent : IntegrationEvent - { - public int OrderId { get; } +public record GracePeriodConfirmedIntegrationEvent : IntegrationEvent +{ + public int OrderId { get; } - public GracePeriodConfirmedIntegrationEvent(int orderId) => - OrderId = orderId; - } + public GracePeriodConfirmedIntegrationEvent(int orderId) => + OrderId = orderId; } diff --git a/src/OrderProcessor/Services/GracePeriodManagerService.cs b/src/OrderProcessor/Services/GracePeriodManagerService.cs index ad3fc1dc1..8fcafeccf 100644 --- a/src/OrderProcessor/Services/GracePeriodManagerService.cs +++ b/src/OrderProcessor/Services/GracePeriodManagerService.cs @@ -2,64 +2,63 @@ using Microsoft.Extensions.Options; using eShop.OrderProcessor.Events; -namespace eShop.OrderProcessor.Services +namespace eShop.OrderProcessor.Services; + +public class GracePeriodManagerService( + IOptions options, + IEventBus eventBus, + ILogger logger, + IGracePeriodOrdersRepository repository) : BackgroundService { - public class GracePeriodManagerService( - IOptions options, - IEventBus eventBus, - ILogger logger, - IGracePeriodOrdersRepository repository) : BackgroundService + private readonly BackgroundTaskOptions _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - private readonly BackgroundTaskOptions _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); + var delayTime = TimeSpan.FromSeconds(_options.CheckUpdateTime); - protected override async Task ExecuteAsync(CancellationToken stoppingToken) + if (logger.IsEnabled(LogLevel.Debug)) { - var delayTime = TimeSpan.FromSeconds(_options.CheckUpdateTime); + logger.LogDebug("GracePeriodManagerService is starting."); + stoppingToken.Register(() => logger.LogDebug("GracePeriodManagerService background task is stopping.")); + } + while (!stoppingToken.IsCancellationRequested) + { if (logger.IsEnabled(LogLevel.Debug)) { - logger.LogDebug("GracePeriodManagerService is starting."); - stoppingToken.Register(() => logger.LogDebug("GracePeriodManagerService background task is stopping.")); + logger.LogDebug("GracePeriodManagerService background task is doing background work."); } - while (!stoppingToken.IsCancellationRequested) - { - if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug("GracePeriodManagerService background task is doing background work."); - } - - await CheckConfirmedGracePeriodOrders(stoppingToken); + await CheckConfirmedGracePeriodOrders(stoppingToken); - await Task.Delay(delayTime, stoppingToken); - } + await Task.Delay(delayTime, stoppingToken); + } - if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug("GracePeriodManagerService background task is stopping."); - } + if (logger.IsEnabled(LogLevel.Debug)) + { + logger.LogDebug("GracePeriodManagerService background task is stopping."); } + } - internal async Task CheckConfirmedGracePeriodOrders(CancellationToken cancellationToken = default) + internal async Task CheckConfirmedGracePeriodOrders(CancellationToken cancellationToken = default) + { + if (logger.IsEnabled(LogLevel.Debug)) { - if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug("Checking confirmed grace period orders"); - } + logger.LogDebug("Checking confirmed grace period orders"); + } - var orderIds = await repository.GetConfirmedGracePeriodOrdersAsync( - TimeSpan.FromMinutes(_options.GracePeriodTime), - cancellationToken); + var orderIds = await repository.GetConfirmedGracePeriodOrdersAsync( + TimeSpan.FromMinutes(_options.GracePeriodTime), + cancellationToken); - foreach (var orderId in orderIds) - { - var confirmGracePeriodEvent = new GracePeriodConfirmedIntegrationEvent(orderId); + foreach (var orderId in orderIds) + { + var confirmGracePeriodEvent = new GracePeriodConfirmedIntegrationEvent(orderId); - logger.LogInformation("Publishing integration event: {IntegrationEventId} - ({@IntegrationEvent})", confirmGracePeriodEvent.Id, confirmGracePeriodEvent); + logger.LogInformation("Publishing integration event: {IntegrationEventId} - ({@IntegrationEvent})", confirmGracePeriodEvent.Id, confirmGracePeriodEvent); - await eventBus.PublishAsync(confirmGracePeriodEvent); - } + await eventBus.PublishAsync(confirmGracePeriodEvent); } - } + } diff --git a/src/Ordering.API/Apis/OrdersApi.cs b/src/Ordering.API/Apis/OrdersApi.cs index b8c339cf8..50282c288 100644 --- a/src/Ordering.API/Apis/OrdersApi.cs +++ b/src/Ordering.API/Apis/OrdersApi.cs @@ -90,9 +90,9 @@ public static async Task, NotFound>> GetOrderAsync(int orderId } } - public static async Task>> GetOrdersByUserAsync([AsParameters] OrderServices services) + public static async Task>> GetOrdersByUserAsync([AsParameters] OrderServices services, string buyerId = null) { - var userId = services.IdentityService.GetUserIdentity(); + var userId = buyerId ?? services.IdentityService.GetUserIdentity(); var orders = await services.Queries.GetOrdersFromUserAsync(userId); return TypedResults.Ok(orders); } diff --git a/src/WebApp/Services/IBasketState.cs b/src/WebApp/Services/IBasketState.cs index bd6480702..03a9986ca 100644 --- a/src/WebApp/Services/IBasketState.cs +++ b/src/WebApp/Services/IBasketState.cs @@ -1,11 +1,10 @@ using eShop.WebAppComponents.Catalog; -namespace eShop.WebApp.Services +namespace eShop.WebApp.Services; + +public interface IBasketState { - public interface IBasketState - { - public Task> GetBasketItemsAsync(); + public Task> GetBasketItemsAsync(); - public Task AddAsync(CatalogItem item); - } + public Task AddAsync(CatalogItem item); } diff --git a/src/WebAppComponents/Services/ICatalogService.cs b/src/WebAppComponents/Services/ICatalogService.cs index 45874b2a8..e465a6c41 100644 --- a/src/WebAppComponents/Services/ICatalogService.cs +++ b/src/WebAppComponents/Services/ICatalogService.cs @@ -2,15 +2,14 @@ using System.Threading.Tasks; using eShop.WebAppComponents.Catalog; -namespace eShop.WebAppComponents.Services +namespace eShop.WebAppComponents.Services; + +public interface ICatalogService { - public interface ICatalogService - { - Task GetCatalogItem(int id); - Task GetCatalogItems(int pageIndex, int pageSize, int[]? brands, int[]? types); - Task> GetCatalogItems(IEnumerable ids); - Task GetCatalogItemsWithSemanticRelevance(int page, int take, string text); - Task> GetBrands(); - Task> GetTypes(); - } + Task GetCatalogItem(int id); + Task GetCatalogItems(int pageIndex, int pageSize, int[]? brands, int[]? types); + Task> GetCatalogItems(IEnumerable ids); + Task GetCatalogItemsWithSemanticRelevance(int page, int take, string text); + Task> GetBrands(); + Task> GetTypes(); }