In case of a page (instead of full Facebook account), impersonated token is needed to post on page's behalf (post as a page)
556241
public function getPageToken($Token, $Id)
	{
		$options = array(
			CURLOPT_URL				=> 'https://graph.facebook.com/me/accounts?access_token=' . $Token,
			CURLOPT_USERAGENT		=> self::useragent,
			CURLOPT_RETURNTRANSFER	=> true,
			CURLOPT_HEADER			=> 0,
			CURLOPT_POST			=> 0
		);

		$ch = curl_init($url);
		curl_setopt_array($ch, $options);

		$content	= curl_exec($ch);
		$errno		= curl_errno($ch);
		$errmsg		= curl_error($ch);
		$header		= curl_getinfo($ch);

		if ($FacebookResponse = json_decode($content, true))
		{
			foreach ($FacebookResponse['data'] as $Account)
			{
				if ($Account['id'] == $Id) return $Account['access_token'];
			}
		}

		//In case of an error or no account, return regular access token (post as a page admin)
		return $Token;
	}
53985
def get_page_access_token(self, app_id, app_secret, user_token):
        
        url_extend = (
            self._url_base + '/oauth/access_token?grant_type=fb_exchange_token&'
                             'client_id=%(app_id)s&client_secret=%(app_secret)s&fb_exchange_token=%(user_token)s')

        response = self.lib.get(url_extend % {'app_id': app_id, 'app_secret': app_secret, 'user_token': user_token})

        user_token_long_lived = response.text.split('=')[-1]

        response = self.lib.get(self._url_versioned + '/me/accounts?access_token=%s' % user_token_long_lived)
        json = response.json()

        tokens = {item['name']: item['access_token'] for item in json['data'] if item.get('access_token')}

        return tokens
1092509
private static boolean mergeAllowed(Element child, IAuthorizationPrincipal ap)
            throws AuthorizationException {
        if (!child.getTagName().equals("channel")) return true;

        String channelPublishId = child.getAttribute("chanID");
        return ap.canRender(channelPublishId);
    }
925269
def get_fb_token():
    
    global ACCESS_TOKEN
    if not os.path.exists(TOKEN_FILE):
        print "Logging you in to facebook..."
        webbrowser.open(get_url('/oauth/authorize',
                                {'client_id':APP_ID,
                                 'redirect_uri':REDIRECT_URI,
                                 'scope':'manage_pages,publish_stream,photo_upload,user_photos,video_upload'}))
 
        httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), RequestHandler)
        while ACCESS_TOKEN is None:
            httpd.handle_request()
    else:
        ACCESS_TOKEN = open(TOKEN_FILE).read()

    return ACCESS_TOKEN
858069
def process_request(self, request):
        """"""

        # User has already been authed by alternate middleware
        if hasattr(request, "facebook") and request.facebook:
            return

        request.facebook = False

        if not self.is_valid_path(request):
            return

        if self.is_access_denied(request):
            return authorization_denied_view(request)

        request.facebook = Facebook()
        oauth_token = False

        # Is there a token cookie already present?
        if 'oauth_token' in request.COOKIES:
            try:
                # Check if the current token is already in DB
                oauth_token = OAuthToken.objects.get(token=request.COOKIES['oauth_token'])
            except OAuthToken.DoesNotExist:
                request.facebook = False
                return

        # Is there a code in the GET request?
        elif 'code' in request.GET:
            try:
                graph = GraphAPI()

                # Exchange code for an access_token
                response = graph.get('oauth/access_token',
                    client_id = FACEBOOK_APPLICATION_ID,
                    redirect_uri = get_post_authorization_redirect_url(request, canvas=False),
                    client_secret = FACEBOOK_APPLICATION_SECRET_KEY,
                    code = request.GET['code'],
                )
        
                components = parse_qs(response)
                
                # Save new OAuth-token in DB
                oauth_token, new_oauth_token = OAuthToken.objects.get_or_create(
                    token = components['access_token'][0],
                    issued_at = now(),
                    expires_at = now() + timedelta(seconds = int(components['expires'][0]))
                )

            except GraphAPI.OAuthError:
                pass
        
        # There isn't a valid access_token
        if not oauth_token or oauth_token.expired:
            request.facebook = False
            return
        
        # Is there a user already connected to the current token?
        try:
            user = oauth_token.user
            if not user.authorized:
                request.facebook = False
                return
            user.last_seen_at = now()
            user.save()
        except User.DoesNotExist:
            graph = GraphAPI(oauth_token.token)
            profile = graph.get('me')
            
            # Either the user already exists and its just a new token, or user and token both are new
            try:
                user = User.objects.get(facebook_id = profile.get('id'))
                if not user.authorized:
                    if new_oauth_token:
                        user.last_seen_at = now()
                        user.authorized = True
                    else:
                        request.facebook = False
                        return
            except User.DoesNotExist:
                # Create a new user to go with token
                user = User.objects.create(
                    facebook_id = profile.get('id'),
                    oauth_token = oauth_token
                )                    
            
            user.synchronize(profile)
            
            # Delete old access token if there is any and  only if the new one is different
            old_oauth_token = None
            if user.oauth_token != oauth_token:
                old_oauth_token = user.oauth_token
                user.oauth_token = oauth_token
            
            user.save()

            if old_oauth_token:
                old_oauth_token.delete()

        if not user.oauth_token.extended:
            # Attempt to extend the OAuth token, but ignore exceptions raised by
            # bug #102727766518358 in the Facebook Platform.
            #
            # http://developers.facebook.com/bugs/102727766518358/
            try:
                user.oauth_token.extend()
            except:
                pass

        request.facebook.user = user
        request.facebook.oauth_token = oauth_token
1079593
function authFacebook(response) {
    var $this = this;

    return EVT.api({
      url: '/auth/facebook',
      method: 'post',
      data: {
        access: {
          token: response.authResponse.accessToken
        }
      },
      authorization: this.apiKey
    }).then(function (access) {

      // Create User Scope with the user information and Api Key returned
      // from the REST API.
      var user = new EVT.User({
        id: access.evrythngUser,
        apiKey: access.evrythngApiKey
      }, $this);

      // Fetch user dto from the platform and then
      // return initial response
      // TODO: Introduce proper read when DEV-190 merged
      return EVT.api({
        url: '/users/' + user.id,
        authorization: user.apiKey
      }).then(function(userDetails) {
        // Prepare resolve object. Move Facebook user data to
        // 'user.facebook' object
        Utils.extend(user, { facebook: response.user }, true);

        // Merge user data from the platform to User Scope
        Utils.extend(user, userDetails, true);

        response.user = user;

        return response;
      });
    });
  }
857101
function(service, credentials, accounts, keywords) {
  Stream.call(this, service, credentials, accounts, keywords);
  
  // Initialize FBGraph
  fbgraph.setAccessToken(credentials.access_token);
  
  // Set api endpoint URL for subscriber
  this.api_endpoint = 'https://graph.facebook.com/'+ credentials.app_id +'/subscriptions/';
  
  // Initialize subscriber object
  this.subscriber = new Subscriber(credentials, this.callback_url(), this.api_endpoint);
  
  // Initialize responder
  this.responder = new Responder();
  
  // Start listening for incoming
  process.nextTick(function() {
      this.delegateResponder();
    }.bind(this));
  
}
583034
function(){
                /*
                 * page:
                 *    PAGE_SYM S* IDENT? pseudo_page? S*
                 *    '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S*
                 *    ;
                 */
                var tokenStream = this._tokenStream,
                    line,
                    col,
                    identifier  = null,
                    pseudoPage  = null;

                //look for @page
                tokenStream.mustMatch(Tokens.PAGE_SYM);
                var node = this.startNode('Page', tokenStream.curr().range[0], 'body'); //ORION AST generation
                line = tokenStream.token().startLine;
                col = tokenStream.token().startCol;

                this._readWhitespace();

                if (tokenStream.match(Tokens.IDENT)){
                    identifier = tokenStream.token().value;
                    //The value 'auto' may not be used as a page name and MUST be treated as a syntax error.
                    if (identifier.toLowerCase() === "auto"){
                        this._unexpectedToken(tokenStream.token());
                    }
                }

                //see if there's a colon upcoming
                if (tokenStream.peek() === Tokens.COLON){
                    pseudoPage = this._pseudo_page();
                }

                this._readWhitespace();

                this.fire({
                    type:   "startpage",
                    id:     identifier,
                    pseudo: pseudoPage,
                    line:   line,
                    col:    col
                });

                this._readDeclarations(true, true);

                this.fire({
                    type:   "endpage",
                    id:     identifier,
                    pseudo: pseudoPage,
                    line:   line,
                    col:    col
                });
                
                if (identifier){
                	node.id = identifier; //ORION AST generation
            	}
                var rbraceRange = this.findLastTokenRange('RBRACE', node.range[0]); // ORION AST Generation select the RBRACE token
            	this.endNode(node, rbraceRange[1]); //ORION AST Generation
            }
1228441
public static Authenticator createFacebookAuthenticator(String token) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", token);
        return new TokenAuthenticator("_facebook", params);
    }
1302330
function createPage(ref, user) {
  const NOW = new Date().toISOString(),
    users = [userOrRobot(user)],
    meta = {
      createdAt: NOW,
      archived: false,
      published: false,
      publishTime: null,
      updateTime: null,
      urlHistory: [],
      firstPublishTime: null,
      url: '',
      title: '',
      authors: [],
      users,
      history: [{action: 'create', timestamp: NOW, users }],
      siteSlug: sitesService.getSiteFromPrefix(ref.substring(0, ref.indexOf('/_pages'))).slug
    };

  return putMeta(ref, meta);
}
1205987
private void requestProfileAlbums(final List<Object[]> pageAlbums) {
        Callback callback = new Callback() {
            @Override
            public void onCompleted(Response response) {
                FacebookSettingsActivity activity = (FacebookSettingsActivity) getActivity();
                if (activity == null || activity.isFinishing()) {
                    return;
                }

                if (response != null && response.getError() == null) {
                    Object[] appAlbum = null;
                    List<Object[]> albums = new ArrayList<Object[]>();

                    GraphObject graphObject = response.getGraphObject();
                    if (graphObject != null) {
                        JSONObject jsonObject = graphObject.getInnerJSONObject();
                        try {
                            JSONArray jsonArray = jsonObject
                                    .getJSONArray(FacebookEndpoint.ALBUMS_LISTING_RESULT_DATA_KEY);
                            long cursorId = 1L + pageAlbums.size();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                try {
                                    // Get data from json.
                                    JSONObject album = jsonArray.getJSONObject(i);
                                    String id = album.getString(FacebookEndpoint.ALBUMS_LISTING_FIELD_ID);
                                    String name = album.getString(FacebookEndpoint.ALBUMS_LISTING_FIELD_NAME);
                                    String type = album.getString(FacebookEndpoint.ALBUMS_LISTING_FIELD_TYPE);
                                    String privacy = album.getString(FacebookEndpoint.ALBUMS_LISTING_FIELD_PRIVACY);
                                    boolean canUpload = album
                                            .getBoolean(FacebookEndpoint.ALBUMS_LISTING_FIELD_CAN_UPLOAD);

                                    // Filter out albums that do not allow upload.
                                    if (canUpload && id != null && id.length() > 0 && name != null && name.length() > 0
                                            && type != null && type.length() > 0 && privacy != null
                                            && privacy.length() > 0) {
                                        String graphPath = id + FacebookEndpoint.TO_UPLOAD_PHOTOS_GRAPH_PATH;
                                        if (FacebookEndpoint.DEFAULT_ALBUM_TYPE.equals(type)) {
                                            appAlbum = new Object[]{APP_ALBUM_CURSOR_ID, FacebookEndpoint.DestinationId.PROFILE,
                                                    name, graphPath, FacebookEndpoint.APP_ALBUM_PRIVACY, null};
                                        } else {
                                            albums.add(new Object[]{cursorId, FacebookEndpoint.DestinationId.PROFILE,
                                                    name, graphPath, privacy, null});
                                            cursorId++;
                                        }
                                    }
                                } catch (JSONException e) {
                                    // Do nothing.
                                }
                            }
                        } catch (JSONException e) {
                            // Do nothing.
                        }
                    }

                    // If not already present, construct row to represent the default app album that will be auto
                    // created.
                    if (appAlbum == null) {
                        appAlbum = new Object[]{APP_ALBUM_CURSOR_ID, FacebookEndpoint.DestinationId.PROFILE,
                                activity.getString(R.string.wings_facebook__app_album_default_name), FacebookEndpoint.APP_ALBUM_GRAPH_PATH,
                                FacebookEndpoint.APP_ALBUM_PRIVACY, null};
                    }

                    // Construct matrix cursor.
                    mAlbumCursor.addRow(appAlbum);
                    for (Object[] pageAlbum : pageAlbums) {
                        mAlbumCursor.addRow(pageAlbum);
                    }
                    for (Object[] album : albums) {
                        mAlbumCursor.addRow(album);
                    }

                    // Set adapter.
                    setListAdapter(new SimpleCursorAdapter(activity, R.layout.facebook_album_list_view_item,
                            mAlbumCursor, new String[]{CURSOR_ALBUM_NAME, CURSOR_ALBUM_PRIVACY}, new int[]{
                            R.id.album_name, R.id.album_privacy}
                    ));
                } else {
                    // Finish Activity with error.
                    activity.mHasErrorOccurred = true;
                    activity.tryFinish();
                }
            }
        };

        mFacebookEndpoint.requestAlbums(FacebookEndpoint.ME, callback);
    }
130811
def post(self, request, provider=None):
        
        # if settings.CAS_FEDERATE is not True redirect to the login page
        if not settings.CAS_FEDERATE:
            logger.warning("CAS_FEDERATE is False, set it to True to use federation")
            return redirect("cas_server:login")
        # POST with a provider suffix, this is probably an SLO request. csrf is disabled for
        # allowing SLO requests reception
        try:
            provider = FederatedIendityProvider.objects.get(suffix=provider)
            auth = self.get_cas_client(request, provider)
            try:
                auth.clean_sessions(request.POST['logoutRequest'])
            except (KeyError, AttributeError):
                pass
            return HttpResponse("ok")
        # else, a User is trying to log in using an identity provider
        except FederatedIendityProvider.DoesNotExist:
            # Manually checking for csrf to protect the code below
            reason = CsrfViewMiddleware().process_view(request, None, (), {})
            if reason is not None:  # pragma: no cover (csrf checks are disabled during tests)
                return reason  # Failed the test, stop here.
            form = forms.FederateSelect(request.POST)
            if form.is_valid():
                params = utils.copy_params(
                    request.POST,
                    ignore={"provider", "csrfmiddlewaretoken", "ticket", "lt"}
                )
                if params.get("renew") == "False":
                    del params["renew"]
                url = utils.reverse_params(
                    "cas_server:federateAuth",
                    kwargs=dict(provider=form.cleaned_data["provider"].suffix),
                    params=params
                )
                return HttpResponseRedirect(url)
            else:
                return redirect("cas_server:login")
128728
function() {	
		console.warn("FB.login...");
		FB.login(function(response) {
			console.warn("FB.login", response);
			if (response.status === 'connected') {
				doFBLogin_connected(response);
			} else {
				// fail
			}
		}); //, {scope: 'public_profile,email,user_friends'}); // what permissions??
		// see https://developers.facebook.com/docs/facebook-login/permissions
	}
583363
def _make_fake_message(self, user_id, page_id, payload):
        

        event = {
            'sender': {
                'id': user_id,
            },
            'recipient': {
                'id': page_id,
            },
            'postback': {
                'payload': ujson.dumps(payload),
            },
        }

        return FacebookMessage(event, self, False)
955243
function s(originalUrl) {
  var parts = new url.URL(originalUrl);
  return url.format(parts, { auth: false });
}
687023
def resolve_page(self, request, context, is_staff):
        """"""
        path = context['path']
        lang = context['lang']
        page = Page.objects.from_path(
            path, lang,
            exclude_drafts=(not is_staff))
        if page:
            return page
        # if the complete path didn't worked out properly
        # and if didn't used PAGE_USE_STRICT_URL setting we gonna
        # try to see if it might be a delegation page.
        # To do that we remove the right part of the url and try again
        # to find a page that match
        if not settings.PAGE_USE_STRICT_URL:
            path = remove_slug(path)
            while path is not None:
                page = Page.objects.from_path(
                    path, lang,
                    exclude_drafts=(not is_staff))
                # find a match. Is the page delegating?
                if page:
                    if page.delegate_to:
                        return page
                path = remove_slug(path)

        return None
370292
function TistoryStrategy(options, verify) {
  var oauthHost = 'https://www.tistory.com';
  options = options || {};
  options.authorizationURL = options.authorizationURL || oauthHost + '/oauth/authorize';
  options.tokenURL = options.tokenURL || oauthHost + '/oauth/access_token/';

  options.customHeaders = options.customHeaders || {};

  if (!options.customHeaders['User-Agent']) {
    options.customHeaders['User-Agent'] = options.userAgent || 'passport-tistory';
  }

  OAuth2Strategy.call(this, options, verify);
  this.name = 'tistory';
  this._userProfileURL = 'https://www.tistory.com/apis/blog/info?output=json';
  this._oauth2.getOAuthAccessToken = function (code, params, callback) {
    var params = params || {};
    params['client_id'] = this._clientId;
    params['client_secret'] = this._clientSecret;
    var codeParam = (params.grant_type === 'refresh_token') ? 'refresh_token' : 'code';
    params[codeParam] = code;


    var url = this._getAccessTokenUrl() + "?" + querystring.stringify(params);

    request(url, function (error, response, data) {
      if (error) callback(error);
      else {
        var results;
        try {
          // As of http://tools.ietf.org/html/draft-ietf-oauth-v2-07
          // responses should be in JSON
          results = JSON.parse(data);
        }
        catch (e) {
          // .... However both Facebook + Github currently use rev05 of the spec
          // and neither seem to specify a content-type correctly in their response headers :(
          // clients of these services will suffer a *minor* performance cost of the exception
          // being thrown
          results = querystring.parse(data);
        }
        var access_token = results["access_token"];
        var refresh_token = results["refresh_token"];
        delete results["refresh_token"];
        callback(null, access_token, refresh_token, results); // callback results =-=
      }
    });
  }

}