using System; using System.Security.Principal; using BO.AppServer.Data.Entity; using BO.AppServer.Metadata.Enums; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Quadarax.Foundation.Core.Business; namespace BO.AppServer.Business.Services.Base { public abstract class UserContextService : AbstractService { protected UserManager _manUser; protected UserRepo _repoUser; protected Configuration.Configuration _configuration; protected UserContextService(IOptions config, UserRepo repoUser, UserManager userManager, IPrincipal currentPrincipal, ILoggerFactory logger) : base(MaySetDefaultPrincipal(currentPrincipal, config), logger) { _manUser = userManager ?? throw new ArgumentNullException(nameof(userManager)); _repoUser = repoUser ?? throw new ArgumentNullException(nameof(repoUser)); _configuration = config?.Value ?? throw new ArgumentNullException(nameof(config)); } protected User GetCurrentUser() { var userIdt = _manUser.FindByNameAsync(CurrentPrincipal.Identity.Name).Result; return _repoUser.GetByIfReference(userIdt.Id); } protected long GetCurrentUserId() { var user = GetCurrentUser(); return user.Id; } private static IPrincipal MaySetDefaultPrincipal(IPrincipal principal, IOptions config) { if (principal?.Identity == null || principal.Identity.Name == "genericIdentity") principal = new GenericPrincipal(new GenericIdentity(config.Value.System.AccountSystem.Name),new[] { RoleEnum.System.ToString() }); return principal; } } }