public ActionResult NoPermission(Topic topic)
 {
     // Trying to be a sneaky mo fo, so tell them
     var message = new GenericMessageViewModel
     {
         Message = Lang("Errors.NoPermission"),
         MessageType = GenericMessages.Warning
     };
     ShowMessage(message);
     return Redirect(topic.Url);
 }
        public ActionResult GoogleLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            Callback = Request.QueryString["callback"];
            ContentTypeAlias = Request.QueryString["contentTypeAlias"];
            PropertyAlias = Request.QueryString["propertyAlias"];
            Feature = Request.QueryString["feature"];

            if (AuthState != null)
            {
                var stateValue = Session["Dialogue_" + AuthState] as NameValueCollection;
                if (stateValue != null)
                {
                    Callback = stateValue["Callback"];
                    ContentTypeAlias = stateValue["ContentTypeAlias"];
                    PropertyAlias = stateValue["PropertyAlias"];
                    Feature = stateValue["Feature"];
                }
            }

            if (string.IsNullOrEmpty(Dialogue.Settings().GoogleClientId) ||
                string.IsNullOrEmpty(Dialogue.Settings().GoogleClientSecret))
            {
                resultMessage.Message = "You need to add the Google app credentials";
                resultMessage.MessageType = GenericMessages.Danger;
            }
            else
            {
                // Configure the OAuth client based on the options of the prevalue options
                var client = new GoogleOAuthClient
                {
                    ClientId = Dialogue.Settings().GoogleClientId,
                    ClientSecret = Dialogue.Settings().GoogleClientSecret,
                    RedirectUri = ReturnUrl
                };

                // Session expired?
                if (AuthState != null && Session["Dialogue_" + AuthState] == null)
                {
                    resultMessage.Message = "Session Expired";
                    resultMessage.MessageType = GenericMessages.Danger;
                }

                // Check whether an error response was received from Google
                if (AuthError != null)
                {
                    resultMessage.Message = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.Danger;
                    if (AuthState != null) Session.Remove("Dialogue_" + AuthState);
                }

                // Redirect the user to the Google login dialog
                if (AuthCode == null)
                {

                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session["Dialogue_" + state] = new NameValueCollection {
                    { "Callback", Callback},
                    { "ContentTypeAlias", ContentTypeAlias},
                    { "PropertyAlias", PropertyAlias},
                    { "Feature", Feature}
                };

                    // Declare the scope
                    var scope = new[] {
                    GoogleScope.OpenId,
                    GoogleScope.Email,
                    GoogleScope.Profile
                };

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, scope, GoogleAccessType.Offline, GoogleApprovalPrompt.Force);

                    // Redirect the user
                    return Redirect(url);
                }

                var info = new GoogleAccessTokenResponse();
                try
                {
                    info = client.GetAccessTokenFromAuthorizationCode(AuthCode);
                }
                catch (Exception ex)
                {
                    resultMessage.Message = string.Format("Unable to acquire access token<br/>{0}", ex.Message);
                    resultMessage.MessageType = GenericMessages.Danger;
                }

                try
                {

                    // Initialize the Google service
                    var service = GoogleService.CreateFromRefreshToken(client.ClientIdFull, client.ClientSecret, info.RefreshToken);

                    // Get information about the authenticated user
                    var user = service.GetUserInfo();                    
                    using (UnitOfWorkManager.NewUnitOfWork())
                    {
                        var userExists = AppHelpers.UmbServices().MemberService.GetByEmail(user.Email);

                        if (userExists != null)
                        {
                            // Update access token
                            userExists.Properties[AppConstants.PropMemberGoogleAccessToken].Value = info.RefreshToken;
                            AppHelpers.UmbServices().MemberService.Save(userExists);

                            // Users already exists, so log them in
                            FormsAuthentication.SetAuthCookie(userExists.Username, true);
                            resultMessage.Message = Lang("Members.NowLoggedIn");
                            resultMessage.MessageType = GenericMessages.Success;
                        }
                        else
                        {
                            // Not registered already so register them
                            var viewModel = new RegisterViewModel
                            {
                                Email = user.Email,
                                LoginType = LoginType.Google,
                                Password = AppHelpers.RandomString(8),
                                UserName = user.Name,
                                SocialProfileImageUrl = user.Picture,
                                UserAccessToken = info.RefreshToken
                            };

                            return RedirectToAction("MemberRegisterLogic", "DialogueLoginRegisterSurface", viewModel);
                        }
                    }

                }
                catch (Exception ex)
                {
                    resultMessage.Message = string.Format("Unable to get user information<br/>{0}", ex.Message);
                    resultMessage.MessageType = GenericMessages.Danger;
                }

            }


            ShowMessage(resultMessage);
            return RedirectToUmbracoPage(Dialogue.Settings().ForumId);
        }
 public ActionResult PrivateMessages(DialoguePage page)
 {
     if (CurrentMember.DisablePrivateMessages)
     {
         var message = new GenericMessageViewModel
         {
             Message = Lang("Errors.NoPermission"),
             MessageType = GenericMessages.Danger
         };
         ShowMessage(message);
         return Redirect(Settings.ForumRootUrl);
     }
     using (UnitOfWorkManager.NewUnitOfWork())
     {
         var pageIndex = AppHelpers.ReturnCurrentPagingNo();
         var pagedMessages = ServiceFactory.PrivateMessageService.GetPagedReceivedMessagesByUser(pageIndex, AppConstants.PrivateMessageListSize, CurrentMember);
         var viewModel = new PageListPrivateMessageViewModel(page)
         {
             ListPrivateMessageViewModel = new ListPrivateMessageViewModel
             {
                 Messages = pagedMessages,
                 PageIndex = pageIndex,
                 TotalCount = pagedMessages.TotalCount
             },
             PageTitle = Lang("PM.ReceivedPrivateMessages")
         };
         return View(PathHelper.GetThemeViewPath("PrivateMessages"), viewModel);
     }
 }
        public ActionResult UnBanMember()
        {
            //Check permission
            if (User.IsInRole(AppConstants.AdminRoleName) || CurrentMember.CanEditOtherMembers)
            {

                using (UnitOfWorkManager.NewUnitOfWork())
                {
                    var id = Request["id"];
                    if (id != null)
                    {
                        // Get the member
                        var member = ServiceFactory.MemberService.Get(Convert.ToInt32(id));

                        var message = new GenericMessageViewModel
                        {
                            Message = Lang("Member.IsUnBanned"),
                            MessageType = GenericMessages.Success
                        };

                        try
                        {
                            ServiceFactory.MemberService.UnBanMember(member);
                        }
                        catch (Exception ex)
                        {
                            LogError(ex);
                            message.MessageType = GenericMessages.Danger;
                            message.Message = ex.Message;
                        }
                        ShowMessage(message);
                        return Redirect(member.Url);
                    }
                }
            }
            return ErrorToHomePage(Lang("Errors.NoPermission"));
        }
        public ActionResult KillSpammer()
        {
            //Check permission
            if (User.IsInRole(AppConstants.AdminRoleName) || CurrentMember.CanEditOtherMembers)
            {

                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    var id = Request["id"];
                    if (id != null)
                    {
                        // Get the member
                        var member = ServiceFactory.MemberService.Get(Convert.ToInt32(id));

                        // Delete all their posts and votes and delete etc..
                        var worked = ServiceFactory.MemberService.DeleteAllAssociatedMemberInfo(member.Id, unitOfWork);

                        // SAVE UOW
                        var message = new GenericMessageViewModel
                        {
                            Message = Lang("Member.SpammerIsKilled"),
                            MessageType = GenericMessages.Success
                        };

                        try
                        {
                            // Clear the website and signature fields and ban them
                            ServiceFactory.MemberService.KillSpammer(member);
                        }
                        catch (Exception ex)
                        {
                            LogError(ex);
                            message.MessageType = GenericMessages.Danger;
                            message.Message = ex.Message;
                        }
                        ShowMessage(message);
                        return Redirect(member.Url);
                    }
                }


            }
            return ErrorToHomePage(Lang("Errors.NoPermission"));
        }
 public void ShowModelErrors()
 {
     var message = new GenericMessageViewModel();
     var sb = new StringBuilder();
     foreach (var modelState in ViewData.ModelState.Values)
     {
         foreach (var error in modelState.Errors)
         {
             sb.AppendFormat("<li>{0}</li>", error.ErrorMessage);
         }
     }
     var fullMessage = sb.ToString();
     if (!string.IsNullOrEmpty(fullMessage))
     {
         message.Message = string.Concat("<ul>", fullMessage, "</ul>");
         message.MessageType = GenericMessages.Danger;
         ShowMessage(message);
     }
 }
 public void ShowMessage(GenericMessageViewModel messageViewModel)
 {
     // We have to put it on two because some umbraco redirects only work with ViewData!!
     ViewData[AppConstants.MessageViewBagName] = messageViewModel;
     TempData[AppConstants.MessageViewBagName] = messageViewModel;
 }
        public ActionResult Report(ReportPostViewModel viewModel)
        {
            if (Settings.EnableSpamReporting)
            {
                using (UnitOfWorkManager.NewUnitOfWork())
                {
                    var post = ServiceFactory.PostService.Get(viewModel.PostId);

                    // Banned link?
                    if (ServiceFactory.BannedLinkService.ContainsBannedLink(viewModel.Reason))
                    {
                        ShowMessage(new GenericMessageViewModel
                        {
                            Message = Lang("Errors.BannedLink"),
                            MessageType = GenericMessages.Danger
                        });
                        return Redirect(post.Topic.Url);
                    }

                    var report = new Report
                    {
                        Reason = viewModel.Reason,
                        ReportedPost = post,
                        Reporter = CurrentMember
                    };
                    ServiceFactory.ReportService.PostReport(report);

                    var message= new GenericMessageViewModel
                    {
                        Message = Lang("Report.ReportSent"),
                        MessageType = GenericMessages.Success
                    };
                    ShowMessage(message);
                    return Redirect(post.Topic.Url);
                }
            }
            return ErrorToHomePage(Lang("Errors.GenericMessage"));
        }
        public ActionResult EditPost(EditPostViewModel editPostViewModel)
        {

            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Got to get a lot of things here as we have to check permissions
                // Get the post
                var post = ServiceFactory.PostService.Get(editPostViewModel.Id);

                // Get the topic
                var topic = post.Topic;
                var category = ServiceFactory.CategoryService.Get(topic.CategoryId);
                topic.Category = category;

                // get the users permissions
                var permissions = ServiceFactory.PermissionService.GetPermissions(category, _membersGroup);

                if (post.MemberId == CurrentMember.Id || permissions[AppConstants.PermissionModerate].IsTicked)
                {
                    // User has permission so update the post
                    post.PostContent = AppHelpers.GetSafeHtml(ServiceFactory.BannedWordService.SanitiseBannedWords(editPostViewModel.Content));
                    post.DateEdited = DateTime.UtcNow;

                    // if topic starter update the topic
                    if (post.IsTopicStarter)
                    {
                        // if category has changed then update it
                        if (topic.Category.Id != editPostViewModel.Category)
                        {
                            var cat = ServiceFactory.CategoryService.Get(editPostViewModel.Category);
                            topic.Category = cat;
                        }

                        topic.IsLocked = editPostViewModel.IsLocked;
                        topic.IsSticky = editPostViewModel.IsSticky;
                        topic.Name = AppHelpers.GetSafeHtml(ServiceFactory.BannedWordService.SanitiseBannedWords(editPostViewModel.Name));

                        // See if there is a poll
                        if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count > 0)
                        {
                            // Now sort the poll answers, what to add and what to remove
                            // Poll answers already in this poll.
                            var postedIds = editPostViewModel.PollAnswers.Select(x => x.Id);
                            //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList();
                            var existingAnswers = editPostViewModel.PollAnswers.Where(x => topic.Poll.PollAnswers.Select(p => p.Id).Contains(x.Id)).ToList();
                            var newPollAnswers = editPostViewModel.PollAnswers.Where(x => !topic.Poll.PollAnswers.Select(p => p.Id).Contains(x.Id)).ToList();
                            var pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList();

                            // Loop through existing and update names if need be
                            //TODO: Need to think about this in future versions if they change the name
                            //TODO: As they could game the system by getting votes and changing name?
                            foreach (var existPollAnswer in existingAnswers)
                            {
                                // Get the existing answer from the current topic
                                var pa = topic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id);
                                if (pa != null && pa.Answer != existPollAnswer.Answer)
                                {
                                    // If the answer has changed then update it
                                    pa.Answer = existPollAnswer.Answer;
                                }
                            }

                            // Loop through and remove the old poll answers and delete
                            foreach (var oldPollAnswer in pollAnswersToRemove)
                            {
                                // Delete
                                ServiceFactory.PollService.Delete(oldPollAnswer);

                                // Remove from Poll
                                topic.Poll.PollAnswers.Remove(oldPollAnswer);
                            }

                            // Poll answers to add
                            foreach (var newPollAnswer in newPollAnswers)
                            {
                                var npa = new PollAnswer
                                {
                                    Poll = topic.Poll,
                                    Answer = newPollAnswer.Answer
                                };
                                ServiceFactory.PollService.Add(npa);
                                topic.Poll.PollAnswers.Add(npa);
                            }
                        }
                        else
                        {
                            // Need to check if this topic has a poll, because if it does
                            // All the answers have now been removed so remove the poll.
                            if (topic.Poll != null)
                            {
                                //Firstly remove the answers if there are any
                                if (topic.Poll.PollAnswers != null && topic.Poll.PollAnswers.Any())
                                {
                                    var answersToDelete = new List<PollAnswer>();
                                    answersToDelete.AddRange(topic.Poll.PollAnswers);
                                    foreach (var answer in answersToDelete)
                                    {
                                        // Delete
                                        ServiceFactory.PollService.Delete(answer);

                                        // Remove from Poll
                                        topic.Poll.PollAnswers.Remove(answer);
                                    }
                                }

                                // Now delete the poll
                                var pollToDelete = topic.Poll;
                                ServiceFactory.PollService.Delete(pollToDelete);

                                // Remove from topic.
                                topic.Poll = null;
                            }
                        }
                    }

                    // redirect back to topic
                    var message = new GenericMessageViewModel
                    {
                        Message = Lang("Post.Updated"),
                        MessageType = GenericMessages.Success
                    };
                    try
                    {
                        unitOfWork.Commit();
                        ShowMessage(message);
                        return Redirect(topic.Url);
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LogError(ex);
                        throw new Exception(Lang("Errors.GenericError"));
                    }
                }

                return NoPermission(topic);
            }
        }
        public ActionResult FacebookLogin()
        {
            var resultMessage = new GenericMessageViewModel();

            Callback = Request.QueryString["callback"];
            ContentTypeAlias = Request.QueryString["contentTypeAlias"];
            PropertyAlias = Request.QueryString["propertyAlias"];

            if (AuthState != null)
            {
                var stateValue = Session["Dialogue_" + AuthState] as string[];
                if (stateValue != null && stateValue.Length == 3)
                {
                    Callback = stateValue[0];
                    ContentTypeAlias = stateValue[1];
                    PropertyAlias = stateValue[2];
                }
            }

            // Get the prevalue options
            if (string.IsNullOrEmpty(Dialogue.Settings().FacebookAppId) || string.IsNullOrEmpty(Dialogue.Settings().FacebookAppSecret))
            {
                resultMessage.Message = "You need to add the Facebook app credentials";
                resultMessage.MessageType = GenericMessages.Danger;
            }
            else
            {

                // Settings valid move on
                // Configure the OAuth client based on the options of the prevalue options
                var client = new FacebookOAuthClient
                {
                    AppId = Dialogue.Settings().FacebookAppId,
                    AppSecret = Dialogue.Settings().FacebookAppSecret,
                    RedirectUri = ReturnUrl
                };

                // Session expired?
                if (AuthState != null && Session["Dialogue_" + AuthState] == null)
                {
                    resultMessage.Message = "Session Expired";
                    resultMessage.MessageType = GenericMessages.Danger;
                }

                // Check whether an error response was received from Facebook
                if (AuthError != null)
                {
                    resultMessage.Message = AuthErrorDescription;
                    resultMessage.MessageType = GenericMessages.Danger;
                }

                // Redirect the user to the Facebook login dialog
                if (AuthCode == null)
                {
                    // Generate a new unique/random state
                    var state = Guid.NewGuid().ToString();

                    // Save the state in the current user session
                    Session["Dialogue_" + state] = new[] { Callback, ContentTypeAlias, PropertyAlias };

                    // Construct the authorization URL
                    var url = client.GetAuthorizationUrl(state, "public_profile", "email"); //"user_friends"

                    // Redirect the user
                    return Redirect(url);
                }

                // Exchange the authorization code for a user access token
                var userAccessToken = string.Empty;
                try
                {
                    userAccessToken = client.GetAccessTokenFromAuthCode(AuthCode);
                }
                catch (Exception ex)
                {
                    resultMessage.Message = string.Format("Unable to acquire access token<br/>{0}", ex.Message);
                    resultMessage.MessageType = GenericMessages.Danger;
                }

                try
                {
                    if (string.IsNullOrEmpty(resultMessage.Message))
                    {
                        // Initialize the Facebook service (no calls are made here)
                        var service = FacebookService.CreateFromAccessToken(userAccessToken);

                        var user = service.Users.GetUser();


                        // Try to get the email - Some FB accounts have protected passwords
                        var email = user.Body.Email;
                        // TODO - Ignore if no email - Have to check PropMemberFacebookAccessToken has a value
                        // TODO - and the me.UserName is there to match existing logged in accounts
                        
     
                        // First see if this user has registered already - Use email address
                        using (UnitOfWorkManager.NewUnitOfWork())
                        {

                            var userExists = AppHelpers.UmbServices().MemberService.GetByEmail(email);

                            if (userExists != null)
                            {
                                // Update access token
                                userExists.Properties[AppConstants.PropMemberFacebookAccessToken].Value = userAccessToken;
                                AppHelpers.UmbServices().MemberService.Save(userExists);

                                // Users already exists, so log them in
                                FormsAuthentication.SetAuthCookie(userExists.Username, true);
                                resultMessage.Message = Lang("Members.NowLoggedIn");
                                resultMessage.MessageType = GenericMessages.Success;
                            }
                            else
                            {
                                // Not registered already so register them
                                var viewModel = new RegisterViewModel
                                {
                                    Email = email,
                                    LoginType = LoginType.Facebook,
                                    Password = AppHelpers.RandomString(8),
                                    UserName = user.Body.Name,
                                    UserAccessToken = userAccessToken
                                };

                                // Get the image and save it
                                var getImageUrl = string.Format("http://graph.facebook.com/{0}/picture?type=square", user.Body.Id);
                                viewModel.SocialProfileImageUrl = getImageUrl;

                                //Large size photo https://graph.facebook.com/{facebookId}/picture?type=large
                                //Medium size photo https://graph.facebook.com/{facebookId}/picture?type=normal
                                //Small size photo https://graph.facebook.com/{facebookId}/picture?type=small
                                //Square photo https://graph.facebook.com/{facebookId}/picture?type=square

                                return RedirectToAction("MemberRegisterLogic", "DialogueLoginRegisterSurface", viewModel);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    resultMessage.Message = string.Format("Unable to get user information<br/>{0}", ex.Message);
                    resultMessage.MessageType = GenericMessages.Danger;
                }

            }

            ShowMessage(resultMessage);
            return RedirectToUmbracoPage(Dialogue.Settings().ForumId);
        }
        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 (ServiceFactory.BannedEmailService.EmailIsBanned(userModel.Email))
                {
                    ModelState.AddModelError(string.Empty, Lang("Error.EmailIsBanned"));

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

                var userToSave = AppHelpers.UmbMemberHelper().CreateRegistrationModel(AppConstants.MemberTypeAlias);
                userToSave.Username = ServiceFactory.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, ServiceFactory.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 = AppHelpers.GetMemberUploadPath(umbracoMember.Id);

                        // Upload the file
                        var uploadResult = AppHelpers.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 = ServiceFactory.EmailService.EmailTemplate(email.NameTo, sb.ToString());
                        ServiceFactory.EmailService.SendMail(email);
                    }

                    // Fire the activity Service
                    ServiceFactory.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                        
                        SendEmailConfirmationEmail(umbracoMember);

                        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)
                {
                    ShowModelErrors();
                    return Redirect(Settings.RegisterUrl);
                }
                return CurrentUmbracoPage();
            }


        }
        public ActionResult LogOn(LogOnViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {                   
                    var message = new GenericMessageViewModel();
                    var user = new Member();
                    if (ServiceFactory.MemberService.Login(model.UserName, model.Password))
                    {
                        // Set last login date
                        user = ServiceFactory.MemberService.Get(model.UserName);
                        if (user.IsApproved && !user.IsLockedOut)
                        {
                            if (Url.IsLocalUrl(model.ReturnUrl) && model.ReturnUrl.Length > 1 && model.ReturnUrl.StartsWith("/")
                                && !model.ReturnUrl.StartsWith("//") && !model.ReturnUrl.StartsWith("/\\"))
                            {
                                return Redirect(model.ReturnUrl);
                            }

                            message.Message = Lang("Members.NowLoggedIn");
                            message.MessageType = GenericMessages.Success;

                            return RedirectToUmbracoPage(Dialogue.Settings().ForumId);
                        }
                    }

                    // Only show if we have something to actually show to the user
                    if (!string.IsNullOrEmpty(message.Message))
                    {
                        ShowMessage(message);
                    }
                    else
                    {
                        if (user.IsApproved)
                        {
                            ModelState.AddModelError(string.Empty, Lang("Members.Errors.NotApproved"));
                        }
                        else if (user.IsLockedOut)
                        {
                            ModelState.AddModelError(string.Empty, Lang("Members.Errors.LockedOut"));
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, Lang("Members.Errors.LogonGeneric"));
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, Lang("Members.Errors.LogonGeneric"));
                }
            }
            catch (Exception ex)
            {
                LogError("Error when user logging in", ex);
            }

            // Hack to show form validation
            ShowModelErrors();

            return CurrentUmbracoPage();
        }
        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 = ServiceFactory.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 = ServiceFactory.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 = ServiceFactory.PermissionService.GetPermissions(category, _membersGroup);
                            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 = AppHelpers.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
                                    };
                                    ServiceFactory.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 = ServiceFactory.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
                            ServiceFactory.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"));
        }