Created
July 27, 2022 13:28
-
-
Save rickbutterfield/6e5ffbb3286dd4fc86ddf14c1cae6b1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.DependencyInjection; | |
using System; | |
using System.Linq; | |
using Umbraco.Cms.Core; | |
using Umbraco.Cms.Core.PropertyEditors; | |
using Umbraco.Cms.Core.Services; | |
using Umbraco.Extensions; | |
namespace Our.Umbraco.PersonalisationGroups.Core.Providers.MemberProfileField | |
{ | |
public class UmbracoMemberProfileFieldProvider : IMemberProfileFieldProvider | |
{ | |
private readonly IHttpContextAccessor _httpContextAccessor; | |
private readonly IMemberService _memberService; | |
private readonly IDataTypeService _dataTypeService; | |
private readonly IServiceScopeFactory _scopeFactory; | |
public UmbracoMemberProfileFieldProvider(IHttpContextAccessor httpContextAccessor, IMemberService memberService, IDataTypeService dataTypeService, IServiceScopeFactory scopeFactory) | |
{ | |
_httpContextAccessor = httpContextAccessor; | |
_memberService = memberService; | |
_dataTypeService = dataTypeService; | |
_scopeFactory = scopeFactory; | |
} | |
public string GetMemberProfileFieldValue(string alias) | |
{ | |
return _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated | |
? GetAuthenticatedMemberProfileFieldValue(alias) | |
: string.Empty; | |
} | |
private string GetAuthenticatedMemberProfileFieldValue(string alias) | |
{ | |
string memberId = _httpContextAccessor.HttpContext?.User.Identity.GetUserId(); | |
int.TryParse(memberId, out var memberIdAsInt); | |
if (memberIdAsInt != 0) | |
{ | |
var member = _memberService.GetById(memberIdAsInt); | |
var profileField = member.Properties.Where(x => x.Alias == alias).FirstOrDefault(); | |
if (profileField != null) | |
{ | |
if (profileField.Values.Any()) | |
{ | |
var dataType = _dataTypeService.GetDataType(profileField.PropertyType.DataTypeId); | |
if (dataType.EditorAlias == Constants.PropertyEditors.Aliases.ContentPicker) | |
{ | |
var nodeId = profileField.GetValue().ToString(); | |
if (!string.IsNullOrEmpty(nodeId)) | |
{ | |
using var scope = _scopeFactory.CreateScope(); | |
var _contentQuery = scope.ServiceProvider.GetRequiredService<IPublishedContentQuery>(); | |
var node = _contentQuery.Content(nodeId); | |
return node.Name; | |
} | |
} | |
// It's likely text... | |
else return profileField.GetValue().ToString(); | |
} | |
} | |
} | |
return string.Empty; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment