UserContextService.cs 2.8 KB

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