From e2ac82abca757897b367405dd3faa95988b2e92d Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 18:44:41 +1100 Subject: [PATCH] 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. --- src/Umbraco.Core/Models/Membership/IUser.cs | 5 +- src/Umbraco.Core/Models/Membership/User.cs | 20 +- .../Persistence/RepositoryFactory.cs | 3 + .../Services/IMembershipMemberService.cs | 2 +- src/Umbraco.Core/Services/IUserService.cs | 15 +- src/Umbraco.Core/Services/UserService.cs | 79 +-- .../Services/MemberServiceTests.cs | 4 +- .../Services/UserServiceTests.cs | 1 + .../TestHelpers/BaseDatabaseFactoryTest.cs | 2 + .../config/metablogConfig.config | 2 +- .../UmbracoServiceMembershipProvider.cs | 7 +- src/umbraco.businesslogic/User.cs | 457 +++++++----------- src/umbraco.businesslogic/UserType.cs | 46 +- 13 files changed, 291 insertions(+), 352 deletions(-) diff --git a/src/Umbraco.Core/Models/Membership/IUser.cs b/src/Umbraco.Core/Models/Membership/IUser.cs index 4aee69705e..c48b371f1a 100644 --- a/src/Umbraco.Core/Models/Membership/IUser.cs +++ b/src/Umbraco.Core/Models/Membership/IUser.cs @@ -15,7 +15,10 @@ namespace Umbraco.Core.Models.Membership int StartMediaId { get; set; } string Language { get; set; } - IUserType UserType { get; } + /// + /// Gets/sets the user type for the user + /// + IUserType UserType { get; set; } /// /// The default permission set for the user diff --git a/src/Umbraco.Core/Models/Membership/User.cs b/src/Umbraco.Core/Models/Membership/User.cs index d1ecd0971f..22cb80c727 100644 --- a/src/Umbraco.Core/Models/Membership/User.cs +++ b/src/Umbraco.Core/Models/Membership/User.cs @@ -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(); _addedSections = new List(); _removedSections = new List(); + _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>(x => x.DefaultPermissions); private static readonly PropertyInfo DefaultToLiveEditingSelector = ExpressionHelper.GetPropertyInfo(x => x.DefaultToLiveEditing); private static readonly PropertyInfo HasIdentitySelector = ExpressionHelper.GetPropertyInfo(x => x.HasIdentity); + private static readonly PropertyInfo UserTypeSelector = ExpressionHelper.GetPropertyInfo(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 diff --git a/src/Umbraco.Core/Persistence/RepositoryFactory.cs b/src/Umbraco.Core/Persistence/RepositoryFactory.cs index b97e80d187..ce3568925e 100644 --- a/src/Umbraco.Core/Persistence/RepositoryFactory.cs +++ b/src/Umbraco.Core/Persistence/RepositoryFactory.cs @@ -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, diff --git a/src/Umbraco.Core/Services/IMembershipMemberService.cs b/src/Umbraco.Core/Services/IMembershipMemberService.cs index b27b8f660a..8827d71860 100644 --- a/src/Umbraco.Core/Services/IMembershipMemberService.cs +++ b/src/Umbraco.Core/Services/IMembershipMemberService.cs @@ -51,7 +51,7 @@ namespace Umbraco.Core.Services /// T CreateMemberWithIdentity(string username, string email, string password, string memberTypeAlias, bool raiseEvents = true); - T GetById(object id); + T GetById(int id); /// /// Get a member by email diff --git a/src/Umbraco.Core/Services/IUserService.cs b/src/Umbraco.Core/Services/IUserService.cs index d6ca2514d5..3c40d9d175 100644 --- a/src/Umbraco.Core/Services/IUserService.cs +++ b/src/Umbraco.Core/Services/IUserService.cs @@ -9,6 +9,13 @@ namespace Umbraco.Core.Services /// public interface IUserService : IMembershipUserService { + /// + /// To permanently delete the user pass in true, otherwise they will just be disabled + /// + /// + /// + void Delete(IUser user, bool deletePermanently); + /// /// Gets an IProfile by User Id. /// @@ -35,13 +42,7 @@ namespace Umbraco.Core.Services /// /// void DeleteSectionFromAllUsers(string sectionAlias); - - /// - /// Returns a list of the sections that the user is allowed access to - /// - /// - IEnumerable GetUserSections(IUser user); - + /// /// Get permissions set for user and specified node ids /// diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index 92ff2d5dc9..5891c88247 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -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 } } + /// + /// This disables and renames the user, it does not delete them, use the overload to delete them + /// + /// public void Delete(IUser membershipUser) - { - if (DeletingUser.IsRaisedEventCancelled(new DeleteEventArgs(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(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}); + } + + /// + /// To permanently delete the user pass in true, otherwise they will just be disabled + /// + /// + /// + public void Delete(IUser user, bool deletePermanently) + { + if (deletePermanently == false) + { + Delete(user); + } + else + { + if (DeletingUser.IsRaisedEventCancelled(new DeleteEventArgs(user), this)) + return; + + var uow = _uowProvider.GetUnitOfWork(); + using (var repository = _repositoryFactory.CreateUserRepository(uow)) + { + repository.Delete(user); + uow.Commit(); + } + + DeletedUser.RaiseEvent(new DeleteEventArgs(user, false), this); + } } public void Save(IUser membershipUser, bool raiseEvents = true) @@ -461,22 +488,6 @@ namespace Umbraco.Core.Services } } - /// - /// Returns the user's applications that they are allowed to access - /// - /// - /// - public IEnumerable GetUserSections(IUser user) - { - //TODO: We need to cache this result - - var uow = _uowProvider.GetUnitOfWork(); - var sql = new Sql(); - sql.Select("app").From() - .Where(dto => dto.UserId == (int)user.Id); - return uow.Database.Fetch(sql); - } - /// /// Returns permissions for a given user for any number of nodes /// diff --git a/src/Umbraco.Tests/Services/MemberServiceTests.cs b/src/Umbraco.Tests/Services/MemberServiceTests.cs index 6529cbeee2..39bddf102e 100644 --- a/src/Umbraco.Tests/Services/MemberServiceTests.cs +++ b/src/Umbraco.Tests/Services/MemberServiceTests.cs @@ -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] diff --git a/src/Umbraco.Tests/Services/UserServiceTests.cs b/src/Umbraco.Tests/Services/UserServiceTests.cs index 8658957ab9..0ebaf58e7e 100644 --- a/src/Umbraco.Tests/Services/UserServiceTests.cs +++ b/src/Umbraco.Tests/Services/UserServiceTests.cs @@ -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; diff --git a/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs b/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs index 6bd46836ae..c030ad3c04 100644 --- a/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs +++ b/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs @@ -78,6 +78,8 @@ namespace Umbraco.Tests.TestHelpers using (DisposableTimer.TraceDuration("init")) { + //TODO: Somehow make this faster - takes 5s + + DatabaseContext.Initialize(dbFactory.ProviderName, dbFactory.ConnectionString); CreateSqlCeDatabase(); InitializeDatabase(); diff --git a/src/Umbraco.Web.UI/config/metablogConfig.config b/src/Umbraco.Web.UI/config/metablogConfig.config index 5621dbee75..82502df5e3 100644 --- a/src/Umbraco.Web.UI/config/metablogConfig.config +++ b/src/Umbraco.Web.UI/config/metablogConfig.config @@ -5,7 +5,7 @@ 0 1080 False - Base + umbBlog diff --git a/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs index dd92a50c57..66892d316b 100644 --- a/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs @@ -344,7 +344,12 @@ namespace Umbraco.Web.Security.Providers /// 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; diff --git a/src/umbraco.businesslogic/User.cs b/src/umbraco.businesslogic/User.cs index 9a5bfc38e6..e4d9557bb9 100644 --- a/src/umbraco.businesslogic/User.cs +++ b/src/umbraco.businesslogic/User.cs @@ -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 /// 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; } /// @@ -63,7 +68,7 @@ namespace umbraco.BusinessLogic /// The ID. public User(int ID) { - setupUser(ID); + SetupUser(ID); } /// @@ -73,7 +78,7 @@ namespace umbraco.BusinessLogic /// if set to true [no setup]. public User(int ID, bool noSetup) { - _id = ID; + _lazyId = ID; } /// @@ -83,7 +88,7 @@ namespace umbraco.BusinessLogic /// The password. public User(string Login, string Password) { - setupUser(getUserId(Login, Password)); + SetupUser(getUserId(Login, Password)); } /// @@ -92,33 +97,16 @@ namespace umbraco.BusinessLogic /// The login. 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("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; } /// @@ -126,6 +114,7 @@ namespace umbraco.BusinessLogic /// 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( - "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( - "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( - "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( - "SET UserPassword = @pw WHERE id = @id", new { pw = value, id = Id }); - - FlushFromCache(); + _user.Language = value; } } @@ -223,8 +192,8 @@ namespace umbraco.BusinessLogic /// public string GetPassword() { - return ApplicationContext.Current.DatabaseContext.Database.ExecuteScalar( - "SELECT UserPassword FROM umbracoUser WHERE id = @id", new {id = Id}); + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + return _user.Password; } /// @@ -277,17 +246,16 @@ namespace umbraco.BusinessLogic /// public List GetApplications() { - if (_isInitialized == false) - setupUser(_id); + if (_lazyId.HasValue) SetupUser(_lazyId.Value); var allApps = Application.getAll(); var apps = new List(); - var dtos = ApplicationContext.Current.DatabaseContext.Database.Fetch( - "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( - "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( - "SET userType = @type WHERE id = @id", new { type = value.Id, id = Id }); - - FlushFromCache(); + _user.UserType = value.UserTypeItem; } } @@ -404,17 +360,13 @@ namespace umbraco.BusinessLogic /// 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(); - - 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 /// public static User[] getAllByEmail(string email, bool useExactMatch) { - var retVal = new List(); - 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(); } /// @@ -487,7 +438,7 @@ namespace umbraco.BusinessLogic /// Gets all users by login name. /// /// The login. - /// whether to use a partial match + /// whether to use a partial match /// public static User[] getAllByLoginName(string login, bool partialMatch) { @@ -496,36 +447,21 @@ namespace umbraco.BusinessLogic public static IEnumerable GetAllByLoginName(string login, bool partialMatch) { - - var users = new List(); - + 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; - - } /// @@ -535,21 +471,12 @@ namespace umbraco.BusinessLogic /// The login name. /// The password. /// The user type. - [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 /// The lname. /// The passw. /// The email. - /// The ut. - [MethodImpl(MethodImplOptions.Synchronized)] + /// The ut. 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 /// The ut. 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); } /// @@ -632,11 +550,13 @@ namespace umbraco.BusinessLogic /// 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); } /// @@ -647,9 +567,8 @@ namespace umbraco.BusinessLogic /// a user ID 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; } /// @@ -659,16 +578,10 @@ namespace umbraco.BusinessLogic /// a user ID 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(query, parameterValues); - return (userId != null && userId != DBNull.Value) ? int.Parse(userId.ToString()) : -1; - } - + /// /// Deletes this instance. /// @@ -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); } /// @@ -722,13 +617,15 @@ namespace umbraco.BusinessLogic /// 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 /// 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 /// The id. public int Id { - get { return _id; } + get { return _user.Id; } } /// @@ -842,7 +740,14 @@ namespace umbraco.BusinessLogic /// 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); } /// @@ -851,7 +756,11 @@ namespace umbraco.BusinessLogic /// The app alias. 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); } /// @@ -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; } } - /// - /// Gets or sets a value indicating whether a user should be redirected to liveediting by default. - /// - /// - /// true if defaults to live editing; otherwise, false. - /// + //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("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 /// 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()), () => { diff --git a/src/umbraco.businesslogic/UserType.cs b/src/umbraco.businesslogic/UserType.cs index 57308423b0..7bf95b74d8 100644 --- a/src/umbraco.businesslogic/UserType.cs +++ b/src/umbraco.businesslogic/UserType.cs @@ -19,19 +19,19 @@ namespace umbraco.BusinessLogic public class UserType { - private Umbraco.Core.Models.Membership.IUserType _userType; + internal Umbraco.Core.Models.Membership.IUserType UserTypeItem; /// /// Creates a new empty instance of a UserType /// 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; } /// @@ -55,8 +55,9 @@ namespace umbraco.BusinessLogic /// The name. 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; } /// @@ -68,10 +69,11 @@ namespace umbraco.BusinessLogic /// 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)); } /// @@ -93,8 +95,8 @@ namespace umbraco.BusinessLogic /// public string Alias { - get { return _userType.Alias; } - set { _userType.Alias = value; } + get { return UserTypeItem.Alias; } + set { UserTypeItem.Alias = value; } } /// @@ -102,8 +104,8 @@ namespace umbraco.BusinessLogic /// public string Name { - get { return _userType.Name; } - set { _userType.Name = value; } + get { return UserTypeItem.Name; } + set { UserTypeItem.Name = value; } } /// @@ -111,7 +113,7 @@ namespace umbraco.BusinessLogic /// public int Id { - get { return _userType.Id; } + get { return UserTypeItem.Id; } } /// @@ -119,8 +121,8 @@ namespace umbraco.BusinessLogic /// 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)); } } /// @@ -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 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; } ///