The awaiting authorization screen
3732
public function awaitingAuthorization()
    {
        $deliveryExecution = $this->getCurrentDeliveryExecution();
        $deliveryExecutionStateService = $this->getServiceManager()->get(DeliveryExecutionStateService::SERVICE_ID);
        $executionState = $deliveryExecution->getState()->getUri();

        $runDeliveryUrl = _url('runDeliveryExecution', null, null, array('deliveryExecution' => $deliveryExecution->getIdentifier()));

        // if the test is in progress, first pause it to avoid inconsistent storage state
        if (DeliveryExecutionState::STATE_ACTIVE == $executionState) {
            $deliveryExecutionStateService->pauseExecution($deliveryExecution, [
                'reasons' => ['category' => 'System'],
                'comment' => __('System generated pause.'),
            ]);
        }

        // we need to change the state of the delivery execution
        if (!in_array($executionState , array(DeliveryExecutionState::STATE_FINISHED, DeliveryExecutionState::STATE_TERMINATED))) {
            if (DeliveryExecutionState::STATE_AUTHORIZED !== $executionState) {
                $deliveryExecutionStateService->waitExecution($deliveryExecution);
            }

            $this->setData('deliveryExecution', $deliveryExecution->getIdentifier());
            $this->setData('deliveryLabel', addslashes($deliveryExecution->getLabel()));
            $this->setData('returnUrl', $this->getReturnUrl());
            $this->setData('cancelUrl', _url('cancelExecution', 'DeliveryServer', 'taoProctoring', ['deliveryExecution' => $deliveryExecution->getIdentifier()]));
            $this->setData('cancelable', $deliveryExecutionStateService->isCancelable($deliveryExecution));
            $this->setData('userLabel', common_session_SessionManager::getSession()->getUserLabel());
            $this->setData('client_config_url', $this->getClientConfigUrl());
            $this->setData('showControls', true);
            $this->setData('runDeliveryUrl', $runDeliveryUrl);

            //set template
            $this->setData('homeUrl', $this->getServiceManager()->get(DefaultUrlService::SERVICE_ID)->getUrl('ProctoringHome'));
            $this->setData('logout', $this->getServiceManager()->get(DefaultUrlService::SERVICE_ID)->getUrl('ProctoringLogout'));
            $this->setData('content-template', 'DeliveryServer/awaiting.tpl');
            $this->setData('content-extension', 'taoProctoring');
            $this->setView('DeliveryServer/layout.tpl', 'taoDelivery');
        } else {
            // inconsistent state
            common_Logger::i(get_called_class() . '::awaitingAuthorization(): cannot wait authorization for delivery execution ' . $deliveryExecution->getIdentifier() . ' with state ' . $executionState);
            return $this->redirect($this->getReturnUrl());
        }
    }
212501
def client_ready(self):
        
        if not self.auth_complete():
            return False
        if not self._client_ready():
            self._connection.work()
            return False
        return True
775463
void notifyAcceptBind(Bind bindParameter) throws IllegalStateException {
        lock.lock();
        try {
            if (request == null) {
                request = new BindRequest(bindParameter, responseHandler);
                requestCondition.signal();
            } else {
                throw new IllegalStateException("Already waiting for acceptance bind");
            }
        } finally {
            lock.unlock();
        }
    }
1110284
def on_aborted(self):
        

        print('Authentication aborted')

        # Authentication aborted
        self.is_authenticating.acquire()
        self.is_authenticating.notify_all()
        self.is_authenticating.release()
199433
def lock_status(account_id, resource_id, parent_id):
    
    return output(
        Client(BASE_URL, account_id).lock_status(resource_id, parent_id))
957749
public void startAuthorizationProcess(final Context context, ResponseListener listener) {
        authorizationQueue.add(listener);

        //start the authorization process only if this is the first time we ask for authorization
        if (authorizationQueue.size() == 1) {
            try {
                if (preferences.clientId.get() == null) {
                    logger.info("starting registration process");
                    invokeInstanceRegistrationRequest(context);
                } else {
                    logger.info("starting authorization process");
                    invokeAuthorizationRequest(context);
                }
            } catch (Throwable t) {
                handleAuthorizationFailure(t);
            }
        }

        else{
            logger.info("authorization process already running, adding response listener to the queue");
            logger.debug(String.format("authorization process currently handling %d requests", authorizationQueue.size()));
        }
    }
696678
function checkAccessRights(req, res, next) {
	const uri = (typeof req.contextPath === "string" && req.baseUrl.substring(req.contextPath.length)) || req.baseUrl;
	req.user.checkRights(req.user.username, uri, req, res, next);
}
1157507
function onRegistered(client, url) {
  let server
  return new Promise(resolve => {
    server = http.createServer((request, response) => {
      if (request.url.indexOf('/do_access') === 0) {
        log('debug', request.url, 'url received')
        resolve(request.url)
        response.end(
          'Authorization registered, you can close this page and go back to the cli'
        )
      }
    })
    server.listen(3333, () => {
      require('opn')(url, { wait: false })
      console.log(
        'A new tab just opened in your browser to require the right authorizations for this connector in your cozy. Waiting for it...'
      )
      console.log(
        'If your browser does not open (maybe your are in a headless virtual machine...), then paste this url in your browser'
      )
      console.log(url)
    })
  }).then(
    url => {
      server.close()
      return url
    },
    err => {
      server.close()
      log('error', err, 'registration error')
      throw err
    }
  )
}
1124710
function (context, authorisationRequest, callback) {

            try {
                this._isAuthorized(context, authorisationRequest);
                callback();
            } catch (e) {
                callback(e);
            }
        }
277138
def main():
    """"""
    if len(sys.argv) != 2:
        print("Usage: {} USERNAME".format(sys.argv[0]))
        return 1

    caching_requestor = prawcore.Requestor(
        "prawcore_device_id_auth_example", session=CachingSession()
    )
    authenticator = prawcore.TrustedAuthenticator(
        caching_requestor,
        os.environ["PRAWCORE_CLIENT_ID"],
        os.environ["PRAWCORE_CLIENT_SECRET"],
    )
    authorizer = prawcore.ReadOnlyAuthorizer(authenticator)
    authorizer.refresh()

    user = sys.argv[1]
    with prawcore.session(authorizer) as session:
        data1 = session.request("GET", "/api/v1/user/{}/trophies".format(user))

    with prawcore.session(authorizer) as session:
        data2 = session.request("GET", "/api/v1/user/{}/trophies".format(user))

    for trophy in data1["data"]["trophies"]:
        description = trophy["data"]["description"]
        print(
            "Original:",
            trophy["data"]["name"]
            + (" ({})".format(description) if description else ""),
        )

    for trophy in data2["data"]["trophies"]:
        description = trophy["data"]["description"]
        print(
            "Cached:",
            trophy["data"]["name"]
            + (" ({})".format(description) if description else ""),
        )
    print(
        "----\nCached == Original:",
        data2["data"]["trophies"] == data2["data"]["trophies"],
    )

    return 0
66501
def _wait_for_tasks(tasks, service_instance):
    '''
    
    '''
    log.trace('Waiting for vsan tasks: {0}',
              ', '.join([six.text_type(t) for t in tasks]))
    try:
        vsanapiutils.WaitForTasks(tasks, service_instance)
    except vim.fault.NoPermission as exc:
        log.exception(exc)
        raise VMwareApiError('Not enough permissions. Required privilege: '
                             '{0}'.format(exc.privilegeId))
    except vim.fault.VimFault as exc:
        log.exception(exc)
        raise VMwareApiError(exc.msg)
    except vmodl.RuntimeFault as exc:
        log.exception(exc)
        raise VMwareRuntimeError(exc.msg)
    log.trace('Tasks %s finished successfully',
              ', '.join([six.text_type(t) for t in tasks]))
530942
async def client_ready_async(self):
        
        if not await self.auth_complete_async():
            return False
        if not await self._client_ready_async():
            await self._connection.work_async()
            return False
        return True
35053
function wait(key, cb) {
    if (!waiting[key]) {
        waiting[key] = [];
    }

    waiting[key].push(cb);
}
928652
def _do_login_locked(self):
    """"""
    self._telnet = telnetlib.Telnet(self._host)
    self._telnet.read_until(LutronConnection.USER_PROMPT)
    self._telnet.write(self._user + b'\r\n')
    self._telnet.read_until(LutronConnection.PW_PROMPT)
    self._telnet.write(self._password + b'\r\n')
    self._telnet.read_until(LutronConnection.PROMPT)

    self._send_locked("#MONITORING,12,2")
    self._send_locked("#MONITORING,255,2")
    self._send_locked("#MONITORING,3,1")
    self._send_locked("#MONITORING,4,1")
    self._send_locked("#MONITORING,5,1")
    self._send_locked("#MONITORING,6,1")
    self._send_locked("#MONITORING,8,1")
567682
def connectionAuthenticated(self):
        
        self.router = router.MessageRouter()
        self.match_rules = {}
        self.objHandler = objects.DBusObjectHandler(self)
        # serial_number => (deferred, delayed_timeout_cb | None):
        self._pendingCalls = {}
        self._dcCallbacks = []

        d = self.callRemote(
            '/Hello',
            'Hello',
            interface='org.freedesktop.DBus',
            destination='org.freedesktop.DBus',
        )

        d.addCallbacks(
            self._cbGotHello,
            lambda err: self.factory._failed(err),
        )
505298
function batchAuthorization ({ resourceBatch, userId, organizationId, sourceIpAddress, sourcePort }, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      async.waterfall([
        function validate (next) {
          Joi.validate({ resourceBatch, userId, organizationId }, validationRules.batchAuthorization, badRequestWrap(next))
        },
        function listPolicies (result, next) {
          policyOps.listAllUserPolicies({ userId, organizationId }, badImplementationWrap(next))
        },
        function check (policies, next) {
          let context = buildContext({userId, organizationId, sourceIpAddress, sourcePort})

          resourceBatch.forEach((rb) => {
            rb.access = iam(policies).isAuthorized({resource: rb.resource, action: rb.action, context})
          })
          next(null, resourceBatch)
        }
      ], function (err, access) {
        cb(err, resourceBatch)
      })

      return promise
    }
461964
function checkCollabAuthenticated(req, res, next) {
		if (req.user) {
			req.user.workspaceDir = options.workspaceDir + (req.user.workspace ? "/" + req.user.workspace : "");
			next();
		} else if (req.headers['authorization'] && checkCollabServerToken(req.headers['authorization'])){
			next();
		} else {
			api.writeError(401, res, "Not authenticated");
		}
	}