facebook will send back the token and profile
420935
function(req, token, refreshToken, profile, done) {
        // asynchronous
        process.nextTick(function() {
            var User = app.userModel;
            // find the user in the database based on their facebook id
            User.findOne({ 'facebook.id' : profile.id }, function(err, user) {

                // if there is an error, stop everything and return that
                // ie an error connecting to the database
                if (err)
                    return done(err);

                // if the user is found, then log them in
                if (user) {
                    if (req.session.reauthenticate) {
                      delete req.session.reauthenticate;
                      req.session.loginTime = new Date();
                    }
                    return done(null, user); // user found, return that user
                } else {
                    // if there is no user found with that facebook id, create them
                    var newUser            = new User();

                    // set all of the facebook information in our user model
                    newUser.facebook.id    = profile.id; // set the users facebook id
                    newUser.facebook.token = token; // we will save the token that facebook provides to the user
                    newUser.facebook.name  = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned
                    newUser.facebook.email = profile.emails[0].value; // facebook can return multiple emails so we'll take the first

                    //XXX if the user with that email already exists -- associate with facebook (prompt for password?)
                    //XXX need a way for a currently logged in user to login to facebook and associate accounts

                    // save our user to the database
                    newUser.save(function(err) {
                        if (err)
                            return done(err);
                        if (req.session.reauthenticate) {
                          delete req.session.reauthenticate;
                          req.session.loginTime = new Date();
                        }
                        // if successful, return the new user
                        return done(null, newUser);
                    });
                }

            });
        });

    }
269515
function updateUserProfileWithToken(messagingToken) {
  const currentUserUid =
    firebase.auth().currentUser && firebase.auth().currentUser.uid
  if (!currentUserUid) {
    return Promise.resolve();
  }
  return firebase
    .firestore()
    .collection('users')
    .doc(currentUserUid)
    .update({
      messaging: {
        mostRecentToken: messagingToken,
        updatedAt: firebase.firestore.FieldValue.serverTimestamp()
      }
    })
}
1273743
public function tokenResetAction()
    {
        $token = $this->get('request_stack')->getCurrentRequest()->get('token');
        if (!$token) {
            return $this->render('FOMUserBundle:Login:error-notoken.html.twig');
        }

        $user = $this->getDoctrine()->getRepository("FOMUserBundle:User")->findOneByResetToken($token);
        if (!$user) {
            $mail = $this->container->getParameter('fom_user.mail_from_address');
            return $this->render('FOMUserBundle:Login:error-notoken.html.twig', array(
                'site_email' => $mail));
        }

        $this->setResetToken($user);

        return $this->redirect($this->generateUrl('fom_user_password_send'));
    }
1044847
async def _handle_fb_response(self, response: aiohttp.ClientResponse):
        

        ok = response.status == 200

        if not ok:
            # noinspection PyBroadException
            try:
                error = (await response.json())['error']['message']
            except Exception:
                error = '(nothing)'

            raise PlatformOperationError('Facebook says: "{}"'
                                         .format(error))
825557
function getUserProfile(callback) {
    if (_.isUndefined(callback)) {
    } else {
      var u = baseUrl + "/me";
      var tokenData = this.getAuthToken();
      if (tokenData.type != "bearer") {
        throw new Error("Invalid token type. Must use a token of type bearer.");
      }
      return helper.get(tokenData, u, callback);
    }
  }
1211112
def send_facebook(self, token):
        
        self.send_struct('<B%iB' % len(token), 81, *map(ord, token))
        self.facebook_token = token
660846
public function setExtendedAccessToken() {
    try {
      // need to circumvent json_decode by calling _oauthRequest
      // directly, since response isn't JSON format.
      $access_token_response = $this->_oauthRequest(
        $this->getUrl('graph', '/oauth/access_token'),
        $params = array(
          'client_id' => $this->getAppId(),
          'client_secret' => $this->getAppSecret(),
          'grant_type' => 'fb_exchange_token',
          'fb_exchange_token' => $this->getAccessToken(),
        )
      );
    }
    catch (FacebookApiException $e) {
      // most likely that user very recently revoked authorization.
      // In any event, we don't have an access token, so say so.
      return false;
    }

    if (empty($access_token_response)) {
      return false;
    }

    $response_params = array();
    parse_str($access_token_response, $response_params);

    if (!isset($response_params['access_token'])) {
      return false;
    }

    $this->destroySession();

    $this->setPersistentData(
      'access_token', $response_params['access_token']
    );
  }
825050
def token_create(self, label=None, expiry=None, scopes=None, **kwargs):
        
        if label:
            kwargs['label'] = label
        if expiry:
            if isinstance(expiry, datetime):
                expiry = datetime.strftime(expiry, "%Y-%m-%dT%H:%M:%S")
            kwargs['expiry'] = expiry
        if scopes:
            kwargs['scopes'] = scopes

        result = self.client.post('/profile/tokens', data=kwargs)

        if not 'id' in result:
            raise UnexpectedResponseError('Unexpected response when creating Personal Access '
                    'Token!', json=result)

        token = PersonalAccessToken(self.client, result['id'], result)
        return token
351229
function _loadUserFromToken(){
    return BB
        .bind(this)
        .then(function() {
            return grasshopper.request(this.token).users.current();
        })
        .then(function(user){
            this.user = user;
        });
}
393577
function(req, res, next) {
    var accessToken = req.accessToken;
    var profileUrl = 'https://apis.live.net/v5.0/me?access_token=' + accessToken;
    request.get({ url: profileUrl, json: true }, function(err, response, profile) {
      if (err) {
        res.status(500).send(err);
        return;
      }
      req.profile = profile;
      next();
    });
  }
670160
private String token() {
        List<String> key = new ArrayList<String>();
        key.add(email);
        key.add(getRemoteURL().toExternalForm().toLowerCase());
        Log.v(TAG, "FacebookAuthorizer looking up key: %s from list of access tokens", key);
        return sRegisteredTokens.get(key);
    }
432864
private User fetch(final String token) {
        try {
            return new DefaultFacebookClient(
                token,
                this.requestor,
                new DefaultJsonMapper(),
                Version.LATEST
            ).fetchObject(
                "me", User.class
            );
        } catch (final FacebookException ex) {
            throw new IllegalArgumentException(ex);
        }
    }
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;
	}
770716
public function getData()
    {
        if (! $this->getReturnUrl()) {
            $this->validate('notifyUrl');
        }

        $data = $this->getBaseAuthorizeData();

        // If a token is being used, then include the token data.
        // With a valid token or card reference, the user is just asked
        // for the CVV and not any remaining card details.

        $data = $this->getTokenData($data);

        // ReturnUrl is for legacy usage.

        $data['NotificationURL'] = $this->getNotifyUrl() ?: $this->getReturnUrl();

        // Set the profile only if it is LOW (for iframe use) or NORMAL (for full-page redirects)

        $profile = strtoupper($this->getProfile());

        if ($profile === static::PROFILE_NORMAL || $profile === static::PROFILE_LOW) {
            $data['Profile'] = $this->getProfile();
        }

        $createCard = $this->getCreateToken() ?: $this->getCreateCard();

        if ($createCard !== null) {
            $data['CreateToken'] = $createCard ? static::CREATE_TOKEN_YES : static::CREATE_TOKEN_NO;
        }

        return $data;
    }
1371098
function normalizeUserData() {
		function handler(req, res, next) {
			if (req.session && !req.session.user && req.session.auth && req.session.auth.loggedIn) {
				var user = {};
				if (req.session.auth.github) {
					user.image = 'http://1.gravatar.com/avatar/'+req.session.auth.github.user.gravatar_id+'?s=48';
					user.name = req.session.auth.github.user.name;
					user.id = 'github-'+req.session.auth.github.user.id;
				}
				if (req.session.auth.twitter) {
					user.image = req.session.auth.twitter.user.profile_image_url;
					user.name = req.session.auth.twitter.user.name;
					user.id = 'twitter-'+req.session.auth.twitter.user.id_str;
				}
				if (req.session.auth.facebook) {
					user.image = req.session.auth.facebook.user.picture;
					user.name = req.session.auth.facebook.user.name;
					user.id = 'facebook-'+req.session.auth.facebook.user.id;

					// Need to fetch the users image...
					https.get({
						'host': 'graph.facebook.com'
						, 'path': '/me/picture?access_token='+req.session.auth.facebook.accessToken
					}, function(response) {
						user.image = response.headers.location;
						req.session.user = user;
						next();
					}).on('error', function(e) {
						req.session.user = user;
						next();
					});
					return;
				}
				req.session.user = user;
			}
			next();
		}
		return handler;
	}
12389
def get_profile_data(self, raw_token):
        """"""
        token_data = json.loads(raw_token)
        # This header is the 'magic' that makes this empty GET request work.
        headers = {'Authorization': 'OAuth %s' % token_data['access_token']}

        try:
            response = self.request('get', self.profile_url, headers=headers)
            response.raise_for_status()
        except RequestException as e:
            logger.error('Unable to fetch user profile: {0}'.format(e))
            return None
        else:
            return response.json() or response.text
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