protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext, IFacebookApplication settings)
        {
            Contract.Requires(filterContext != null);
            Contract.Requires(filterContext.HttpContext != null);
            Contract.Requires(filterContext.HttpContext.Request != null);
            Contract.Requires(filterContext.RouteData != null);
            Contract.Requires(filterContext.Controller != null);
            Contract.Requires(settings != null);

            var model = new FacebookAuthorizeInfo(
                GetLoginUrl(settings, filterContext.HttpContext, null),
                Perms,
                filterContext.HttpContext.Request.QueryString.AllKeys.Contains("error_reason"),
                filterContext.RouteData.Values);

            var viewResult = new ViewResult
                                       {
                                           MasterName = Master,
                                           ViewName = View,
                                           ViewData = new ViewDataDictionary<FacebookAuthorizeInfo>(model),
                                           TempData = filterContext.Controller.TempData
                                       };

            filterContext.Result = viewResult;
        }
예제 #2
0
        /// <summary>
        /// Creates a Facebook session from a signed request.
        /// </summary>
        /// <param name="appSecret">
        /// The app secret.
        /// </param>
        /// <param name="signedRequest">
        /// The signed request.
        /// </param>
        /// <returns>
        /// The Facebook session.
        /// </returns>
        internal static FacebookSession Create(IFacebookApplication settings, FacebookSignedRequest signedRequest)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            if (signedRequest == null)
            {
                return(null);
            }

            var data = (IDictionary <string, object>)signedRequest.Data;

            if (data == null)
            {
                return(null);
            }

            if (!data.ContainsKey("code") && string.IsNullOrEmpty(signedRequest.AccessToken))
            {
                return(null);
            }

            var dictionary = new JsonObject
            {
                { "uid", signedRequest.UserId.ToString() }
            };

            if (!string.IsNullOrEmpty(signedRequest.AccessToken))
            {
                dictionary["access_token"] = signedRequest.AccessToken;
            }

            if (data.ContainsKey("code"))
            {
                foreach (var key in data.Keys)
                {
                    dictionary[key] = data[key];
                }
            }
            else
            {
                if (signedRequest.Expires == DateTime.MaxValue)
                {
                    dictionary["expires"] = 0;
                }
                else if (signedRequest.Expires != DateTime.MinValue)
                {
                    dictionary["expires"] = DateTimeConvertor.ToUnixTime(signedRequest.Expires);
                }

                if (settings != null && !string.IsNullOrEmpty(settings.AppSecret))
                {
                    dictionary["sig"] = GenerateSessionSignature(settings.AppSecret, dictionary);
                }
            }

            return(new FacebookSession(dictionary, settings));
        }
예제 #3
0
        /// <summary>
        /// Gets the login url.
        /// </summary>
        /// <param name="settings">The Facebook application settings.</param>
        /// <param name="httpContext">The http context.</param>
        /// <param name="parameters">The login parameters.</param>
        /// <returns>The login url.</returns>
        internal virtual protected Uri GetLoginUrl(IFacebookApplication settings, HttpContextBase httpContext, IDictionary <string, object> parameters)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            var authorizer = new CanvasAuthorizer(settings, httpContext)
            {
                ReturnUrlPath    = this.ReturnUrlPath,
                CancelUrlPath    = this.CancelUrlPath,
                LoginDisplayMode = this.LoginDisplayMode
            };

            if (!String.IsNullOrEmpty(this.Permissions))
            {
                authorizer.Permissions = this.Permissions.Replace(" ", String.Empty).Split(',');
            }

            return(authorizer.GetLoginUrl(parameters));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="FacebookApplication"/> class. 
        /// </summary>
        public FacebookApplication()
        {

#if !(SILVERLIGHT || WINRT || MONOTOUCH)
            _current = FacebookConfigurationSection.Current;
#endif
        }
        public override void OnAuthorization(AuthorizationContext filterContext, IFacebookApplication settings)
        {
            var authorizer = new FacebookWebContext(settings, filterContext.HttpContext);

            if (!string.IsNullOrEmpty(Permissions) && Permissions.IndexOf(" ") != -1)
            {
                throw new ArgumentException("Permissions cannot contain whitespace.");
            }

            long? userId = (null != FacebookWebContext.Current.Session) ? (long?)FacebookWebContext.Current.Session.UserId : null;

            if (null == userId || !AuthorizedUsers.Contains(userId.Value))
            {
                if (!authorizer.IsAuthorized(ToArrayString(Permissions)))
                {
                    this.HandleUnauthorizedRequest(filterContext, FacebookApplication.Current);
                }
                else
                {
                    if (!AuthorizedUsers.Contains(FacebookWebContext.Current.Session.UserId))
                    {
                        AuthorizedUsers.Add(FacebookWebContext.Current.Session.UserId);
                    }
                }
            }
        }
        /// <summary>
        /// Set the inner application.
        /// </summary>
        /// <param name="facebookApplication">
        /// The Facebook application.
        /// </param>
        public void InnerSetApplication(IFacebookApplication facebookApplication)
        {
            if (facebookApplication == null)
                throw new ArgumentNullException("facebookApplication");

            _current = facebookApplication;
        }
        public override void OnAuthorization(AuthorizationContext filterContext, IFacebookApplication settings)
        {
            var authorizer = new FacebookWebContext(settings, filterContext.HttpContext);

            if (!string.IsNullOrEmpty(Permissions) && Permissions.IndexOf(" ") != -1)
            {
                throw new ArgumentException("Permissions cannot contain whitespace.");
            }

            long?userId = (null != FacebookWebContext.Current.Session) ? (long?)FacebookWebContext.Current.Session.UserId : null;

            if (null == userId || !AuthorizedUsers.Contains(userId.Value))
            {
                if (!authorizer.IsAuthorized(ToArrayString(Permissions)))
                {
                    this.HandleUnauthorizedRequest(filterContext, FacebookApplication.Current);
                }
                else
                {
                    if (!AuthorizedUsers.Contains(FacebookWebContext.Current.Session.UserId))
                    {
                        AuthorizedUsers.Add(FacebookWebContext.Current.Session.UserId);
                    }
                }
            }
        }
예제 #8
0
        /// <summary>
        /// Try parsing the signed request.
        /// </summary>
        /// <param name="facebookApplication">
        /// The facebook application.
        /// </param>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="signedRequest">
        /// The signed request.
        /// </param>
        /// <returns>
        /// Returns true if parsing is successful otherwise false.
        /// </returns>
        public static bool TryParse(IFacebookApplication facebookApplication, HttpRequestBase request, out FacebookSignedRequest signedRequest)
        {
            signedRequest = null;

            return(request.Params.AllKeys.Contains(SignedRequestKey) &&
                   TryParse(facebookApplication, request.Params[SignedRequestKey], out signedRequest));
        }
예제 #9
0
        protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext, IFacebookApplication settings)
        {
            Contract.Requires(filterContext != null);
            Contract.Requires(settings != null);

            var loginUri = this.GetLoginUrl(settings, filterContext.HttpContext, null);
            filterContext.Result = new CanvasRedirectResult(loginUri.ToString());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookOAuthClient"/> class.
 /// </summary>
 /// <param name="facebookApplication">
 /// The facebook application.
 /// </param>
 public FacebookOAuthClient(IFacebookApplication facebookApplication)
 {
     if (facebookApplication != null)
     {
         AppId     = facebookApplication.AppId;
         AppSecret = facebookApplication.AppSecret;
     }
 }
예제 #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookOAuthClient"/> class.
 /// </summary>
 /// <param name="facebookApplication">
 /// The facebook application.
 /// </param>
 public FacebookOAuthClient(IFacebookApplication facebookApplication)
 {
     if (facebookApplication != null)
     {
         AppId = facebookApplication.AppId;
         AppSecret = facebookApplication.AppSecret;
     }
 }
 public FacebookCanvasModule(FacebookClient fb, IFacebookApplication facebookApplication)
     : base("/canvas")
 {
     Post["/"] = parameters =>
                     {
                         return Request.ParseFacebookSignedRequest(facebookApplication.AppId, facebookApplication.AppSecret).ToString();
                     };
 }
예제 #13
0
        /// <summary>
        ///  Gets the Facebook session from the http request.
        /// </summary>
        /// <param name="settings">
        /// The app settings.
        /// </param>
        /// <param name="httpContext">
        /// The http context.
        /// </param>
        /// <returns>
        /// Returns the Facebook session if found, otherwise null.
        /// </returns>
        internal static FacebookSession GetSession(IFacebookApplication settings, HttpContextBase httpContext)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            return(GetSession(settings, httpContext, null));
        }
예제 #14
0
        public override void OnAuthorization(AuthorizationContext filterContext, IFacebookApplication facebookApplication)
        {
            var authorizer = new FacebookWebContext(facebookApplication, filterContext.HttpContext);

            if (!authorizer.IsAuthorized(string.IsNullOrEmpty(Permissions) ? null : Permissions.Split(',')))
            {
                throw new UnauthorizedAccessException();
            }
        }
예제 #15
0
        /// <summary>
        /// Parse the signed request.
        /// </summary>
        /// <param name="facebookApplication">
        /// The facebook application.
        /// </param>
        /// <param name="signedRequestValue">
        /// The signed request value.
        /// </param>
        /// <returns>
        /// Returns the signed request.
        /// </returns>
        public static FacebookSignedRequest Parse(IFacebookApplication facebookApplication, string signedRequestValue)
        {
            Contract.Requires(facebookApplication != null);
            Contract.Requires(!string.IsNullOrEmpty(facebookApplication.AppSecret));
            Contract.Requires(!String.IsNullOrEmpty(signedRequestValue));
            Contract.Requires(signedRequestValue.Contains("."), Properties.Resources.InvalidSignedRequest);

            return(Parse(facebookApplication.AppSecret, signedRequestValue));
        }
예제 #16
0
        /// <summary>
        /// Set the inner application.
        /// </summary>
        /// <param name="getFacebookApplication">
        /// The get Facebook application.
        /// </param>
        public void InnerSetApplication(Func <IFacebookApplication> getFacebookApplication)
        {
            if (getFacebookApplication == null)
            {
                throw new ArgumentNullException("getFacebookApplication");
            }

            _current = getFacebookApplication();
        }
예제 #17
0
        /// <summary>
        /// Parse the signed request.
        /// </summary>
        /// <param name="facebookApplication">
        /// The Facebook application.
        /// </param>
        /// <param name="signedRequestValue">
        /// The signed request value.
        /// </param>
        /// <returns>
        /// Returns the signed request.
        /// </returns>
        public static FacebookSignedRequest Parse(IFacebookApplication facebookApplication, string signedRequestValue)
        {
            if (facebookApplication == null)
            {
                throw new ArgumentNullException("facebookApplication");
            }

            return(Parse(facebookApplication.AppSecret, signedRequestValue));
        }
예제 #18
0
        /// <summary>
        /// Set the inner application.
        /// </summary>
        /// <param name="facebookApplication">
        /// The Facebook application.
        /// </param>
        public void InnerSetApplication(IFacebookApplication facebookApplication)
        {
            if (facebookApplication == null)
            {
                throw new ArgumentNullException("facebookApplication");
            }

            _current = facebookApplication;
        }
예제 #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookClient"/> class.
 /// </summary>
 /// <param name="facebookApplication">
 /// The facebook application.
 /// </param>
 public FacebookClient(IFacebookApplication facebookApplication)
 {
     if (facebookApplication != null)
     {
         if (!string.IsNullOrEmpty(facebookApplication.AppId) && !string.IsNullOrEmpty(facebookApplication.AppSecret))
         {
             this.AccessToken = string.Concat(facebookApplication.AppId, "|", facebookApplication.AppSecret);
         }
     }
 }
예제 #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookApp"/> class.
 /// </summary>
 /// <param name="facebookApplication">
 /// The facebook application.
 /// </param>
 public FacebookApp(IFacebookApplication facebookApplication)
     : this(FacebookWebContext.Current)
 {
     if (facebookApplication != null)
     {
         if (!string.IsNullOrEmpty(facebookApplication.AppId) && !string.IsNullOrEmpty(facebookApplication.AppSecret))
         {
             this.AccessToken = string.Concat(facebookApplication.AppId, "|", facebookApplication.AppSecret);
         }
     }
 }
예제 #21
0
        protected internal override Uri GetLoginUrl(IFacebookApplication settings, HttpContextBase httpContext, IDictionary <string, object> parameters)
        {
            var authorizer = new CanvasAuthorizer(settings, httpContext)
            {
                ReturnUrlPath    = ReturnUrlPath,
                CancelUrlPath    = CancelUrlPath,
                LoginDisplayMode = LoginDisplayMode
            };

            if (!String.IsNullOrEmpty(Permissions))
            {
                authorizer.Permissions = Permissions.Replace(" ", String.Empty).Split(',');
            }

            if (string.IsNullOrEmpty(CancelUrlPath))
            {
                // set it to this same url instead of going to facebook.com
                var canvasUrlBuilder    = new CanvasUrlBuilder(settings, httpContext.Request);
                var currentPathAndQuery = canvasUrlBuilder.CurrentCanvasPathAndQuery;

                if (currentPathAndQuery.Contains("?"))
                {
                    var parts = currentPathAndQuery.Split('?');
                    if (parts.Length == 2 && !string.IsNullOrEmpty(parts[1]))
                    {
                        var queryStrings = FacebookUtils.ParseUrlQueryString(parts[1]);

                        // remove oauth 2 error querystrings.
                        // error_reason=user_denied&error_denied=access_denied&error_description=The+user+denied+your+request.
                        if (queryStrings.ContainsKey("error_reason"))
                        {
                            queryStrings.Remove("error_reason");
                        }

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

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

                        currentPathAndQuery = parts[0] + "?" + FacebookUtils.ToJsonQueryString(queryStrings);
                    }
                }

                authorizer.CancelUrlPath = currentPathAndQuery;
            }

            return(authorizer.GetLoginUrl(null));
        }
예제 #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookApp"/> class.
 /// </summary>
 /// <param name="facebookApplication">
 /// The facebook application.
 /// </param>
 public FacebookApp(IFacebookApplication facebookApplication)
 {
     if (facebookApplication != null)
     {
         if (!string.IsNullOrEmpty(facebookApplication.AppId) && !string.IsNullOrEmpty(facebookApplication.AppSecret))
         {
             AppId       = facebookApplication.AppId;
             AppSecret   = facebookApplication.AppSecret;
             AccessToken = string.Concat(facebookApplication.AppId, "|", facebookApplication.AppSecret);
         }
     }
 }
        protected internal override System.Uri GetLoginUrl(IFacebookApplication settings, HttpContextBase httpContext, IDictionary<string, object> parameters)
        {
            var authorizer = new CanvasAuthorizer(settings, httpContext)
            {
                ReturnUrlPath = ReturnUrlPath,
                CancelUrlPath = CancelUrlPath,
                LoginDisplayMode = LoginDisplayMode
            };

            if (!String.IsNullOrEmpty(Permissions))
            {
                authorizer.Permissions = Permissions.Replace(" ", String.Empty).Split(',');
            }

            if (string.IsNullOrEmpty(CancelUrlPath))
            {
                // set it to this same url instead of going to facebook.com
                var canvasUrlBuilder = new CanvasUrlBuilder(settings, httpContext.Request);
                var currentPathAndQuery = canvasUrlBuilder.CurrentCanvasPathAndQuery;

                if (currentPathAndQuery.Contains("?"))
                {
                    var parts = currentPathAndQuery.Split('?');
                    if (parts.Length == 2 && !string.IsNullOrEmpty(parts[1]))
                    {
                        var queryStrings = FacebookUtils.ParseUrlQueryString(parts[1]);

                        // remove oauth 2 error querystrings.
                        // error_reason=user_denied&error_denied=access_denied&error_description=The+user+denied+your+request.
                        if (queryStrings.ContainsKey("error_reason"))
                        {
                            queryStrings.Remove("error_reason");
                        }

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

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

                        currentPathAndQuery = parts[0] + "?" + FacebookUtils.ToJsonQueryString(queryStrings);
                    }
                }

                authorizer.CancelUrlPath = currentPathAndQuery;
            }

            return authorizer.GetLoginUrl(null);
        }
예제 #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CanvasUrlBuilder"/> class.
        /// </summary>
        /// <param name="settings">
        /// The settings.
        /// </param>
        /// <param name="httpRequest">
        /// The http request.
        /// </param>
        public CanvasUrlBuilder(IFacebookApplication settings, HttpRequestBase httpRequest)
        {
            Contract.Requires(settings != null);
            Contract.Requires(httpRequest != null);
            Contract.Requires(httpRequest.Url != null);

            _settings = settings;
            _httpRequest = httpRequest;

            // cache it for performance improvements
            _useFacebookBeta = IsBeta(_httpRequest.UrlReferrer);
            _isSecureConnection = IsSecureUrl(_httpRequest.Url);
        }
예제 #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CanvasUrlBuilder"/> class.
        /// </summary>
        /// <param name="settings">
        /// The settings.
        /// </param>
        /// <param name="httpRequest">
        /// The http request.
        /// </param>
        public CanvasUrlBuilder(IFacebookApplication settings, HttpRequestBase httpRequest)
        {
            Contract.Requires(settings != null);
            Contract.Requires(httpRequest != null);
            Contract.Requires(httpRequest.Url != null);

            _settings    = settings;
            _httpRequest = httpRequest;

            // cache it for performance improvements
            _useFacebookBeta    = IsBeta(_httpRequest.UrlReferrer);
            _isSecureConnection = IsSecureUrl(_httpRequest.Url);
        }
예제 #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FacebookWebContext"/> class.
        /// </summary>
        /// <param name="settings">
        /// The settings.
        /// </param>
        /// <param name="httpContext">
        /// The http context.
        /// </param>
        public FacebookWebContext(IFacebookApplication settings, HttpContextBase httpContext)
        {
            Contract.Requires(settings != null);
            Contract.Requires(!string.IsNullOrEmpty(settings.AppId));
            Contract.Requires(!string.IsNullOrEmpty(settings.AppSecret));
            Contract.Requires(httpContext != null);
            Contract.Requires(httpContext.Request != null);
            Contract.Requires(httpContext.Request.Url != null);
            Contract.Requires(httpContext.Request.Params != null);
            Contract.Requires(httpContext.Response != null);

            _facebookApplication = settings;
            _httpContext = httpContext;
        }
예제 #27
0
        /// <summary>
        /// Parse the signed request.
        /// </summary>
        /// <param name="facebookApplication">
        /// The facebook application.
        /// </param>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// Returns the signed request.
        /// </returns>
        public static FacebookSignedRequest Parse(IFacebookApplication facebookApplication, HttpRequestBase request)
        {
            var signedRequest = request.Params.AllKeys.Contains(SignedRequestKey) && !string.IsNullOrEmpty(request.Params[SignedRequestKey])
                       ? Parse(facebookApplication, request.Params[SignedRequestKey])
                       : null;

            if (signedRequest == null && facebookApplication != null && !string.IsNullOrEmpty(facebookApplication.AppId))
            {
                var signedRequestCookieValue = GetSignedRequestCookieValue(facebookApplication.AppId, request);
                signedRequest = Parse(facebookApplication, signedRequestCookieValue);
            }

            return(signedRequest);
        }
예제 #28
0
        public override void OnAuthorization(AuthorizationContext filterContext, IFacebookApplication facebookApplication)
        {
            var authorizer = new FacebookWebContext(facebookApplication, filterContext.HttpContext);

            if (!string.IsNullOrEmpty(Permissions) && Permissions.IndexOf(" ") != -1)
            {
                throw new ArgumentException("Permissions cannot contain whitespace.");
            }

            if (!authorizer.IsAuthorized(ToArrayString(Permissions)))
            {
                filterContext.Result = new RedirectResult(this.LoginUrl ?? "/");
            }
        }
예제 #29
0
        public override void OnAuthorization(AuthorizationContext filterContext, IFacebookApplication settings)
        {
            var authorizer = new FacebookWebContext(settings, filterContext.HttpContext);

            if (!string.IsNullOrEmpty(Permissions) && Permissions.IndexOf(" ") != -1)
            {
                throw new ArgumentException("Permissions cannot contain whitespace.");
            }

            if (!authorizer.IsAuthorized(ToArrayString(Permissions)))
            {
                this.HandleUnauthorizedRequest(filterContext, FacebookApplication.Current);
            }
        }
예제 #30
0
        /// <summary>
        /// Authorization.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        /// <param name="settings">The Facebook application settings.</param>
        /// <exception cref="ArgumentException">Throws if Permissions contains space.</exception>
        public override void OnAuthorization(AuthorizationContext filterContext, IFacebookApplication settings)
        {
            var authorizer = new FacebookWebContext(settings, filterContext.HttpContext);

            if (!string.IsNullOrEmpty(Permissions) && Permissions.IndexOf(" ") != -1)
            {
                throw new ArgumentException("Permissions cannot contain whitespace.");
            }

            if (!authorizer.IsAuthorized(ToArrayString(Permissions)))
            {
                this.HandleUnauthorizedRequest(filterContext, FacebookApplication.Current);
            }
        }
예제 #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FacebookWebContext"/> class.
        /// </summary>
        /// <param name="settings">
        /// The settings.
        /// </param>
        /// <param name="httpContext">
        /// The http context.
        /// </param>
        public FacebookWebContext(IFacebookApplication settings, HttpContextBase httpContext)
        {
            Contract.Requires(settings != null);
            Contract.Requires(!string.IsNullOrEmpty(settings.AppId));
            Contract.Requires(!string.IsNullOrEmpty(settings.AppSecret));
            Contract.Requires(httpContext != null);
            Contract.Requires(httpContext.Request != null);
            Contract.Requires(httpContext.Request.Url != null);
            Contract.Requires(httpContext.Request.Params != null);
            Contract.Requires(httpContext.Response != null);

            _facebookApplication = settings;
            _httpContext         = httpContext;
        }
예제 #32
0
        /// <summary>
        /// Authorization.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        /// <param name="facebookApplication">The Facebook applicatio settings.</param>
        public override void OnAuthorization(AuthorizationContext filterContext, IFacebookApplication facebookApplication)
        {
            var authorizer = new FacebookWebContext(facebookApplication, filterContext.HttpContext);

            if (!string.IsNullOrEmpty(Permissions) && Permissions.IndexOf(" ") != -1)
            {
                throw new ArgumentException("Permissions cannot contain whitespace.");
            }

            if (!authorizer.IsAuthorized(ToArrayString(Permissions)))
            {
                filterContext.Result = new RedirectResult(LoginUrl ?? "/");
            }
        }
예제 #33
0
        /// <summary>
        /// Try parsing the signed request.
        /// </summary>
        /// <param name="facebookApplication">
        /// The facebook application.
        /// </param>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="signedRequest">
        /// The signed request.
        /// </param>
        /// <returns>
        /// Returns true if parsing is successful otherwise false.
        /// </returns>
        public static bool TryParse(IFacebookApplication facebookApplication, HttpRequestBase request, out FacebookSignedRequest signedRequest)
        {
            if (request.Params.AllKeys.Contains(SignedRequestKey) && !string.IsNullOrEmpty(request.Params[SignedRequestKey]))
            {
                return(TryParse(facebookApplication, request.Params[SignedRequestKey], out signedRequest));
            }
            if (facebookApplication != null && !string.IsNullOrEmpty(facebookApplication.AppId))
            {
                var signedRequestCookieValue = GetSignedRequestCookieValue(facebookApplication.AppId, request);
                return(TryParse(facebookApplication, signedRequestCookieValue, out signedRequest));
            }

            signedRequest = null;
            return(false);
        }
예제 #34
0
        public void Start()
        {
            Log.Info("Starting");
            this.UpdateTimer = new System.Threading.Timer(delegate(object state)
            {
                try
                {
                    FacebookOAuthClient authClient = new FacebookOAuthClient(FacebookApplication.Current);
                    string token = authClient.GetApplicationAccessToken() as string;

                    FacebookClient facebook  = new FacebookClient(token);
                    IFacebookApplication app = ConfigurationManager.GetSection("facebookSettings") as IFacebookApplication;

                    Dictionary <string, object> authParameters = new Dictionary <string, object>();
                    authParameters.Add("client_id", app.AppId);
                    authParameters.Add("client_secret", app.AppSecret);
                    authParameters.Add("grant_type", "client_credentials");

                    facebook.Get("/oauth/access_token", authParameters);


                    ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["ComicModelContext"];
                    using (ComicModelContext context = new ComicModelContext(connectionString.ConnectionString))
                    {
                        foreach (User user in context.ListUnsubscriberUsers())
                        {
                            Dictionary <string, object> parameters = new Dictionary <string, object>();
                            parameters.Add("object", "user");
                            parameters.Add("fields", "name,link,email,locale");
                            parameters.Add("callback_url", ComicUrlHelper.GetWebUrl("/User/Subscription"));
                            parameters.Add("verify_token", "erock");


                            //this.Facebook.Post(String.Format("/{0}/subscriptions", ComicConfigSectionGroup.Facebook.AppId), parameters);
                            //this.ActiveUser.IsSubscribed = true;
                        }
                    }
                }
                catch (Exception x)
                {
                    Log.Error(x);
                }
            }, null, new TimeSpan(0, 0, 0), new TimeSpan(1, 0, 0));
        }
예제 #35
0
        public FacebookSession(IDictionary <string, object> dictionary, IFacebookApplication settings)
        {
            if (dictionary == null)
            {
                throw new ArgumentNullException("dictionary");
            }
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            _settings = settings;
            var data = dictionary is JsonObject ? dictionary : FacebookUtils.ToDictionary(dictionary);

            AccessToken = data.ContainsKey("access_token") ? (string)data["access_token"] : null;

            if (!data.ContainsKey("uid") && !string.IsNullOrEmpty(AccessToken))
            {
                data.Add("uid", ParseUserIdFromAccessToken(AccessToken));
            }

            string sUserId = data.ContainsKey("uid") && data["uid"] != null ? data["uid"].ToString() : null;
            long   userId  = 0;

            long.TryParse(sUserId, out userId);
            UserId = userId;

            Secret     = data.ContainsKey("secret") ? (string)data["secret"] : null;
            SessionKey = data.ContainsKey("session_key") ? (string)data["session_key"] : null;

            if (data.ContainsKey("expires"))
            {
                Expires = data["expires"].ToString() == "0" ? DateTime.MaxValue : DateTimeConvertor.FromUnixTime(Convert.ToDouble(data["expires"]));
            }
            else
            {
                Expires = DateTime.MinValue;
            }

            Signature  = data.ContainsKey("sig") ? (string)data["sig"] : null;
            BaseDomain = data.ContainsKey("base_domain") ? (string)data["base_domain"] : null;

            _data = data;
        }
예제 #36
0
        internal virtual protected Uri GetLoginUrl(IFacebookApplication settings, HttpContextBase httpContext, IDictionary<string, object> parameters)
        {
            Contract.Requires(settings != null);
            Contract.Requires(httpContext != null);

            var authorizer = new CanvasAuthorizer(settings, httpContext)
            {
                ReturnUrlPath = this.ReturnUrlPath,
                CancelUrlPath = this.CancelUrlPath,
                LoginDisplayMode = this.LoginDisplayMode
            };

            if (!String.IsNullOrEmpty(this.Permissions))
            {
                authorizer.Permissions = this.Permissions.Replace(" ", String.Empty).Split(',');
            }

            return authorizer.GetLoginUrl(parameters);
        }
예제 #37
0
        /// <summary>
        /// Parses the session value from a cookie.
        /// </summary>
        /// <param name="appSecret">
        /// The app Secret.
        /// </param>
        /// <param name="cookieValue">
        /// The session value.
        /// </param>
        /// <returns>
        /// The Facebook session object.
        /// </returns>
        internal static FacebookSession ParseCookieValue(IFacebookApplication settings, string cookieValue)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (string.IsNullOrEmpty(settings.AppSecret))
            {
                throw new Exception("settings.AppSecret is null.");
            }

            // var cookieValue = "\"access_token=124973200873702%7C2.OAaqICOCk_B4sZNv59q8Yg__.3600.1295118000-100001327642026%7Cvz4H9xjlRZPfg2quCv0XOM5g9_o&expires=1295118000&secret=lddpssZCuPoEtjcDFcWtoA__&session_key=2.OAaqICOCk_B4sZNv59q8Yg__.3600.1295118000-100001327642026&sig=1d95fa4b3dfa5b26c01c8ac8676d80b8&uid=100001327642026\"";
            // var result = FacebookSession.Parse("3b4a872617be2ae1932baa1d4d240272", cookieValue);

            // Parse the cookie
            var dictionary = new JsonObject();
            var parts      = cookieValue.Replace("\"", string.Empty).Split('&');

            foreach (var part in parts)
            {
                if (!string.IsNullOrEmpty(part) && part.Contains("="))
                {
                    var nameValue = part.Split('=');
                    if (nameValue.Length == 2)
                    {
                        var s = FluentHttp.HttpHelper.UrlDecode(nameValue[1]);
                        dictionary.Add(nameValue[0], s);
                    }
                }
            }

            var signature = GenerateSessionSignature(settings.AppSecret, dictionary);

            if (dictionary.ContainsKey("sig") && dictionary["sig"].ToString() == signature)
            {
                return(new FacebookSession(dictionary, settings));
            }

            return(null);
        }
예제 #38
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FacebookWebContext"/> class.
        /// </summary>
        /// <param name="settings">
        /// The settings.
        /// </param>
        /// <param name="httpContext">
        /// The http context.
        /// </param>
        public FacebookWebContext(IFacebookApplication settings, HttpContextBase httpContext)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (string.IsNullOrEmpty(settings.AppId))
            {
                throw new Exception("settings.AppId is null.");
            }
            if (string.IsNullOrEmpty(settings.AppSecret))
            {
                throw new Exception("settings.AppSecret is null.");
            }
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            _facebookApplication = settings;
            _httpContext         = httpContext;
        }
예제 #39
0
        internal virtual protected Uri GetLoginUrl(IFacebookApplication settings, HttpContextBase httpContext, IDictionary <string, object> parameters)
        {
            Contract.Requires(settings != null);
            Contract.Requires(httpContext != null);

            this.ReturnUrlPath = FacebookConfigurationSection.Current.ReturnUrlPath;
            this.CancelUrlPath = FacebookConfigurationSection.Current.CancelUrlPath;

            var authorizer = new CanvasAuthorizer(settings, httpContext)
            {
                ReturnUrlPath    = this.ReturnUrlPath,
                CancelUrlPath    = this.CancelUrlPath,
                LoginDisplayMode = this.LoginDisplayMode
            };

            if (!String.IsNullOrEmpty(this.Permissions))
            {
                authorizer.Permissions = this.Permissions.Replace(" ", String.Empty).Split(',');
            }

            return(authorizer.GetLoginUrl(parameters));
        }
예제 #40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CanvasUrlBuilder"/> class.
        /// </summary>
        /// <param name="settings">
        /// The settings.
        /// </param>
        /// <param name="httpRequest">
        /// The http request.
        /// </param>
        public CanvasUrlBuilder(IFacebookApplication settings, HttpRequestBase httpRequest)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (httpRequest == null)
            {
                throw new ArgumentNullException("httpRequest");
            }
            if (httpRequest.Url == null)
            {
                throw new ArgumentNullException("httpRequest.Url");
            }

            _settings    = settings;
            _httpRequest = httpRequest;

            // cache it for performance improvements
            _useFacebookBeta    = IsBeta(_httpRequest.UrlReferrer);
            _isSecureConnection = IsSecureUrl(_httpRequest.Url);
        }
예제 #41
0
        public FacebookContextSettings()
        {
            IFacebookApplication settings = FacebookApplication.Current;

            if (settings != null)
            {
                CanvasPage = settings.CanvasPage;
                AppId      = settings.AppId;
            }

            FacebookWebContext    facebookContext = FacebookWebContext.Current;
            FacebookSignedRequest signedRequest   = facebookContext.SignedRequest;

            if (settings != null && signedRequest == null)
            {
                signedRequest = ParseSignedRequest(settings);
            }

            if (signedRequest != null)
            {
                AccessToken = signedRequest.AccessToken;
                UserId      = signedRequest.UserId;
            }
        }
예제 #42
0
        private FacebookSignedRequest ParseSignedRequest(IFacebookApplication settings)
        {
            HttpContext context = HttpContext.Current;

            if (context != null)
            {
                HttpContextWrapper contextWrapper = new HttpContextWrapper(context);
                if (contextWrapper.Request.IsAjaxRequest())
                {
                    // ajax requests won't have a signed request, so we need to build it from the current http request
                    // see http://facebooksdk.codeplex.com/discussions/251878

                    try
                    {
                        return(FacebookSignedRequest.Parse(settings, SignedRequest));
                    }
                    catch (Exception exception)
                    {
                        // Facebook posts to the iframe, but only IE supports this so the first request will always fail for non IE browsers
                        if (context.Request.Browser.Browser.Contains("IE"))
                        {
                            throw;
                        }

                        // it doesn't break anything so we'll throw a custom exception so that we can filter it out later
                        InvalidSignedRequestException signedRequestException =
                            new InvalidSignedRequestException(
                                "Invalid SignedRequest - Non - IE (" + SignedRequest + ")",
                                exception);
                        throw signedRequestException;
                    }
                }
            }

            return(null);
        }
        public FacebookRegistrationModule(IFacebookApplication facebookApplication, IAppUserMapper userMapper)
        {
            Get["/register"] =
                _ =>
                {
                    // note: for more options to https://developers.facebook.com/docs/plugins/registration/

                    var fields = new object[]
                                         {
                                             new {name = "name"},
                                             new {name = "email"},
                                             new {name = "location"},
                                             new {name = "gender"},
                                             new {name = "birthday"},
                                             new {name = "password", view = "not_prefilled"},
                                             new
                                                 {
                                                     name = "like",
                                                     description = "Do you like this plugin?",
                                                     type = "checkbox",
                                                     @default = "checked"
                                                 },
                                             new
                                                 {
                                                     name = "phone",
                                                     description = "Phone Number",
                                                     type = "text"
                                                 },
                                             new {name = "captcha"}
                                         };

                    dynamic model = new ExpandoObject();
                    model.FacebookRegistrationUrl = string.Format(
                        "http://www.facebook.com/plugins/registration.php?client_id={0}&redirect_uri={1}&fields={2}&fb_only=true",
                        facebookApplication.AppId,
                        HttpUtility.UrlEncode("http://localhost:45254" + Context.ToFullPath("~/register/facebookcallback")),
                        HttpUtility.UrlEncode(JsonSerializer.Current.SerializeObject(fields)));

                    return View["register", model];
                };

            Post["/register/facebookcallback"] =
                _ =>
                {
                    dynamic signedRequest = Request.ParseFacebookSignedRequest(facebookApplication.AppId, facebookApplication.AppSecret);
                    DateTime expiresOn = signedRequest.expires == 0 ? DateTime.MaxValue : DateTime.UtcNow.AddSeconds(Convert.ToDouble(signedRequest.expires));
                    DateTime issuedAt = DateTimeConvertor.FromUnixTime(signedRequest.issued_at);
                    var accessToken = signedRequest.oauth_token;

                    var name = signedRequest.registration.name;
                    var userId = Convert.ToInt64(signedRequest.user_id);

                    var user = new User
                                   {
                                       FacebookAccessToken = accessToken,
                                       FacebookId = userId,
                                       FacebookName = name,
                                       UserName = name
                                   };

                    userMapper.AddOrUpdate(user);

                    return this.LoginAndRedirect(user.Identifier, expiresOn, "~/facebook");
                };
        }
예제 #44
0
 public FacebookWebAuthorizer(IFacebookApplication settings, HttpContextBase httpContext)
 {
     _request = new FacebookWebContext(settings, httpContext);
 }
 public abstract void OnAuthorization(AuthorizationContext filterContext, IFacebookApplication facebookApplication);
예제 #46
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookWebContext"/> class.
 /// </summary>
 /// <param name="settings">
 /// The settings.
 /// </param>
 public FacebookWebContext(IFacebookApplication settings)
     : this(settings, new HttpContextWrapper(System.Web.HttpContext.Current))
 {
 }
        /// <summary>
        /// Set the inner application.
        /// </summary>
        /// <param name="getFacebookApplication">
        /// The get Facebook application.
        /// </param>
        public void InnerSetApplication(Func<IFacebookApplication> getFacebookApplication)
        {
            if (getFacebookApplication == null)
                throw new ArgumentNullException("getFacebookApplication");

            _current = getFacebookApplication();
        }
 /// <summary>
 /// Set the current Facebook application.
 /// </summary>
 /// <param name="facebookApplication">
 /// The Facebook application.
 /// </param>
 public static void SetApplication(IFacebookApplication facebookApplication)
 {
     Instance.InnerSetApplication(facebookApplication);
 }
예제 #49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookWebContext"/> class.
 /// </summary>
 /// <param name="settings">
 /// The settings.
 /// </param>
 public FacebookWebContext(IFacebookApplication settings)
     : this(settings, new HttpContextWrapper(System.Web.HttpContext.Current))
 {
 }
예제 #50
0
 public CanvasAuthorizer(IFacebookApplication settings, HttpContextBase httpContext)
     : base(settings, httpContext)
 {
 }
예제 #51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FacebookWebClient"/> class.
 /// </summary>
 /// <param name="facebookApplication">
 /// The facebook application.
 /// </param>
 public FacebookWebClient(IFacebookApplication facebookApplication)
     : base(facebookApplication)
 {
     Initialize(FacebookWebContext.Current);
 }
        public CanvasModule(IFacebookApplication fbApp, FacebookClient fb)
        {
            this.HandleFacebookOAuthDialogError(fbApp.AppId, scope: "user_about_me,read_stream");
            this.DropFacebookQueryStrings();

            Post["/"] = _ =>
                            {
                                var canvasPageUrl = Context.FacebookCanvasPageUrl(fbApp.CanvasPage);
                                return View["index", canvasPageUrl];
                            };

            Post["/feed"] = _ =>
            {
                var perms = Context.FacebooPermissions();

                if (!perms.Intersect(new[] { "user_about_me", "read_stream" }).Any())
                    return Response.AsFacebookLogin(fbApp.AppId, scope: "user_about_me,read_stream");

                dynamic model = new JsonObject();
                model.canvasPageUrl = Context.FacebookCanvasPageUrl(fbApp.CanvasPage);
                model.facebookLoginUrl = Context.FacebookLoginUrl(fbApp.AppId, scope: "user_about_me,read_stream");

                if (perms.Contains("user_about_me"))
                {
                    dynamic result = fb.Get("me?fields=picture,name");
                    model.name = result.name;
                    model.picture = result.picture;
                }

                if (perms.Contains("read_stream"))
                {
                    dynamic result = fb.Get("me/feed");
                    model.feeds = result;
                }

                return View["Feed", model];
            };

            Post["/feed/batch"] = _ =>
                                {
                                    var perms = Context.FacebooPermissions();

                                    if (!perms.Intersect(new[] { "user_about_me", "read_stream" }).Any())
                                        return Response.AsFacebookLogin(fbApp.AppId, scope: "user_about_me,read_stream");

                                    dynamic model = new JsonObject();
                                    model.canvasPageUrl = Context.FacebookCanvasPageUrl(fbApp.CanvasPage);
                                    model.facebookLoginUrl = Context.FacebookLoginUrl(fbApp.AppId, scope: "user_about_me,read_stream");

                                    var bp = new Dictionary<string, Tuple<int, FacebookBatchParameter>>();
                                    int bpi = 0;
                                    if (perms.Contains("user_about_me"))
                                        bp.Add("me", new Tuple<int, FacebookBatchParameter>(bpi++, new FacebookBatchParameter("me?fields=picture,name")));

                                    if (perms.Contains("read_stream"))
                                        bp.Add("feeds", new Tuple<int, FacebookBatchParameter>(bpi++, new FacebookBatchParameter("me/feed")));

                                    dynamic result = fb.Batch(bp.Values.Select(t => t.Item2).ToArray());

                                    if (bp.ContainsKey("me"))
                                    {
                                        dynamic me = result[bp["me"].Item1];
                                        if (!(me is Exception))
                                        {
                                            model.name = me.name;
                                            model.picture = me.picture;
                                        }
                                    }

                                    if (bp.ContainsKey("feeds"))
                                    {
                                        dynamic feeds = result[bp["feeds"].Item1];
                                        if (!(feeds is Exception))
                                            model.feeds = feeds;
                                    }

                                    return View["Feed", model];
                                };
        }
예제 #53
0
        /// <summary>
        /// Parse the signed request.
        /// </summary>
        /// <param name="facebookApplication">
        /// The facebook application.
        /// </param>
        /// <param name="signedRequestValue">
        /// The signed request value.
        /// </param>
        /// <returns>
        /// Returns the signed request.
        /// </returns>
        public static FacebookSignedRequest Parse(IFacebookApplication facebookApplication, string signedRequestValue)
        {
            Contract.Requires(facebookApplication != null);
            Contract.Requires(!string.IsNullOrEmpty(facebookApplication.AppSecret));
            Contract.Requires(!String.IsNullOrEmpty(signedRequestValue));
            Contract.Requires(signedRequestValue.Contains("."), Properties.Resources.InvalidSignedRequest);

            return Parse(facebookApplication.AppSecret, signedRequestValue);
        }
예제 #54
0
 /// <summary>
 /// Parse the signed request.
 /// </summary>
 /// <param name="facebookApplication">
 /// The facebook application.
 /// </param>
 /// <param name="request">
 /// The request.
 /// </param>
 /// <returns>
 /// Returns the signed request.
 /// </returns>
 public static FacebookSignedRequest Parse(IFacebookApplication facebookApplication, HttpRequestBase request)
 {
     return request.Params.AllKeys.Contains(SignedRequestKey)
                ? Parse(facebookApplication, request.Params[SignedRequestKey])
                : null;
 }
예제 #55
0
        /// <summary>
        /// Try parsing the signed request.
        /// </summary>
        /// <param name="facebookApplication">
        /// The facebook application.
        /// </param>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="signedRequest">
        /// The signed request.
        /// </param>
        /// <returns>
        /// Returns true if parsing is successful otherwise false.
        /// </returns>
        public static bool TryParse(IFacebookApplication facebookApplication, HttpRequestBase request, out FacebookSignedRequest signedRequest)
        {
            signedRequest = null;

            return request.Params.AllKeys.Contains(SignedRequestKey) &&
                   TryParse(facebookApplication, request.Params[SignedRequestKey], out signedRequest);
        }