public ActionResult RegisterForm()
        {
            var viewModel = new RegisterViewModel();

            // See if a return url is present or not and add it
            var returnUrl = Request["ReturnUrl"];
            if (!string.IsNullOrEmpty(returnUrl))
            {
                viewModel.ReturnUrl = returnUrl;
            }

            return View(PathHelper.GetThemePartialViewPath("RegisterForm"), viewModel);
        }
        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 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 Register(RegisterViewModel userModel)
        {
            if (Settings.SuspendRegistration != true)
            {
                if (!AppHelpers.IsValidEmail(userModel.Email))
                {
                    return CurrentUmbracoPage();
                }

                // First see if there is a spam question and if so, the answer matches
                if (!string.IsNullOrEmpty(Settings.SpamQuestion))
                {
                    // There is a spam question, if answer is wrong return with error
                    if (userModel.SpamAnswer == null || userModel.SpamAnswer.ToLower().Trim() != Settings.SpamAnswer.ToLower())
                    {
                        // POTENTIAL SPAMMER!
                        ModelState.AddModelError(string.Empty, Lang("Error.WrongAnswerRegistration"));
                        //ShowModelErrors();
                        return CurrentUmbracoPage();
                    }
                }

                // Standard Login
                userModel.LoginType = LoginType.Standard;

                // Do the register logic
                return MemberRegisterLogic(userModel);

            }

            return CurrentUmbracoPage();
        }