// private string basePath = "http://localhost:81";

        public FacebookSecurityModule()
        {
            Get["/login"] = x =>
            {
                return(Context.GetRedirect(GetFacebookOAuthClient().GetLoginUrl().AbsoluteUri));
            };

            Get["/oath"] = x =>
            {
                string code = Context.Request.Query.code;
                FacebookOAuthResult oauthResult;
                var stringUri = GetRequestUriAbsolutePath();

                if (FacebookOAuthResult.TryParse(stringUri, out oauthResult))
                {
                    if (oauthResult.IsSuccess)
                    {
                        //Assign a temporary GUID to identify the user via cookies, we follow Nancy Forms Authentication to prevent storing facebook ids or tokens in cookies.
                        var userId = Guid.NewGuid();
                        AddAuthenticatedUserToCache(code, userId);
                        return(this.LoginAndRedirect(userId));
                    }
                }

                return(this.LogoutAndRedirect("~/"));
            };


            Get["/logout"] = x =>
            {
                return(this.LogoutAndRedirect("~/"));
            };
        }
Ejemplo n.º 2
0
        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 + "/");
                }
            }
        }
Ejemplo n.º 3
0
        public ActionResult FacebookAuthenticationCallback()
        {
            FacebookOAuthResult facebookOAuthResult;

            if (!FacebookOAuthResult.TryParse(Request.Url, out facebookOAuthResult))
            {
                return(Content("failed to retrieve a facebook oauth result."));
            }

            if (!facebookOAuthResult.IsSuccess)
            {
                return(Content("failed to authenticate."));
            }

            // Nice! Authenticated with Facebook AND we have the OAuth Token.
            // So lets extract any data and create this user account.
            Core.Entities.User user = AcceptFacebookOAuthToken(facebookOAuthResult);

            // Now FormsAuthenticate this user, if they are active.
            if (user == null || !user.IsActive)
            {
                // Failed to authenticate.
                // ToDo: proper error message and clean UI.
                return(Content("failed to authenticate - user is inactive."));
            }

            _customFormsAuthentication.SignIn(user.Id, user.DisplayName, Response);

            return(RedirectToAction("Index", "Home", new { area = "" })); // If I don't provide the area .. I get boom-ski :~(
        }
Ejemplo n.º 4
0
        public AuthorizeState Authorize(string returnUrl)
        {
            FacebookOAuthResult oAuthResult;

            if (FacebookOAuthResult.TryParse(_httpContext.Request.Url, out oAuthResult))
            {
                return(TranslateResponseState(returnUrl, oAuthResult));
            }

            return(GenerateRequestState(returnUrl));
        }
Ejemplo n.º 5
0
        private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            // whenever the browser navigates to a new url, try parsing the url
            // the url may be the result of OAuth 2.0 authentication.
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(e.Uri, out oauthResult))
            {
                // The url is the result of OAuth 2.0 authentication.
                if (oauthResult.IsSuccess)
                {
                    var oauthClient = new FacebookOAuthClient {
                        AppId = AppId, AppSecret = AppSecret
                    };

                    // we got the code here
                    var code = oauthResult.Code;
                    oauthClient.ExchangeCodeForAccessTokenCompleted +=
                        (o, args) =>
                    {
                        // make sure to check that no error has occurred.
                        if (args.Error != null)
                        {
                            // make sure to access ui stuffs on the correct thread.
                            Dispatcher.BeginInvoke(
                                () =>
                            {
                                MessageBox.Show(args.Error.Message);
                                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                            });
                        }
                        else
                        {
                            var result      = (IDictionary <string, object>)args.GetResultData();
                            var accessToken = (string)result["access_token"];

                            // make sure to access ui stuffs on the correct thread.
                            Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/FacebookInfoPage.xaml?access_token=" + accessToken, UriKind.Relative)));
                        }
                    };

                    oauthClient.ExchangeCodeForAccessTokenAsync(code);
                }
                else
                {
                    // the user clicked don't allow or some other error occurred.
                    MessageBox.Show(oauthResult.ErrorDescription);
                }
            }
            else
            {
                // The url is NOT the result of OAuth 2.0 authentication.
            }
        }
        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")));
        }
        private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            FacebookOAuthResult result;

            if (FacebookOAuthResult.TryParse(e.Url, out result))
            {
                this.FacebookOAuthResult = result;
                this.DialogResult        = result.IsSuccess ? DialogResult.OK : DialogResult.No;
            }
            else
            {
                this.FacebookOAuthResult = null;
            }
        }
Ejemplo n.º 8
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"));
        }
Ejemplo n.º 9
0
        private void WebView1_LoadCompleted(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
        {
            FacebookOAuthResult oauthResult;

            if (!FacebookOAuthResult.TryParse(e.Uri, out oauthResult))
            {
                return;
            }

            if (oauthResult.IsSuccess)
            {
                LoginSucceeded(oauthResult.AccessToken);
            }
            else
            {
                // user cancelled.
            }
        }
Ejemplo n.º 10
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"));
        }
Ejemplo n.º 11
0
        /// <summary>
        ///  Facebook authentication
        /// </summary>
        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    string url = string.Format(@"https://graph.facebook.com/oauth/access_token?client_id=146563355411375&client_secret=03232f1f920aec6f4e4600105f1dfba4&scope=publish_stream&grant_type=client_credentials&redirect_uri={0}", redirectUrl);

                    var request = (HttpWebRequest)WebRequest.Create(url);

                    var response    = (HttpWebResponse)request.GetResponse();
                    var reader      = new StreamReader(response.GetResponseStream());
                    var token       = reader.ReadToEnd();
                    var accessToken = token.Split('=')[1];

                    var expiresOn = DateTime.MaxValue;

                    var     fbClient   = new FacebookClient(accessToken);
                    dynamic me         = fbClient.Get("drquipe");
                    string  facebookId = me.id;

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

                    FormsAuthentication.SetAuthCookie(facebookId, false);
                }

                return(RedirectToAction("Index", "Productos"));
            }


            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 12
0
        private void webBrowser_Navigated(object sender, NavigationEventArgs e)
        {
            Debug.WriteLine("webBrowser_Navigated: {0}", e.Uri);

            FacebookOAuthResult oauthResult;

            if (!FacebookOAuthResult.TryParse(e.Uri, out oauthResult) || !oauthResult.IsSuccess)
            {
                return;
            }

            var oauthClient = new FacebookOAuthClient {
                AppId = ApplicationID
            };

            oauthClient.AppSecret = ApplicationSecret;
            var code = oauthResult.Code;

            // アクセストークンを要求(非同期実行)
            oauthClient.ExchangeCodeForAccessTokenCompleted += oauthClient_ExchangeCodeForAccessTokenCompleted;
            oauthClient.ExchangeCodeForAccessTokenAsync(code);
        }
Ejemplo n.º 13
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.
                }
            }
        }
Ejemplo n.º 14
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;
            //}

        }
Ejemplo n.º 15
0
        protected Uri GetUrl(HttpContextBase context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (context.Request == null)
            {
                throw new Exception("context.Request is null");
            }

            // TODO: need unit tests for this method, might as well need to refactor this method.
            UriBuilder redirectUriBuilder;

            if (!context.Request.QueryString.AllKeys.Contains("state"))
            {
                // todo: better to redirect to the default canvas page.
                return(new Uri("http://www.facebook.com"));
            }

            // if state is present.
            var state = Encoding.UTF8.GetString(FacebookWebUtils.Base64UrlDecode(context.Request.QueryString["state"]));
            var json  = (IDictionary <string, object>)JsonSerializer.Current.DeserializeObject(state);

            // make it one letter character so more info can fit in.
            // r -> return_url_path (full uri)
            // c -> cancel_url_path (full uri)
            // s -> user_state
            FacebookOAuthResult oauthResult;

            if (!FacebookOAuthResult.TryParse(context.Request.Url, out oauthResult))
            {
                // todo: better to redirect to the default canvas page.
                return(new Uri("http://www.facebook.com"));
            }

            if (oauthResult.IsSuccess)
            {
                var returnUrl = json["r"].ToString();

                redirectUriBuilder = new UriBuilder(returnUrl);

                if (returnUrl.Contains("?"))
                {
                    // incase return url path contains querystrings.
                    var returnUrlParts = returnUrl.Split('?');
                    if (returnUrlParts.Length == 2 && !string.IsNullOrEmpty(returnUrlParts[1]))
                    {
                        var queryStrings = FacebookUtils.ParseUrlQueryString(returnUrlParts[1]);

                        if (queryStrings.ContainsKey("error_reason"))
                        {
                            // remove oauth stuffs.
                            if (queryStrings.ContainsKey("error_reason"))
                            {
                                queryStrings.Remove("error_reason");
                            }

                            if (queryStrings.ContainsKey("error"))
                            {
                                queryStrings.Remove("error");
                            }

                            if (queryStrings.ContainsKey("error_description"))
                            {
                                queryStrings.Remove("error_description");
                            }

                            redirectUriBuilder.Query = FacebookUtils.ToJsonQueryString(queryStrings);
                        }
                    }
                }
            }
            else
            {
                if (!json.ContainsKey("c"))
                {
                    // there is no cancel url path
                    redirectUriBuilder = new UriBuilder("http://facebook.com");
                }
                else
                {
                    var cancelUrl = json["c"].ToString();

                    IDictionary <string, object> cancelUrlQueryStrings = new Dictionary <string, object>
                    {
                        { "error_reason", context.Request.QueryString["error_reason"] },
                        { "error", context.Request.QueryString["error"] },
                        { "error_description", context.Request.QueryString["error_description"] }
                    };

                    if (cancelUrl.Contains("?"))
                    {
                        // incase cancel url path contains querystrings.
                        var cancelUrlParts = cancelUrl.Split('?');
                        if (cancelUrlParts.Length == 2 && !string.IsNullOrEmpty(cancelUrlParts[1]))
                        {
                            var queryStrings = FacebookUtils.ParseUrlQueryString(cancelUrlParts[1]);
                            cancelUrlQueryStrings = FacebookUtils.Merge(cancelUrlQueryStrings, queryStrings);
                        }
                    }

                    redirectUriBuilder = new UriBuilder(cancelUrl)
                    {
                        Query = FacebookUtils.ToJsonQueryString(cancelUrlQueryStrings)
                    };
                }
            }

            return(redirectUriBuilder.Uri);
        }
Ejemplo n.º 16
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"));
        }