Files
Umbraco-CMS/src/Umbraco.Web.Common/Security/BackofficeSecurity.cs

77 lines
2.2 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Http;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
2020-10-23 14:18:53 +11:00
using Umbraco.Core.Security;
using Umbraco.Core.Services;
using Umbraco.Extensions;
namespace Umbraco.Web.Common.Security
{
// TODO: This is only for the back office, does it need to be in common?
2020-10-23 14:18:53 +11:00
public class BackOfficeSecurity : IBackOfficeSecurity
{
private readonly IUserService _userService;
private readonly IHttpContextAccessor _httpContextAccessor;
private object _currentUserLock = new object();
private IUser _currentUser;
2020-10-23 14:18:53 +11:00
public BackOfficeSecurity(
IUserService userService,
IHttpContextAccessor httpContextAccessor)
{
_userService = userService;
_httpContextAccessor = httpContextAccessor;
}
2020-06-02 14:46:58 +10:00
/// <inheritdoc />
public IUser CurrentUser
{
get
{
//only load it once per instance! (but make sure groups are loaded)
if (_currentUser == null)
{
lock (_currentUserLock)
{
//Check again
if (_currentUser == null)
{
var id = GetUserId();
_currentUser = id ? _userService.GetUserById(id.Result) : null;
}
}
}
return _currentUser;
}
}
2020-06-02 14:46:58 +10:00
/// <inheritdoc />
public Attempt<int> GetUserId()
{
var identity = _httpContextAccessor.HttpContext?.GetCurrentIdentity();
2020-06-02 14:46:58 +10:00
return identity == null ? Attempt.Fail<int>() : Attempt.Succeed(identity.Id);
}
2020-06-02 14:46:58 +10:00
/// <inheritdoc />
public bool IsAuthenticated()
{
var httpContext = _httpContextAccessor.HttpContext;
return httpContext?.User != null && httpContext.User.Identity.IsAuthenticated && httpContext.GetCurrentIdentity() != null;
}
2020-06-02 14:46:58 +10:00
/// <inheritdoc />
public bool UserHasSectionAccess(string section, IUser user)
{
2020-06-02 14:46:58 +10:00
return user.HasSectionAccess(section);
}
}
}