private static void MemberServiceOnDeleting(IMemberService sender, DeleteEventArgs <IMember> deleteEventArgs)
        {
            var memberService     = new Services.MemberService();
            var unitOfWorkManager = new UnitOfWorkManager(ContextPerRequest.Db);

            var uploadedFileService         = new UploadedFileService();
            var postService                 = new PostService();
            var memberPointsService         = new MemberPointsService();
            var pollService                 = new PollService();
            var topicService                = new TopicService();
            var topicNotificationService    = new TopicNotificationService();
            var activityService             = new ActivityService();
            var privateMessageService       = new PrivateMessageService();
            var badgeService                = new BadgeService();
            var voteService                 = new VoteService();
            var categoryNotificationService = new CategoryNotificationService();

            using (var unitOfWork = unitOfWorkManager.NewUnitOfWork())
            {
                try
                {
                    foreach (var member in deleteEventArgs.DeletedEntities)
                    {
                        var canDelete = memberService.DeleteAllAssociatedMemberInfo(member.Id, unitOfWork, uploadedFileService, postService, memberPointsService, pollService, topicService,
                                                                                    topicNotificationService, activityService, privateMessageService, badgeService, voteService, categoryNotificationService);
                        if (!canDelete)
                        {
                            deleteEventArgs.Cancel = true;
                            //TODO - THIS DOESN'T WORK - JUST LOG IT
                            //var clientTool = new ClientTools((Page)HttpContext.Current.CurrentHandler);
                            //clientTool.ShowSpeechBubble(SpeechBubbleIcon.Error, "Error", "Unable to delete member. Check logfile for further information");
                            AppHelpers.LogError($"There was an error attemping to delete member {member.Name} and all of their associated data (Posts, Topics etc...)");

                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    AppHelpers.LogError("Error attempting to delete members", ex);
                }
            }
        }
        public ActionResult MemberRegisterLogic(RegisterViewModel userModel)
        {
            var forumReturnUrl = Settings.ForumRootUrl;
            var newMemberGroup = Settings.Group;

            if (userModel.ForumId != null && userModel.ForumId != Settings.ForumId)
            {
                var correctForum = Dialogue.Settings((int)userModel.ForumId);
                forumReturnUrl = correctForum.ForumRootUrl;
                newMemberGroup = correctForum.Group;
            }

            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Secondly see if the email is banned
                if (BannedEmailService.EmailIsBanned(userModel.Email))
                {
                    ModelState.AddModelError(string.Empty, Lang("Error.EmailIsBanned"));

                    if (userModel.LoginType != LoginType.Standard)
                    {
                        ShowMessage();
                        return(Redirect(Settings.RegisterUrl));
                    }
                    return(CurrentUmbracoPage());
                }

                var userToSave = AppHelpers.UmbMemberHelper().CreateRegistrationModel(DialogueConfiguration.Instance.MemberTypeAlias);
                userToSave.Username        = BannedWordService.SanitiseBannedWords(userModel.UserName);
                userToSave.Name            = userToSave.Username;
                userToSave.UsernameIsEmail = false;
                userToSave.Email           = userModel.Email;
                userToSave.Password        = userModel.Password;

                var homeRedirect = false;

                MembershipCreateStatus createStatus;
                AppHelpers.UmbMemberHelper().RegisterMember(userToSave, out createStatus, false);

                if (createStatus != MembershipCreateStatus.Success)
                {
                    ModelState.AddModelError(string.Empty, MemberService.ErrorCodeToString(createStatus));
                }
                else
                {
                    // Get the umbraco member
                    var umbracoMember = AppHelpers.UmbServices().MemberService.GetByUsername(userToSave.Username);

                    // Set the role/group they should be in
                    AppHelpers.UmbServices().MemberService.AssignRole(umbracoMember.Id, newMemberGroup.Name);

                    // See if this is a social login and we have their profile pic
                    if (!string.IsNullOrEmpty(userModel.SocialProfileImageUrl))
                    {
                        // We have an image url - Need to save it to their profile
                        var image = AppHelpers.GetImageFromExternalUrl(userModel.SocialProfileImageUrl);

                        // Upload folder path for member
                        var uploadFolderPath = MemberService.GetMemberUploadPath(umbracoMember.Id);

                        // Upload the file
                        var uploadResult = UploadedFileService.UploadFile(image, uploadFolderPath);

                        // Don't throw error if problem saving avatar, just don't save it.
                        if (uploadResult.UploadSuccessful)
                        {
                            umbracoMember.Properties[AppConstants.PropMemberAvatar].Value = string.Concat(VirtualPathUtility.ToAbsolute(AppConstants.UploadFolderPath), umbracoMember.Id, "/", uploadResult.UploadedFileName);
                        }
                    }

                    // Now check settings, see if users need to be manually authorised
                    // OR Does the user need to confirm their email
                    var manuallyAuthoriseMembers       = Settings.ManuallyAuthoriseNewMembers;
                    var memberEmailAuthorisationNeeded = Settings.NewMembersMustConfirmAccountsViaEmail;
                    if (manuallyAuthoriseMembers || memberEmailAuthorisationNeeded)
                    {
                        umbracoMember.IsApproved = false;
                    }

                    // Store access token for social media account in case we want to do anything with it
                    if (userModel.LoginType == LoginType.Facebook)
                    {
                        umbracoMember.Properties[AppConstants.PropMemberFacebookAccessToken].Value = userModel.UserAccessToken;
                    }
                    if (userModel.LoginType == LoginType.Google)
                    {
                        umbracoMember.Properties[AppConstants.PropMemberGoogleAccessToken].Value = userModel.UserAccessToken;
                    }

                    // Do a save on the member
                    AppHelpers.UmbServices().MemberService.Save(umbracoMember);

                    if (Settings.EmailAdminOnNewMemberSignup)
                    {
                        var sb = new StringBuilder();
                        sb.AppendFormat("<p>{0}</p>", string.Format(Lang("Members.NewMemberRegistered"), Settings.ForumName, Settings.ForumRootUrl));
                        sb.AppendFormat("<p>{0} - {1}</p>", userToSave.Username, userToSave.Email);
                        var email = new Email
                        {
                            EmailTo   = Settings.AdminEmailAddress,
                            EmailFrom = Settings.NotificationReplyEmailAddress,
                            NameTo    = Lang("Members.Admin"),
                            Subject   = Lang("Members.NewMemberSubject")
                        };
                        email.Body = EmailService.EmailTemplate(email.NameTo, sb.ToString());
                        EmailService.SendMail(email);
                    }

                    // Fire the activity Service
                    ActivityService.MemberJoined(MemberMapper.MapMember(umbracoMember));

                    var userMessage = new GenericMessageViewModel();

                    // Set the view bag message here
                    if (manuallyAuthoriseMembers)
                    {
                        userMessage.Message     = Lang("Members.NowRegisteredNeedApproval");
                        userMessage.MessageType = GenericMessages.Success;
                    }
                    else if (memberEmailAuthorisationNeeded)
                    {
                        userMessage.Message     = Lang("Members.MemberEmailAuthorisationNeeded");
                        userMessage.MessageType = GenericMessages.Success;
                    }
                    else
                    {
                        // If not manually authorise then log the user in
                        FormsAuthentication.SetAuthCookie(userToSave.Username, true);
                        userMessage.Message     = Lang("Members.NowRegistered");
                        userMessage.MessageType = GenericMessages.Success;
                    }

                    //Show the message
                    ShowMessage(userMessage);

                    if (!manuallyAuthoriseMembers && !memberEmailAuthorisationNeeded)
                    {
                        homeRedirect = true;
                    }

                    try
                    {
                        unitOfWork.Commit();

                        // Only send the email if the admin is not manually authorising emails or it's pointless
                        EmailService.SendEmailConfirmationEmail(umbracoMember, Settings);

                        if (homeRedirect && !string.IsNullOrEmpty(forumReturnUrl))
                        {
                            if (Url.IsLocalUrl(userModel.ReturnUrl) && userModel.ReturnUrl.Length >= 1 && userModel.ReturnUrl.StartsWith("/") &&
                                !userModel.ReturnUrl.StartsWith("//") && !userModel.ReturnUrl.StartsWith("/\\"))
                            {
                                return(Redirect(userModel.ReturnUrl));
                            }
                            return(Redirect(forumReturnUrl));
                        }
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LogError("Eror during member registering", ex);
                        FormsAuthentication.SignOut();
                        ModelState.AddModelError(string.Empty, ex.Message);
                    }
                }
                if (userModel.LoginType != LoginType.Standard)
                {
                    ShowMessage();
                    return(Redirect(Settings.RegisterUrl));
                }
                return(CurrentUmbracoPage());
            }
        }
Ejemplo n.º 3
0
        public ActionResult Edit(PostMemberEditViewModel userModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var user        = MemberService.Get(userModel.MemberEditViewModel.Id);
                var userEditUrl = $"{Urls.GenerateUrl(Urls.UrlType.EditMember)}?id={user.Id}";

                // Before we do anything DB wise, check it contains no bad links
                if (BannedLinkService.ContainsBannedLink(userModel.MemberEditViewModel.Signature) || BannedLinkService.ContainsBannedLink(userModel.MemberEditViewModel.Website))
                {
                    ShowMessage(new GenericMessageViewModel
                    {
                        Message     = Lang("Errors.BannedLink"),
                        MessageType = GenericMessages.Danger
                    });
                    return(Redirect(userEditUrl));
                }

                // Sort image out first
                if (userModel.MemberEditViewModel.Files != null)
                {
                    // Before we save anything, check the user already has an upload folder and if not create one
                    //var uploadFolderPath = AppHelpers.GetMemberUploadPath(CurrentMember.Id);

                    // Loop through each file and get the file info and save to the users folder and Db
                    var file = userModel.MemberEditViewModel.Files[0];
                    if (file != null)
                    {
                        // If successful then upload the file
                        var memberMediFolderId = MemberService.ConfirmMemberAvatarMediaFolder();
                        var uploadResult       = UploadedFileService.UploadFile(file, memberMediFolderId, true);

                        if (!uploadResult.UploadSuccessful)
                        {
                            ShowMessage(new GenericMessageViewModel
                            {
                                Message     = uploadResult.ErrorMessage,
                                MessageType = GenericMessages.Danger
                            });
                            return(Redirect(userEditUrl));
                        }


                        // Save avatar to user
                        user.Avatar = uploadResult.UploadedFileUrl;
                    }
                }

                user.Signature = BannedWordService.SanitiseBannedWords(AppHelpers.ScrubHtml(userModel.MemberEditViewModel.Signature));
                if (userModel.MemberEditViewModel.Twitter != null && userModel.MemberEditViewModel.Twitter.IndexOf("http", StringComparison.OrdinalIgnoreCase) <= 0)
                {
                    user.Twitter = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.Twitter));
                }
                user.Website  = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.Website));
                user.Comments = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.Comments));


                // User is trying to update their email address, need to
                // check the email is not already in use
                if (userModel.MemberEditViewModel.Email != user.Email)
                {
                    // Add get by email address
                    var sanitisedEmail    = AppHelpers.SafePlainText(userModel.MemberEditViewModel.Email);
                    var userWithSameEmail = MemberService.GetByEmail(sanitisedEmail);

                    //Firstly check new email isn't banned!
                    if (BannedEmailService.EmailIsBanned(sanitisedEmail))
                    {
                        unitOfWork.Rollback();
                        ModelState.AddModelError(string.Empty, Lang("Error.EmailIsBanned"));
                        ShowMessage();
                        return(Redirect(userEditUrl));
                    }

                    // If the username doesn't match this user then someone else has this email address already
                    if (userWithSameEmail != null && userWithSameEmail.UserName != user.UserName)
                    {
                        unitOfWork.Rollback();
                        ModelState.AddModelError(string.Empty, Lang("Members.Errors.DuplicateEmail"));
                        ShowMessage();
                        return(Redirect(userEditUrl));
                    }

                    user.Email = sanitisedEmail;
                }

                // User is trying to change username, need to check if a user already exists
                // with the username they are trying to change to
                var changedUsername   = false;
                var sanitisedUsername = BannedWordService.SanitiseBannedWords(AppHelpers.SafePlainText(userModel.MemberEditViewModel.UserName));
                if (sanitisedUsername != user.UserName)
                {
                    if (MemberService.Get(sanitisedUsername) != null)
                    {
                        unitOfWork.Rollback();
                        ModelState.AddModelError(string.Empty, Lang("Members.Errors.DuplicateUserName"));
                        ShowMessage();
                        return(Redirect(userEditUrl));
                    }

                    user.UserName   = sanitisedUsername;
                    changedUsername = true;
                }

                // Update Everything
                MemberService.SaveMember(user, changedUsername);
                ActivityService.ProfileUpdated(user);

                ShowMessage(new GenericMessageViewModel
                {
                    Message     = Lang("Member.ProfileUpdated"),
                    MessageType = GenericMessages.Success
                });

                try
                {
                    // Need to save member here

                    unitOfWork.Commit();

                    if (changedUsername)
                    {
                        // User has changed their username so need to log them in
                        // as there new username of
                        var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                        if (authCookie != null)
                        {
                            var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                            if (authTicket != null)
                            {
                                var newFormsIdentity = new FormsIdentity(new FormsAuthenticationTicket(authTicket.Version,
                                                                                                       user.UserName,
                                                                                                       authTicket.IssueDate,
                                                                                                       authTicket.Expiration,
                                                                                                       authTicket.IsPersistent,
                                                                                                       authTicket.UserData));
                                var roles = authTicket.UserData.Split("|".ToCharArray());
                                var newGenericPrincipal = new GenericPrincipal(newFormsIdentity, roles);
                                System.Web.HttpContext.Current.User = newGenericPrincipal;
                            }
                        }

                        // sign out current user
                        FormsAuthentication.SignOut();

                        // Abandon the session
                        Session.Abandon();

                        // Sign in new user
                        FormsAuthentication.SetAuthCookie(user.UserName, false);
                    }
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    LogError(ex);
                    ModelState.AddModelError(string.Empty, Lang("Errors.GenericMessage"));
                }

                ShowMessage();
                return(Redirect(userEditUrl));
            }
        }
        public ActionResult UploadPostFiles(AttachFileToPostViewModel attachFileToPostViewModel)
        {
            if (attachFileToPostViewModel != null && attachFileToPostViewModel.Files != null)
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    var message = new GenericMessageViewModel();

                    // First this to do is get the post
                    var post = PostService.Get(attachFileToPostViewModel.UploadPostId);

                    // Check we get a valid post back and have some file
                    if (post != null && attachFileToPostViewModel.Files != null)
                    {
                        Topic topic = null;
                        try
                        {
                            // Now get the topic
                            topic = post.Topic;

                            // Now get the category
                            var category = CategoryService.Get(topic.CategoryId);


                            // Get the permissions for this category, and check they are allowed to update and
                            // not trying to be a sneaky mofo
                            var permissions = PermissionService.GetPermissions(category, _membersGroup, MemberService, CategoryPermissionService);
                            if (permissions[AppConstants.PermissionAttachFiles].IsTicked == false && CurrentMember.DisableFileUploads != true)
                            {
                                return(ErrorToHomePage(Lang("Errors.NoPermission")));
                            }

                            // woot! User has permission and all seems ok
                            // Before we save anything, check the user already has an upload folder and if not create one
                            var uploadFolderPath = Server.MapPath(string.Concat(AppConstants.UploadFolderPath, CurrentMember.Id));
                            if (!Directory.Exists(uploadFolderPath))
                            {
                                Directory.CreateDirectory(uploadFolderPath);
                            }

                            // Loop through each file and get the file info and save to the users folder and Db
                            foreach (var file in attachFileToPostViewModel.Files)
                            {
                                if (file != null)
                                {
                                    // If successful then upload the file
                                    var uploadResult = UploadedFileService.UploadFile(file, uploadFolderPath);
                                    if (!uploadResult.UploadSuccessful)
                                    {
                                        message.Message     = uploadResult.ErrorMessage;
                                        message.MessageType = GenericMessages.Danger;
                                        ShowMessage(message);
                                        return(Redirect(topic.Url));
                                    }

                                    // Add the filename to the database
                                    var uploadedFile = new UploadedFile
                                    {
                                        Filename = uploadResult.UploadedFileName,
                                        Post     = post,
                                        MemberId = CurrentMember.Id
                                    };
                                    UploadedFileService.Add(uploadedFile);
                                }
                            }

                            //Commit
                            unitOfWork.Commit();

                            // Redirect to the topic with a success message
                            message.Message     = Lang("Post.FilesUploaded");
                            message.MessageType = GenericMessages.Success;
                            ShowMessage(message);

                            return(Redirect(topic.Url));
                        }
                        catch (Exception ex)
                        {
                            unitOfWork.Rollback();
                            LogError(ex);
                            message.Message     = Lang("Errors.GenericMessage");
                            message.MessageType = GenericMessages.Danger;
                            ShowMessage(message);
                            return(topic != null?Redirect(topic.Url) : ErrorToHomePage(Lang("Errors.GenericMessage")));
                        }
                    }
                }
            }

            // Else return with error to home page
            return(ErrorToHomePage(Lang("Errors.GenericMessage")));
        }
        public ActionResult DeleteUploadedFile(Guid id)
        {
            if (id != Guid.Empty)
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    Topic topic   = null;
                    var   message = new GenericMessageViewModel();
                    try
                    {
                        // Get the file and associated objects we'll need
                        var uploadedFile = UploadedFileService.Get(id);
                        var post         = uploadedFile.Post;
                        topic = post.Topic;

                        if (_membersGroup.Name == AppConstants.AdminRoleName || uploadedFile.MemberId == CurrentMember.Id)
                        {
                            // Ok to delete file
                            // Remove it from the post
                            post.Files.Remove(uploadedFile);

                            // store the file path as we'll need it to delete on the file system
                            var filePath = uploadedFile.FilePath;

                            // Now delete it
                            UploadedFileService.Delete(uploadedFile);


                            // And finally delete from the file system
                            System.IO.File.Delete(Server.MapPath(filePath));
                        }
                        else
                        {
                            message.Message     = Lang("Errors.NoPermission");
                            message.MessageType = GenericMessages.Danger;
                            ShowMessage(message);

                            Redirect(topic.Url);
                        }

                        //Commit
                        unitOfWork.Commit();

                        message.Message     = Lang("Post.FileSuccessfullyDeleted");
                        message.MessageType = GenericMessages.Success;
                        ShowMessage(message);

                        return(Redirect(topic.Url));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LogError(ex);

                        message.Message     = Lang("Errors.GenericMessage");
                        message.MessageType = GenericMessages.Danger;
                        ShowMessage(message);

                        return(topic != null?Redirect(topic.Url) : ErrorToHomePage(Lang("Errors.GenericMessage")));
                    }
                }
            }
            return(ErrorToHomePage(Lang("Errors.GenericMessage")));
        }