// ************************************** // RegisterUser // ************************************** public static User RegisterUser(User user, Guid invitationCode) { using (var ctx = new SongSearchContext()) { var existing = ctx.GetUser(user); if (existing != null) { return existing; } else { var inv = ctx.Invitations.SingleOrDefault(i => i.InvitationId.Equals(invitationCode) && i.InvitationEmailAddress.Equals(user.UserName)); var pricingPlan = ctx.PricingPlans.SingleOrDefault(x => x.PricingPlanId == user.PricingPlanId); if (inv == null) { throw new ArgumentOutOfRangeException(String.Format("Invalid invitation {0}", inv.InvitationId), innerException: null); } else { // ---------------------------------- // CREATE USER // ---------------------------------- var newUser = ctx.Create(user, inv, pricingPlan); ctx.SaveChanges(); // ---------------------------------- // GET / CREATE PLAN SUBSCRIPTION // ---------------------------------- if (!inv.IsPlanInvitation) { // ---------------------------------- // GET / CREATE PLAN BALANCE // ---------------------------------- var balance = ctx.SubscribeUserTo(newUser, pricingPlan); } else { newUser.PlanBalanceId = inv.InvitedByUser.PlanBalance.PlanBalanceId; newUser.PlanUserId = inv.InvitedByUser.UserId; ctx.AddToUserBalance(newUser); ctx.AddToAdminBalance(newUser); } // ---------------------------------- // CATALOG ACCESS // ---------------------------------- // Get parent users catalog where parent user is at least a plugger and assign to new user in client role var catalogs = ctx.UserCatalogRoles.Where(x => x.UserId == inv.InvitedByUserId && x.RoleId <= (int)Roles.Admin); catalogs.ForEach(c => newUser.UserCatalogRoles.Add(new UserCatalogRole() { CatalogId = c.CatalogId, RoleId = (int)Roles.Client }) ); inv.InvitationStatus = (int)InvitationStatusCodes.Registered; ctx.SaveChanges(); inv = null; return newUser; } } } }
public static void AddToSongsBalance(this SongSearchContext ctx, User user) { ctx.UpdateBalance(new PlanBalance() { PlanBalanceId = user.PlanBalanceId, NumberOfSongs = 1, NumberOfInvitedUsers = 0, NumberOfCatalogAdmins = 0 }); }
public static byte[] GetContentMedia(ContentMedia contentMedia, User user) { //try { return GetContentMedia(contentMedia); //} //catch (Exception ex) { // Log.Error(ex); // throw ex; //} }
public virtual ActionResult ChangePassword(UpdateProfileModel model) { if (ModelState.IsValid) { var userName = this.UserName(); var user = new User() { UserName = userName, Password = model.OldPassword }; if (AccountService.ChangePassword(user, model.NewPassword)) { //_acctService.UpdateCurrentUserInSession(); UserEventLogService.LogUserEvent(UserActions.ChangePassword); return RedirectToAction(Actions.ChangePasswordSuccess()); } else { ModelState.AddModelError("", SystemErrors.PasswordChangeFailed); } } // If we got this far, something failed, redisplay form ViewData["PasswordLength"] = AccountService.MinPasswordLength; this.FeedbackError("There was an error changing your password..."); model.NavigationLocation = new string[] { "Account", "ChangePassword" }; return View(model); }
// ************************************** // UpdateProfile // ************************************** public static bool ChangePassword(User user, string newPassword) { using (var ctx = new SongSearchContext()) { var dbuser = ctx.GetUser(user); if (dbuser == null) { return false; } if (!String.IsNullOrEmpty(newPassword)) { if (PasswordHashMatches(dbuser.Password, user.Password)) { dbuser.Password = newPassword.PasswordHashString(); } else { throw new ArgumentException("Passwords do not match"); } } else { throw new ArgumentNullException("New password cannot be blank"); } ctx.SaveChanges(); dbuser = null; return true; } }
/// <summary> /// Deprecated Method for adding a new object to the Users EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// </summary> public void AddToUsers(User user) { base.AddObject("Users", user); }
private static void TakeOwnerShip(this SongSearchContext ctx, User user) { //become the parent user var userId = Account.User().UserId; user.ParentUserId = userId; ctx.RemoveFromUserBalance(user); //put user on a plan if (!user.IsPlanOwner) { user.PricingPlanId = (int)PricingPlans.Introductory; ctx.SubscribeUserTo(user, new PricingPlan() { PricingPlanId = (int)PricingPlans.Introductory }); } // take over the child users var childUsers = ctx.Users.Where(u => u.ParentUserId == user.UserId); foreach (var child in childUsers) { //child.ParentUserId = userId; child.PlanUserId = user.UserId; } //Re-assign invite from this user to active user var invites = ctx.Invitations.Where(i => i.InvitedByUserId == user.UserId); foreach (var invite in invites) { invite.InvitedByUserId = userId; } }
private static void ReParentOrphans(this SongSearchContext ctx, User user, User newParent) { // take over the child users var childUsers = ctx.Users.Where(u => u.ParentUserId == user.UserId); foreach (var child in childUsers) { child.ParentUserId = newParent.UserId; child.PlanUserId = newParent.PlanUserId; child.PlanBalanceId = newParent.PlanBalanceId; } //Re-assign invite from this user to active user var invites = ctx.Invitations.Where(i => i.InvitedByUserId == user.UserId); foreach (var invite in invites) { invite.InvitedByUserId = newParent.UserId; } }
private static User GetUserDetail(this SongSearchContext ctx, User user) { //TODO: is this not handled via self-join? user = ctx.GetUserGraph(user.UserId); user.ParentUser = user.ParentUserId.HasValue ? ctx.GetUserGraph(user.ParentUserId.Value) : null; return user; }
public static IList<Catalog> LimitToAdministeredBy(this IList<Catalog> catalogs, User user) { if (user.IsSuperAdmin()) { return catalogs; } else { var adminCatalogIds = user.UserCatalogRoles.Where(x => x.RoleId <= (int)Roles.Admin).Select(x => x.CatalogId); return catalogs.Where(c => adminCatalogIds.Contains(c.CatalogId)).ToList(); } // return catalogs.Where(c => c.UserCatalogRoles.Any(x => x.UserId == user.UserId && x.RoleId <= (int)Roles.Admin)).ToList(); }
// ************************************** // LimitToAdministeredBy // ************************************** public static IQueryable<Catalog> LimitToAdministeredBy(this IQueryable<Catalog> catalogs, User user) { var adminCatalogIds = user.UserCatalogRoles.Where(x => x.RoleId <= (int)Roles.Admin).Select(x => x.CatalogId); return catalogs.Where(c => adminCatalogIds.Contains(c.CatalogId)); // return catalogs.Where(c => c.UserCatalogRoles.Any(x => x.UserId == user.UserId && x.RoleId <= (int)Roles.Admin)); }
/// <summary> /// Create a new User object. /// </summary> /// <param name="userId">Initial value of the UserId property.</param> /// <param name="userName">Initial value of the UserName property.</param> /// <param name="password">Initial value of the Password property.</param> /// <param name="roleId">Initial value of the RoleId property.</param> /// <param name="registeredOn">Initial value of the RegisteredOn property.</param> /// <param name="siteProfileId">Initial value of the SiteProfileId property.</param> /// <param name="appendSignatureToTitle">Initial value of the AppendSignatureToTitle property.</param> /// <param name="pricingPlanId">Initial value of the PricingPlanId property.</param> /// <param name="hasAgreedToPrivacyPolicy">Initial value of the HasAgreedToPrivacyPolicy property.</param> /// <param name="hasAllowedCommunication">Initial value of the HasAllowedCommunication property.</param> /// <param name="planUserId">Initial value of the PlanUserId property.</param> /// <param name="planBalanceId">Initial value of the PlanBalanceId property.</param> public static User CreateUser(global::System.Int32 userId, global::System.String userName, global::System.String password, global::System.Int32 roleId, global::System.DateTime registeredOn, global::System.Int32 siteProfileId, global::System.Boolean appendSignatureToTitle, global::System.Int32 pricingPlanId, global::System.Boolean hasAgreedToPrivacyPolicy, global::System.Boolean hasAllowedCommunication, global::System.Int32 planUserId, global::System.Int32 planBalanceId) { User user = new User(); user.UserId = userId; user.UserName = userName; user.Password = password; user.RoleId = roleId; user.RegisteredOn = registeredOn; user.SiteProfileId = siteProfileId; user.AppendSignatureToTitle = appendSignatureToTitle; user.PricingPlanId = pricingPlanId; user.HasAgreedToPrivacyPolicy = hasAgreedToPrivacyPolicy; user.HasAllowedCommunication = hasAllowedCommunication; user.PlanUserId = planUserId; user.PlanBalanceId = planBalanceId; return user; }
internal static PlanBalance SubscribeUserTo(this SongSearchContext ctx, User user, PricingPlan pricingPlan) { if (user.EntityState == System.Data.EntityState.Detached) { //ctx.Detach(user); ctx.Attach(user); } var oldSubs = user.Subscriptions; foreach (var sub in oldSubs) { if (sub.SubscriptionEndDate == null) { sub.SubscriptionEndDate = DateTime.Now; } } //Start a new Subscription var subscription = new Subscription() { SubscriptionStartDate = DateTime.Now, SubscriptionEndDate = null, PricingPlanId = pricingPlan.PricingPlanId, PlanCharge = pricingPlan.PlanCharge.GetValueOrDefault() }; user.Subscriptions.Add(subscription); ctx.Subscriptions.AddObject(subscription); // Adjust current plan user.PricingPlanId = pricingPlan.PricingPlanId; // if user was already on a plan, switch the balance over; if not, open a new balance PlanBalance balance; if (user.IsPlanOwner) { balance = user.PlanBalance; balance.PricingPlanId = pricingPlan.PricingPlanId; balance.LastUpdatedByUserId = user.UserId; balance.LastUpdatedOn = DateTime.Now; } else { balance = new PlanBalance() { PricingPlanId = pricingPlan.PricingPlanId, NumberOfCatalogAdmins = 1, NumberOfInvitedUsers = 1, NumberOfSongs = 0, LastUpdatedByUserId = user.UserId, LastUpdatedOn = DateTime.Now }; user.PlanUserId = user.UserId; balance.Users.Add(user); ctx.PlanBalances.AddObject(balance); } return balance; }
// ---------------------------------------------------------------------------- // (Internal) // ---------------------------------------------------------------------------- // ************************************** // GetUser // ************************************** internal static User GetUser(this SongSearchContext ctx, User user) { return ctx.GetUser(user.UserName); }
// ************************************** // CreateUser // ************************************** internal static User Create(this SongSearchContext ctx, User user, Invitation inv, PricingPlan pricingPlan) { var newUser = new User() { UserName = user.UserName, FirstName = user.FirstName, LastName = user.LastName, HasAgreedToPrivacyPolicy = user.HasAgreedToPrivacyPolicy, HasAllowedCommunication = user.HasAllowedCommunication, Password = user.Password.PasswordHashString(), ParentUserId = inv.InvitedByUserId > 0 ? inv.InvitedByUserId : _defaultUserId, PlanUserId = inv.InvitedByUser != null ? inv.InvitedByUser.UserId : _defaultUserId, //default placeholder;_defaultUserId; //default placeholder; PricingPlanId = pricingPlan.PricingPlanId, PlanBalanceId = inv.InvitedByUser != null ? inv.InvitedByUser.PlanBalanceId : _defaultUserId, //default placeholder; //// Members are Clients until promoted, new plans are admins from the start: //RoleId = inv.IsPlanInvitation ? (int)Roles.Client : (int)Roles.Admin, RoleId = (int)Roles.Admin, //making all new invitees admins from the start //user.PricingPlanId = (int)PricingPlans.Basic; SiteProfileId = inv.InvitedByUser.SiteProfileId,// int.Parse(SystemConfig.DefaultSiteProfileId); RegisteredOn = DateTime.Now, InvitationId = inv.InvitationId }; //create user to get a userid ctx.Users.AddObject(newUser); return newUser; }
// ************************************** // UpdateProfile // ************************************** public static IList<Contact> UpdateProfile(User user, IList<Contact> contacts) { using (var ctx = new SongSearchContext()) { var dbuser = ctx.GetUser(user); if (dbuser == null) { throw new ArgumentException("User does not exist."); } dbuser.FirstName = user.FirstName; dbuser.LastName = user.LastName; dbuser.Signature = user.Signature; dbuser.AppendSignatureToTitle = user.AppendSignatureToTitle; dbuser.HasAllowedCommunication = user.HasAllowedCommunication; if (!contacts.Any(c => c.IsDefault)) { contacts.First().IsDefault = true; } foreach (var contact in contacts) { if (contact != null && (!String.IsNullOrWhiteSpace(contact.Phone1) || !String.IsNullOrWhiteSpace(contact.Email))) { var dbContact = dbuser.Contacts.SingleOrDefault(c => c.ContactId == contact.ContactId) ?? new Contact() { ContactTypeId = contact.ContactTypeId > 0 ? contact.ContactTypeId : (int)ContactTypes.Main, //IsDefault = true, UserId = dbuser.UserId, CreatedOn = DateTime.Now }; dbContact.IsDefault = contact.IsDefault; dbContact.ContactName = contact.ContactName; dbContact.CompanyName = contact.CompanyName; dbContact.Address1 = contact.Address1; dbContact.Address2 = contact.Address2; dbContact.City = contact.City; dbContact.StateRegion = contact.StateRegion; dbContact.PostalCode = contact.PostalCode; dbContact.Country = contact.Country; dbContact.Phone1 = contact.Phone1; dbContact.Phone2 = contact.Phone2; dbContact.Fax = contact.Fax; dbContact.Email = contact.Email; dbContact.AdminEmail = contact.AdminEmail; if (dbContact.ContactId == 0) { ctx.Contacts.AddObject(dbContact); dbuser.Contacts.Add(dbContact); } } } ctx.SaveChanges(); return dbuser.Contacts.ToList(); } }
// ************************************** // GetContactInfo // ************************************** public static Contact GetContactInfo(this SiteProfile profile, User user) { return (user != null ? user.GetContactInfo() : null) ?? profile.Contacts.FirstOrDefault(c => c.IsDefault); }
public static byte[] WriteMediaSignature(byte[] mediaFile, Content content, User user) { var tempPath = String.Concat(SystemConfig.ZipPath, "\\", Guid.NewGuid(), ".mp3"); File.WriteAllBytes(tempPath, mediaFile); // id3 ID3Writer.UpdateUserTag(tempPath, content, user); var assetFile = new FileInfo(tempPath); if (assetFile.Exists) { var assetBytes = File.ReadAllBytes(tempPath); File.Delete(tempPath); return assetBytes; } else { var ex = new ArgumentOutOfRangeException("Content media file is missing"); Log.Error(ex); throw ex; } }
public virtual ActionResult Register(RegisterModel model) { //set username to email address //contentModel.UserName = contentModel.Email; if (ModelState.IsValid) { if (AccountService.UserExists(model.Email)) { ModelState.AddModelError("Email", SystemErrors.UserAlreadyRegistered); } else if (!model.HasAgreedToPrivacyPolicy){ ModelState.AddModelError("HasAgreedToPrivacyPolicy", "We''re sorry, we can only register you if you accept our Terms of Use."); } else { // Check invitation code Invitation inv = null; try { inv = UserManagementService.GetInvitation(model.InviteId, model.Email); } catch (Exception ex){ Log.Error(ex); ModelState.AddModelError("InviteId", SystemErrors.InviteCodeNoMatch); } if (inv != null) { // model.SiteProfile = SiteProfileData.SiteProfile(inv.InvitedByUser.SiteProfileId, true); switch (inv.InvitationStatus) { case (int)InvitationStatusCodes.Open: { model.Invitation = inv; // Attempt to register the myUser //MembershipCreateStatus createStatus = _ms.CreateUser(contentModel.Email, contentModel.Password, contentModel.Email); if (String.IsNullOrEmpty(model.Email)) throw new ArgumentException("Value cannot be null or empty.", "Email"); if (String.IsNullOrEmpty(model.Password)) throw new ArgumentException("Value cannot be null or empty.", "Password"); if (String.IsNullOrEmpty(model.InviteId)) throw new ArgumentException("Value cannot be null or empty.", "InviteId"); var selectedPricingPlanId = (int)model.SelectedPricingPlan; User user = new User() { UserName = model.Email, Password = model.Password, FirstName = model.FirstName, LastName = model.LastName, ParentUserId = model.Invitation.InvitedByUserId, PricingPlanId = selectedPricingPlanId > 0 ? selectedPricingPlanId : (int)PricingPlans.Member, HasAgreedToPrivacyPolicy = model.HasAgreedToPrivacyPolicy, HasAllowedCommunication = model.HasAllowedCommunication, SiteProfileId = model.Invitation.InvitedByUser.SiteProfileId }; try { user = AccountService.RegisterUser(user, inv.InvitationId); SetFriendlyNameCookie(user.FullName()); SetSiteProfileCookie(SiteProfileData.SiteProfile().ProfileId); UserEventLogService.LogUserEvent(UserActions.Register); FormsAuthenticationService.SignIn(user.UserName, true /* createPersistentCookie */); SessionService.Session().RefreshUser(this.UserName()); return RedirectToAction(MVC.Home.Index()); } catch (Exception ex){ Log.Error(ex); ModelState.AddModelError("Email", SystemErrors.UserCreationFailed);//AccountValidation.ErrorCodeToString(createStatus)); } break; } case (int)InvitationStatusCodes.Registered: { ModelState.AddModelError("InviteId", SystemErrors.InviteCodeAlreadyUsed); break; } case (int)InvitationStatusCodes.Expired: { ModelState.AddModelError("InviteId", SystemErrors.InviteCodeExpired); break; } } } else { ModelState.AddModelError("InviteId", SystemErrors.InviteCodeNoMatch); } } } // If we got this far, something failed, redisplay form model.NavigationLocation = new string[] { "Register" }; this.FeedbackError("There was an error registering you..."); ViewData["PasswordLength"] = AccountService.MinPasswordLength; return View(model); }
// ************************************** // IsAvailableTo // ************************************** public static bool IsAvailableTo(this Content content, User user) { if (content == null) { return false; } if (user.IsSuperAdmin()) { return true; } else if (user.UserCatalogRoles != null && user.UserCatalogRoles.AsParallel().Any(x => x.CatalogId == content.CatalogId)) { return true; } else { return false; } }
public virtual ActionResult UpdateProfile(UpdateProfileModel model, Contact contact) { var userModel = new User() { UserName = this.UserName(), FirstName = model.FirstName, LastName = model.LastName, Signature = model.Signature, AppendSignatureToTitle = model.AppendSignatureToTitle, HasAllowedCommunication = model.HasAllowedCommunication }; //var contact = model.Contact; //var session = SessionService.Session(); var currentUser = Account.User();//session.User(User.Identity.Name); model.ShowSignatureField = currentUser.IsAtLeastInCatalogRole(Roles.Plugger); model.ShowContactInfo = currentUser.PricingPlan.CustomContactUs && currentUser.IsAtLeastInCatalogRole(Roles.Admin); //update the user's profile in the database try { var contactList = AccountService.UpdateProfile(userModel, new List<Contact>() { contact }); UserEventLogService.LogUserEvent(UserActions.UpdateProfile); // UpdateModelWith the user dataSession cached in dataSession SessionService.Session().InitializeSession(true); CacheService.CacheUpdate(CacheService.CacheKeys.SiteProfile); var friendly = userModel.FullName(); SetFriendlyNameCookie(friendly); this.FeedbackInfo("Successfully updated your profile"); model.Contact = contactList.FirstOrDefault(); ViewData["PasswordLength"] = AccountService.MinPasswordLength; } catch (Exception ex){ Log.Error(ex); //model.ShowSignatureField = user.IsAtLeastInCatalogRole(Roles.Plugger); ModelState.AddModelError("", SystemErrors.PasswordChangeFailed); this.FeedbackError("There was an error updating your profile"); } model.NavigationLocation = new string[] { "Account", "Profile" }; model.PageTitle = "Update Profile"; model.PageMessage = "My Profile"; return View(model); }
// ************************************** // GetSearchViewModel // ************************************** private SearchViewModel GetSearchViewModel(User user) { return new SearchViewModel() { NavigationLocation = new string[] { "Search" }, SearchMenuProperties = CacheService.SearchProperties((Roles)user.RoleId).OrderBy(x => x.SearchMenuOrder).ToList(), SearchTags = CacheService.TopTags() }; }