UserContextService.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Security.Principal;
  3. using BO.AppServer.Data.Entity;
  4. using BO.AppServer.Metadata.Enums;
  5. using Microsoft.AspNetCore.Identity;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. using Quadarax.Foundation.Core.Business;
  9. namespace BO.AppServer.Business.Services.Base
  10. {
  11. public abstract class UserContextService : AbstractService
  12. {
  13. protected UserManager<IdentityUser> _manUser;
  14. protected UserRepo _repoUser;
  15. protected Configuration.Configuration _configuration;
  16. protected UserContextService(IOptions<Configuration.Configuration> config, UserRepo repoUser, UserManager<IdentityUser> userManager, IPrincipal currentPrincipal, ILoggerFactory logger) : base(MaySetDefaultPrincipal(currentPrincipal, config), logger)
  17. {
  18. _manUser = userManager ?? throw new ArgumentNullException(nameof(userManager));
  19. _repoUser = repoUser ?? throw new ArgumentNullException(nameof(repoUser));
  20. _configuration = config?.Value ?? throw new ArgumentNullException(nameof(config));
  21. }
  22. protected User GetCurrentUser()
  23. {
  24. var userIdt = _manUser.FindByNameAsync(CurrentPrincipal.Identity.Name).Result;
  25. return _repoUser.GetByIfReference(userIdt.Id);
  26. }
  27. protected long GetCurrentUserId()
  28. {
  29. var user = GetCurrentUser();
  30. return user.Id;
  31. }
  32. private static IPrincipal MaySetDefaultPrincipal(IPrincipal principal, IOptions<Configuration.Configuration> config)
  33. {
  34. if (principal?.Identity == null || principal.Identity.Name == "genericIdentity")
  35. principal = new GenericPrincipal(new GenericIdentity(config.Value.System.AccountSystem.Name),new[] { RoleEnum.System.ToString() });
  36. return principal;
  37. }
  38. }
  39. }