public static void handleOAuthResult(HttpRequest request, int id)
        {
            FacebookOAuthResult oAuthResult;

            if (FacebookOAuthResult.TryParse(request.Url, out oAuthResult))
            {
                if (oAuthResult.IsSuccess)
                {
                    string code = request.Params["code"];
                    FacebookOAuthClient oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
                    oAuthClient.RedirectUri = new Uri(redirectUrl + "/" + id + "/");
                    oAuthClient.AppId       = ConfigurationManager.AppSettings["Facebook_API_Key"];
                    oAuthClient.AppSecret   = ConfigurationManager.AppSettings["Facebook_API_Secret"];
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);

                    string accessToken = tokenResult.access_token;

                    FacebookClient facebookClient = new FacebookClient(accessToken);
                    dynamic        me             = facebookClient.Get("me");
                    long           facebookId     = Convert.ToInt64(me.id);

                    var          facebookService = new FacebookService();
                    FacebookUser fbUser          = facebookService.AddFacebookUser(facebookId, accessToken, me.name, me.gender);
                    HttpContext.Current.Session["FBUser"] = fbUser;
                    var _publishedArticleService = new PublishedArticleService();
                    var article = _publishedArticleService.GetPublishedArticle(id);
                    System.Web.HttpContext.Current.Response.Redirect("/Blog/Details/" + article.headline.Replace(" ", "_") + "/" + article.articleId + "/");
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var url = HttpContext.Current.Request.Url;
            FacebookOAuthResult oauthResult;

            var oauthClient = new FacebookOAuthClient {
                AppId = AppId, AppSecret = AppSecret, RedirectUri = new Uri(_silverlightFacebookCallback)
            };

            if (oauthClient.TryParseResult(url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    var result = (IDictionary <string, object>)oauthClient.ExchangeCodeForAccessToken(oauthResult.Code);
                    AccessToken = result["access_token"].ToString();
                }
                else
                {
                    ErrorDescription = oauthResult.ErrorDescription;
                }

                Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }
            else
            {
                Response.Redirect("~/");
            }
        }
        private Core.Entities.User AcceptFacebookOAuthToken(FacebookOAuthResult facebookOAuthResult)
        {
            Condition.Requires(facebookOAuthResult).IsNotNull();

            // Grab the code.
            string code = facebookOAuthResult.Code;

            // Grab the access token.
            FacebookOAuthClient facebookOAuthClient = FacebookOAuthClient;
            dynamic             result = facebookOAuthClient.ExchangeCodeForAccessToken(code);

            var oauthData = new OAuthData
            {
                OAuthProvider = OAuthProvider.Facebook,
                AccessToken   = result.access_token,
                ExpiresOn     = DateTime.UtcNow.AddSeconds(result.expires)
            };

            // Now grab their info.
            var     facebookWebClient = new FacebookWebClient(oauthData.AccessToken);
            dynamic facebookUser      = facebookWebClient.Get("me");

            oauthData.Id = facebookUser.id;


            // Not sure how to Inject an IUserService because it requires a Session .. which I don't have.
            var userService = new UserService(DocumentSession);

            // Now associate this facebook user to an existing user OR create a new one.
            return(userService.CreateOrUpdate(oauthData, facebookUser.username, facebookUser.name, facebookUser.email));
        }
        private string GetAccessToken(string code)
        {
            var cl = new FacebookOAuthClient(FacebookApplication);

            cl.RedirectUri = GenerateCallbackUri();
            cl.AppId       = FacebookApplication.AppId;
            cl.AppSecret   = FacebookApplication.AppSecret;
            var dict = (JsonObject)cl.ExchangeCodeForAccessToken(code, new Dictionary <string, object> {
                { "permissions", "offline_access" }
            });

            return(dict.Values.ElementAt(0).ToString());
        }
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            var builder = new UriBuilder(context.Request.GetUrlRewriter())
            {
                Query = "p=" + context.Request["p"]
            };
            var oauth = new FacebookOAuthClient
            {
                AppId       = KeyStorage.Get("facebookAppID"),
                AppSecret   = KeyStorage.Get("facebookAppSecret"),
                RedirectUri = builder.Uri
            };
            FacebookOAuthResult result;

            if (FacebookOAuthResult.TryParse(context.Request.GetUrlRewriter(), out result))
            {
                if (result.IsSuccess)
                {
                    var accessToken = (Facebook.JsonObject)oauth.ExchangeCodeForAccessToken(result.Code);
                    var request     = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString((string)accessToken["access_token"]));
                    using (var response = request.GetResponse())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            var graph   = FacebookGraph.Deserialize(responseStream);
                            var profile = ProfileFromFacebook(graph);
                            return(profile);
                        }
                    }
                }
                return(LoginProfile.FromError(new Exception(result.ErrorReason)));
            }
            //Maybe we didn't query
            var extendedPermissions = new[] { "email", "user_about_me" };
            var parameters          = new Dictionary <string, object>
            {
                { "display", "popup" }
            };

            if (extendedPermissions.Length > 0)
            {
                var scope = new StringBuilder();
                scope.Append(string.Join(",", extendedPermissions));
                parameters["scope"] = scope.ToString();
            }
            var loginUrl = oauth.GetLoginUrl(parameters);

            context.Response.Redirect(loginUrl.ToString());
            return(LoginProfile.FromError(new Exception("Failed to login with facebook")));
        }
Beispiel #6
0
        //
        // GET: /Account/OAuth/

        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current)
                    {
                        RedirectUri = new Uri(RedirectUrl)
                    };
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    var expiresOn = DateTime.MaxValue;

                    if (tokenResult.ContainsKey("expires"))
                    {
                        DateTimeConvertor.FromUnixTime(tokenResult.expires);
                    }

                    var     fbClient   = new FacebookClient(accessToken);
                    dynamic me         = fbClient.Get("me?fields=id,name");
                    long    facebookId = Convert.ToInt64(me.id);

                    InMemoryUserStore.Add(new FacebookUser
                    {
                        AccessToken = accessToken,
                        Expires     = expiresOn,
                        FacebookId  = facebookId,
                        Name        = (string)me.name,
                    });

                    FormsAuthentication.SetAuthCookie(facebookId.ToString(), false);

                    // prevent open redirection attack by checking if the url is local.
                    if (Url.IsLocalUrl(state))
                    {
                        return(Redirect(state));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #7
0
        //
        // GET: /Account/OAuth/

        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    string redirectUrl = "http://" + Request.Url.Host + "/Account/OAuth/";
                    var    oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
                    oAuthClient.RedirectUri = new Uri(redirectUrl);
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    DateTime expiresOn = DateTime.MaxValue;

                    if (tokenResult.ContainsKey("expires"))
                    {
                        DateTimeConvertor.FromUnixTime(tokenResult.expires);
                    }

                    FacebookClient fbClient   = new FacebookClient(accessToken);
                    dynamic        me         = fbClient.Get("me?fields=id,name");
                    long           facebookId = Convert.ToInt64(me.id);

                    FormsAuthentication.SetAuthCookie(facebookId.ToString(), false);

                    // prevent open redirection attack by checking if the url is local.
                    if (Url.IsLocalUrl(state))
                    {
                        return(Redirect(state));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #8
0
        /// <summary>
        /// Awaits permission of facebook user and will issue authenication cookie if successful.
        /// </summary>
        /// <param name="code">Facebook authorization code</param>
        /// <param name="state">Redirect url</param>
        private void ProcessOAuth(string code, string state)
        {
            FacebookOAuthResult oAuthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oAuthResult) && oAuthResult.IsSuccess)
            {
                try
                {
                    // create client to read response
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current)
                    {
                        RedirectUri = new Uri(GetOAuthRedirectUrl())
                    };
                    oAuthClient.AppId     = PageInstance.Site.FacebookAppId;
                    oAuthClient.AppSecret = PageInstance.Site.FacebookAppSecret;
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    FacebookClient fbClient   = new FacebookClient(accessToken);
                    dynamic        me         = fbClient.Get("me");
                    string         facebookId = "FACEBOOK_" + me.id.ToString();

                    // query for matching id in the user table
                    UserService userService = new UserService();
                    var         user        = userService.GetByUserName(facebookId);

                    // if not user was found see if we can find a match in the person table
                    if (user == null)
                    {
                        try
                        {
                            // determine if we can find a match and if so add an user login record

                            // get properties from Facebook dynamic object
                            string lastName  = me.last_name.ToString();
                            string firstName = me.first_name.ToString();
                            string email     = me.email.ToString();

                            var personService = new PersonService();
                            var person        = personService.Queryable().FirstOrDefault(u => u.LastName == lastName && (u.GivenName == firstName || u.NickName == firstName) && u.Email == email);

                            if (person != null)
                            {
                                // since we have the data enter the birthday from Facebook to the db if we don't have it yet
                                DateTime birthdate = Convert.ToDateTime(me.birthday.ToString());

                                if (person.BirthDay == null)
                                {
                                    person.BirthDate = birthdate;
                                    personService.Save(person, person.Id);
                                }
                            }
                            else
                            {
                                person           = new Person();
                                person.GivenName = me.first_name.ToString();
                                person.LastName  = me.last_name.ToString();
                                person.Email     = me.email.ToString();

                                if (me.gender.ToString() == "male")
                                {
                                    person.Gender = Gender.Male;
                                }
                                if (me.gender.ToString() == "female")
                                {
                                    person.Gender = Gender.Female;
                                }

                                person.BirthDate = Convert.ToDateTime(me.birthday.ToString());

                                personService.Add(person, null);
                                personService.Save(person, null);
                            }

                            user = userService.Create(person, AuthenticationType.Facebook, facebookId, "fb", true, person.Id);
                        }
                        catch (Exception ex)
                        {
                            string msg = ex.Message;
                            // TODO: probably should report something...
                        }

                        // TODO: Show label indicating inability to find user corresponding to facebook id
                    }

                    // update user record noting the login datetime
                    user.LastLoginDate    = DateTime.Now;
                    user.LastActivityDate = DateTime.Now;
                    userService.Save(user, user.PersonId);

                    FormsAuthentication.SetAuthCookie(user.UserName, false);
                    Session["UserIsAuthenticated"] = true;

                    if (state != null)
                    {
                        Response.Redirect(state);
                    }
                }
                catch (FacebookOAuthException oae)
                {
                    string msg = oae.Message;
                    // TODO: Add error handeling
                    // Error validating verification code. (usually from wrong return url very picky with formatting)
                    // Error validating client secret.
                    // Error validating application.
                }
            }
        }
Beispiel #9
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params)
        {
            var builder = new UriBuilder(context.Request.GetUrlRewriter()) {Query = "p=" + context.Request["p"]};
            var oauth = new FacebookOAuthClient
            {
                AppId = KeyStorage.Get("facebookAppID"),
                AppSecret = KeyStorage.Get("facebookAppSecret"),
                RedirectUri = builder.Uri
            };
            FacebookOAuthResult result;
            if (FacebookOAuthResult.TryParse(context.Request.GetUrlRewriter(), out result))
            {
                if (result.IsSuccess)
                {
                    var accessToken = (Facebook.JsonObject)oauth.ExchangeCodeForAccessToken(result.Code);
                    var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString((string)accessToken["access_token"]));
                    using (var response = request.GetResponse())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            var graph = FacebookGraph.Deserialize(responseStream);
                            var profile = ProfileFromFacebook(graph);
                            return profile;
                        }
                    }
                }
                return LoginProfile.FromError(new Exception(result.ErrorReason));
            }
            //Maybe we didn't query
            var extendedPermissions = new[] { "email", "user_about_me" };
            var parameters = new Dictionary<string, object>
                                 {
                                     { "display", "popup" }
                                 };

            if (extendedPermissions.Length > 0)
            {
                var scope = new StringBuilder();
                scope.Append(string.Join(",", extendedPermissions));
                parameters["scope"] = scope.ToString();
            }
            var loginUrl = oauth.GetLoginUrl(parameters);
            context.Response.Redirect(loginUrl.ToString());
            return LoginProfile.FromError(new Exception("Failed to login with facebook"));




            //var client = new FacebookClient
            //                 {
            //                     ClientIdentifier = KeyStorage.Get("facebookAppID"),
            //                     ClientSecret = KeyStorage.Get("facebookAppSecret"),
            //                 };
            //try
            //{
            //    IAuthorizationState authorization = client.ProcessUserAuthorization(new HttpRequestInfo(context.Request));
            //    if (authorization == null)
            //    {
            //        // Kick off authorization request
            //        var scope = new List<string>()
            //                    {
            //                        "email,user_about_me",
            //                    };
            //        client.RequestUserAuthorization(scope, null, null);
            //    }
            //    else
            //    {
            //        var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
            //        using (var response = request.GetResponse())
            //        {
            //            if (response != null)
            //                using (var responseStream = response.GetResponseStream())
            //                {
            //                    var graph = FacebookGraph.Deserialize(responseStream);
            //                    var profile = ProfileFromFacebook(graph);
            //                    return profile;
            //                }
            //        }
            //    }
            //}
            //catch (ProtocolException e)
            //{
            //    if (e.InnerException is WebException)
            //    {
            //        //Read stream
            //        var responce =
            //            new StreamReader((e.InnerException as WebException).Response.GetResponseStream()).ReadToEnd();
            //    }
            //    throw;
            //}

        }
Beispiel #10
0
        //
        // GET: /Account/OAuth/

        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
                    oAuthClient.RedirectUri = new Uri(redirectUrl);

                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    DateTime expiresOn = DateTime.MaxValue;

                    if (tokenResult.ContainsKey("expires"))
                    {
                        DateTimeConvertor.FromUnixTime(tokenResult.expires);
                    }

                    FacebookClient fbClient   = new FacebookClient(accessToken);
                    dynamic        me         = fbClient.Get("me?fields=id,name,email,birthday,gender");
                    long           facebookId = Convert.ToInt64(me.id);

                    InMemoryUserStore.Add(new FacebookUser
                    {
                        AccessToken = accessToken,
                        Expires     = expiresOn,
                        FacebookId  = facebookId,
                        Name        = (string)me.name,
                    });

                    var user = Membership.GetUser(facebookId.ToString());

                    FormsAuthentication.SetAuthCookie(facebookId.ToString(), false);

                    string      format   = "d";
                    CultureInfo provider = CultureInfo.InvariantCulture;
                    DateTime    birthday = new DateTime();
                    try
                    {
                        birthday = DateTime.ParseExact(me.birthday, format, provider);
                    }
                    catch
                    {
                    }

                    if (user == null)
                    {
                        var u = Membership.CreateUser(facebookId.ToString(), Guid.NewGuid().ToString());
                        using (BestPlaceEntities db = new BestPlaceEntities())
                        {
                            db.bp_Profile_Create((Guid)u.ProviderUserKey,
                                                 facebookId.ToString(),
                                                 (string)me.name,
                                                 Transfer.GetPictureUrl(facebookId.ToString()),
                                                 (string)me.email,
                                                 null,
                                                 birthday,
                                                 ((string)me.gender == "male") ? true : false,
                                                 null, null);
                        }
                    }
                    else
                    {
                        using (BestPlaceEntities db = new BestPlaceEntities())
                        {
                            db.bp_Profile_Update((Guid)user.ProviderUserKey,
                                                 (string)me.name,
                                                 (string)me.email,
                                                 null,
                                                 birthday,
                                                 ((string)me.gender == "male") ? true : false,
                                                 null, null);
                        }
                    }

                    // prevent open redirection attack by checking if the url is local.
                    if (Url.IsLocalUrl(state))
                    {
                        return(Redirect(state));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #11
0
        public ActionResult FacebookCallback()
        {
            var oauthClient = new FacebookOAuthClient(FacebookApplication.Current)
            {
                RedirectUri = GetFacebookRedirectUri()
            };

            FacebookOAuthResult oAuthResult;

            if (oauthClient.TryParseResult(Request.Url, out oAuthResult))
            {
                if (oAuthResult.IsSuccess)
                {
                    if (!string.IsNullOrWhiteSpace(oAuthResult.Code))
                    {
                        string returnUrl = null;
                        try
                        {
                            if (!string.IsNullOrWhiteSpace(oAuthResult.State))
                            {
                                dynamic state = JsonSerializer.Current.DeserializeObject(Encoding.UTF8.GetString(Base64UrlDecode(oAuthResult.State)));
                                if (!state.ContainsKey("csrf_token") || !ValidateFacebookCsrfToken(state.csrf_token))
                                {
                                    // someone tried to hack the site.
                                    return(RedirectToAction("Index", "Home"));
                                }

                                if (state.ContainsKey("return_url") && !string.IsNullOrWhiteSpace(state.return_url))
                                {
                                    returnUrl = Encoding.UTF8.GetString(Base64UrlDecode(oAuthResult.State));
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // catch incase user puts his own state,
                            // Base64UrlDecode might throw exception if the value is not properly encoded.
                            return(RedirectToAction("Index", "Home"));
                        }

                        try
                        {
                            var result = (IDictionary <string, object>)oauthClient.ExchangeCodeForAccessToken(oAuthResult.Code);

                            ProcessSuccesfulFacebookCallback(result);

                            // prevent open redirection attacks. make sure the returnUrl is trusted before redirecting to it
                            if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                            {
                                return(Redirect(returnUrl));
                            }
                            else
                            {
                                return(RedirectToAction("Index", "Facebook"));
                            }
                        }
                        catch (FacebookApiException)
                        {
                            // catch incase the user entered dummy code or the code expired.
                        }
                    }

                    return(Redirect("~/"));
                }

                return(View("FacebookCallbackError", oAuthResult));
            }

            return(Redirect("~/"));
        }
        public FacebookProfile Authenticate(HttpRequest request = null)
        {
            FacebookOAuthClient facebookOAuthClient = new FacebookOAuthClient
            {
                AppId       = AppID,
                AppSecret   = AppSecret,
                RedirectUri = RedirectUri
            };

            Dictionary <string, object> oauthParams = new Dictionary <string, object>
            {
                {
                    "redirect_uri", RedirectUri
                }
            };

            FacebookAuthResult facebookAuthResult = SerilizationHelper.Deserialize <FacebookAuthResult>(facebookOAuthClient.ExchangeCodeForAccessToken(AuthCode, oauthParams).ToString());

            Token = facebookAuthResult.access_token;
            FacebookClient facebookClient = new FacebookClient(Token);

            return(SerilizationHelper.Deserialize <FacebookProfile>(facebookClient.Get("/me").ToString()));
        }
Beispiel #13
0
        public ActionResult Callback()
        {
            var oauthClient = new FacebookOAuthClient(FacebookApplication.Current)
            {
                RedirectUri = GetFacebookRedirectUri()
            };
            FacebookOAuthResult oAuthResult;

            if (oauthClient.TryParseResult(Request.Url, out oAuthResult))
            {
                if (oAuthResult.IsSuccess)
                {
                    if (!string.IsNullOrWhiteSpace(oAuthResult.Code))
                    {
                        string returnUrl  = "";
                        string domainName = null;
                        string planName   = null;
                        string affiliate  = null;
                        var    state      = new CallbackState();
                        try
                        {
                            if (!string.IsNullOrWhiteSpace(oAuthResult.State))
                            {
                                state = (CallbackState)JsonSerializer.Current.DeserializeObject(Encoding.UTF8.GetString(OAuthFacebook.Base64UrlDecode(oAuthResult.State)), typeof(CallbackState));
                                // TODO: at the moment only check if there is token. Hack Bug
                                // we do this because for logins we are saving token in a separate domain
                                if (!string.IsNullOrEmpty(state.csrf_token) && !ValidateFacebookCsrfToken(state.csrf_token))
                                {
                                    // someone tried to hack the site.
                                    return(RedirectToAction("Index", "Error"));
                                }

                                if (!string.IsNullOrEmpty(state.return_url))
                                {
                                    returnUrl = state.return_url;
                                }

                                if (!string.IsNullOrEmpty(state.domain_name))
                                {
                                    domainName = state.domain_name;
                                }

                                if (!string.IsNullOrEmpty(state.plan_name))
                                {
                                    planName = state.plan_name;
                                }

                                if (!string.IsNullOrEmpty(state.affiliate))
                                {
                                    affiliate = state.affiliate;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Syslog.Write(ex);
                            // catch incase user puts his own state,
                            // Base64UrlDecode might throw exception if the value is not properly encoded.
                            return(RedirectToAction("Index", "Error"));
                        }

                        try
                        {
                            var token         = (IDictionary <string, object>)oauthClient.ExchangeCodeForAccessToken(oAuthResult.Code);
                            var token_key     = (string)token["access_token"];
                            var token_expires = token.ContainsKey("expires") ? token["expires"].ToString() : "";
                            if (state.isRegistration && !string.IsNullOrEmpty(domainName))
                            {
                                var errorMessage = ProcessSuccesfulFacebookRegistrationCallback(token, domainName, planName, affiliate);

                                if (!string.IsNullOrEmpty(errorMessage))
                                {
                                    return(Redirect(ErrorHelper.CreateErrorPage(errorMessage, "/register/" + planName)));
                                }
                            }

                            if (state.isLogin || state.isLink)
                            {
                                var returnUri       = new Uri(returnUrl);
                                var queryParameters = HttpUtility.ParseQueryString(returnUri.Query);
                                queryParameters.Add("token", token_key);
                                queryParameters.Add("expires", token_expires);
                                returnUrl = string.Format("{0}://{1}{2}{3}", returnUri.Scheme, returnUri.Host, returnUri.LocalPath, queryParameters.ToQueryString(true));
                            }

                            if (state.requestPageTokens && !string.IsNullOrEmpty(state.domain_name))
                            {
                                // obtain any other account tokens
                                var facebook = new FacebookService(token_key);
                                var accounts = facebook.Account.GetAccountTokens("me");
                                if (accounts != null && accounts.data != null)
                                {
                                    var domain =
                                        repository.GetSubDomains().SingleOrDefault(x => x.name == state.domain_name);
                                    if (domain != null)
                                    {
                                        foreach (var entry in accounts.data)
                                        {
                                            if (entry.name != null)
                                            {
                                                var ftoken = new facebook_token
                                                {
                                                    pageid      = entry.id,
                                                    subdomainid = domain.id,
                                                    accesstoken = entry.access_token,
                                                    name        = entry.name,
                                                    category    = entry.category,
                                                    flags       = (int)FacebookTokenSettings.NONE
                                                };
                                                repository.AddUpdateFacebookToken(ftoken);
                                            }
                                        }
                                    }
                                }
                            }

                            // save any changes
                            repository.Save();

                            // prevent open redirection attacks. make sure the returnUrl is trusted before redirecting to it
                            if (!string.IsNullOrWhiteSpace(returnUrl) && returnUrl.Contains(GeneralConstants.SUBDOMAIN_HOST))
                            {
                                return(Redirect(returnUrl));
                            }
                        }
                        catch (FacebookApiException ex)
                        {
                            // catch incase the user entered dummy code or the code expired.
                            Syslog.Write(ex);
                        }
                    }
                }
                else
                {
                    switch (oAuthResult.ErrorReason)
                    {
                    // permission request denied
                    case "user_denied":
                        return(RedirectToAction("NoAuth", "Error"));

                    default:
                        Syslog.Write(string.Format("Unhandled Facebook OAUTH {0} - {1}", oAuthResult.ErrorReason, oAuthResult.ErrorDescription));
                        break;
                    }
                }
            }
            return(RedirectToAction("Index", "Error"));
        }