UserContextService.cs 2.2 KB

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