add/revoke a pass token returns the token or undefined if token store fail
776967
function (uid, token_source, onDone) {
	
	// generate a valid token to be returned
	var token = UTIL.createToken();
	
	// store token back to DB
	var onUpdated = function (error) {
		if (error) {
			var err = new Error(error.toString());
			err.name = "l_createToken Error";
			UTIL.safeCall(onDone, err);
		}
		else {
			LOG.warn('pass_token [' + token + '] stored');
			UTIL.safeCall(onDone, null, token);			
		}
	};
	l_updateUser({uid: uid}, 'pass_tokens.' + token, token_source, onUpdated);
}
835640
def revoke_token(token_id, user):
    
    try:
        token = TokenBlacklist.query.filter_by(id=token_id, user_identity=user).one()
        token.revoked = True
        db.session.commit()
    except NoResultFound:
        raise TokenNotFound("Could not find the token {}".format(token_id))
1054021
function checkToken (client) {
  debug("checkToken");
  return Promise.promisify(client.user.get, client.user)({})
    .then(null, function (err) {
      console.error("Failed to validate Github OAuth token: please check API access (network?) or force re-authentication with 'github-todos auth --force'");
      throw err;
    })
    .then(function () {
      // Store client for next API calls
      return promisifyClient(client);
    });
}
644990
def on_post(self, req, resp):
        

        token = req.get_param('token')
        token_type_hint = req.get_param('token_type_hint')

        # errors or not, disable client caching along the way
        # per the spec
        resp.disable_caching()

        if not token:
            resp.status = falcon.HTTP_400
            resp.serialize({
                'error': 'invalid_request',
                'error_description': 'A token parameter is required during '
                                     'revocation according to RFC 7009.',
                'error_uri': 'tools.ietf.org/html/rfc7009#section-2.1',
            })
        elif token_type_hint == 'refresh_token':
            resp.status = falcon.HTTP_400
            resp.serialize({
                'error': 'unsupported_token_type',
                'error_description': 'Currently only access_token types can '
                                     'be revoked, NOT refresh_token types.',
                'error_uri': 'tools.ietf.org/html/rfc7009#section-2.2.1',
            })
        else:
            # ignore return code per section 2.2
            self.revoke_token(token)
            resp.status = falcon.HTTP_200
1061233
function signOutUser(req, res, next) {
    debug('Signing out user');
    //make a best attempt effort at revoking the tokens
    var accessToken = req.session.auth ? req.session.auth.access_token: null;
    var refreshToken = req.session.auth ? req.session.auth.refresh_token: null;
    if (accessToken) {
        debug('Revoking access token');
        request.get({
            url: LOGOUT_URL,
            qs: {
                token: accessToken
            }
        }, function(err, response, body) {
            if (err) {
                debug('Error revoking access token', err.message);
            } else {
                debug('Revoked access token, %s', response.statusCode);
            }
        });
    }

    if (refreshToken) {

        request.get({
            url: LOGOUT_URL,
            qs: {
                token: refreshToken
            }
        }, function (err, response, body) {
            if (err) {
                debug('Error revoking refresh token', err.message);
            } else {
                debug('Revoked refresh token, %s', response.statusCode);
            }
        });
    }
    delete req.session.auth;
    res.sendStatus(200);
}
429425
function handleUnauthorizedAPIResponse(error) {
    const response = error && error.response;
    const errorStatus = response && response.status;
    const requestUrl = response && response.config && response.config.url;
    const requestIsTokenRefresh = requestUrl === authenticatedAPIClient.refreshAccessTokenEndpoint;

    switch (errorStatus) { // eslint-disable-line default-case
      case 401:
        if (requestIsTokenRefresh) {
          logInfo(`Unauthorized token refresh response from ${requestUrl}. This is expected if the user is not yet logged in.`);
        } else {
          logInfo(`Unauthorized API response from ${requestUrl}`);
        }
        break;
      case 403:
        logInfo(`Forbidden API response from ${requestUrl}`);
        break;
    }

    return Promise.reject(error);
  }
570098
def revoke_token
      r = HTTP.auth('Bearer ' + @access_token).post(API + '/auth/token/revoke')
      raise ApiError.new(r) if r.code != 200
    end
1081651
def delete(self, token_id, *args, **kwargs):
        

        return self.client._put(
            "{0}/revoked".format(
                self._url(token_id)
            ),
            None,
            *args,
            **kwargs
        )
983227
function TokenRequest(authenticate, options) {

	var self = this;
	this.status = 'expired';
	this.pendingCallbacks = [];

	// execute accumulated callbacks during the 'pending' state
	function fireCallbacks(err, token) {
		self.pendingCallbacks.forEach(function (callback) {
			callback(err, token);
		});
		self.pendingCallbacks = [];
	}

	TokenRequest.prototype.get = function (callback) {

		if (this.status == 'expired') {

			this.status = 'pending';
			this.pendingCallbacks.push(callback);

			authenticate(options, function (err, token) {
				if (err) {
					self.status = 'expired';
					return fireCallbacks(err, null);
				}
				self.issued = Date.now();
				self.duration = options.expiration || 60 * 60 * 1000;
				self.token = token;
				self.status = 'completed';
				return fireCallbacks(null, token);
			});

		} else if (this.status == 'pending') {
			// wait for the pending request instead of issuing a new one
			this.pendingCallbacks.push(callback);
		} else if (this.status == 'completed') {

			if (this.issued + this.duration < Date.now()) {
				this.status = 'expired';
				debug('token is expired, a new token will be requested');
				this.get(callback);
			} else {
				callback(null, this.token);
			}

		}
	};
}
721031
function checkAccess({ accessToken, id, model, method, options, ctx }) {

     return new Promise((resolve, reject) => {
         // ignore checking if does not enable auth
         if (model.app.isAuthEnabled) {
             if (!model.app.models.ACL) {
                 console.log('ACL has not been setup, skipping access check.')
                 resolve(true);
             } else {
                 model.checkAccess(accessToken, id, method, ctx,
                     ((err, allowed) => {
                         if (err)
                             reject(err);
                         else if (allowed)
                             resolve(allowed);
                         else
                             reject(`ACCESS_DENIED`);
                     }));
             }
         } else {
             resolve(true);
         }
     })

 }
57912
def validate_token(self, token):
    '''
    '''
    # A token that is finished or revoked is not valid
    subid = None
    if not token.endswith(('finished','revoked')):
        subid = self.generate_subid(token=token)
        data_base = "%s/%s" %(self.data_base, subid)
        if not os.path.exists(data_base):
            subid = None
    return subid
1082209
public function resetPassword($token = null, $options = []) {
		$options = Hash::merge($this->getConfig('resetPassword'), $options);

		$tokenParam = $this->_getRequest()->getQuery($options['queryParam']);
		if (!empty($tokenParam)) {
			$token = $tokenParam;
		}

		// Check of the token exists
		try {
			$entity = $this->UserTable->verifyPasswordResetToken($token, $options['tokenOptions']);
		} catch (RecordNotFoundException $e) {
			if (empty($options['errorMessage']) && $options['errorMessage'] !== false) {
				$options['errorMessage'] = $e->getMessage();
			}

			$redirect = $this->handleFlashAndRedirect('invalidError', $options);
			if ($redirect instanceof Response) {
				return $redirect;
			}
			$entity = $this->UserTable->newEntity();
		}

		// Check if the token has expired
		if ($entity->get('token_is_expired') === true) {
			if (empty($options['invalidErrorMessage'])) {
				$options['invalidErrorMessage'] = $e->getMessage();
			}
			$redirect = $this->handleFlashAndRedirect('expiredError', $options);
			if ($redirect instanceof Response) {
				return $redirect;
			}
		}

		// Handle the POST
		if ($this->_getRequest()->is('post')) {
			$entity = $this->UserTable->patchEntity($entity, $this->_getRequest()->getData());
			if ($this->UserTable->resetPassword($entity)) {
				$redirect = $this->handleFlashAndRedirect('success', $options);
			} else {
				$redirect = $this->handleFlashAndRedirect('error', $options);
			}
			if ($redirect instanceof Response) {
				return $redirect;
			}
		} else {
			$entity = $this->UserTable->newEntity();
		}

		$this->_setViewVar('entity', $entity);
	}
253019
function (error_msg) {
    var self = this;
    return function (err, resp) {
      self._lock_refresh = undefined;
      if (!err) {
        var auth = JSON.parse(resp);
        if (!auth.error) {
          setToken.call(self, auth);
          return emit.call(self, 'auth.refresh', token.call(self));
        }
        return emit.call(self, 'auth.fail', error_msg + ': ' + JSON.stringify(auth.error));
      }
      return emit.call(self, 'auth.fail', error_msg + ': ' + JSON.stringify(err));
    };
  }
365068
def revoke_tokens(self):
        

        self.is_active = False
        self.save()

        for access_token in self.access_tokens.all():
            access_token.revoke()
477369
function () {
                try {
                    authHandler.sign(authInterface, context.item.request, function (err) {
                        // handle all types of errors in one place, see catch block
                        if (err) { throw err; }

                        done();
                    });
                }
                catch (err) {
                    // handles synchronous and asynchronous errors in auth.sign
                    run.triggers.console(context.coords,
                        'warn',
                        'runtime~' + authType + '.auth: could not sign the request: ' + (err.message || err),
                        err
                    );

                    // swallow the error, we've warned the user
                    done();
                }
            }
1056672
function() {
      var oauth_accessToken = StackMob.Storage.retrieve('oauth2.accessToken');
      var oauth_macKey = StackMob.Storage.retrieve('oauth2.macKey');
      var oauth_expires = StackMob.Storage.retrieve('oauth2.expires');
      var oauth_refreshToken = StackMob.Storage.retrieve(StackMob.REFRESH_TOKEN_KEY);
      var userSchemaInfo = StackMob.Storage.retrieve('oauth2.userSchemaInfo');
      var oauth_schema = null;

      try {
        oauth_schema = JSON.parse(userSchemaInfo);
      } catch (e) { /* Harmless if this fails (in theory!)*/ }

      if (_.every([oauth_accessToken, oauth_macKey, oauth_expires, oauth_refreshToken, oauth_schema])) {
        var creds = {
          'oauth2.accessToken' : oauth_accessToken,
          'oauth2.macKey' : oauth_macKey,
          'oauth2.expires' : oauth_expires,
          'oauth2.userSchemaInfo' : oauth_schema
        };
        creds[StackMob.REFRESH_TOKEN_KEY] = oauth_refreshToken;

        return creds;
      } else {
        return {};
      }

    }
980538
def revoke(client_id, client_secret,
        client_email=None, private_key=None,
        access_token=None, refresh_token=None,
        identity=None, prefix=None, suffix=None):

    

    if client_email and private_key:
        raise ValueError('Two-legged OAuth does not use revokable tokens.')
    
    credentials = oauth.Credentials.find(
        complete=True,
        interactive=False,
        identity=identity,
        client_id=client_id,
        client_secret=client_secret,
        access_token=access_token,
        refresh_token=refresh_token,
        prefix=prefix,
        suffix=suffix,
        )

    retval = credentials.revoke()
    keyring.delete(credentials.identity)
    return retval