Gets most of the User and UserType legacy objects wrapping the new services, yay! Now just need to sort out all the caching stuff which I have tasks for.

This commit is contained in:
Shannon
2014-01-23 18:44:41 +11:00
parent 64d1a484bd
commit e2ac82abca
13 changed files with 291 additions and 352 deletions

View File

@@ -15,7 +15,10 @@ namespace Umbraco.Core.Models.Membership
int StartMediaId { get; set; }
string Language { get; set; }
IUserType UserType { get; }
/// <summary>
/// Gets/sets the user type for the user
/// </summary>
IUserType UserType { get; set; }
/// <summary>
/// The default permission set for the user

View File

@@ -5,6 +5,7 @@ using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Persistence.Mappers;
@@ -31,6 +32,7 @@ namespace Umbraco.Core.Models.Membership
_sectionCollection = new ObservableCollection<string>();
_addedSections = new List<string>();
_removedSections = new List<string>();
_language = GlobalSettings.DefaultUILanguage;
_sectionCollection.CollectionChanged += SectionCollectionChanged;
}
@@ -40,10 +42,10 @@ namespace Umbraco.Core.Models.Membership
_name = name;
_email = email;
_username = username;
_password = password;
_password = password;
}
private readonly IUserType _userType;
private IUserType _userType;
private bool _hasIdentity;
private int _id;
private string _name;
@@ -81,6 +83,7 @@ namespace Umbraco.Core.Models.Membership
private static readonly PropertyInfo DefaultPermissionsSelector = ExpressionHelper.GetPropertyInfo<User, IEnumerable<string>>(x => x.DefaultPermissions);
private static readonly PropertyInfo DefaultToLiveEditingSelector = ExpressionHelper.GetPropertyInfo<User, bool>(x => x.DefaultToLiveEditing);
private static readonly PropertyInfo HasIdentitySelector = ExpressionHelper.GetPropertyInfo<User, bool>(x => x.HasIdentity);
private static readonly PropertyInfo UserTypeSelector = ExpressionHelper.GetPropertyInfo<User, IUserType>(x => x.UserType);
#region Implementation of IEntity
@@ -419,6 +422,19 @@ namespace Umbraco.Core.Models.Membership
public IUserType UserType
{
get { return _userType; }
set
{
if (value.HasIdentity == false)
{
throw new InvalidOperationException("Cannot assign a User Type that has not been persisted");
}
SetPropertyValueAndDetectChanges(o =>
{
_userType = value;
return _userType;
}, _userType, UserTypeSelector);
}
}
#endregion

View File

@@ -124,6 +124,9 @@ namespace Umbraco.Core.Persistence
internal virtual IUserRepository CreateUserRepository(IDatabaseUnitOfWork uow)
{
//TODO: Should we cache users? we did in the legacy API, might be a good idea considering the amount we query for the current user but will
// need to check that, in v7 with the new forms auth way we shouldn't be querying for a user a lot of times but now that we're wrapping in v6
// we need to ensure that the constant user lookups are cached!
return new UserRepository(
uow,
NullCacheProvider.Current,

View File

@@ -51,7 +51,7 @@ namespace Umbraco.Core.Services
/// <returns></returns>
T CreateMemberWithIdentity(string username, string email, string password, string memberTypeAlias, bool raiseEvents = true);
T GetById(object id);
T GetById(int id);
/// <summary>
/// Get a member by email

View File

@@ -9,6 +9,13 @@ namespace Umbraco.Core.Services
/// </summary>
public interface IUserService : IMembershipUserService
{
/// <summary>
/// To permanently delete the user pass in true, otherwise they will just be disabled
/// </summary>
/// <param name="user"></param>
/// <param name="deletePermanently"></param>
void Delete(IUser user, bool deletePermanently);
/// <summary>
/// Gets an IProfile by User Id.
/// </summary>
@@ -35,13 +42,7 @@ namespace Umbraco.Core.Services
/// </summary>
/// <param name="sectionAlias"></param>
void DeleteSectionFromAllUsers(string sectionAlias);
/// <summary>
/// Returns a list of the sections that the user is allowed access to
/// </summary>
/// <returns></returns>
IEnumerable<string> GetUserSections(IUser user);
/// <summary>
/// Get permissions set for user and specified node ids
/// </summary>

View File

@@ -130,19 +130,14 @@ namespace Umbraco.Core.Services
return CreateMemberWithIdentity(username, email, password, userType);
}
public IUser GetById(object id)
public IUser GetById(int id)
{
if (id is int)
using (var repository = _repositoryFactory.CreateUserRepository(_uowProvider.GetUnitOfWork()))
{
using (var repository = _repositoryFactory.CreateUserRepository(_uowProvider.GetUnitOfWork()))
{
var user = repository.Get((int) id);
var user = repository.Get((int)id);
return user;
}
return user;
}
return null;
}
public IUser GetByEmail(string email)
@@ -165,19 +160,51 @@ namespace Umbraco.Core.Services
}
}
/// <summary>
/// This disables and renames the user, it does not delete them, use the overload to delete them
/// </summary>
/// <param name="membershipUser"></param>
public void Delete(IUser membershipUser)
{
if (DeletingUser.IsRaisedEventCancelled(new DeleteEventArgs<IUser>(membershipUser), this))
return;
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
//disable
membershipUser.IsApproved = false;
//can't rename if it's going to take up too many chars
if (membershipUser.Username.Length + 9 <= 125)
{
repository.Delete(membershipUser);
uow.Commit();
membershipUser.Username = DateTime.Now.ToString("yyyyMMdd") + "_" + membershipUser.Username;
}
Save(membershipUser);
DeletedUser.RaiseEvent(new DeleteEventArgs<IUser>(membershipUser, false), this);
//clear out the user logins!
var uow = _uowProvider.GetUnitOfWork();
uow.Database.Execute("delete from umbracoUserLogins where userID = @id", new {id = membershipUser.Id});
}
/// <summary>
/// To permanently delete the user pass in true, otherwise they will just be disabled
/// </summary>
/// <param name="user"></param>
/// <param name="deletePermanently"></param>
public void Delete(IUser user, bool deletePermanently)
{
if (deletePermanently == false)
{
Delete(user);
}
else
{
if (DeletingUser.IsRaisedEventCancelled(new DeleteEventArgs<IUser>(user), this))
return;
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateUserRepository(uow))
{
repository.Delete(user);
uow.Commit();
}
DeletedUser.RaiseEvent(new DeleteEventArgs<IUser>(user, false), this);
}
}
public void Save(IUser membershipUser, bool raiseEvents = true)
@@ -461,22 +488,6 @@ namespace Umbraco.Core.Services
}
}
/// <summary>
/// Returns the user's applications that they are allowed to access
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public IEnumerable<string> GetUserSections(IUser user)
{
//TODO: We need to cache this result
var uow = _uowProvider.GetUnitOfWork();
var sql = new Sql();
sql.Select("app").From<User2AppDto>()
.Where<User2AppDto>(dto => dto.UserId == (int)user.Id);
return uow.Database.Fetch<string>(sql);
}
/// <summary>
/// Returns permissions for a given user for any number of nodes
/// </summary>

View File

@@ -108,8 +108,8 @@ namespace Umbraco.Tests.Services
IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test");
ServiceContext.MemberService.Save(member);
Assert.IsNotNull(ServiceContext.MemberService.GetById((object)member.Id));
Assert.IsNull(ServiceContext.MemberService.GetById((object)9876));
Assert.IsNotNull(ServiceContext.MemberService.GetById(member.Id));
Assert.IsNull(ServiceContext.MemberService.GetById(9876));
}
[Test]

View File

@@ -6,6 +6,7 @@ using NUnit.Framework;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Services;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
using umbraco.BusinessLogic.Actions;

View File

@@ -78,6 +78,8 @@ namespace Umbraco.Tests.TestHelpers
using (DisposableTimer.TraceDuration<BaseDatabaseFactoryTest>("init"))
{
//TODO: Somehow make this faster - takes 5s +
DatabaseContext.Initialize(dbFactory.ProviderName, dbFactory.ConnectionString);
CreateSqlCeDatabase();
InitializeDatabase();

View File

@@ -5,7 +5,7 @@
<user>0</user>
<startNode>1080</startNode>
<fullTree>False</fullTree>
<documentTypeAlias>Base</documentTypeAlias>
<documentTypeAlias>umbBlog</documentTypeAlias>
<fields>
<categories>
</categories>

View File

@@ -344,7 +344,12 @@ namespace Umbraco.Web.Security.Providers
/// </returns>
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
var member = MemberService.GetById(providerUserKey);
if ((providerUserKey is int) == false)
{
return null;
}
var member = MemberService.GetById((int)providerUserKey);
if (member == null)
{
return null;

View File

@@ -6,6 +6,7 @@ using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.Querying;
using umbraco.DataLayer;
using System.Collections.Generic;
using System.Linq;
@@ -18,19 +19,22 @@ namespace umbraco.BusinessLogic
/// </summary>
public class User
{
private int _id;
private bool _isInitialized;
private string _name;
private string _loginname;
private int _startnodeid;
private int _startmediaid;
private string _email;
private string _language = "";
private UserType _usertype;
private bool _userNoConsole;
private bool _userDisabled;
private bool _defaultToLiveEditing;
private IUser _user;
private int? _lazyId;
//private int _id;
//private bool _isInitialized;
//private string _name;
//private string _loginname;
//private int _startnodeid;
//private int _startmediaid;
//private string _email;
//private string _language = "";
//private UserType _usertype;
//private bool _userNoConsole;
//private bool _userDisabled;
private bool? _defaultToLiveEditing;
private readonly Hashtable _notifications = new Hashtable();
private bool _notificationsInitialized = false;
@@ -42,19 +46,20 @@ namespace umbraco.BusinessLogic
internal User(IUser user)
{
_id = user.Id;
_userNoConsole = user.IsLockedOut;
_userDisabled = user.IsApproved;
_name = user.Name;
_loginname = user.Username;
_email = user.Email;
_language = user.Language;
_startnodeid = user.StartContentId;
_startmediaid = user.StartMediaId;
//this is cached, so should be 'ok'
_usertype = UserType.GetUserType(user.UserType.Id);
_user = user;
//_id = user.Id;
//_userNoConsole = user.IsLockedOut;
//_userDisabled = user.IsApproved;
//_name = user.Name;
//_loginname = user.Username;
//_email = user.Email;
//_language = user.Language;
//_startnodeid = user.StartContentId;
//_startmediaid = user.StartMediaId;
//_usertype = new UserType(_user.UserType);
_isInitialized = true;
//_isInitialized = true;
}
/// <summary>
@@ -63,7 +68,7 @@ namespace umbraco.BusinessLogic
/// <param name="ID">The ID.</param>
public User(int ID)
{
setupUser(ID);
SetupUser(ID);
}
/// <summary>
@@ -73,7 +78,7 @@ namespace umbraco.BusinessLogic
/// <param name="noSetup">if set to <c>true</c> [no setup].</param>
public User(int ID, bool noSetup)
{
_id = ID;
_lazyId = ID;
}
/// <summary>
@@ -83,7 +88,7 @@ namespace umbraco.BusinessLogic
/// <param name="Password">The password.</param>
public User(string Login, string Password)
{
setupUser(getUserId(Login, Password));
SetupUser(getUserId(Login, Password));
}
/// <summary>
@@ -92,33 +97,16 @@ namespace umbraco.BusinessLogic
/// <param name="Login">The login.</param>
public User(string Login)
{
setupUser(getUserId(Login));
SetupUser(getUserId(Login));
}
private void setupUser(int ID)
private void SetupUser(int ID)
{
_id = ID;
var dto = ApplicationContext.Current.DatabaseContext.Database.FirstOrDefault<UserDto>("WHERE id = @id", new { id = ID});
if (dto != null)
{
_userNoConsole = dto.NoConsole;
_userDisabled = dto.Disabled;
_name = dto.UserName;
_loginname = dto.Login;
_email = dto.Email;
_language = dto.UserLanguage;
_startnodeid = dto.ContentStartId;
if (dto.MediaStartId.HasValue)
_startmediaid = dto.MediaStartId.Value;
_usertype = UserType.GetUserType(dto.Type);
_defaultToLiveEditing = dto.DefaultToLiveEditing;
}
else
_user = ApplicationContext.Current.Services.UserService.GetById(ID);
if (_user == null)
{
throw new ArgumentException("No User exists with ID " + ID);
}
_isInitialized = true;
}
/// <summary>
@@ -126,6 +114,7 @@ namespace umbraco.BusinessLogic
/// </summary>
public void Save()
{
FlushFromCache();
OnSaving(EventArgs.Empty);
}
@@ -137,18 +126,13 @@ namespace umbraco.BusinessLogic
{
get
{
if (_isInitialized == false)
setupUser(_id);
return _name;
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return _user.Name;
}
set
{
_name = value;
ApplicationContext.Current.DatabaseContext.Database.Update<UserDto>(
"SET UserName = @userName WHERE id = @id", new { userName = value, id = Id});
FlushFromCache();
_user.Name = value;
}
}
@@ -160,18 +144,12 @@ namespace umbraco.BusinessLogic
{
get
{
if (_isInitialized == false)
setupUser(_id);
return _email;
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return _user.Email;
}
set
{
_email = value;
ApplicationContext.Current.DatabaseContext.Database.Update<UserDto>(
"SET UserEmail = @email WHERE id = @id", new { email = value, id = Id });
FlushFromCache();
_user.Email = value;
}
}
@@ -183,18 +161,12 @@ namespace umbraco.BusinessLogic
{
get
{
if (_isInitialized == false)
setupUser(_id);
return _language;
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return _user.Language;
}
set
{
_language = value;
ApplicationContext.Current.DatabaseContext.Database.Update<UserDto>(
"SET userLanguage = @language WHERE id = @id", new { language = value, id = Id });
FlushFromCache();
_user.Language = value;
}
}
@@ -210,10 +182,7 @@ namespace umbraco.BusinessLogic
}
set
{
ApplicationContext.Current.DatabaseContext.Database.Update<UserDto>(
"SET UserPassword = @pw WHERE id = @id", new { pw = value, id = Id });
FlushFromCache();
_user.Language = value;
}
}
@@ -223,8 +192,8 @@ namespace umbraco.BusinessLogic
/// <returns></returns>
public string GetPassword()
{
return ApplicationContext.Current.DatabaseContext.Database.ExecuteScalar<string>(
"SELECT UserPassword FROM umbracoUser WHERE id = @id", new {id = Id});
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return _user.Password;
}
/// <summary>
@@ -277,17 +246,16 @@ namespace umbraco.BusinessLogic
/// <returns></returns>
public List<Application> GetApplications()
{
if (_isInitialized == false)
setupUser(_id);
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
var allApps = Application.getAll();
var apps = new List<Application>();
var dtos = ApplicationContext.Current.DatabaseContext.Database.Fetch<User2AppDto>(
"SELECT * FROM umbracoUser2app WHERE [user] = @userID", new {userID = Id});
foreach (var dto in dtos)
var sections = _user.AllowedSections;
foreach (var s in sections)
{
var app = allApps.SingleOrDefault(x => x.alias == dto.AppAlias);
var app = allApps.SingleOrDefault(x => x.alias == s);
if (app != null)
apps.Add(app);
}
@@ -303,21 +271,15 @@ namespace umbraco.BusinessLogic
{
get
{
if (_isInitialized == false)
setupUser(_id);
return _loginname;
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return _user.Username;
}
set
{
if (EnsureUniqueLoginName(value, this) == false)
throw new Exception(String.Format("A user with the login '{0}' already exists", value));
_loginname = value;
ApplicationContext.Current.DatabaseContext.Database.Update<UserDto>(
"SET UserLogin = @login WHERE id = @id", new { login = value, id = Id });
FlushFromCache();
_user.Username = value;
}
}
@@ -382,18 +344,12 @@ namespace umbraco.BusinessLogic
{
get
{
if (_isInitialized == false)
setupUser(_id);
return _usertype;
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return new UserType(_user.UserType);
}
set
{
_usertype = value;
ApplicationContext.Current.DatabaseContext.Database.Update<UserDto>(
"SET userType = @type WHERE id = @id", new { type = value.Id, id = Id });
FlushFromCache();
_user.UserType = value.UserTypeItem;
}
}
@@ -404,17 +360,13 @@ namespace umbraco.BusinessLogic
/// <returns></returns>
public static User[] getAll()
{
IRecordsReader dr = SqlHelper.ExecuteReader("Select id from umbracoUser");
int totalRecs;
var users = ApplicationContext.Current.Services.UserService.GetAllMembers(
0, int.MaxValue, out totalRecs);
var users = new List<User>();
while (dr.Read())
{
users.Add(User.GetUser(dr.GetInt("id")));
}
dr.Close();
return users.OrderBy(x => x.Name).ToArray();
return users.Select(x => new User(x))
.OrderBy(x => x.Name)
.ToArray();
}
@@ -455,22 +407,21 @@ namespace umbraco.BusinessLogic
/// <returns></returns>
public static User[] getAllByEmail(string email, bool useExactMatch)
{
var retVal = new List<User>();
var tmpContainer = new ArrayList();
IRecordsReader dr = useExactMatch
? SqlHelper.ExecuteReader("Select id from umbracoUser where userEmail = @email",
SqlHelper.CreateParameter("@email", email))
: SqlHelper.ExecuteReader("Select id from umbracoUser where userEmail LIKE {0} @email",
SqlHelper.CreateParameter("@email", String.Format("%{0}%", email)));
while (dr.Read())
int totalRecs;
if (useExactMatch)
{
retVal.Add(GetUser(dr.GetInt("id")));
return ApplicationContext.Current.Services.UserService.FindMembersByEmail(
email, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact)
.Select(x => new User(x))
.ToArray();
}
else
{
return ApplicationContext.Current.Services.UserService.FindMembersByEmail(
string.Format("%{0}%", email), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Wildcard)
.Select(x => new User(x))
.ToArray();
}
dr.Close();
return retVal.ToArray();
}
/// <summary>
@@ -487,7 +438,7 @@ namespace umbraco.BusinessLogic
/// Gets all users by login name.
/// </summary>
/// <param name="login">The login.</param>
/// <param name="">whether to use a partial match</param>
/// <param name="partialMatch">whether to use a partial match</param>
/// <returns></returns>
public static User[] getAllByLoginName(string login, bool partialMatch)
{
@@ -496,36 +447,21 @@ namespace umbraco.BusinessLogic
public static IEnumerable<User> GetAllByLoginName(string login, bool partialMatch)
{
var users = new List<User>();
int totalRecs;
if (partialMatch)
{
using (var dr = SqlHelper.ExecuteReader(
"Select id from umbracoUser where userLogin LIKE @login", SqlHelper.CreateParameter("@login", String.Format("%{0}%", login))))
{
while (dr.Read())
{
users.Add(BusinessLogic.User.GetUser(dr.GetInt("id")));
}
}
return ApplicationContext.Current.Services.UserService.FindMembersByUsername(
string.Format("%{0}%", login), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Wildcard)
.Select(x => new User(x))
.ToArray();
}
else
{
using (var dr = SqlHelper.ExecuteReader(
"Select id from umbracoUser where userLogin=@login", SqlHelper.CreateParameter("@login", login)))
{
while (dr.Read())
{
users.Add(BusinessLogic.User.GetUser(dr.GetInt("id")));
}
}
return ApplicationContext.Current.Services.UserService.FindMembersByUsername(
login, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact)
.Select(x => new User(x))
.ToArray();
}
return users;
}
/// <summary>
@@ -535,21 +471,12 @@ namespace umbraco.BusinessLogic
/// <param name="lname">The login name.</param>
/// <param name="passw">The password.</param>
/// <param name="ut">The user type.</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static User MakeNew(string name, string lname, string passw, UserType ut)
{
var user = new Umbraco.Core.Models.Membership.User(name, "", lname, passw, ut.UserTypeItem);
ApplicationContext.Current.Services.UserService.Save(user);
SqlHelper.ExecuteNonQuery(@"
insert into umbracoUser
(UserType,startStructureId,startMediaId, UserName, userLogin, userPassword, userEmail,userLanguage)
values (@type,-1,-1,@name,@lname,@pw,'',@lang)",
SqlHelper.CreateParameter("@lang", GlobalSettings.DefaultUILanguage),
SqlHelper.CreateParameter("@name", name),
SqlHelper.CreateParameter("@lname", lname),
SqlHelper.CreateParameter("@type", ut.Id),
SqlHelper.CreateParameter("@pw", passw));
var u = new User(lname);
var u = new User(user);
u.OnNew(EventArgs.Empty);
return u;
@@ -563,22 +490,13 @@ namespace umbraco.BusinessLogic
/// <param name="lname">The lname.</param>
/// <param name="passw">The passw.</param>
/// <param name="email">The email.</param>
/// <param name="ut">The ut.</param>
[MethodImpl(MethodImplOptions.Synchronized)]
/// <param name="ut">The ut.</param>
public static User MakeNew(string name, string lname, string passw, string email, UserType ut)
{
SqlHelper.ExecuteNonQuery(@"
insert into umbracoUser
(UserType,startStructureId,startMediaId, UserName, userLogin, userPassword, userEmail,userLanguage)
values (@type,-1,-1,@name,@lname,@pw,@email,@lang)",
SqlHelper.CreateParameter("@lang", GlobalSettings.DefaultUILanguage),
SqlHelper.CreateParameter("@name", name),
SqlHelper.CreateParameter("@lname", lname),
SqlHelper.CreateParameter("@email", email),
SqlHelper.CreateParameter("@type", ut.Id),
SqlHelper.CreateParameter("@pw", passw));
var user = new Umbraco.Core.Models.Membership.User(name, email, lname, passw, ut.UserTypeItem);
ApplicationContext.Current.Services.UserService.Save(user);
var u = new User(lname);
var u = new User(user);
u.OnNew(EventArgs.Empty);
return u;
@@ -595,32 +513,32 @@ namespace umbraco.BusinessLogic
/// <param name="ut">The ut.</param>
public static void Update(int id, string name, string lname, string email, UserType ut)
{
if (!EnsureUniqueLoginName(lname, User.GetUser(id)))
if (EnsureUniqueLoginName(lname, GetUser(id)) == false)
throw new Exception(String.Format("A user with the login '{0}' already exists", lname));
SqlHelper.ExecuteNonQuery(@"Update umbracoUser set userName=@name, userLogin=@lname, userEmail=@email, UserType=@type where id = @id",
SqlHelper.CreateParameter("@name", name),
SqlHelper.CreateParameter("@lname", lname),
SqlHelper.CreateParameter("@email", email),
SqlHelper.CreateParameter("@type", ut.Id),
SqlHelper.CreateParameter("@id", id));
var found = ApplicationContext.Current.Services.UserService.GetById(id);
if (found == null) return;
found.Name = name;
found.Username = lname;
found.Email = email;
found.UserType = ut.UserTypeItem;
ApplicationContext.Current.Services.UserService.Save(found);
}
public static void Update(int id, string name, string lname, string email, bool disabled, bool noConsole, UserType ut)
{
if (!EnsureUniqueLoginName(lname, User.GetUser(id)))
if (EnsureUniqueLoginName(lname, GetUser(id)) == false)
throw new Exception(String.Format("A user with the login '{0}' already exists", lname));
SqlHelper.ExecuteNonQuery(@"Update umbracoUser set userName=@name, userLogin=@lname, userEmail=@email, UserType=@type, userDisabled=@disabled, userNoConsole=@noconsole where id = @id",
SqlHelper.CreateParameter("@name", name),
SqlHelper.CreateParameter("@lname", lname),
SqlHelper.CreateParameter("@email", email),
SqlHelper.CreateParameter("@type", ut.Id),
SqlHelper.CreateParameter("@disabled", disabled),
SqlHelper.CreateParameter("@noconsole", noConsole),
SqlHelper.CreateParameter("@id", id));
var found = ApplicationContext.Current.Services.UserService.GetById(id);
if (found == null) return;
found.Name = name;
found.Username = lname;
found.Email = email;
found.UserType = ut.UserTypeItem;
found.IsApproved = disabled == false;
found.IsLockedOut = noConsole;
ApplicationContext.Current.Services.UserService.Save(found);
}
/// <summary>
@@ -632,11 +550,13 @@ namespace umbraco.BusinessLogic
/// <param name="noConsole"></param>
public static void Update(int id, string email, bool disabled, bool noConsole)
{
SqlHelper.ExecuteNonQuery(@"Update umbracoUser set userEmail=@email, userDisabled=@disabled, userNoConsole=@noconsole where id = @id",
SqlHelper.CreateParameter("@email", email),
SqlHelper.CreateParameter("@disabled", disabled),
SqlHelper.CreateParameter("@noconsole", noConsole),
SqlHelper.CreateParameter("@id", id));
var found = ApplicationContext.Current.Services.UserService.GetById(id);
if (found == null) return;
found.Email = email;
found.IsApproved = disabled == false;
found.IsLockedOut = noConsole;
ApplicationContext.Current.Services.UserService.Save(found);
}
/// <summary>
@@ -647,9 +567,8 @@ namespace umbraco.BusinessLogic
/// <returns>a user ID</returns>
public static int getUserId(string lname, string passw)
{
return getUserId("select id from umbracoUser where userDisabled = 0 and userNoConsole = 0 and userLogin = @login and userPassword = @pw",
SqlHelper.CreateParameter("@login", lname),
SqlHelper.CreateParameter("@pw", passw));
var found = ApplicationContext.Current.Services.UserService.GetByUsername(lname);
return found.Password == passw ? found.Id : -1;
}
/// <summary>
@@ -659,16 +578,10 @@ namespace umbraco.BusinessLogic
/// <returns>a user ID</returns>
public static int getUserId(string lname)
{
return getUserId("select id from umbracoUser where userLogin = @login",
SqlHelper.CreateParameter("@login", lname));
var found = ApplicationContext.Current.Services.UserService.GetByUsername(lname);
return found == null ? -1 : found.Id;
}
private static int getUserId(string query, params IParameter[] parameterValues)
{
object userId = SqlHelper.ExecuteScalar<object>(query, parameterValues);
return (userId != null && userId != DBNull.Value) ? int.Parse(userId.ToString()) : -1;
}
/// <summary>
/// Deletes this instance.
/// </summary>
@@ -681,18 +594,8 @@ namespace umbraco.BusinessLogic
OnDeleting(EventArgs.Empty);
//would be better in the notifications class but since we can't reference the cms project (poorly architected) we need to use raw sql
SqlHelper.ExecuteNonQuery("delete from umbracoUser2NodeNotify where userId = @userId", SqlHelper.CreateParameter("@userId", Id));
ApplicationContext.Current.Services.UserService.Delete(_user, true);
//would be better in the permissions class but since we can't reference the cms project (poorly architected) we need to use raw sql
SqlHelper.ExecuteNonQuery("delete from umbracoUser2NodePermission where userId = @userId", SqlHelper.CreateParameter("@userId", Id));
//delete the assigned applications
clearApplications();
SqlHelper.ExecuteNonQuery("delete from umbracoUserLogins where userID = @id", SqlHelper.CreateParameter("@id", Id));
SqlHelper.ExecuteNonQuery("delete from umbracoUser where id = @id", SqlHelper.CreateParameter("@id", Id));
FlushFromCache();
}
@@ -702,17 +605,9 @@ namespace umbraco.BusinessLogic
public void disable()
{
OnDisabling(EventArgs.Empty);
//change disabled and userLogin (prefix with yyyyMMdd_ )
this.Disabled = true;
//MUST clear out the umbraco logins otherwise if they are still logged in they can still do stuff:
//http://issues.umbraco.org/issue/U4-2042
SqlHelper.ExecuteNonQuery("delete from umbracoUserLogins where userID = @id", SqlHelper.CreateParameter("@id", Id));
//can't rename if it's going to take up too many chars
if (this.LoginName.Length + 9 <= 125)
{
this.LoginName = DateTime.Now.ToString("yyyyMMdd") + "_" + this.LoginName;
}
this.Save();
//delete without the true overload will perform the disable operation
ApplicationContext.Current.Services.UserService.Delete(_user);
}
/// <summary>
@@ -722,13 +617,15 @@ namespace umbraco.BusinessLogic
/// <returns></returns>
public string GetPermissions(string Path)
{
if (!_isInitialized)
setupUser(_id);
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
string defaultPermissions = UserType.DefaultPermissions;
//TODO: Wrap all this with the new services!
//get the cached permissions for the user
var cachedPermissions = ApplicationContext.Current.ApplicationCache.GetCacheItem(
string.Format("{0}{1}", CacheKeys.UserPermissionsCacheKey, _id),
string.Format("{0}{1}", CacheKeys.UserPermissionsCacheKey, _user.Id),
//Since this cache can be quite large (http://issues.umbraco.org/issue/U4-2161) we will make this priority below average
CacheItemPriority.BelowNormal,
null,
@@ -785,7 +682,7 @@ namespace umbraco.BusinessLogic
{
string notifications = "";
if (!_notificationsInitialized)
if (_notificationsInitialized == false)
initNotifications();
foreach (string nodeId in Path.Split(','))
@@ -811,8 +708,9 @@ namespace umbraco.BusinessLogic
/// </summary>
public void initNotifications()
{
if (!_isInitialized)
setupUser(_id);
//TODO: Wrap all this with new services!
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
using (IRecordsReader dr = SqlHelper.ExecuteReader("select * from umbracoUser2NodeNotify where userId = @userId order by nodeId", SqlHelper.CreateParameter("@userId", this.Id)))
{
@@ -834,7 +732,7 @@ namespace umbraco.BusinessLogic
/// <value>The id.</value>
public int Id
{
get { return _id; }
get { return _user.Id; }
}
/// <summary>
@@ -842,7 +740,14 @@ namespace umbraco.BusinessLogic
/// </summary>
public void clearApplications()
{
SqlHelper.ExecuteNonQuery("delete from umbracoUser2app where [user] = @id", SqlHelper.CreateParameter("@id", this.Id));
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
foreach (var s in _user.AllowedSections.ToArray())
{
_user.RemoveAllowedSection(s);
}
ApplicationContext.Current.Services.UserService.Save(_user);
}
/// <summary>
@@ -851,7 +756,11 @@ namespace umbraco.BusinessLogic
/// <param name="AppAlias">The app alias.</param>
public void addApplication(string AppAlias)
{
SqlHelper.ExecuteNonQuery("insert into umbracoUser2app ([user],app) values (@id, @app)", SqlHelper.CreateParameter("@id", this.Id), SqlHelper.CreateParameter("@app", AppAlias));
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
_user.AddAllowedSection(AppAlias);
ApplicationContext.Current.Services.UserService.Save(_user);
}
/// <summary>
@@ -862,15 +771,12 @@ namespace umbraco.BusinessLogic
{
get
{
if (!_isInitialized)
setupUser(_id);
return _userNoConsole;
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return _user.IsLockedOut;
}
set
{
_userNoConsole = value;
SqlHelper.ExecuteNonQuery("update umbracoUser set userNoConsole = @userNoConsole where id = @id", SqlHelper.CreateParameter("@id", this.Id), SqlHelper.CreateParameter("@userNoConsole", _userNoConsole));
FlushFromCache();
_user.IsLockedOut = value;
}
}
@@ -882,31 +788,26 @@ namespace umbraco.BusinessLogic
{
get
{
if (!_isInitialized)
setupUser(_id);
return _userDisabled;
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return _user.IsApproved == false;
}
set
{
_userDisabled = value;
SqlHelper.ExecuteNonQuery("update umbracoUser set userDisabled = @userDisabled where id = @id", SqlHelper.CreateParameter("@id", this.Id), SqlHelper.CreateParameter("@userDisabled", _userDisabled));
FlushFromCache();
_user.IsApproved = value == false;
}
}
/// <summary>
/// Gets or sets a value indicating whether a user should be redirected to liveediting by default.
/// </summary>
/// <value>
/// <c>true</c> if defaults to live editing; otherwise, <c>false</c>.
/// </value>
//NOTE: we cannot wrap this because it's no longer supported so we'll just go directly to the db
public bool DefaultToLiveEditing
{
get
{
if (!_isInitialized)
setupUser(_id);
return _defaultToLiveEditing;
{
if (_defaultToLiveEditing.HasValue == false)
{
_defaultToLiveEditing = SqlHelper.ExecuteScalar<bool>("select defaultToLiveEditing from umbracoUser where id = @id",
SqlHelper.CreateParameter("@id", Id));
}
return _defaultToLiveEditing.Value;
}
set
{
@@ -924,16 +825,12 @@ namespace umbraco.BusinessLogic
{
get
{
if (!_isInitialized)
setupUser(_id);
return _startnodeid;
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return _user.StartContentId;
}
set
{
_startnodeid = value;
SqlHelper.ExecuteNonQuery("update umbracoUser set startStructureId = @start where id = @id", SqlHelper.CreateParameter("@start", value), SqlHelper.CreateParameter("@id", this.Id));
FlushFromCache();
_user.StartContentId = value;
}
}
@@ -945,16 +842,12 @@ namespace umbraco.BusinessLogic
{
get
{
if (!_isInitialized)
setupUser(_id);
return _startmediaid;
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return _user.StartMediaId;
}
set
{
_startmediaid = value;
SqlHelper.ExecuteNonQuery("update umbracoUser set startMediaId = @start where id = @id", SqlHelper.CreateParameter("@start", value), SqlHelper.CreateParameter("@id", this.Id));
FlushFromCache();
_user.StartMediaId = value;
}
}
@@ -975,6 +868,8 @@ namespace umbraco.BusinessLogic
/// <returns></returns>
public static User GetUser(int id)
{
//TODO: Ref: http://issues.umbraco.org/issue/U4-4123
return ApplicationContext.Current.ApplicationCache.GetCacheItem(
string.Format("{0}{1}", CacheKeys.UserCacheKey, id.ToString()), () =>
{

View File

@@ -19,19 +19,19 @@ namespace umbraco.BusinessLogic
public class UserType
{
private Umbraco.Core.Models.Membership.IUserType _userType;
internal Umbraco.Core.Models.Membership.IUserType UserTypeItem;
/// <summary>
/// Creates a new empty instance of a UserType
/// </summary>
public UserType()
{
_userType = new Umbraco.Core.Models.Membership.UserType();
UserTypeItem = new Umbraco.Core.Models.Membership.UserType();
}
internal UserType(Umbraco.Core.Models.Membership.IUserType userType)
{
_userType = userType;
UserTypeItem = userType;
}
/// <summary>
@@ -55,8 +55,9 @@ namespace umbraco.BusinessLogic
/// <param name="name">The name.</param>
public UserType(int id, string name)
{
_userType.Id = id;
_userType.Name = name;
UserTypeItem = new Umbraco.Core.Models.Membership.UserType();
UserTypeItem.Id = id;
UserTypeItem.Name = name;
}
/// <summary>
@@ -68,10 +69,11 @@ namespace umbraco.BusinessLogic
/// <param name="alias"></param>
public UserType(int id, string name, string defaultPermissions, string alias)
{
_userType.Id = id;
_userType.Name = name;
_userType.Alias = alias;
_userType.Permissions = defaultPermissions.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture));
UserTypeItem = new Umbraco.Core.Models.Membership.UserType();
UserTypeItem.Id = id;
UserTypeItem.Name = name;
UserTypeItem.Alias = alias;
UserTypeItem.Permissions = defaultPermissions.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
@@ -93,8 +95,8 @@ namespace umbraco.BusinessLogic
/// </summary>
public string Alias
{
get { return _userType.Alias; }
set { _userType.Alias = value; }
get { return UserTypeItem.Alias; }
set { UserTypeItem.Alias = value; }
}
/// <summary>
@@ -102,8 +104,8 @@ namespace umbraco.BusinessLogic
/// </summary>
public string Name
{
get { return _userType.Name; }
set { _userType.Name = value; }
get { return UserTypeItem.Name; }
set { UserTypeItem.Name = value; }
}
/// <summary>
@@ -111,7 +113,7 @@ namespace umbraco.BusinessLogic
/// </summary>
public int Id
{
get { return _userType.Id; }
get { return UserTypeItem.Id; }
}
/// <summary>
@@ -119,8 +121,8 @@ namespace umbraco.BusinessLogic
/// </summary>
public string DefaultPermissions
{
get { return string.Join("", _userType.Permissions); }
set { _userType.Permissions = value.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); }
get { return string.Join("", UserTypeItem.Permissions); }
set { UserTypeItem.Permissions = value.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); }
}
/// <summary>
@@ -139,10 +141,10 @@ namespace umbraco.BusinessLogic
public void Save()
{
//ensure that this object has an ID specified (it exists in the database)
if (_userType.HasIdentity == false)
if (UserTypeItem.HasIdentity == false)
throw new Exception("The current UserType object does not exist in the database. New UserTypes should be created with the MakeNew method");
ApplicationContext.Current.Services.UserService.SaveUserType(_userType);
ApplicationContext.Current.Services.UserService.SaveUserType(UserTypeItem);
//raise event
OnUpdated(this, new EventArgs());
@@ -154,10 +156,10 @@ namespace umbraco.BusinessLogic
public void Delete()
{
//ensure that this object has an ID specified (it exists in the database)
if (_userType.HasIdentity == false)
if (UserTypeItem.HasIdentity == false)
throw new Exception("The current UserType object does not exist in the database. New UserTypes should be created with the MakeNew method");
ApplicationContext.Current.Services.UserService.DeleteUserType(_userType);
ApplicationContext.Current.Services.UserService.DeleteUserType(UserTypeItem);
//raise event
OnDeleted(this, new EventArgs());
@@ -171,8 +173,8 @@ namespace umbraco.BusinessLogic
/// and the data was loaded, false if it wasn't</returns>
public bool LoadByPrimaryKey(int id)
{
_userType = ApplicationContext.Current.Services.UserService.GetUserTypeById(id);
return _userType != null;
UserTypeItem = ApplicationContext.Current.Services.UserService.GetUserTypeById(id);
return UserTypeItem != null;
}
/// <summary>