Files
Umbraco-CMS/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs

258 lines
12 KiB
C#
Raw Normal View History

using System;
2018-03-27 16:18:51 +02:00
using System.Collections.Generic;
using System.Globalization;
2018-03-27 10:04:07 +02:00
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
2018-03-27 10:04:07 +02:00
using Newtonsoft.Json;
using Umbraco.Core;
2019-12-18 13:05:34 +01:00
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Mapping;
using Umbraco.Core.Media;
using Umbraco.Core.Models;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
using Umbraco.Core.Strings;
2020-05-18 13:00:32 +01:00
using Umbraco.Extensions;
using Umbraco.Web.BackOffice.Filters;
using Umbraco.Web.BackOffice.Security;
using Umbraco.Web.Common.ActionsResults;
using Umbraco.Web.Common.Attributes;
using Umbraco.Web.Common.Authorization;
using Umbraco.Web.Models;
using Umbraco.Web.Models.ContentEditing;
namespace Umbraco.Web.BackOffice.Controllers
{
/// <summary>
/// Controller to back the User.Resource service, used for fetching user data when already authenticated. user.service is currently used for handling authentication
/// </summary>
[PluginController(Constants.Web.Mvc.BackOfficeApiArea)]
public class CurrentUserController : UmbracoAuthorizedJsonController
{
2019-12-18 13:05:34 +01:00
private readonly IMediaFileSystem _mediaFileSystem;
private readonly ContentSettings _contentSettings;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IImageUrlGenerator _imageUrlGenerator;
private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor;
private readonly IUserService _userService;
private readonly UmbracoMapper _umbracoMapper;
private readonly IBackOfficeUserManager _backOfficeUserManager;
private readonly ILoggerFactory _loggerFactory;
private readonly ILocalizedTextService _localizedTextService;
private readonly AppCaches _appCaches;
private readonly IShortStringHelper _shortStringHelper;
2019-12-18 13:05:34 +01:00
public CurrentUserController(
IMediaFileSystem mediaFileSystem,
IOptions<ContentSettings> contentSettings,
IHostingEnvironment hostingEnvironment,
IImageUrlGenerator imageUrlGenerator,
IBackOfficeSecurityAccessor backofficeSecurityAccessor,
IUserService userService,
UmbracoMapper umbracoMapper,
IBackOfficeUserManager backOfficeUserManager,
ILoggerFactory loggerFactory,
ILocalizedTextService localizedTextService,
AppCaches appCaches,
IShortStringHelper shortStringHelper)
2019-12-18 13:05:34 +01:00
{
_mediaFileSystem = mediaFileSystem;
_contentSettings = contentSettings.Value;
_hostingEnvironment = hostingEnvironment;
_imageUrlGenerator = imageUrlGenerator;
_backofficeSecurityAccessor = backofficeSecurityAccessor;
_userService = userService;
_umbracoMapper = umbracoMapper;
_backOfficeUserManager = backOfficeUserManager;
_loggerFactory = loggerFactory;
_localizedTextService = localizedTextService;
_appCaches = appCaches;
_shortStringHelper = shortStringHelper;
2019-12-18 13:05:34 +01:00
}
/// <summary>
/// Returns permissions for all nodes passed in for the current user
/// </summary>
/// <param name="nodeIds"></param>
/// <returns></returns>
[HttpPost]
public Dictionary<int, string[]> GetPermissions(int[] nodeIds)
{
var permissions = _userService
.GetPermissions(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, nodeIds);
var permissionsDictionary = new Dictionary<int, string[]>();
foreach (var nodeId in nodeIds)
{
var aggregatePerms = permissions.GetAllPermissions(nodeId).ToArray();
permissionsDictionary.Add(nodeId, aggregatePerms);
}
return permissionsDictionary;
}
/// <summary>
/// Checks a nodes permission for the current user
/// </summary>
/// <param name="permissionToCheck"></param>
/// <param name="nodeId"></param>
/// <returns></returns>
[HttpGet]
public bool HasPermission(string permissionToCheck, int nodeId)
{
var p = _userService.GetPermissions(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, nodeId).GetAllPermissions();
if (p.Contains(permissionToCheck.ToString(CultureInfo.InvariantCulture)))
{
return true;
}
return false;
}
2018-03-27 10:04:07 +02:00
/// <summary>
/// Saves a tour status for the current user
/// </summary>
/// <param name="status"></param>
/// <returns></returns>
public IEnumerable<UserTourStatus> PostSetUserTour(UserTourStatus status)
{
2018-03-28 16:38:10 +02:00
if (status == null) throw new ArgumentNullException(nameof(status));
2018-03-27 10:04:07 +02:00
List<UserTourStatus> userTours;
if (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData.IsNullOrWhiteSpace())
2018-03-27 10:04:07 +02:00
{
2018-03-28 16:38:10 +02:00
userTours = new List<UserTourStatus> { status };
_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData = JsonConvert.SerializeObject(userTours);
_userService.Save(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser);
2018-03-27 10:04:07 +02:00
return userTours;
}
userTours = JsonConvert.DeserializeObject<IEnumerable<UserTourStatus>>(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData).ToList();
2018-03-27 10:04:07 +02:00
var found = userTours.FirstOrDefault(x => x.Alias == status.Alias);
if (found != null)
{
//remove it and we'll replace it next
userTours.Remove(found);
}
userTours.Add(status);
_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData = JsonConvert.SerializeObject(userTours);
_userService.Save(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser);
2018-03-27 10:04:07 +02:00
return userTours;
}
/// <summary>
/// Returns the user's tours
/// </summary>
/// <returns></returns>
public IEnumerable<UserTourStatus> GetUserTours()
{
if (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData.IsNullOrWhiteSpace())
2018-03-27 10:04:07 +02:00
return Enumerable.Empty<UserTourStatus>();
var userTours = JsonConvert.DeserializeObject<IEnumerable<UserTourStatus>>(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData);
2018-03-27 10:04:07 +02:00
return userTours;
}
2017-09-12 16:22:16 +02:00
/// <summary>
2017-09-12 16:22:16 +02:00
/// When a user is invited and they click on the invitation link, they will be partially logged in
/// where they can set their username/password
/// </summary>
2017-09-12 16:22:16 +02:00
/// <param name="newPassword"></param>
/// <returns></returns>
2017-09-12 16:22:16 +02:00
/// <remarks>
/// This only works when the user is logged in (partially)
/// </remarks>
[AllowAnonymous]
public async Task<ActionResult<UserDetail>> PostSetInvitedUserPassword([FromBody]string newPassword)
{
var user = await _backOfficeUserManager.FindByIdAsync(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0).ToString());
if (user == null) throw new InvalidOperationException("Could not find user");
var result = await _backOfficeUserManager.AddPasswordAsync(user, newPassword);
2017-09-12 16:22:16 +02:00
if (result.Succeeded == false)
{
//it wasn't successful, so add the change error to the model state, we've name the property alias _umb_password on the form
// so that is why it is being used here.
ModelState.AddModelError("value", result.Errors.ToErrorMessage());
2017-09-12 16:22:16 +02:00
return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary()));
2017-09-12 16:22:16 +02:00
}
//They've successfully set their password, we can now update their user account to be approved
_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsApproved = true;
//They've successfully set their password, and will now get fully logged into the back office, so the lastlogindate is set so the backoffice shows they have logged in
_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.LastLoginDate = DateTime.UtcNow;
_userService.Save(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser);
2017-09-12 16:22:16 +02:00
//now we can return their full object since they are now really logged into the back office
var userDisplay = _umbracoMapper.Map<UserDetail>(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser);
userDisplay.SecondsUntilTimeout = HttpContext.User.GetRemainingAuthSeconds();
2017-09-12 16:22:16 +02:00
return userDisplay;
}
[AppendUserModifiedHeader]
public IActionResult PostSetAvatar(IList<IFormFile> file)
2017-09-12 16:22:16 +02:00
{
//borrow the logic from the user controller
return UsersController.PostSetAvatarInternal(file, _userService, _appCaches.RuntimeCache, _mediaFileSystem, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0));
}
/// <summary>
/// Changes the users password
/// </summary>
/// <param name="data"></param>
/// <returns>
/// If the password is being reset it will return the newly reset password, otherwise will return an empty value
/// </returns>
public async Task<ActionResult<ModelWithNotifications<string>>> PostChangePassword(ChangingPasswordModel data)
{
2020-10-23 14:18:53 +11:00
// TODO: Why don't we inject this? Then we can just inject a logger
var passwordChanger = new PasswordChanger(_loggerFactory.CreateLogger<PasswordChanger>());
var passwordChangeResult = await passwordChanger.ChangePasswordWithIdentityAsync(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, data, _backOfficeUserManager);
if (passwordChangeResult.Success)
{
//even if we weren't resetting this, it is the correct value (null), otherwise if we were resetting then it will contain the new pword
var result = new ModelWithNotifications<string>(passwordChangeResult.Result.ResetPassword);
result.AddSuccessNotification(_localizedTextService.Localize("user/password"), _localizedTextService.Localize("user/passwordChanged"));
return result;
}
2017-09-19 15:51:47 +02:00
foreach (var memberName in passwordChangeResult.Result.ChangeError.MemberNames)
{
ModelState.AddModelError(memberName, passwordChangeResult.Result.ChangeError.ErrorMessage);
}
return new ValidationErrorResult(new SimpleValidationModel(ModelState.ToErrorDictionary()));
}
// TODO: Why is this necessary? This inherits from UmbracoAuthorizedApiController
[Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)]
2020-08-20 11:54:35 +02:00
[ValidateAngularAntiForgeryToken]
public async Task<Dictionary<string, string>> GetCurrentUserLinkedLogins()
{
var identityUser = await _backOfficeUserManager.FindByIdAsync(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0).ToString());
2020-10-23 14:18:53 +11:00
// deduplicate in case there are duplicates (there shouldn't be now since we have a unique constraint on the external logins
// but there didn't used to be)
var result = new Dictionary<string, string>();
foreach (var l in identityUser.Logins)
{
result[l.LoginProvider] = l.ProviderKey;
}
return result;
2020-08-20 11:54:35 +02:00
}
}
}