TODO: do token based auth for both http and ws server because this is for ONVIF device which requires token auth
169720
function installHandler(deviceRootUrl) {
  deviceUrl = url.parse(deviceRootUrl);
  //do we need to handle https device root Url?
  if (deviceUrl.protocol !== 'http:') {
    console.error('do not support non-http device url');
    return;
  }
  // TODO: in real production this must be hosted on https
  app.use('/', function(req, res) {
    var parsedUrl = url.parse(req.url);
    var headersCopy = {};
    // create a copy of request headers
    for (attr in req.headers) {
      if (!req.headers.hasOwnProperty(attr)) continue;
      headersCopy[attr] = req.headers[attr];
    }
    deviceUrl.path = req.url;
    var options = {
      uri: deviceUrl,
      method: req.method,
      path: parsedUrl.path,
      headers: headersCopy
    };

    var clientRequest = request(options);
    clientRequest.on('response', function(response) {
      res.statusCode = response.statusCode;
      for (header in response.headers) {
        if (!response.headers.hasOwnProperty(header)) continue;
        res.setHeader(header, response.headers[header]);
      }
      response.pipe(res);
    });
    req.pipe(clientRequest);
  });
}
373623
function (url, requestItemsCb) {
      // use the bearer auth token
      request.get(url, {
        'auth': {
          'bearer': exports.authorizedToken
        }
      },
        (error, response, body) => {
          if (error) console.error(error)
          if (response.statusCode && response.statusCode === 200) {
            if (requestItemsCb) requestItemsCb(null, JSON.parse(body))
          } else {
            if (requestItemsCb) requestItemsCb(null, false)
          }
        })
    }
183651
function WPOAuth(options){
  if (!(this instanceof WPOAuth)) return new WPOAuth(options);

  // Options
  this.opts = globals = options || {};
  for (var attr in def){
    this.opts[attr] = this.opts[attr] || def[attr];
  }

  this._code = this.opts.code;

  // Error exceptions
  if (!this.opts.client_id) {
    throw new Error('`client_id` is required');
  }

  if (!this.opts.client_secret) {
    throw new Error('`client_secret` is required');
  }
}
537464
function() {
      const AUTH_TOKEN = 'AUTH_TOKEN';
      var req = {
        protocol: this.isSrvRecord ? 'mongodb+srv' : 'mongodb',
        slashes: true,
        hostname: this.hostname,
        port: this.isSrvRecord ? null : this.port,
        pathname: '/',
        query: {}
      };

      if (this.replica_set_name) {
        req.query.replicaSet = this.replica_set_name;
      }

      req.query.readPreference = this.read_preference;

      if (this.app_name) {
        req.query.appname = this.app_name;
      }

      if (this.ns) {
        req.pathname = format('/%s', this.ns);
      }

      const encodeAuthForUrlFormat = () => {
        if (this.authentication === 'MONGODB') {
          req.auth = AUTH_TOKEN;
          req.query.authSource = this.mongodb_database_name || MONGODB_DATABASE_NAME_DEFAULT;
        } else if (this.authentication === 'SCRAM-SHA-256') {
          req.auth = AUTH_TOKEN;
          req.query.authSource = this.mongodb_database_name || MONGODB_DATABASE_NAME_DEFAULT;
          req.query.authMechanism = this.driver_auth_mechanism;
        } else if (this.authentication === 'KERBEROS') {
          defaults(req.query, {
            gssapiServiceName: this.kerberos_service_name,
            authMechanism: this.driver_auth_mechanism
          });
          req.auth = AUTH_TOKEN;
        } else if (this.authentication === 'X509') {
          req.auth = this.x509_username;
          defaults(req.query, {
            authMechanism: this.driver_auth_mechanism
          });
        } else if (this.authentication === 'LDAP') {
          req.auth = AUTH_TOKEN;

          defaults(req.query, {
            authMechanism: this.driver_auth_mechanism
          });
        }
      };
      encodeAuthForUrlFormat();

      if (includes(['UNVALIDATED', 'SYSTEMCA', 'SERVER', 'ALL'], this.ssl)) {
        req.query.ssl = 'true';
      } else if (this.ssl === 'IFAVAILABLE') {
        req.query.ssl = 'prefer';
      } else if (this.ssl === 'NONE') {
        req.query.ssl = 'false';
      }
      var reqClone = clone(req);
      if (this.ssh_tunnel !== 'NONE') {
        // Populate the SSH Tunnel options correctly
        reqClone.hostname = this.ssh_tunnel_options.localAddr;
        reqClone.port = this.ssh_tunnel_options.localPort;
      }
      var result = toURL(reqClone);

      // Post url.format() workaround for
      // https://github.com/nodejs/node/issues/1802
      if (this.authentication === 'MONGODB' || this.authentication === 'SCRAM-SHA-256') {
        const authField = format(
          '%s:%s',
          encodeURIComponent(this.mongodb_username),
          encodeURIComponent(this.mongodb_password)
        );

        // The auth component comes straight after the mongodb:// so
        // a single string replace should always work
        result = result.replace(AUTH_TOKEN, authField, 1);
      }
      if (this.authentication === 'LDAP') {
        const authField = format(
          '%s:%s',
          encodeURIComponent(this.ldap_username),
          encodeURIComponent(this.ldap_password)
        );
        result = result.replace(AUTH_TOKEN, authField, 1);
        result = `${result}&authSource=$external`;
      }
      if (this.authentication === 'KERBEROS') {
        if (this.kerberos_password) {
          const authField = format(
            '%s:%s',
            encodeURIComponent(this.kerberos_principal),
            encodeURIComponent(this.kerberos_password)
          );
          result = result.replace(AUTH_TOKEN, authField, 1);
        } else {
          const authField = format(
            '%s:',
            encodeURIComponent(this.kerberos_principal)
          );
          result = result.replace(AUTH_TOKEN, authField, 1);
        }
        result = `${result}&authSource=$external`;
        if (this.kerberos_canonicalize_hostname) {
          result = `${result}&authMechanismProperties=CANONICALIZE_HOST_NAME:true`;
        }
      }
      return result;
    }
834246
function authenticateClient (req, res, next) {
  Client.authenticate(req, function (err, client) {
    if (err) { return next(err) }
    req.client = client
    next()
  })
}
1166017
function authDetectionMiddleware(req, res, next) {
    logger.debug('Running Auth Detection Middleware...', req.body);

    if (req.headers['token']) {
      try {
        req.user = encryption.decode(req.headers['token'], config.secret);
        req.session = { user: req.user };
      } catch (ex) {
        logger.logError('Unexpectedly could not decode a token.', ex);
        res.status(401).send();
        // ensure no user is authenticated.
        req.user = null;
        req.session = { user: null };
      }
      if (!req.user.id) throw 'AUTH FAILED:USER HAS NO MEMBER: id';
      if (!req.user.tokenExpiry || req.user.tokenExpiry <= new Date().getTime()) {
        logger.log('Expired Token:', req.user);
        res.status(401).send({errorCode: 'expired token'});
      }
      else {
        logger.log('Authenticated User:', req.user.id);
        next();
      }
    } else {
      //logger.debug('Checking permissions to ', req.path);
      //if (config.routesNotRequiringAuthentication[req.path]) next();
      //else if (m.isPublicRoute(req.path)) next();
      //else {
      //  logger.debug('Disallowing request to:', req.path);
      //  res.status(401).send();
      //}
      if (config.authenticatedRoutes[req.path] || !m.isPublicRoute(req.path))
        res.status(401).send();
      else
        next();
    }
  }
303808
function OnvifManager() {
	this.ws = null; // WebSocket object
	this.el = { // jQuery objects for the HTML elements
		'frm_con' : $('#connect-form'),
		'sel_dev' : $('#connect-form select[name="device"]'),
		'inp_usr' : $('#connect-form input[name="user"]'),
		'inp_pas' : $('#connect-form input[name="pass"]'),
		'btn_con' : $('#connect-form button[name="connect"]'),
		'div_pnl' : $('#connected-device'),
		'img_snp' : $('#connected-device img.snapshot'),
		'btn_dcn' : $('#connected-device button[name="disconnect"]'),
		'mdl_msg' : $('#message-modal'),
		'ptz_spd' : $('input[name="ptz-speed"]'),
		'btn_hme' : $('#connected-device div.ptz-pad-box button.ptz-goto-home'),
		'ptz_pad' : $('#connected-device div.ptz-pad-box'),
		'zom_in'  : $('#connected-device div.ptz-zom-ctl-box button.ptz-zom-in'),
		'zom_out' : $('#connected-device div.ptz-zom-ctl-box button.ptz-zom-ot'),
	};
	this.selected_address = '';
	this.device_connected = false;
	this.ptz_moving = false;
	this.snapshot_w = 400;
	this.snapshot_h = 300;
}
84632
function applyAuth(authContexts, server, callback) {
    if (authContexts.length === 0) return callback();
    // Get the first auth context
    var authContext = authContexts.shift();
    // Copy the params
    var customAuthContext = authContext.slice(0);
    // Push our callback handler
    customAuthContext.push(function(/* err */) {
      applyAuth(authContexts, server, callback);
    });

    // Attempt authentication
    server.auth.apply(server, customAuthContext);
  }
1356698
def __get_auth(self):
        ''''''
        if self.api_key == None and self.login == None:
            self.logger.error("No authentication provided! Unable to connect.")
            sys.exit(1)

        if self.api_key == None:
            self.logger.info("Authenticating with email/password.")
            return [
                "email: " + self.login,
                "password: " + self.password
            ]
        else:
            self.logger.info("Authenticating with API Key.")
            # To auth to the WS using an API key, we generate a signature of a nonce and
            # the WS API endpoint.
            nonce = generate_nonce()
            return [
                "api-nonce: " + str(nonce),
                "api-signature: " + generate_signature(self.api_secret, 'GET', '/realtime', nonce, ''),
                "api-key:" + self.api_key
            ]
943133
def get_token(code, token_service, client_id, client_secret, redirect_uri,
              grant_type):
  """"""
  data = {
      'code': code,
      'client_id': client_id,
      'client_secret': client_secret,
      'redirect_uri': redirect_uri,
      'grant_type': grant_type,
  }
  # Get the default http client
  resp = requests.post(token_service, data, verify=False)
  return resp.json()
1325854
def fetch_token(self, **kwargs):
        """"""
        return super(AsanaOAuth2Session, self).fetch_token(self.token_url, client_secret=self.client_secret, **kwargs)
271325
function (scopes, tokenUrl, OAuthSchemeKey) {
        var params = {
            'client_id': clientId,
            'client_secret': clientSecret,
            'scope': scopes.join(' '),
            'grant_type': 'client_credentials'
        };
        $.ajax({
            url : tokenUrl,
            type: 'POST',
            data: params,
            success: function (data)
            {
                onOAuthComplete(data, OAuthSchemeKey);
            },
            error: function ()
            {
                onOAuthComplete('');
            }
        });
    }
432720
async function authenticate(options) {
    const tokenFile = path.join(constants.GLOBAL_DIR, constants.GLOBAL_TOKEN);
    const configFile = path.join(constants.GLOBAL_DIR, constants.GLOBAL_CONFIG);

    // Ensure a config file exists
    if (!fs.pathExistsSync(configFile)) {
        createFile({
            name: configFile,
            source: `{}\n`,
        });
    }

    // Remove the token file if we are forcing reauth
    if (options.force) {
        fs.removeSync(tokenFile);
    }

    // get Oauth client
    const oauth2ClientResult = await getAuthClient();
    const oauth2Client = oauth2ClientResult.client;
    const isCustomClient = oauth2ClientResult.custom;
    let newOauth2Client;

    // Check if we have previously stored a token.
    let token;
    try {
        token = fs.readFileSync(tokenFile, 'utf8');
    } catch (err) {
        newOauth2Client = await getNewToken(oauth2Client, isCustomClient, options);
        await firebase.setUserInfo(newOauth2Client);
        return newOauth2Client;
    }

    // If we can find the token, refresh it, get a new one or do nothing
    const tokenObject = JSON.parse(token);
    oauth2Client.credentials = tokenObject;
    const ttl = oauth2Client.credentials.expiry_date - Date.now();

    if (ttl < 10 * 1000 || options.refresh) {
        try {
            newOauth2Client = await getToken(null, token, oauth2Client, isCustomClient);
            await firebase.setUserInfo(newOauth2Client);
            return newOauth2Client;
        } catch (err) {
            newOauth2Client = await getNewToken(oauth2Client, isCustomClient, options);
            await firebase.setUserInfo(newOauth2Client);
            return newOauth2Client;
        }
    } else {
        return oauth2Client;
    }
}
528555
def auth(self, transport, account_name, password):
        
        auth_token = AuthToken()
        auth_token.account_name = account_name

        attrs = {sconstant.A_BY: sconstant.V_NAME}
        account = SOAPpy.Types.stringType(data=account_name, attrs=attrs)

        params = {sconstant.E_ACCOUNT: account,
                  sconstant.E_PASSWORD: password}

        self.log.debug('Authenticating account %s' % account_name)
        try:
            res = transport.invoke(zconstant.NS_ZIMBRA_ACC_URL,
                                   sconstant.AuthRequest,
                                   params,
                                   auth_token)
        except SoapException as exc:
            raise AuthException(unicode(exc), exc)

        auth_token.token = res.authToken
        
        if hasattr(res, 'sessionId'):
            auth_token.session_id = res.sessionId

        self.log.info('Authenticated account %s, session id %s'
                      % (account_name, auth_token.session_id))

        return auth_token
958826
def set_wsse(self, user=None, passwd=None):
        '''  '''
        if user:
            self.user = user
        if passwd:
            self.passwd = passwd

        security = Security()

        if self.encrypt:
            token = UsernameDigestTokenDtDiff(self.user, self.passwd, dt_diff=self.dt_diff)
        else:
            token = UsernameToken(self.user, self.passwd)
            token.setnonce()
            token.setcreated()

        security.tokens.append(token)
        self.ws_client.set_options(wsse=security)
820658
function addAuthHeaders ({ 
  auth,
  bearerToken, 
  headers, 
  overrideHeaders=false, 
}) {
  if (overrideHeaders) return
  if (bearerToken) return { 
    headers: { ...headers, Authorization: `Bearer ${ bearerToken }` } 
  }
  if (auth) {
    const username = auth.username || ''
    const password = auth.password || ''
    const encodedToken = Base64.btoa(`${ username }:${ password }`)
    return {
      headers: { ...headers, Authorization: `Basic ${ encodedToken }` }
    }
  }
}
1352365
private Auth constructAuth(String authToken, String tokenSecret, String username) throws IOException {

        Auth auth = new Auth();
        auth.setToken(authToken);
        auth.setTokenSecret(tokenSecret);

        // Prompt to ask what permission is needed: read, update or delete.
        auth.setPermission(Permission.fromString("delete"));

        User user = new User();
        // Later change the following 3. Either ask user to pass on command line or read
        // from saved file.
        user.setId(nsid);
        user.setUsername((username));
        user.setRealName("");
        auth.setUser(user);
        this.authStore.store(auth);
        return auth;
    }