Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Grand.Business.Authentication - Code cleanup (ReSharper)

supportde65787f2a54
diff --git a/src/Business/Grand.Business.Authentication/Events/CustomerDeletedEventHandler.cs b/src/Business/Grand.Business.Authentication/Events/CustomerDeletedEventHandler.cs
index f9796b731..16fa0d150 100644
--- a/src/Business/Grand.Business.Authentication/Events/CustomerDeletedEventHandler.cs
+++ b/src/Business/Grand.Business.Authentication/Events/CustomerDeletedEventHandler.cs
@@ -1,24 +1,23 @@
-using Grand.Infrastructure.Events;
+using Grand.Data;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Infrastructure.Events;
using MediatR;
-namespace Grand.Business.Authentication.Events
+namespace Grand.Business.Authentication.Events;
+
+public class CustomerDeletedEventHandler : INotificationHandler<EntityDeleted<Customer>>
{
- public class CustomerDeletedEventHandler : INotificationHandler<EntityDeleted<Customer>>
+ private readonly IRepository<ExternalAuthentication> _externalAuthenticationRepository;
+
+ public CustomerDeletedEventHandler(IRepository<ExternalAuthentication> externalAuthenticationRepository)
+ {
+ _externalAuthenticationRepository = externalAuthenticationRepository;
+ }
+
+ public async Task Handle(EntityDeleted<Customer> notification, CancellationToken cancellationToken)
{
- private readonly IRepository<ExternalAuthentication> _externalAuthenticationRepository;
- public CustomerDeletedEventHandler(IRepository<ExternalAuthentication> externalAuthenticationRepository)
- {
- _externalAuthenticationRepository = externalAuthenticationRepository;
- }
- public async Task Handle(EntityDeleted<Customer> notification, CancellationToken cancellationToken)
- {
- var externalRecords = _externalAuthenticationRepository.Table.Where(x => x.CustomerId == notification.Entity.Id).ToList();
- foreach (var item in externalRecords)
- {
- await _externalAuthenticationRepository.DeleteAsync(item);
- }
- }
+ var externalRecords = _externalAuthenticationRepository.Table.Where(x => x.CustomerId == notification.Entity.Id)
+ .ToList();
+ foreach (var item in externalRecords) await _externalAuthenticationRepository.DeleteAsync(item);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
index 561f458ee..1ba913def 100644
--- a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
@@ -8,91 +8,93 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
-namespace Grand.Business.Authentication.Services
+namespace Grand.Business.Authentication.Services;
+
+public class ApiAuthenticationService : IApiAuthenticationService
{
- public class ApiAuthenticationService : IApiAuthenticationService
+ private readonly ICustomerService _customerService;
+ private readonly IGroupService _groupService;
+ private readonly IHttpContextAccessor _httpContextAccessor;
+ private Customer _cachedCustomer;
+
+
+ public ApiAuthenticationService(
+ ICustomerService customerService,
+ IGroupService groupService, IHttpContextAccessor httpContextAccessor)
+ {
+ _customerService = customerService;
+ _groupService = groupService;
+ _httpContextAccessor = httpContextAccessor;
+ }
+
+ public virtual async Task<Customer> GetAuthenticatedCustomer()
{
- private readonly ICustomerService _customerService;
- private readonly IGroupService _groupService;
- private readonly IHttpContextAccessor _httpContextAccessor;
- private Customer _cachedCustomer;
+ //whether there is a cached customer
+ if (_cachedCustomer != null)
+ return _cachedCustomer;
+ Customer customer = null;
+ if (_httpContextAccessor.HttpContext == null) return null;
- public ApiAuthenticationService(
- ICustomerService customerService,
- IGroupService groupService, IHttpContextAccessor httpContextAccessor)
- {
- _customerService = customerService;
- _groupService = groupService;
- _httpContextAccessor = httpContextAccessor;
- }
+ string authHeader = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Authorization];
+ if (string.IsNullOrEmpty(authHeader))
+ return null;
- public virtual async Task<Customer> GetAuthenticatedCustomer()
+ if (_httpContextAccessor.HttpContext.Request.Path.Value != null
+ && !_httpContextAccessor.HttpContext.Request.Path.Value.StartsWith("/odata"))
{
- //whether there is a cached customer
- if (_cachedCustomer != null)
- return _cachedCustomer;
-
- Customer customer = null;
- if (_httpContextAccessor.HttpContext == null) return null;
-
- string authHeader = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Authorization];
- if (string.IsNullOrEmpty(authHeader))
- return null;
-
- if (_httpContextAccessor.HttpContext.Request.Path.Value != null
- && !_httpContextAccessor.HttpContext.Request.Path.Value.StartsWith("/odata"))
- {
- customer = await ApiCustomer();
- if (customer == null) return null;
- _cachedCustomer = customer;
- return _cachedCustomer;
- }
-
- var authenticateResult =
- await _httpContextAccessor.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
- if (!authenticateResult.Succeeded)
- return null;
-
- //try to get customer by email
- var emailClaim = authenticateResult.Principal.Claims.FirstOrDefault(claim => claim.Type == "Email");
- if (emailClaim != null)
- customer = await _customerService.GetCustomerByEmail(emailClaim.Value);
-
- //whether the found customer is available
- if (customer is not { Active: true } || customer.Deleted || !await _groupService.IsRegistered(customer))
- return null;
-
- //cache authenticated customer
+ customer = await ApiCustomer();
+ if (customer == null) return null;
_cachedCustomer = customer;
-
return _cachedCustomer;
}
- private async Task<Customer> ApiCustomer()
+ var authenticateResult =
+ await _httpContextAccessor.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
+ if (!authenticateResult.Succeeded)
+ return null;
+
+ //try to get customer by email
+ var emailClaim = authenticateResult.Principal.Claims.FirstOrDefault(claim => claim.Type == "Email");
+ if (emailClaim != null)
+ customer = await _customerService.GetCustomerByEmail(emailClaim.Value);
+
+ //whether the found customer is available
+ if (customer is not { Active: true } || customer.Deleted || !await _groupService.IsRegistered(customer))
+ return null;
+
+ //cache authenticated customer
+ _cachedCustomer = customer;
+
+ return _cachedCustomer;
+ }
+
+ private async Task<Customer> ApiCustomer()
+ {
+ Customer customer = null;
+ var authResult =
+ await _httpContextAccessor.HttpContext!.AuthenticateAsync(FrontendAPIConfig.AuthenticationScheme);
+ if (!authResult.Succeeded)
{
- Customer customer = null;
- var authResult = await _httpContextAccessor.HttpContext!.AuthenticateAsync(FrontendAPIConfig.AuthenticationScheme);
- if (!authResult.Succeeded)
- {
- _httpContextAccessor.HttpContext.Response.StatusCode = 400;
- _httpContextAccessor.HttpContext.Response.ContentType = "text/plain";
- if (authResult.Failure != null)
- await _httpContextAccessor.HttpContext.Response.WriteAsync(authResult.Failure.Message);
- return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);
- }
- var email = authResult.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;
- if (email is null)
- {
- //guest
- var id = authResult.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;
- if (id != null) customer = await _customerService.GetCustomerByGuid(Guid.Parse(id));
- }
- else
- {
- customer = await _customerService.GetCustomerByEmail(email);
- }
- return customer;
+ _httpContextAccessor.HttpContext.Response.StatusCode = 400;
+ _httpContextAccessor.HttpContext.Response.ContentType = "text/plain";
+ if (authResult.Failure != null)
+ await _httpContextAccessor.HttpContext.Response.WriteAsync(authResult.Failure.Message);
+ return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);
}
+
+ var email = authResult.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;
+ if (email is null)
+ {
+ //guest
+ var id = authResult.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;
+ if (id != null) customer = await _customerService.GetCustomerByGuid(Guid.Parse(id));
+ }
+ else
+ {
+ customer = await _customerService.GetCustomerByEmail(email);
+ }
+
+ return customer;
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs
index 2d1f14925..8882b0e04 100644
--- a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs
@@ -1,238 +1,251 @@
-using Grand.Business.Core.Interfaces.Authentication;
-using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Customers;
-using Grand.Infrastructure.Configuration;
+using Grand.Business.Core.Utilities.Authentication;
using Grand.Domain.Common;
using Grand.Domain.Customers;
+using Grand.Infrastructure.Configuration;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
-using Grand.Business.Core.Utilities.Authentication;
-namespace Grand.Business.Authentication.Services
+namespace Grand.Business.Authentication.Services;
+
+/// <summary>
+/// Represents service using cookie middleware for the authentication
+/// </summary>
+public class CookieAuthenticationService : IGrandAuthenticationService
{
+ #region Ctor
+
/// <summary>
- /// Represents service using cookie middleware for the authentication
+ /// Ctor
/// </summary>
- public class CookieAuthenticationService : IGrandAuthenticationService
+ /// <param name="customerSettings">Customer settings</param>
+ /// <param name="customerService">Customer service</param>
+ /// <param name="groupService">Group service</param>
+ /// <param name="userFieldService">Generic attribute service</param>
+ /// <param name="httpContextAccessor">HTTP context accessor</param>
+ /// <param name="securityConfig">SecurityConfig</param>
+ public CookieAuthenticationService(
+ CustomerSettings customerSettings,
+ ICustomerService customerService,
+ IGroupService groupService,
+ IUserFieldService userFieldService,
+ IHttpContextAccessor httpContextAccessor,
+ SecurityConfig securityConfig)
{
- #region Const
-
- private string CustomerCookieName => $"{_securityConfig.CookiePrefix}Customer";
-
- #endregion
-
- #region Fields
-
- private readonly CustomerSettings _customerSettings;
- private readonly ICustomerService _customerService;
- private readonly IGroupService _groupService;
- private readonly IUserFieldService _userFieldService;
- private readonly IHttpContextAccessor _httpContextAccessor;
- private readonly SecurityConfig _securityConfig;
- private Customer _cachedCustomer;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="customerSettings">Customer settings</param>
- /// <param name="customerService">Customer service</param>
- /// <param name="groupService">Group service</param>
- /// <param name="userFieldService">Generic attribute service</param>
- /// <param name="httpContextAccessor">HTTP context accessor</param>
- /// <param name="securityConfig">SecurityConfig</param>
- public CookieAuthenticationService(
- CustomerSettings customerSettings,
- ICustomerService customerService,
- IGroupService groupService,
- IUserFieldService userFieldService,
- IHttpContextAccessor httpContextAccessor,
- SecurityConfig securityConfig)
- {
- _customerSettings = customerSettings;
- _customerService = customerService;
- _groupService = groupService;
- _userFieldService = userFieldService;
- _httpContextAccessor = httpContextAccessor;
- _securityConfig = securityConfig;
+ _customerSettings = customerSettings;
+ _customerService = customerService;
+ _groupService = groupService;
+ _userFieldService = userFieldService;
+ _httpContextAccessor = httpContextAccessor;
+ _securityConfig = securityConfig;
+ }
- }
+ #endregion
- #endregion
+ #region Const
- #region Methods
+ private string CustomerCookieName => $"{_securityConfig.CookiePrefix}Customer";
- /// <summary>
- /// Sign in
- /// </summary>
- /// <param name="customer">Customer</param>
- /// <param name="isPersistent">Whether the authentication session is persisted across multiple requests</param>
- public virtual async Task SignIn(Customer customer, bool isPersistent)
- {
- ArgumentNullException.ThrowIfNull(customer);
+ #endregion
- //create claims for customer's username and email
- var claims = new List<Claim>();
+ #region Fields
- if (!string.IsNullOrEmpty(customer.Username))
- claims.Add(new Claim(ClaimTypes.Name, customer.Username, ClaimValueTypes.String, _securityConfig.CookieClaimsIssuer));
+ private readonly CustomerSettings _customerSettings;
+ private readonly ICustomerService _customerService;
+ private readonly IGroupService _groupService;
+ private readonly IUserFieldService _userFieldService;
+ private readonly IHttpContextAccessor _httpContextAccessor;
+ private readonly SecurityConfig _securityConfig;
+ private Customer _cachedCustomer;
- if (!string.IsNullOrEmpty(customer.Email))
- claims.Add(new Claim(ClaimTypes.Email, customer.Email, ClaimValueTypes.Email, _securityConfig.CookieClaimsIssuer));
+ #endregion
- //add token
- var passwordToken = await customer.GetUserField<string>(_userFieldService, SystemCustomerFieldNames.PasswordToken);
- if (string.IsNullOrEmpty(passwordToken))
- {
- var passwordGuid = Guid.NewGuid().ToString();
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PasswordToken, passwordGuid);
- claims.Add(new Claim(ClaimTypes.UserData, passwordGuid, ClaimValueTypes.String, _securityConfig.CookieClaimsIssuer));
- }
- else
- claims.Add(new Claim(ClaimTypes.UserData, passwordToken, ClaimValueTypes.String, _securityConfig.CookieClaimsIssuer));
-
- //create principal for the present scheme of authentication
- var userIdentity = new ClaimsIdentity(claims, GrandCookieAuthenticationDefaults.AuthenticationScheme);
- var userPrincipal = new ClaimsPrincipal(userIdentity);
-
- //set value that indicates whether the session is persisted and the time at which the authentication was issued
- var authenticationProperties = new AuthenticationProperties {
- IsPersistent = isPersistent,
- IssuedUtc = DateTime.UtcNow,
- ExpiresUtc = DateTime.UtcNow.AddHours(_securityConfig.CookieAuthExpires)
- };
-
- //sign in user
- if (_httpContextAccessor.HttpContext != null)
- {
- _httpContextAccessor.HttpContext.Response.Cookies.Delete(CustomerCookieName);
-
- await _httpContextAccessor.HttpContext.SignInAsync(
- GrandCookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authenticationProperties);
- }
+ #region Methods
+
+ /// <summary>
+ /// Sign in
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ /// <param name="isPersistent">Whether the authentication session is persisted across multiple requests</param>
+ public virtual async Task SignIn(Customer customer, bool isPersistent)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- //cache authenticated customer
- _cachedCustomer = customer;
+ //create claims for customer's username and email
+ var claims = new List<Claim>();
+
+ if (!string.IsNullOrEmpty(customer.Username))
+ claims.Add(new Claim(ClaimTypes.Name, customer.Username, ClaimValueTypes.String,
+ _securityConfig.CookieClaimsIssuer));
+
+ if (!string.IsNullOrEmpty(customer.Email))
+ claims.Add(new Claim(ClaimTypes.Email, customer.Email, ClaimValueTypes.Email,
+ _securityConfig.CookieClaimsIssuer));
+
+ //add token
+ var passwordToken =
+ await customer.GetUserField<string>(_userFieldService, SystemCustomerFieldNames.PasswordToken);
+ if (string.IsNullOrEmpty(passwordToken))
+ {
+ var passwordGuid = Guid.NewGuid().ToString();
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.PasswordToken, passwordGuid);
+ claims.Add(new Claim(ClaimTypes.UserData, passwordGuid, ClaimValueTypes.String,
+ _securityConfig.CookieClaimsIssuer));
}
+ else
+ {
+ claims.Add(new Claim(ClaimTypes.UserData, passwordToken, ClaimValueTypes.String,
+ _securityConfig.CookieClaimsIssuer));
+ }
+
+ //create principal for the present scheme of authentication
+ var userIdentity = new ClaimsIdentity(claims, GrandCookieAuthenticationDefaults.AuthenticationScheme);
+ var userPrincipal = new ClaimsPrincipal(userIdentity);
- /// <summary>
- /// Sign out customer
- /// </summary>
- public virtual async Task SignOut()
+ //set value that indicates whether the session is persisted and the time at which the authentication was issued
+ var authenticationProperties = new AuthenticationProperties {
+ IsPersistent = isPersistent,
+ IssuedUtc = DateTime.UtcNow,
+ ExpiresUtc = DateTime.UtcNow.AddHours(_securityConfig.CookieAuthExpires)
+ };
+
+ //sign in user
+ if (_httpContextAccessor.HttpContext != null)
{
- //Firstly reset cached customer
- _cachedCustomer = null;
+ _httpContextAccessor.HttpContext.Response.Cookies.Delete(CustomerCookieName);
- //and then sign out customer from the present scheme of authentication
- if (_httpContextAccessor.HttpContext != null)
- {
- await _httpContextAccessor.HttpContext.SignOutAsync(GrandCookieAuthenticationDefaults
- .AuthenticationScheme);
- //sign out also from other schema
- await _httpContextAccessor.HttpContext.SignOutAsync(GrandCookieAuthenticationDefaults
- .ExternalAuthenticationScheme);
- }
+ await _httpContextAccessor.HttpContext.SignInAsync(
+ GrandCookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authenticationProperties);
}
- /// <summary>
- /// Get an authenticated customer
- /// </summary>
- /// <returns>Customer</returns>
- public virtual async Task<Customer> GetAuthenticatedCustomer()
- {
- //check if there is a cached customer
- if (_cachedCustomer != null)
- return _cachedCustomer;
-
- //get the authenticated user identity
- if (_httpContextAccessor.HttpContext == null) return _cachedCustomer;
- var authenticateResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(GrandCookieAuthenticationDefaults.AuthenticationScheme);
- if (!authenticateResult.Succeeded)
- return null;
-
- Customer customer = null;
- if (_customerSettings.UsernamesEnabled)
- {
- //get customer by username if exists
- var usernameClaim = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Name
- && claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer, StringComparison.InvariantCultureIgnoreCase));
- if (usernameClaim != null)
- customer = await _customerService.GetCustomerByUsername(usernameClaim.Value);
- }
- else
- {
- //get customer by email
- var emailClaim = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Email
- && claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer, StringComparison.InvariantCultureIgnoreCase));
- if (emailClaim != null)
- customer = await _customerService.GetCustomerByEmail(emailClaim.Value);
- }
+ //cache authenticated customer
+ _cachedCustomer = customer;
+ }
- if (customer != null)
- {
- var passwordToken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken);
- if (!string.IsNullOrEmpty(passwordToken))
- {
- var tokenClaim = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.UserData
- && claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer, StringComparison.InvariantCultureIgnoreCase));
- if (tokenClaim == null || tokenClaim.Value != passwordToken)
- {
- customer = null;
- }
- }
- }
- //Check if the found customer is available
- if (customer is not { Active: true } || customer.Deleted || !await _groupService.IsRegistered(customer))
- return null;
+ /// <summary>
+ /// Sign out customer
+ /// </summary>
+ public virtual async Task SignOut()
+ {
+ //Firstly reset cached customer
+ _cachedCustomer = null;
- //Cache the authenticated customer
- _cachedCustomer = customer;
+ //and then sign out customer from the present scheme of authentication
+ if (_httpContextAccessor.HttpContext != null)
+ {
+ await _httpContextAccessor.HttpContext.SignOutAsync(GrandCookieAuthenticationDefaults
+ .AuthenticationScheme);
+ //sign out also from other schema
+ await _httpContextAccessor.HttpContext.SignOutAsync(GrandCookieAuthenticationDefaults
+ .ExternalAuthenticationScheme);
+ }
+ }
+ /// <summary>
+ /// Get an authenticated customer
+ /// </summary>
+ /// <returns>Customer</returns>
+ public virtual async Task<Customer> GetAuthenticatedCustomer()
+ {
+ //check if there is a cached customer
+ if (_cachedCustomer != null)
return _cachedCustomer;
- }
- /// <summary>
- /// Get customer cookie
- /// </summary>
- /// <returns>String value of cookie</returns>
- public virtual Task<string> GetCustomerGuid()
+ //get the authenticated user identity
+ if (_httpContextAccessor.HttpContext == null) return _cachedCustomer;
+ var authenticateResult =
+ await _httpContextAccessor.HttpContext.AuthenticateAsync(GrandCookieAuthenticationDefaults
+ .AuthenticationScheme);
+ if (!authenticateResult.Succeeded)
+ return null;
+
+ Customer customer = null;
+ if (_customerSettings.UsernamesEnabled)
{
- return _httpContextAccessor.HttpContext?.Request == null ? Task.FromResult<string>(null) : Task.FromResult(_httpContextAccessor.HttpContext.Request.Cookies[CustomerCookieName]);
+ //get customer by username if exists
+ var usernameClaim = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Name
+ && claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer,
+ StringComparison.InvariantCultureIgnoreCase));
+ if (usernameClaim != null)
+ customer = await _customerService.GetCustomerByUsername(usernameClaim.Value);
+ }
+ else
+ {
+ //get customer by email
+ var emailClaim = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Email
+ && claim.Issuer.Equals(
+ _securityConfig.CookieClaimsIssuer,
+ StringComparison
+ .InvariantCultureIgnoreCase));
+ if (emailClaim != null)
+ customer = await _customerService.GetCustomerByEmail(emailClaim.Value);
}
- /// <summary>
- /// Set customer cookie
- /// </summary>
- /// <param name="customerGuid">Guid of the customer</param>
- public virtual Task SetCustomerGuid(Guid customerGuid)
+ if (customer != null)
{
- if (_httpContextAccessor.HttpContext?.Response == null)
- return Task.CompletedTask;
+ var passwordToken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken);
+ if (!string.IsNullOrEmpty(passwordToken))
+ {
+ var tokenClaim = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.UserData
+ && claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer,
+ StringComparison.InvariantCultureIgnoreCase));
+ if (tokenClaim == null || tokenClaim.Value != passwordToken) customer = null;
+ }
+ }
- //Delete existing cookie value
- _httpContextAccessor.HttpContext.Response.Cookies.Delete(CustomerCookieName);
+ //Check if the found customer is available
+ if (customer is not { Active: true } || customer.Deleted || !await _groupService.IsRegistered(customer))
+ return null;
- //Get the date date of current cookie expiration
- var cookieExpiresDate = DateTime.UtcNow.AddHours(_securityConfig.CookieAuthExpires);
+ //Cache the authenticated customer
+ _cachedCustomer = customer;
- //If provided guid is empty (only remove cookies)
- if (customerGuid == Guid.Empty)
- return Task.CompletedTask;
+ return _cachedCustomer;
+ }
- //set new cookie value
- var options = new CookieOptions {
- HttpOnly = true,
- Expires = cookieExpiresDate
- };
- _httpContextAccessor.HttpContext.Response.Cookies.Append(CustomerCookieName, customerGuid.ToString(), options);
+ /// <summary>
+ /// Get customer cookie
+ /// </summary>
+ /// <returns>String value of cookie</returns>
+ public virtual Task<string> GetCustomerGuid()
+ {
+ return _httpContextAccessor.HttpContext?.Request == null
+ ? Task.FromResult<string>(null)
+ : Task.FromResult(_httpContextAccessor.HttpContext.Request.Cookies[CustomerCookieName]);
+ }
+ /// <summary>
+ /// Set customer cookie
+ /// </summary>
+ /// <param name="customerGuid">Guid of the customer</param>
+ public virtual Task SetCustomerGuid(Guid customerGuid)
+ {
+ if (_httpContextAccessor.HttpContext?.Response == null)
return Task.CompletedTask;
- }
- #endregion
+
+ //Delete existing cookie value
+ _httpContextAccessor.HttpContext.Response.Cookies.Delete(CustomerCookieName);
+
+ //Get the date date of current cookie expiration
+ var cookieExpiresDate = DateTime.UtcNow.AddHours(_securityConfig.CookieAuthExpires);
+
+ //If provided guid is empty (only remove cookies)
+ if (customerGuid == Guid.Empty)
+ return Task.CompletedTask;
+
+ //set new cookie value
+ var options = new CookieOptions {
+ HttpOnly = true,
+ Expires = cookieExpiresDate
+ };
+ _httpContextAccessor.HttpContext.Response.Cookies.Append(CustomerCookieName, customerGuid.ToString(), options);
+
+ return Task.CompletedTask;
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs
index ebc385dc7..329421653 100644
--- a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs
@@ -1,338 +1,345 @@
+using Grand.Business.Core.Commands.Customers;
+using Grand.Business.Core.Events.Customers;
using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Core.Events.Customers;
using Grand.Business.Core.Interfaces.Customers;
+using Grand.Business.Core.Utilities.Authentication;
using Grand.Business.Core.Utilities.Customers;
-using Grand.Domain.Customers;
using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Extensions;
using Grand.SharedKernel.Extensions;
using MediatR;
using Microsoft.AspNetCore.Mvc;
-using Grand.Business.Core.Utilities.Authentication;
-using Grand.Business.Core.Commands.Customers;
-namespace Grand.Business.Authentication.Services
+namespace Grand.Business.Authentication.Services;
+
+/// <summary>
+/// Determines the external authentication service implementation
+/// </summary>
+public class ExternalAuthenticationService : IExternalAuthenticationService
{
+ #region Ctor
+
+ public ExternalAuthenticationService(
+ IGrandAuthenticationService authenticationService,
+ ICustomerManagerService customerManagerService,
+ ICustomerService customerService,
+ IGroupService groupService,
+ IMediator mediator,
+ IRepository<ExternalAuthentication> externalAuthenticationRecordRepository,
+ IWorkContext workContext,
+ IEnumerable<IExternalAuthenticationProvider> externalAuthenticationProviders,
+ CustomerSettings customerSettings,
+ ExternalAuthenticationSettings externalAuthenticationSettings)
+ {
+ _customerSettings = customerSettings;
+ _externalAuthenticationSettings = externalAuthenticationSettings;
+ _authenticationService = authenticationService;
+ _customerManagerService = customerManagerService;
+ _customerService = customerService;
+ _groupService = groupService;
+ _mediator = mediator;
+ _externalAuthenticationRecordRepository = externalAuthenticationRecordRepository;
+ _workContext = workContext;
+ _externalAuthenticationProviders = externalAuthenticationProviders;
+ }
+
+ #endregion
+
+ #region Fields
+
+ private readonly IGrandAuthenticationService _authenticationService;
+ private readonly ICustomerManagerService _customerManagerService;
+ private readonly ICustomerService _customerService;
+ private readonly IGroupService _groupService;
+ private readonly IMediator _mediator;
+ private readonly IRepository<ExternalAuthentication> _externalAuthenticationRecordRepository;
+ private readonly IWorkContext _workContext;
+ private readonly IEnumerable<IExternalAuthenticationProvider> _externalAuthenticationProviders;
+ private readonly CustomerSettings _customerSettings;
+ private readonly ExternalAuthenticationSettings _externalAuthenticationSettings;
+
+ #endregion
+
+ #region Utilities
+
/// <summary>
- /// Determines the external authentication service implementation
+ /// Authenticate user with existing associated external account
/// </summary>
- public class ExternalAuthenticationService : IExternalAuthenticationService
+ /// <param name="associatedUser">Associated with passed external authentication parameters user</param>
+ /// <param name="currentLoggedInUser">Current logged-in user</param>
+ /// <param name="returnUrl">URL to which the user will return after authentication</param>
+ /// <returns>Result of an authentication</returns>
+ protected virtual async Task<IActionResult> AuthenticateExistingUser(Customer associatedUser,
+ Customer currentLoggedInUser, string returnUrl)
{
- #region Fields
-
- private readonly IGrandAuthenticationService _authenticationService;
- private readonly ICustomerManagerService _customerManagerService;
- private readonly ICustomerService _customerService;
- private readonly IGroupService _groupService;
- private readonly IMediator _mediator;
- private readonly IRepository<ExternalAuthentication> _externalAuthenticationRecordRepository;
- private readonly IWorkContext _workContext;
- private readonly IEnumerable<IExternalAuthenticationProvider> _externalAuthenticationProviders;
- private readonly CustomerSettings _customerSettings;
- private readonly ExternalAuthenticationSettings _externalAuthenticationSettings;
-
- #endregion
-
- #region Ctor
-
- public ExternalAuthenticationService(
- IGrandAuthenticationService authenticationService,
- ICustomerManagerService customerManagerService,
- ICustomerService customerService,
- IGroupService groupService,
- IMediator mediator,
- IRepository<ExternalAuthentication> externalAuthenticationRecordRepository,
- IWorkContext workContext,
- IEnumerable<IExternalAuthenticationProvider> externalAuthenticationProviders,
- CustomerSettings customerSettings,
- ExternalAuthenticationSettings externalAuthenticationSettings)
- {
- _customerSettings = customerSettings;
- _externalAuthenticationSettings = externalAuthenticationSettings;
- _authenticationService = authenticationService;
- _customerManagerService = customerManagerService;
- _customerService = customerService;
- _groupService = groupService;
- _mediator = mediator;
- _externalAuthenticationRecordRepository = externalAuthenticationRecordRepository;
- _workContext = workContext;
- _externalAuthenticationProviders = externalAuthenticationProviders;
- }
+ //log in guest user
+ if (currentLoggedInUser == null)
+ return await LoginUser(associatedUser, returnUrl);
- #endregion
+ //account is already assigned to another user
+ if (currentLoggedInUser.Id != associatedUser.Id)
+ return Error(new[] { "Account is already assigned" });
- #region Utilities
+ if (string.IsNullOrEmpty(returnUrl))
+ return new RedirectToRouteResult("HomePage", new { area = "" });
+ return new RedirectResult(returnUrl);
+ }
- /// <summary>
- /// Authenticate user with existing associated external account
- /// </summary>
- /// <param name="associatedUser">Associated with passed external authentication parameters user</param>
- /// <param name="currentLoggedInUser">Current logged-in user</param>
- /// <param name="returnUrl">URL to which the user will return after authentication</param>
- /// <returns>Result of an authentication</returns>
- protected virtual async Task<IActionResult> AuthenticateExistingUser(Customer associatedUser, Customer currentLoggedInUser, string returnUrl)
+ /// <summary>
+ /// Authenticate current user and associate new external account with user
+ /// </summary>
+ /// <param name="currentLoggedInUser">Current logged-in user</param>
+ /// <param name="parameters">Authentication parameters received from external authentication method</param>
+ /// <param name="returnUrl">URL to which the user will return after authentication</param>
+ /// <returns>Result of an authentication</returns>
+ protected virtual async Task<IActionResult> AuthenticateNewUser(Customer currentLoggedInUser,
+ ExternalAuthParam parameters, string returnUrl)
+ {
+ //associate external account with logged-in user
+ if (currentLoggedInUser != null)
{
- //log in guest user
- if (currentLoggedInUser == null)
- return await LoginUser(associatedUser, returnUrl);
-
- //account is already assigned to another user
- if (currentLoggedInUser.Id != associatedUser.Id)
- return Error(new[] { "Account is already assigned" });
-
+ await AssociateCustomer(currentLoggedInUser, parameters);
if (string.IsNullOrEmpty(returnUrl))
return new RedirectToRouteResult("HomePage", new { area = "" });
return new RedirectResult(returnUrl);
}
- /// <summary>
- /// Authenticate current user and associate new external account with user
- /// </summary>
- /// <param name="currentLoggedInUser">Current logged-in user</param>
- /// <param name="parameters">Authentication parameters received from external authentication method</param>
- /// <param name="returnUrl">URL to which the user will return after authentication</param>
- /// <returns>Result of an authentication</returns>
- protected virtual async Task<IActionResult> AuthenticateNewUser(Customer currentLoggedInUser, ExternalAuthParam parameters, string returnUrl)
- {
- //associate external account with logged-in user
- if (currentLoggedInUser != null)
- {
- await AssociateCustomer(currentLoggedInUser, parameters);
- if (string.IsNullOrEmpty(returnUrl))
- return new RedirectToRouteResult("HomePage", new { area = "" });
- return new RedirectResult(returnUrl);
- }
-
- //or try to register new user
- if (_customerSettings.UserRegistrationType != UserRegistrationType.Disabled)
- return await RegisterNewUser(parameters, returnUrl);
-
- //registration is disabled
- return Error(new[] { "Registration is disabled" });
- }
+ //or try to register new user
+ if (_customerSettings.UserRegistrationType != UserRegistrationType.Disabled)
+ return await RegisterNewUser(parameters, returnUrl);
- /// <summary>
- /// Register new user
- /// </summary>
- /// <param name="parameters">Authentication parameters received from external authentication method</param>
- /// <param name="returnUrl">URL to which the user will return after authentication</param>
- /// <returns>Result of an authentication</returns>
- protected virtual async Task<IActionResult> RegisterNewUser(ExternalAuthParam parameters, string returnUrl)
- {
- var approved = _customerSettings.UserRegistrationType is UserRegistrationType.Standard or UserRegistrationType.EmailValidation;
-
- //create registration request
- var registrationRequest = new RegistrationRequest(_workContext.CurrentCustomer,
- parameters.Email, parameters.Email,
- CommonHelper.GenerateRandomDigitCode(20),
- PasswordFormat.Hashed,
- _workContext.CurrentStore.Id,
- approved);
-
- //whether registration request has been completed successfully
- await _customerManagerService.RegisterCustomer(registrationRequest);
-
- //allow to save other customer values by consuming this event
- await _mediator.Publish(new RegisteredByExternalMethod(_workContext.CurrentCustomer, parameters));
-
- //raise customer registered event
- await _mediator.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));
-
- //associate external account with registered user
- await AssociateCustomer(_workContext.CurrentCustomer, parameters);
-
- //authenticate
- if (!approved)
- return _customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval
- ? new RedirectToRouteResult("RegisterResult",
- new { resultId = (int)UserRegistrationType.AdminApproval })
- : Error(new[] { "Error on registration" });
- await _authenticationService.SignIn(_workContext.CurrentCustomer, false);
-
- return new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
- }
+ //registration is disabled
+ return Error(new[] { "Registration is disabled" });
+ }
- /// <summary>
- /// Login passed user
- /// </summary>
- /// <param name="user">User to login</param>
- /// <param name="returnUrl">URL to which the user will return after authentication</param>
- /// <returns>Result of an authentication</returns>
- protected virtual async Task<IActionResult> LoginUser(Customer user, string returnUrl)
- {
- //raise event
- await _mediator.Publish(new CustomerLoggedInEvent(user));
+ /// <summary>
+ /// Register new user
+ /// </summary>
+ /// <param name="parameters">Authentication parameters received from external authentication method</param>
+ /// <param name="returnUrl">URL to which the user will return after authentication</param>
+ /// <returns>Result of an authentication</returns>
+ protected virtual async Task<IActionResult> RegisterNewUser(ExternalAuthParam parameters, string returnUrl)
+ {
+ var approved =
+ _customerSettings.UserRegistrationType is UserRegistrationType.Standard
+ or UserRegistrationType.EmailValidation;
+
+ //create registration request
+ var registrationRequest = new RegistrationRequest(_workContext.CurrentCustomer,
+ parameters.Email, parameters.Email,
+ CommonHelper.GenerateRandomDigitCode(20),
+ PasswordFormat.Hashed,
+ _workContext.CurrentStore.Id,
+ approved);
+
+ //whether registration request has been completed successfully
+ await _customerManagerService.RegisterCustomer(registrationRequest);
+
+ //allow to save other customer values by consuming this event
+ await _mediator.Publish(new RegisteredByExternalMethod(_workContext.CurrentCustomer, parameters));
+
+ //raise customer registered event
+ await _mediator.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));
+
+ //associate external account with registered user
+ await AssociateCustomer(_workContext.CurrentCustomer, parameters);
+
+ //authenticate
+ if (!approved)
+ return _customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval
+ ? new RedirectToRouteResult("RegisterResult",
+ new { resultId = (int)UserRegistrationType.AdminApproval })
+ : Error(new[] { "Error on registration" });
+ await _authenticationService.SignIn(_workContext.CurrentCustomer, false);
+
+ return new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
+ }
- //authenticate
- await _authenticationService.SignIn(user, false);
+ /// <summary>
+ /// Login passed user
+ /// </summary>
+ /// <param name="user">User to login</param>
+ /// <param name="returnUrl">URL to which the user will return after authentication</param>
+ /// <returns>Result of an authentication</returns>
+ protected virtual async Task<IActionResult> LoginUser(Customer user, string returnUrl)
+ {
+ //raise event
+ await _mediator.Publish(new CustomerLoggedInEvent(user));
- if (string.IsNullOrEmpty(returnUrl))
- return new RedirectToRouteResult("HomePage", new { area = "" });
+ //authenticate
+ await _authenticationService.SignIn(user, false);
- return new RedirectResult(returnUrl);
- }
+ if (string.IsNullOrEmpty(returnUrl))
+ return new RedirectToRouteResult("HomePage", new { area = "" });
- /// <summary>
- /// Add errors that occurred during authentication
- /// </summary>
- /// <param name="errors">Collection of errors</param>
- /// <returns>Result of an authentication</returns>
- protected virtual IActionResult Error(IEnumerable<string> errors)
- {
- return new RedirectToActionResult("ExternalAuthenticationError", "Common", new { Errors = errors });
- }
+ return new RedirectResult(returnUrl);
+ }
- #endregion
+ /// <summary>
+ /// Add errors that occurred during authentication
+ /// </summary>
+ /// <param name="errors">Collection of errors</param>
+ /// <returns>Result of an authentication</returns>
+ protected virtual IActionResult Error(IEnumerable<string> errors)
+ {
+ return new RedirectToActionResult("ExternalAuthenticationError", "Common", new { Errors = errors });
+ }
- #region Methods
+ #endregion
- #region External authentication methods
+ #region Methods
- /// <summary>
- /// Load active external authentication providers
- /// </summary>
- /// <returns>External Authentication Providers</returns>
- public virtual IList<IExternalAuthenticationProvider> LoadActiveAuthenticationProviders(Customer customer = null, Store store = null)
- {
- return LoadAllAuthenticationProviders()
- .Where(provider =>
- provider.IsMethodActive(_externalAuthenticationSettings) &&
- provider.IsAuthenticateGroup(_workContext.CurrentCustomer) &&
- provider.IsAuthenticateStore(_workContext.CurrentStore)
- ).ToList();
- }
+ #region External authentication methods
- /// <summary>
- /// Load external authentication provider by system name
- /// </summary>
- /// <param name="systemName">System name</param>
- /// <returns>Found external authentication provider</returns>
- public virtual IExternalAuthenticationProvider LoadAuthenticationProviderBySystemName(string systemName)
- {
- return _externalAuthenticationProviders.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase));
- }
+ /// <summary>
+ /// Load active external authentication providers
+ /// </summary>
+ /// <returns>External Authentication Providers</returns>
+ public virtual IList<IExternalAuthenticationProvider> LoadActiveAuthenticationProviders(Customer customer = null,
+ Store store = null)
+ {
+ return LoadAllAuthenticationProviders()
+ .Where(provider =>
+ provider.IsMethodActive(_externalAuthenticationSettings) &&
+ provider.IsAuthenticateGroup(_workContext.CurrentCustomer) &&
+ provider.IsAuthenticateStore(_workContext.CurrentStore)
+ ).ToList();
+ }
- /// <summary>
- /// Load all external authentication providers
- /// </summary>
- /// <returns>External authentication methods</returns>
- public virtual IList<IExternalAuthenticationProvider> LoadAllAuthenticationProviders()
- {
- return _externalAuthenticationProviders.OrderBy(x => x.Priority).ToList();
- }
+ /// <summary>
+ /// Load external authentication provider by system name
+ /// </summary>
+ /// <param name="systemName">System name</param>
+ /// <returns>Found external authentication provider</returns>
+ public virtual IExternalAuthenticationProvider LoadAuthenticationProviderBySystemName(string systemName)
+ {
+ return _externalAuthenticationProviders.FirstOrDefault(x =>
+ x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase));
+ }
- /// <summary>
- /// Check whether authentication by the passed external authentication provider is available
- /// </summary>
- /// <param name="systemName">System name of the external authentication provider</param>
- /// <returns>True if is available; otherwise false</returns>
- public virtual bool AuthenticationProviderIsAvailable(string systemName)
- {
- var authenticationMethod = LoadAuthenticationProviderBySystemName(systemName);
+ /// <summary>
+ /// Load all external authentication providers
+ /// </summary>
+ /// <returns>External authentication methods</returns>
+ public virtual IList<IExternalAuthenticationProvider> LoadAllAuthenticationProviders()
+ {
+ return _externalAuthenticationProviders.OrderBy(x => x.Priority).ToList();
+ }
- return authenticationMethod != null &&
- authenticationMethod.IsMethodActive(_externalAuthenticationSettings) &&
- authenticationMethod.IsAuthenticateGroup(_workContext.CurrentCustomer) &&
- authenticationMethod.IsAuthenticateStore(_workContext.CurrentStore);
- }
+ /// <summary>
+ /// Check whether authentication by the passed external authentication provider is available
+ /// </summary>
+ /// <param name="systemName">System name of the external authentication provider</param>
+ /// <returns>True if is available; otherwise false</returns>
+ public virtual bool AuthenticationProviderIsAvailable(string systemName)
+ {
+ var authenticationMethod = LoadAuthenticationProviderBySystemName(systemName);
- #endregion
+ return authenticationMethod != null &&
+ authenticationMethod.IsMethodActive(_externalAuthenticationSettings) &&
+ authenticationMethod.IsAuthenticateGroup(_workContext.CurrentCustomer) &&
+ authenticationMethod.IsAuthenticateStore(_workContext.CurrentStore);
+ }
- #region Authentication
+ #endregion
- /// <summary>
- /// Authenticate user by passed parameters
- /// </summary>
- /// <param name="parameters">External authentication parameters</param>
- /// <param name="returnUrl">URL to which the user will return after authentication</param>
- /// <returns>Result of an authentication</returns>
- public virtual async Task<IActionResult> Authenticate(ExternalAuthParam parameters, string returnUrl = null)
- {
- ArgumentNullException.ThrowIfNull(parameters);
+ #region Authentication
- if (!AuthenticationProviderIsAvailable(parameters.ProviderSystemName))
- return Error(new[] { "External authentication method cannot be loaded" });
+ /// <summary>
+ /// Authenticate user by passed parameters
+ /// </summary>
+ /// <param name="parameters">External authentication parameters</param>
+ /// <param name="returnUrl">URL to which the user will return after authentication</param>
+ /// <returns>Result of an authentication</returns>
+ public virtual async Task<IActionResult> Authenticate(ExternalAuthParam parameters, string returnUrl = null)
+ {
+ ArgumentNullException.ThrowIfNull(parameters);
- //get current logged-in user
- var currentLoggedInUser = await _groupService.IsRegistered(_workContext.CurrentCustomer) ? _workContext.CurrentCustomer : null;
+ if (!AuthenticationProviderIsAvailable(parameters.ProviderSystemName))
+ return Error(new[] { "External authentication method cannot be loaded" });
- //authenticate associated user if already exists
- var associatedUser = await GetCustomer(parameters);
- if (associatedUser != null)
- return await AuthenticateExistingUser(associatedUser, currentLoggedInUser, returnUrl);
+ //get current logged-in user
+ var currentLoggedInUser = await _groupService.IsRegistered(_workContext.CurrentCustomer)
+ ? _workContext.CurrentCustomer
+ : null;
- //or associate and authenticate new user
- return await AuthenticateNewUser(currentLoggedInUser, parameters, returnUrl);
- }
+ //authenticate associated user if already exists
+ var associatedUser = await GetCustomer(parameters);
+ if (associatedUser != null)
+ return await AuthenticateExistingUser(associatedUser, currentLoggedInUser, returnUrl);
- #endregion
+ //or associate and authenticate new user
+ return await AuthenticateNewUser(currentLoggedInUser, parameters, returnUrl);
+ }
- /// <summary>
- /// Associate external account with customer
- /// </summary>
- /// <param name="customer">Customer</param>
- /// <param name="parameters">External authentication parameters</param>
- public virtual async Task AssociateCustomer(Customer customer, ExternalAuthParam parameters)
- {
- ArgumentNullException.ThrowIfNull(customer);
-
- var externalAuthenticationRecord = new ExternalAuthentication {
- CustomerId = customer.Id,
- Email = parameters.Email,
- ExternalIdentifier = parameters.Identifier,
- ExternalDisplayIdentifier = parameters.Name,
- OAuthAccessToken = parameters.AccessToken,
- ProviderSystemName = parameters.ProviderSystemName
- };
-
- await _externalAuthenticationRecordRepository.InsertAsync(externalAuthenticationRecord);
- }
+ #endregion
- /// <summary>
- /// Get the particular user with specified parameters
- /// </summary>
- /// <param name="parameters">External authentication parameters</param>
- /// <returns>Customer</returns>
- public virtual async Task<Customer> GetCustomer(ExternalAuthParam parameters)
- {
- ArgumentNullException.ThrowIfNull(parameters);
+ /// <summary>
+ /// Associate external account with customer
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ /// <param name="parameters">External authentication parameters</param>
+ public virtual async Task AssociateCustomer(Customer customer, ExternalAuthParam parameters)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
+
+ var externalAuthenticationRecord = new ExternalAuthentication {
+ CustomerId = customer.Id,
+ Email = parameters.Email,
+ ExternalIdentifier = parameters.Identifier,
+ ExternalDisplayIdentifier = parameters.Name,
+ OAuthAccessToken = parameters.AccessToken,
+ ProviderSystemName = parameters.ProviderSystemName
+ };
+
+ await _externalAuthenticationRecordRepository.InsertAsync(externalAuthenticationRecord);
+ }
- var associationRecord = (from q in _externalAuthenticationRecordRepository.Table
- where q.ExternalIdentifier.ToLowerInvariant() == parameters.Identifier
- && q.ProviderSystemName.ToLowerInvariant() == parameters.ProviderSystemName.ToLowerInvariant()
- select q).FirstOrDefault();
+ /// <summary>
+ /// Get the particular user with specified parameters
+ /// </summary>
+ /// <param name="parameters">External authentication parameters</param>
+ /// <returns>Customer</returns>
+ public virtual async Task<Customer> GetCustomer(ExternalAuthParam parameters)
+ {
+ ArgumentNullException.ThrowIfNull(parameters);
- if (associationRecord == null)
- return null;
+ var associationRecord = (from q in _externalAuthenticationRecordRepository.Table
+ where q.ExternalIdentifier.ToLowerInvariant() == parameters.Identifier
+ && q.ProviderSystemName.ToLowerInvariant() == parameters.ProviderSystemName.ToLowerInvariant()
+ select q).FirstOrDefault();
- return await _customerService.GetCustomerById(associationRecord.CustomerId);
- }
+ if (associationRecord == null)
+ return null;
- public virtual async Task<IList<ExternalAuthentication>> GetExternalIdentifiers(Customer customer)
- {
- ArgumentNullException.ThrowIfNull(customer);
-
- var query = from p in _externalAuthenticationRecordRepository.Table
- where p.CustomerId == customer.Id
- select p;
- return await Task.FromResult(query.ToList());
- }
+ return await _customerService.GetCustomerById(associationRecord.CustomerId);
+ }
- /// <summary>
- /// Delete the external authentication
- /// </summary>
- /// <param name="externalAuthentication">External authentication</param>
- public virtual async Task DeleteExternalAuthentication(ExternalAuthentication externalAuthentication)
- {
- ArgumentNullException.ThrowIfNull(externalAuthentication);
+ public virtual async Task<IList<ExternalAuthentication>> GetExternalIdentifiers(Customer customer)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- await _externalAuthenticationRecordRepository.DeleteAsync(externalAuthentication);
- }
+ var query = from p in _externalAuthenticationRecordRepository.Table
+ where p.CustomerId == customer.Id
+ select p;
+ return await Task.FromResult(query.ToList());
+ }
+
+ /// <summary>
+ /// Delete the external authentication
+ /// </summary>
+ /// <param name="externalAuthentication">External authentication</param>
+ public virtual async Task DeleteExternalAuthentication(ExternalAuthentication externalAuthentication)
+ {
+ ArgumentNullException.ThrowIfNull(externalAuthentication);
- #endregion
+ await _externalAuthenticationRecordRepository.DeleteAsync(externalAuthentication);
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs
index 320b22f6e..0e9be1cc2 100644
--- a/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs
@@ -2,73 +2,70 @@
using Grand.Business.Core.Interfaces.Customers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
-namespace Grand.Business.Authentication.Services
+namespace Grand.Business.Authentication.Services;
+
+public class JwtBearerAuthenticationService : IJwtBearerAuthenticationService
{
- public class JwtBearerAuthenticationService : IJwtBearerAuthenticationService
+ private readonly ICustomerService _customerService;
+ private readonly IUserApiService _userApiService;
+ private string _email;
+
+ private string _errorMessage;
+
+ public JwtBearerAuthenticationService(
+ ICustomerService customerService, IUserApiService userApiService)
{
- private readonly ICustomerService _customerService;
- private readonly IUserApiService _userApiService;
+ _customerService = customerService;
+ _userApiService = userApiService;
+ }
- private string _errorMessage;
- private string _email;
+ /// <summary>
+ /// Valid
+ /// </summary>
+ /// <param name="context">Context</param>
+ public virtual async Task<bool> Valid(TokenValidatedContext context)
+ {
+ if (context.Principal == null) return await Task.FromResult(false);
- public JwtBearerAuthenticationService(
- ICustomerService customerService, IUserApiService userApiService)
+ _email = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;
+ var token = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Token")?.Value;
+ if (string.IsNullOrEmpty(token))
{
- _customerService = customerService;
- _userApiService = userApiService;
+ _errorMessage = "Wrong token, change password on the customer and create token again";
+ return await Task.FromResult(false);
}
- /// <summary>
- /// Valid
- /// </summary>
- /// <param name="context">Context</param>
- public virtual async Task<bool> Valid(TokenValidatedContext context)
+ if (string.IsNullOrEmpty(_email))
{
- if (context.Principal == null) return await Task.FromResult(false);
-
- _email = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;
- var token = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Token")?.Value;
- if (string.IsNullOrEmpty(token))
- {
- _errorMessage = "Wrong token, change password on the customer and create token again";
- return await Task.FromResult(false);
- }
-
- if (string.IsNullOrEmpty(_email))
- {
- _errorMessage = "Email not exists in the context";
- return await Task.FromResult(false);
- }
-
- var customer = await _customerService.GetCustomerByEmail(_email);
- if (customer is not { Active: true } || customer.Deleted)
- {
- _errorMessage = "Email not exists/or not active in the customer table";
- return await Task.FromResult(false);
- }
-
- var userApi = await _userApiService.GetUserByEmail(_email);
- if (userApi is not { IsActive: true })
- {
- _errorMessage = "User api not exists/or not active in the user api table";
- return await Task.FromResult(false);
- }
-
- if (userApi.Token == token) return await Task.FromResult(true);
- _errorMessage = "Wrong token, generate again";
+ _errorMessage = "Email not exists in the context";
return await Task.FromResult(false);
+ }
+ var customer = await _customerService.GetCustomerByEmail(_email);
+ if (customer is not { Active: true } || customer.Deleted)
+ {
+ _errorMessage = "Email not exists/or not active in the customer table";
+ return await Task.FromResult(false);
}
- /// <summary>
- /// Get error message
- /// </summary>
- /// <returns></returns>
- public virtual Task<string> ErrorMessage()
+ var userApi = await _userApiService.GetUserByEmail(_email);
+ if (userApi is not { IsActive: true })
{
- return Task.FromResult(_errorMessage);
+ _errorMessage = "User api not exists/or not active in the user api table";
+ return await Task.FromResult(false);
}
+ if (userApi.Token == token) return await Task.FromResult(true);
+ _errorMessage = "Wrong token, generate again";
+ return await Task.FromResult(false);
+ }
+
+ /// <summary>
+ /// Get error message
+ /// </summary>
+ /// <returns></returns>
+ public virtual Task<string> ErrorMessage()
+ {
+ return Task.FromResult(_errorMessage);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs
index 99c732774..f493a7c00 100644
--- a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs
@@ -1,86 +1,86 @@
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Business.Core.Utilities.Common.Security;
using Grand.Business.Core.Interfaces.Customers;
+using Grand.Business.Core.Utilities.Common.Security;
+using Grand.Domain.Common;
using Grand.Domain.Customers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
-using Grand.Domain.Common;
-namespace Grand.Business.Authentication.Services
+namespace Grand.Business.Authentication.Services;
+
+public class JwtBearerCustomerAuthenticationService : IJwtBearerCustomerAuthenticationService
{
- public class JwtBearerCustomerAuthenticationService : IJwtBearerCustomerAuthenticationService
+ private readonly ICustomerService _customerService;
+ private readonly IGroupService _groupService;
+ private readonly IPermissionService _permissionService;
+ private readonly IRefreshTokenService _refreshTokenService;
+ private string _errorMessage;
+
+ public JwtBearerCustomerAuthenticationService(ICustomerService customerService,
+ IPermissionService permissionService, IGroupService groupService, IRefreshTokenService refreshTokenService)
{
- private readonly ICustomerService _customerService;
- private readonly IPermissionService _permissionService;
- private readonly IGroupService _groupService;
- private readonly IRefreshTokenService _refreshTokenService;
- private string _errorMessage;
+ _customerService = customerService;
+ _permissionService = permissionService;
+ _groupService = groupService;
+ _refreshTokenService = refreshTokenService;
+ }
- public JwtBearerCustomerAuthenticationService(ICustomerService customerService, IPermissionService permissionService, IGroupService groupService, IRefreshTokenService refreshTokenService)
+ public async Task<bool> Valid(TokenValidatedContext context)
+ {
+ if (context.Principal == null) return false;
+ var email = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;
+ var passwordToken = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Token")?.Value;
+ var refreshId = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "RefreshId")?.Value;
+ Customer customer = null;
+ if (email is null)
{
- _customerService = customerService;
- _permissionService = permissionService;
- _groupService = groupService;
- _refreshTokenService = refreshTokenService;
+ //guest
+ var id = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;
+ if (id != null) customer = await _customerService.GetCustomerByGuid(Guid.Parse(id));
}
-
- public async Task<bool> Valid(TokenValidatedContext context)
+ else
{
- if (context.Principal == null) return false;
- var email = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;
- var passwordToken = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Token")?.Value;
- var refreshId = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "RefreshId")?.Value;
- Customer customer = null;
- if (email is null)
- {
- //guest
- var id = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;
- if (id != null) customer = await _customerService.GetCustomerByGuid(Guid.Parse(id));
- }
- else
- {
- customer = await _customerService.GetCustomerByEmail(email);
- }
- if (customer is null)
- {
- _errorMessage = "Not found customer";
- return false;
- }
-
- if (!customer.Active || customer.Deleted)
- {
- _errorMessage = "Customer not exists/or not active in the customer table";
- return false;
- }
-
- var refreshToken = await _refreshTokenService.GetCustomerRefreshToken(customer);
- if (refreshToken is null || string.IsNullOrEmpty(refreshId) || !refreshId.Equals(refreshToken.RefreshId))
- {
- _errorMessage = "Invalid token or cancel by refresh token";
- return false;
- }
+ customer = await _customerService.GetCustomerByEmail(email);
+ }
- if (!await _permissionService.Authorize(StandardPermission.AllowUseApi, customer))
- {
- _errorMessage = "You do not have permission to use API operation (Customer group)";
- return false;
- }
+ if (customer is null)
+ {
+ _errorMessage = "Not found customer";
+ return false;
+ }
- var customerPasswordToken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken);
- var isGuest = await _groupService.IsGuest(customer);
- if (isGuest || (!string.IsNullOrEmpty(passwordToken) && passwordToken.Equals(customerPasswordToken)))
- return true;
-
- _errorMessage = "Invalid password token, create new token";
+ if (!customer.Active || customer.Deleted)
+ {
+ _errorMessage = "Customer not exists/or not active in the customer table";
return false;
}
+ var refreshToken = await _refreshTokenService.GetCustomerRefreshToken(customer);
+ if (refreshToken is null || string.IsNullOrEmpty(refreshId) || !refreshId.Equals(refreshToken.RefreshId))
+ {
+ _errorMessage = "Invalid token or cancel by refresh token";
+ return false;
+ }
- public Task<string> ErrorMessage()
+ if (!await _permissionService.Authorize(StandardPermission.AllowUseApi, customer))
{
- return Task.FromResult(_errorMessage);
+ _errorMessage = "You do not have permission to use API operation (Customer group)";
+ return false;
}
+ var customerPasswordToken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken);
+ var isGuest = await _groupService.IsGuest(customer);
+ if (isGuest || (!string.IsNullOrEmpty(passwordToken) && passwordToken.Equals(customerPasswordToken)))
+ return true;
+
+ _errorMessage = "Invalid password token, create new token";
+ return false;
+ }
+
+
+ public Task<string> ErrorMessage()
+ {
+ return Task.FromResult(_errorMessage);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs b/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs
index 1fc225d21..0a2e781f6 100644
--- a/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs
@@ -8,60 +8,62 @@ using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
-namespace Grand.Business.Authentication.Services
+namespace Grand.Business.Authentication.Services;
+
+public class RefreshTokenService : IRefreshTokenService
{
- public class RefreshTokenService : IRefreshTokenService
- {
- private readonly IUserFieldService _userFieldService;
- private readonly FrontendAPIConfig _apiConfig;
+ private readonly FrontendAPIConfig _apiConfig;
+ private readonly IUserFieldService _userFieldService;
- public RefreshTokenService(IUserFieldService userFieldService, FrontendAPIConfig apiConfig)
- {
- _userFieldService = userFieldService;
- _apiConfig = apiConfig;
- }
+ public RefreshTokenService(IUserFieldService userFieldService, FrontendAPIConfig apiConfig)
+ {
+ _userFieldService = userFieldService;
+ _apiConfig = apiConfig;
+ }
- public string GenerateRefreshToken()
- {
- var randomNumber = new byte[32];
- using var rng = RandomNumberGenerator.Create();
- rng.GetBytes(randomNumber);
- return Convert.ToBase64String(randomNumber);
- }
+ public string GenerateRefreshToken()
+ {
+ var randomNumber = new byte[32];
+ using var rng = RandomNumberGenerator.Create();
+ rng.GetBytes(randomNumber);
+ return Convert.ToBase64String(randomNumber);
+ }
- public async Task<RefreshToken> SaveRefreshTokenToCustomer(Customer customer, string refreshToken)
- {
- var token = new RefreshToken {
- RefreshId=Guid.NewGuid().ToString(),
- Token = refreshToken,
- IsActive = true,
- ValidTo = DateTime.UtcNow.AddMinutes(_apiConfig.RefreshTokenExpiryInMinutes)
- };
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.RefreshToken, token);
- return token;
- }
+ public async Task<RefreshToken> SaveRefreshTokenToCustomer(Customer customer, string refreshToken)
+ {
+ var token = new RefreshToken {
+ RefreshId = Guid.NewGuid().ToString(),
+ Token = refreshToken,
+ IsActive = true,
+ ValidTo = DateTime.UtcNow.AddMinutes(_apiConfig.RefreshTokenExpiryInMinutes)
+ };
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.RefreshToken, token);
+ return token;
+ }
- public async Task<RefreshToken> GetCustomerRefreshToken(Customer customer)
- {
- return await _userFieldService.GetFieldsForEntity<RefreshToken>(customer, SystemCustomerFieldNames.RefreshToken);
- }
+ public async Task<RefreshToken> GetCustomerRefreshToken(Customer customer)
+ {
+ return await _userFieldService.GetFieldsForEntity<RefreshToken>(customer,
+ SystemCustomerFieldNames.RefreshToken);
+ }
- public ClaimsPrincipal GetPrincipalFromToken(string token)
- {
- var tokenValidationParameters = new TokenValidationParameters {
- ValidateAudience = _apiConfig.ValidateAudience,
- ValidateIssuer = _apiConfig.ValidateIssuer,
- ValidateIssuerSigningKey = _apiConfig.ValidateIssuerSigningKey,
- IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_apiConfig.SecretKey)),
- ValidateLifetime = _apiConfig.ValidateLifetime
- };
+ public ClaimsPrincipal GetPrincipalFromToken(string token)
+ {
+ var tokenValidationParameters = new TokenValidationParameters {
+ ValidateAudience = _apiConfig.ValidateAudience,
+ ValidateIssuer = _apiConfig.ValidateIssuer,
+ ValidateIssuerSigningKey = _apiConfig.ValidateIssuerSigningKey,
+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_apiConfig.SecretKey)),
+ ValidateLifetime = _apiConfig.ValidateLifetime
+ };
- var tokenHandler = new JwtSecurityTokenHandler();
- var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken);
- if (securityToken is not JwtSecurityToken jwtSecurityToken || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
- throw new SecurityTokenException("Invalid token");
+ var tokenHandler = new JwtSecurityTokenHandler();
+ var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken);
+ if (securityToken is not JwtSecurityToken jwtSecurityToken ||
+ !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256,
+ StringComparison.InvariantCultureIgnoreCase))
+ throw new SecurityTokenException("Invalid token");
- return principal;
- }
+ return principal;
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs
index 34863cc7c..e561a35d7 100644
--- a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs
@@ -1,89 +1,95 @@
using Google.Authenticator;
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Utilities.Authentication;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Localization;
using Grand.Infrastructure;
-using Grand.Business.Core.Utilities.Authentication;
-namespace Grand.Business.Authentication.Services
+namespace Grand.Business.Authentication.Services;
+
+public class TwoFactorAuthenticationService : ITwoFactorAuthenticationService
{
- public class TwoFactorAuthenticationService : ITwoFactorAuthenticationService
- {
- private readonly IWorkContext _workContext;
- private readonly IUserFieldService _userFieldService;
- private readonly IEnumerable<ISMSVerificationService> _smsVerificationService;
- private readonly TwoFactorAuthenticator _twoFactorAuthentication;
+ private readonly IEnumerable<ISMSVerificationService> _smsVerificationService;
+ private readonly TwoFactorAuthenticator _twoFactorAuthentication;
+ private readonly IUserFieldService _userFieldService;
+ private readonly IWorkContext _workContext;
- public TwoFactorAuthenticationService(
- IWorkContext workContext,
- IUserFieldService userFieldService,
- IEnumerable<ISMSVerificationService> smsVerificationService)
- {
- _workContext = workContext;
- _userFieldService = userFieldService;
- _smsVerificationService = smsVerificationService;
- _twoFactorAuthentication = new TwoFactorAuthenticator();
- }
+ public TwoFactorAuthenticationService(
+ IWorkContext workContext,
+ IUserFieldService userFieldService,
+ IEnumerable<ISMSVerificationService> smsVerificationService)
+ {
+ _workContext = workContext;
+ _userFieldService = userFieldService;
+ _smsVerificationService = smsVerificationService;
+ _twoFactorAuthentication = new TwoFactorAuthenticator();
+ }
- public virtual async Task<bool> AuthenticateTwoFactor(string secretKey, string token, Customer customer, TwoFactorAuthenticationType twoFactorAuthenticationType)
+ public virtual async Task<bool> AuthenticateTwoFactor(string secretKey, string token, Customer customer,
+ TwoFactorAuthenticationType twoFactorAuthenticationType)
+ {
+ switch (twoFactorAuthenticationType)
{
- switch (twoFactorAuthenticationType)
- {
- case TwoFactorAuthenticationType.AppVerification:
- return _twoFactorAuthentication.ValidateTwoFactorPIN(secretKey, token.Trim());
-
- case TwoFactorAuthenticationType.EmailVerification:
- var customerToken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.TwoFactorValidCode);
- if (customerToken != token?.Trim())
- return false;
- var validUntil = customer.GetUserFieldFromEntity<DateTime>(SystemCustomerFieldNames.TwoFactorCodeValidUntil);
- return validUntil >= DateTime.UtcNow;
+ case TwoFactorAuthenticationType.AppVerification:
+ return _twoFactorAuthentication.ValidateTwoFactorPIN(secretKey, token.Trim());
- case TwoFactorAuthenticationType.SMSVerification:
- if (!_smsVerificationService.Any())
- throw new Exception("ISMSVerificationService not registered in DI container");
- var smsVerificationService = _smsVerificationService.FirstOrDefault();
- return await smsVerificationService!.Authenticate(secretKey, token.Trim(), customer);
- default:
+ case TwoFactorAuthenticationType.EmailVerification:
+ var customerToken =
+ customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.TwoFactorValidCode);
+ if (customerToken != token?.Trim())
return false;
- }
+ var validUntil =
+ customer.GetUserFieldFromEntity<DateTime>(SystemCustomerFieldNames.TwoFactorCodeValidUntil);
+ return validUntil >= DateTime.UtcNow;
+
+ case TwoFactorAuthenticationType.SMSVerification:
+ if (!_smsVerificationService.Any())
+ throw new Exception("ISMSVerificationService not registered in DI container");
+ var smsVerificationService = _smsVerificationService.FirstOrDefault();
+ return await smsVerificationService!.Authenticate(secretKey, token.Trim(), customer);
+ default:
+ return false;
}
+ }
- public virtual async Task<TwoFactorCodeSetup> GenerateCodeSetup(string secretKey, Customer customer, Language language, TwoFactorAuthenticationType twoFactorAuthenticationType)
- {
- var model = new TwoFactorCodeSetup();
+ public virtual async Task<TwoFactorCodeSetup> GenerateCodeSetup(string secretKey, Customer customer,
+ Language language, TwoFactorAuthenticationType twoFactorAuthenticationType)
+ {
+ var model = new TwoFactorCodeSetup();
- switch (twoFactorAuthenticationType)
- {
- case TwoFactorAuthenticationType.AppVerification:
- var setupInfo = _twoFactorAuthentication.GenerateSetupCode(_workContext.CurrentStore.CompanyName, customer.Email, secretKey, false);
- model.CustomValues.Add("QrCodeImageUrl", setupInfo.QrCodeSetupImageUrl);
- model.CustomValues.Add("ManualEntryQrCode", setupInfo.ManualEntryKey);
- break;
+ switch (twoFactorAuthenticationType)
+ {
+ case TwoFactorAuthenticationType.AppVerification:
+ var setupInfo = _twoFactorAuthentication.GenerateSetupCode(_workContext.CurrentStore.CompanyName,
+ customer.Email, secretKey, false);
+ model.CustomValues.Add("QrCodeImageUrl", setupInfo.QrCodeSetupImageUrl);
+ model.CustomValues.Add("ManualEntryQrCode", setupInfo.ManualEntryKey);
+ break;
- case TwoFactorAuthenticationType.EmailVerification:
- var token = PrepareRandomCode();
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.TwoFactorValidCode, token);
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.TwoFactorCodeValidUntil, DateTime.UtcNow.AddMinutes(30));
- model.CustomValues.Add("Token", token);
- break;
+ case TwoFactorAuthenticationType.EmailVerification:
+ var token = PrepareRandomCode();
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.TwoFactorValidCode, token);
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.TwoFactorCodeValidUntil,
+ DateTime.UtcNow.AddMinutes(30));
+ model.CustomValues.Add("Token", token);
+ break;
- case TwoFactorAuthenticationType.SMSVerification:
- if (!_smsVerificationService.Any())
- throw new Exception("ISMSVerificationService not registered in DI container");
- var smsVerificationService = _smsVerificationService.FirstOrDefault();
- model = await smsVerificationService!.GenerateCode(secretKey, customer, language);
- break;
- }
- return model;
+ case TwoFactorAuthenticationType.SMSVerification:
+ if (!_smsVerificationService.Any())
+ throw new Exception("ISMSVerificationService not registered in DI container");
+ var smsVerificationService = _smsVerificationService.FirstOrDefault();
+ model = await smsVerificationService!.GenerateCode(secretKey, customer, language);
+ break;
}
- private string PrepareRandomCode()
- {
- Random generator = new Random();
- return generator.Next(0, 999999).ToString("D6");
- }
+ return model;
+ }
+
+ private string PrepareRandomCode()
+ {
+ var generator = new Random();
+ return generator.Next(0, 999999).ToString("D6");
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs b/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs
index 172f6e9c0..3cf110d00 100644
--- a/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs
+++ b/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs
@@ -1,32 +1,30 @@
-using Grand.Business.Core.Interfaces.Authentication;
-using Grand.Business.Authentication.Services;
+using Grand.Business.Authentication.Services;
+using Grand.Business.Core.Interfaces.Authentication;
using Grand.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
-namespace Grand.Business.Authentication.Startup
+namespace Grand.Business.Authentication.Startup;
+
+public class StartupApplication : IStartupApplication
{
- public class StartupApplication : IStartupApplication
+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
+ services.AddScoped<IGrandAuthenticationService, CookieAuthenticationService>();
+ services.AddScoped<IApiAuthenticationService, ApiAuthenticationService>();
+ services.AddScoped<IJwtBearerAuthenticationService, JwtBearerAuthenticationService>();
+ services.AddScoped<ITwoFactorAuthenticationService, TwoFactorAuthenticationService>();
+ services.AddScoped<IExternalAuthenticationService, ExternalAuthenticationService>();
+ services.AddScoped<IJwtBearerCustomerAuthenticationService, JwtBearerCustomerAuthenticationService>();
+ services.AddScoped<IRefreshTokenService, RefreshTokenService>();
+ }
- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
- {
- services.AddScoped<IGrandAuthenticationService, CookieAuthenticationService>();
- services.AddScoped<IApiAuthenticationService, ApiAuthenticationService>();
- services.AddScoped<IJwtBearerAuthenticationService, JwtBearerAuthenticationService>();
- services.AddScoped<ITwoFactorAuthenticationService, TwoFactorAuthenticationService>();
- services.AddScoped<IExternalAuthenticationService, ExternalAuthenticationService>();
- services.AddScoped<IJwtBearerCustomerAuthenticationService, JwtBearerCustomerAuthenticationService>();
- services.AddScoped<IRefreshTokenService, RefreshTokenService>();
- }
- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
- {
-
- }
- public int Priority => 100;
- public bool BeforeConfigure => false;
-
+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
+ {
}
-}
+
+ public int Priority => 100;
+ public bool BeforeConfigure => false;
+}
\ No newline at end of file