migrate remaining methods to UserManager
This commit is contained in:
@ -9,7 +9,6 @@ using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using Oqtane.Shared;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using Oqtane.Enums;
|
||||
using Oqtane.Infrastructure;
|
||||
@ -23,33 +22,27 @@ namespace Oqtane.Controllers
|
||||
public class UserController : Controller
|
||||
{
|
||||
private readonly IUserRepository _users;
|
||||
private readonly IUserRoleRepository _userRoles;
|
||||
private readonly UserManager<IdentityUser> _identityUserManager;
|
||||
private readonly SignInManager<IdentityUser> _identitySignInManager;
|
||||
private readonly ITenantManager _tenantManager;
|
||||
private readonly INotificationRepository _notifications;
|
||||
private readonly IFolderRepository _folders;
|
||||
private readonly IUserManager _userManager;
|
||||
private readonly ISiteRepository _sites;
|
||||
private readonly IUserPermissions _userPermissions;
|
||||
private readonly IJwtManager _jwtManager;
|
||||
private readonly ISyncManager _syncManager;
|
||||
private readonly ILogManager _logger;
|
||||
|
||||
public UserController(IUserRepository users, IUserRoleRepository userRoles, UserManager<IdentityUser> identityUserManager, SignInManager<IdentityUser> identitySignInManager, ITenantManager tenantManager, INotificationRepository notifications, IFolderRepository folders, IUserManager userManager, ISiteRepository sites, IUserPermissions userPermissions, IJwtManager jwtManager, ISyncManager syncManager, ILogManager logger)
|
||||
public UserController(IUserRepository users, UserManager<IdentityUser> identityUserManager, SignInManager<IdentityUser> identitySignInManager, ITenantManager tenantManager, INotificationRepository notifications, IUserManager userManager, ISiteRepository sites, IUserPermissions userPermissions, IJwtManager jwtManager, ILogManager logger)
|
||||
{
|
||||
_users = users;
|
||||
_userRoles = userRoles;
|
||||
_identityUserManager = identityUserManager;
|
||||
_identitySignInManager = identitySignInManager;
|
||||
_tenantManager = tenantManager;
|
||||
_notifications = notifications;
|
||||
_folders = folders;
|
||||
_userManager = userManager;
|
||||
_sites = sites;
|
||||
_userPermissions = userPermissions;
|
||||
_jwtManager = jwtManager;
|
||||
_syncManager = syncManager;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@ -58,16 +51,10 @@ namespace Oqtane.Controllers
|
||||
[Authorize]
|
||||
public User Get(int id, string siteid)
|
||||
{
|
||||
int SiteId;
|
||||
if (int.TryParse(siteid, out SiteId) && SiteId == _tenantManager.GetAlias().SiteId)
|
||||
if (int.TryParse(siteid, out int SiteId) && SiteId == _tenantManager.GetAlias().SiteId)
|
||||
{
|
||||
User user = _users.GetUser(id);
|
||||
if (user != null)
|
||||
{
|
||||
user.SiteId = int.Parse(siteid);
|
||||
user.Roles = GetUserRoles(user.UserId, user.SiteId);
|
||||
}
|
||||
else
|
||||
User user = _userManager.GetUser(id, SiteId);
|
||||
if (user == null)
|
||||
{
|
||||
HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
|
||||
}
|
||||
@ -85,16 +72,10 @@ namespace Oqtane.Controllers
|
||||
[HttpGet("name/{name}")]
|
||||
public User Get(string name, string siteid)
|
||||
{
|
||||
int SiteId;
|
||||
if (int.TryParse(siteid, out SiteId) && SiteId == _tenantManager.GetAlias().SiteId)
|
||||
if (int.TryParse(siteid, out int SiteId) && SiteId == _tenantManager.GetAlias().SiteId)
|
||||
{
|
||||
User user = _users.GetUser(name);
|
||||
if (user != null)
|
||||
{
|
||||
user.SiteId = int.Parse(siteid);
|
||||
user.Roles = GetUserRoles(user.UserId, user.SiteId);
|
||||
}
|
||||
else
|
||||
User user = _userManager.GetUser(name, SiteId);
|
||||
if (user == null)
|
||||
{
|
||||
HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
|
||||
}
|
||||
@ -183,37 +164,7 @@ namespace Oqtane.Controllers
|
||||
if (ModelState.IsValid && user.SiteId == _tenantManager.GetAlias().SiteId && _users.GetUser(user.UserId, false) != null
|
||||
&& (_userPermissions.IsAuthorized(User, user.SiteId, EntityNames.User, -1, PermissionNames.Write, RoleNames.Admin) || User.Identity.Name == user.Username))
|
||||
{
|
||||
IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);
|
||||
if (identityuser != null)
|
||||
{
|
||||
identityuser.Email = user.Email;
|
||||
var valid = true;
|
||||
if (user.Password != "")
|
||||
{
|
||||
var validator = new PasswordValidator<IdentityUser>();
|
||||
var result = await validator.ValidateAsync(_identityUserManager, null, user.Password);
|
||||
valid = result.Succeeded;
|
||||
if (valid)
|
||||
{
|
||||
identityuser.PasswordHash = _identityUserManager.PasswordHasher.HashPassword(identityuser, user.Password);
|
||||
}
|
||||
}
|
||||
if (valid)
|
||||
{
|
||||
await _identityUserManager.UpdateAsync(identityuser);
|
||||
|
||||
user = _users.UpdateUser(user);
|
||||
_syncManager.AddSyncEvent(_tenantManager.GetAlias().TenantId, EntityNames.User, user.UserId, SyncEventActions.Update);
|
||||
_syncManager.AddSyncEvent(_tenantManager.GetAlias().TenantId, EntityNames.User, user.UserId, SyncEventActions.Refresh);
|
||||
user.Password = ""; // remove sensitive information
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Update, "User Updated {User}", user);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Log(user.SiteId, LogLevel.Error, this, LogFunction.Update, "Unable To Update User {Username}. Password Does Not Meet Complexity Requirements.", user.Username);
|
||||
user = null;
|
||||
}
|
||||
}
|
||||
user = await _userManager.UpdateUser(user);
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -230,51 +181,10 @@ namespace Oqtane.Controllers
|
||||
[Authorize(Policy = $"{EntityNames.User}:{PermissionNames.Write}:{RoleNames.Admin}")]
|
||||
public async Task Delete(int id, string siteid)
|
||||
{
|
||||
int SiteId;
|
||||
User user = _users.GetUser(id);
|
||||
if (user != null && int.TryParse(siteid, out SiteId) && SiteId == _tenantManager.GetAlias().SiteId)
|
||||
User user = _users.GetUser(id, false);
|
||||
if (user != null && int.TryParse(siteid, out int SiteId) && SiteId == _tenantManager.GetAlias().SiteId)
|
||||
{
|
||||
// remove user roles for site
|
||||
foreach (UserRole userrole in _userRoles.GetUserRoles(user.UserId, SiteId).ToList())
|
||||
{
|
||||
_userRoles.DeleteUserRole(userrole.UserRoleId);
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Delete, "User Role Deleted {UserRole}", userrole);
|
||||
}
|
||||
|
||||
// remove user folder for site
|
||||
var folder = _folders.GetFolder(SiteId, $"Users{user.UserId}/");
|
||||
if (folder != null)
|
||||
{
|
||||
if (Directory.Exists(_folders.GetFolderPath(folder)))
|
||||
{
|
||||
Directory.Delete(_folders.GetFolderPath(folder), true);
|
||||
}
|
||||
_folders.DeleteFolder(folder.FolderId);
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Delete, "User Folder Deleted {Folder}", folder);
|
||||
}
|
||||
|
||||
// delete user if they are not a member of any other sites
|
||||
if (!_userRoles.GetUserRoles(user.UserId, -1).Any())
|
||||
{
|
||||
// get identity user
|
||||
IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);
|
||||
if (identityuser != null)
|
||||
{
|
||||
// delete identity user
|
||||
var result = await _identityUserManager.DeleteAsync(identityuser);
|
||||
if (result != null)
|
||||
{
|
||||
// delete user
|
||||
_users.DeleteUser(user.UserId);
|
||||
_syncManager.AddSyncEvent(_tenantManager.GetAlias().TenantId, EntityNames.User, user.UserId, SyncEventActions.Delete);
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Delete, "User Deleted {UserId}", user.UserId, result.ToString());
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Log(LogLevel.Error, this, LogFunction.Delete, "Error Deleting User {UserId}", user.UserId);
|
||||
}
|
||||
}
|
||||
}
|
||||
await _userManager.DeleteUser(id, SiteId);
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -287,83 +197,15 @@ namespace Oqtane.Controllers
|
||||
[HttpPost("login")]
|
||||
public async Task<User> Login([FromBody] User user, bool setCookie, bool isPersistent)
|
||||
{
|
||||
User loginUser = new User { SiteId = user.SiteId, Username = user.Username, IsAuthenticated = false };
|
||||
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);
|
||||
if (identityuser != null)
|
||||
{
|
||||
var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, user.Password, true);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
var LastIPAddress = user.LastIPAddress ?? "";
|
||||
|
||||
user = _users.GetUser(user.Username);
|
||||
if (user.TwoFactorRequired)
|
||||
{
|
||||
var token = await _identityUserManager.GenerateTwoFactorTokenAsync(identityuser, "Email");
|
||||
user.TwoFactorCode = token;
|
||||
user.TwoFactorExpiry = DateTime.UtcNow.AddMinutes(10);
|
||||
_users.UpdateUser(user);
|
||||
|
||||
string body = "Dear " + user.DisplayName + ",\n\nYou requested a secure verification code to log in to your account. Please enter the secure verification code on the site:\n\n" + token +
|
||||
"\n\nPlease note that the code is only valid for 10 minutes so if you are unable to take action within that time period, you should initiate a new login on the site." +
|
||||
"\n\nThank You!";
|
||||
var notification = new Notification(loginUser.SiteId, user, "User Verification Code", body);
|
||||
_notifications.AddNotification(notification);
|
||||
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Security, "User Verification Notification Sent For {Username}", user.Username);
|
||||
loginUser.TwoFactorRequired = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
loginUser = _users.GetUser(identityuser.UserName);
|
||||
if (loginUser != null)
|
||||
{
|
||||
if (identityuser.EmailConfirmed)
|
||||
{
|
||||
loginUser.IsAuthenticated = true;
|
||||
loginUser.LastLoginOn = DateTime.UtcNow;
|
||||
loginUser.LastIPAddress = LastIPAddress;
|
||||
_users.UpdateUser(loginUser);
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Security, "User Login Successful {Username}", user.Username);
|
||||
|
||||
if (setCookie)
|
||||
{
|
||||
await _identitySignInManager.SignInAsync(identityuser, isPersistent);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Security, "User Not Verified {Username}", user.Username);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (result.IsLockedOut)
|
||||
{
|
||||
user = _users.GetUser(user.Username);
|
||||
string token = await _identityUserManager.GeneratePasswordResetTokenAsync(identityuser);
|
||||
string url = HttpContext.Request.Scheme + "://" + _tenantManager.GetAlias().Name + "/reset?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token);
|
||||
string body = "Dear " + user.DisplayName + ",\n\nYou attempted multiple times unsuccessfully to log in to your account and it is now locked out. Please wait a few minutes and then try again... or use the link below to reset your password:\n\n" + url +
|
||||
"\n\nPlease note that the link is only valid for 24 hours so if you are unable to take action within that time period, you should initiate another password reset on the site." +
|
||||
"\n\nThank You!";
|
||||
var notification = new Notification(loginUser.SiteId, user, "User Lockout", body);
|
||||
_notifications.AddNotification(notification);
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Security, "User Lockout Notification Sent For {Username}", user.Username);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Security, "User Login Failed {Username}", user.Username);
|
||||
}
|
||||
}
|
||||
}
|
||||
user = await _userManager.LoginUser(user, setCookie, isPersistent);
|
||||
}
|
||||
|
||||
return loginUser;
|
||||
else
|
||||
{
|
||||
user = new User { SiteId = user.SiteId, Username = user.Username, IsAuthenticated = false };
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
// POST api/<controller>/logout
|
||||
@ -381,25 +223,7 @@ namespace Oqtane.Controllers
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);
|
||||
if (identityuser != null && !string.IsNullOrEmpty(token))
|
||||
{
|
||||
var result = await _identityUserManager.ConfirmEmailAsync(identityuser, token);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Security, "Email Verified For {Username}", user.Username);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Log(LogLevel.Error, this, LogFunction.Security, "Email Verification Failed For {Username} - Error {Error}", user.Username, string.Join(" ", result.Errors.ToList().Select(e => e.Description)));
|
||||
user = null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Log(LogLevel.Error, this, LogFunction.Security, "Email Verification Failed For {Username}And Token {Token}", user.Username, token);
|
||||
user = null;
|
||||
}
|
||||
user = await _userManager.VerifyEmail(user, token);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
@ -410,25 +234,7 @@ namespace Oqtane.Controllers
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);
|
||||
if (identityuser != null)
|
||||
{
|
||||
user = _users.GetUser(user.Username);
|
||||
string token = await _identityUserManager.GeneratePasswordResetTokenAsync(identityuser);
|
||||
string url = HttpContext.Request.Scheme + "://" + _tenantManager.GetAlias().Name + "/reset?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token);
|
||||
string body = "Dear " + user.DisplayName + ",\n\nYou recently requested to reset your password. Please use the link below to complete the process:\n\n" + url +
|
||||
"\n\nPlease note that the link is only valid for 24 hours so if you are unable to take action within that time period, you should initiate another password reset on the site." +
|
||||
"\n\nIf you did not request to reset your password you can safely ignore this message." +
|
||||
"\n\nThank You!";
|
||||
|
||||
var notification = new Notification(_tenantManager.GetAlias().SiteId, user, "User Password Reset", body);
|
||||
_notifications.AddNotification(notification);
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Security, "Password Reset Notification Sent For {Username}", user.Username);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Log(LogLevel.Error, this, LogFunction.Security, "Password Reset Notification Failed For {Username}", user.Username);
|
||||
}
|
||||
await _userManager.ForgotPassword(user);
|
||||
}
|
||||
}
|
||||
|
||||
@ -438,26 +244,7 @@ namespace Oqtane.Controllers
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);
|
||||
if (identityuser != null && !string.IsNullOrEmpty(token))
|
||||
{
|
||||
var result = await _identityUserManager.ResetPasswordAsync(identityuser, token, user.Password);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Security, "Password Reset For {Username}", user.Username);
|
||||
user.Password = "";
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Security, "Password Reset Failed For {Username} - Error {Error}", user.Username, string.Join(" ", result.Errors.ToList().Select(e => e.Description)));
|
||||
user = null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Log(LogLevel.Error, this, LogFunction.Security, "Password Reset Failed For {Username} And Token {Token}", user.Username, token);
|
||||
user = null;
|
||||
}
|
||||
user = await _userManager.ResetPassword(user, token);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
@ -466,21 +253,16 @@ namespace Oqtane.Controllers
|
||||
[HttpPost("twofactor")]
|
||||
public User TwoFactor([FromBody] User user, string token)
|
||||
{
|
||||
User loginUser = new User { SiteId = user.SiteId, Username = user.Username, IsAuthenticated = false };
|
||||
|
||||
if (ModelState.IsValid && !string.IsNullOrEmpty(token))
|
||||
{
|
||||
user = _users.GetUser(user.Username);
|
||||
if (user != null)
|
||||
{
|
||||
if (user.TwoFactorRequired && user.TwoFactorCode == token && DateTime.UtcNow < user.TwoFactorExpiry)
|
||||
{
|
||||
loginUser.IsAuthenticated = true;
|
||||
}
|
||||
}
|
||||
user = _userManager.VerifyTwoFactor(user, token);
|
||||
}
|
||||
else
|
||||
{
|
||||
user.IsAuthenticated = false;
|
||||
}
|
||||
|
||||
return loginUser;
|
||||
return user;
|
||||
}
|
||||
|
||||
// POST api/<controller>/link
|
||||
@ -489,23 +271,7 @@ namespace Oqtane.Controllers
|
||||
{
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);
|
||||
if (identityuser != null && !string.IsNullOrEmpty(token))
|
||||
{
|
||||
var result = await _identityUserManager.ConfirmEmailAsync(identityuser, token);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
// make LoginProvider multi-tenant aware
|
||||
type += ":" + user.SiteId.ToString();
|
||||
await _identityUserManager.AddLoginAsync(identityuser, new UserLoginInfo(type, key, name));
|
||||
_logger.Log(LogLevel.Information, this, LogFunction.Security, "External Login Linkage Successful For {Username} And Provider {Provider}", user.Username, type);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Log(LogLevel.Error, this, LogFunction.Security, "External Login Linkage Failed For {Username} - Error {Error}", user.Username, string.Join(" ", result.Errors.ToList().Select(e => e.Description)));
|
||||
user = null;
|
||||
}
|
||||
}
|
||||
user = await _userManager.LinkExternalAccount(user, token, type, key, name);
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -519,9 +285,7 @@ namespace Oqtane.Controllers
|
||||
[HttpGet("validate/{password}")]
|
||||
public async Task<bool> Validate(string password)
|
||||
{
|
||||
var validator = new PasswordValidator<IdentityUser>();
|
||||
var result = await validator.ValidateAsync(_identityUserManager, null, password);
|
||||
return result.Succeeded;
|
||||
return await _userManager.ValidatePassword(password);
|
||||
}
|
||||
|
||||
// GET api/<controller>/token
|
||||
@ -577,25 +341,5 @@ namespace Oqtane.Controllers
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
private string GetUserRoles(int userId, int siteId)
|
||||
{
|
||||
string roles = "";
|
||||
List<UserRole> userroles = _userRoles.GetUserRoles(userId, siteId).ToList();
|
||||
foreach (UserRole userrole in userroles)
|
||||
{
|
||||
roles += userrole.Role.Name + ";";
|
||||
if (userrole.Role.Name == RoleNames.Host && !userroles.Any(item => item.Role.Name == RoleNames.Admin))
|
||||
{
|
||||
roles += RoleNames.Admin + ";";
|
||||
}
|
||||
if (userrole.Role.Name == RoleNames.Host && !userroles.Any(item => item.Role.Name == RoleNames.Registered))
|
||||
{
|
||||
roles += RoleNames.Registered + ";";
|
||||
}
|
||||
}
|
||||
if (roles != "") roles = ";" + roles;
|
||||
return roles;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user