Log in to OneView appliance and return the session token
187023
def login(retries = 2)
      options = {
        'body' => {
          'userName' => @user,
          'password' => @password,
          'authLoginDomain' => @domain
        }
      }
      response = rest_post('/rest/login-sessions', options)
      body = response_handler(response)
      return body['sessionID'] if body['sessionID']
      raise ConnectionError, "\nERROR! Couldn't log into OneView server at #{@url}. Response: #{response}\n#{response.body}"
    rescue StandardError => e
      raise e unless retries > 0
      @logger.debug 'Failed to log in to OneView. Retrying...'
      return login(retries - 1)
    end
72125
function logon() {
    var dfrd = Q.defer();
    var token = cache.get('token');

    function extractToken(xml) {
      var r = _parse(xml, dfrd);
      if (r) {
        return r.response.token[0];
      }
    }

    if (token) {
      dfrd.resolve({
        token: token,
        cached: true
      });
    }

    request(format(URLs.logon, PROTOCOL, conf.host, conf.username,
        conf.password),
      function(err, res, body) {
        var newToken;
        if (err) {
          dfrd.reject(err);
        } else {
          newToken = extractToken(body);
          if (!newToken) {
            dfrd.reject(MODULE_ERRORS.unknown);
          } else {
            cache.put('token', newToken);
            dfrd.resolve({
              token: newToken,
              cached: false
            });
          }
        }
      });
    return dfrd.promise;
  }
73524
def _login(self, csrf_token):
        """"""
        login_response = self.session.post(
            self.URLS['login'],
            data={
                'username': self._get_provider_option('auth_username') or '',
                'password': self._get_provider_option('auth_password') or '',
                'submit': '',
                'loginxtoken': csrf_token,
            }
        )
        self._log('Login', login_response)
        assert login_response.status_code == 200, \
            'Could not login due to a network error.'
        assert login_response.url == self.URLS['overview'], \
            'Easyname login failed, bad EASYNAME_USER or EASYNAME_PASS.'
1346776
def get_logged_in_account(token_manager=None,
                          app_url=defaults.APP_URL):
    
    return get_logged_in_account(token_manager=token_manager,
                                 app_url=app_url)['id']
646133
def requires_login(func, *args, **kwargs):
    
    self = args[0]
    if self.session_token:
        return func(*args, **kwargs)
    raise exceptions.NotLoggedIn()
56475
def get_session(username, password, locale=DEFAULT_LOCALE,
                cookie_path=COOKIE_PATH):
    """"""
    class UPSAuth(AuthBase):  # pylint: disable=too-few-public-methods
        """UPS authorization storage."""

        def __init__(self, username, password, locale, cookie_path):
            """Init."""
            self.username = username
            self.password = password
            self.locale = locale
            self.cookie_path = cookie_path

        def __call__(self, r):
            """Call is no-op."""
            return r

    session = requests.session()
    session.auth = UPSAuth(username, password, locale, cookie_path)
    if os.path.exists(cookie_path):
        session.cookies = _load_cookies(cookie_path)
    else:
        _login(session)
    return session
1271366
def session(self, auth=None):
        
        url = '{server}{auth_url}'.format(**self._options)

        if isinstance(self._session.auth, tuple) or auth:
            if not auth:
                auth = self._session.auth
            username, password = auth
            authentication_data = {'username': username, 'password': password}
            r = self._session.post(url, data=json.dumps(authentication_data))
        else:
            r = self._session.get(url)

        user = User(self._options, self._session, json_loads(r))
        return user
156999
def set_oauth_session(self, provider, oauth_response):
        
        # Get this provider key names for token_key and token_secret
        token_key = self.appbuilder.sm.get_oauth_token_key_name(provider)
        token_secret = self.appbuilder.sm.get_oauth_token_secret_name(provider)
        # Save users token on encrypted session cookie
        session["oauth"] = (
            oauth_response[token_key],
            oauth_response.get(token_secret, ""),
        )
        session["oauth_provider"] = provider
1095083
def _auth_required():
    

    login_mechanisms = (
        ('token', lambda: _check_token()),
        ('session', lambda: current_user.is_authenticated),
    )

    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            for method, mechanism in login_mechanisms:
                if mechanism and mechanism():
                    return fn(*args, **kwargs)
            return security._unauthorized_callback()
        return decorated_view
    return wrapper
568427
def async_login(self):
       """"""
       _LOGGER.debug('Attempting to log into Alarm.com...')

       # Get the session key for future logins.
       response = None
       try:
           with async_timeout.timeout(10, loop=self._loop):
               response = yield from self._websession.get(
                   self.ALARMDOTCOM_URL + '/default.aspx',
               headers={'User-Agent': 'Mozilla/5.0 '
                                      '(Windows NT 6.1;'
                                      ' WOW64; rv:40.0) '
                                      'Gecko/20100101 '
                                      'Firefox/40.1'})

           _LOGGER.debug(
               'Response status from Alarm.com: %s',
               response.status)
           text = yield from response.text()
           _LOGGER.debug(text)
           tree = BeautifulSoup(text, 'html.parser')
           self._login_info = {
               'sessionkey': self.SESSION_KEY_RE.match(
                   str(response.url)).groupdict()['sessionKey'],
               self.VIEWSTATE: tree.select(
                   '#{}'.format(self.VIEWSTATE))[0].attrs.get('value'),
               self.VIEWSTATEGENERATOR: tree.select(
                   '#{}'.format(self.VIEWSTATEGENERATOR))[0].attrs.get('value'),
               self.EVENTVALIDATION: tree.select(
                   '#{}'.format(self.EVENTVALIDATION))[0].attrs.get('value')
           }

           _LOGGER.debug(self._login_info)
           _LOGGER.info('Attempting login to Alarm.com')

       except (asyncio.TimeoutError, aiohttp.ClientError):
           _LOGGER.error('Can not get login page from Alarm.com')
           return False
       except AttributeError:
           _LOGGER.error('Unable to get sessionKey from Alarm.com')
           raise

        # Login params to pass during the post
       params = {
           self.USERNAME: self._username,
           self.PASSWORD: self._password,
           self.VIEWSTATE: self._login_info[self.VIEWSTATE],
           self.VIEWSTATEGENERATOR: self._login_info[self.VIEWSTATEGENERATOR],
           self.EVENTVALIDATION: self._login_info[self.EVENTVALIDATION]
       }

       try:
           # Make an attempt to log in.
           with async_timeout.timeout(10, loop=self._loop):
               response = yield from self._websession.post(
                   self.ALARMDOTCOM_URL + '{}/default.aspx'.format(
                       self._login_info['sessionkey']),
                   data=params,
                   headers={'User-Agent': 'Mozilla/5.0 '
                                          '(Windows NT 6.1; '
                                          'WOW64; rv:40.0) '
                                          'Gecko/20100101 '
                                          'Firefox/40.1'}
               )
           _LOGGER.debug(
               'Status from Alarm.com login %s', response.status)

           # Alarm.com changed their redirect so hit this page directly to get the status of login.
           with async_timeout.timeout(10, loop=self._loop):
               response = yield from self._websession.get(
                   self.ALARMDOTCOM_URL + '{}/main.aspx'.format(
                       self._login_info['sessionkey']),
                   headers={'User-Agent': 'Mozilla/5.0 '
                                          '(Windows NT 6.1; '
                                          'WOW64; rv:40.0) '
                                          'Gecko/20100101 '
                                          'Firefox/40.1'}
               )

           # Get the text from the login to ensure that we are logged in.
           text = yield from response.text()
           _LOGGER.debug(text)
           tree = BeautifulSoup(text, 'html.parser')
           try:
               self.state = tree.select(self.ALARM_STATE)[0].get_text()
               _LOGGER.debug(
                   'Current alarm state: %s', self.state)
               self.sensor_status = tree.select(self.SENSOR_STATUS)[0].get_text()
               _LOGGER.debug(
                   'Current sensor status: %s', self.sensor_status)
           except IndexError:
               try:
                   error_control = tree.select(
                       '#{}'.format(self.ERROR_CONTROL))[0].attrs.get('value')
                   if 'Login failure: Bad Credentials' in error_control:
                       _LOGGER.error(error_control)
                       return False
               except AttributeError:
                   _LOGGER.error('Error while trying to log into Alarm.com')
                   return False
       except (asyncio.TimeoutError, aiohttp.ClientError):
           _LOGGER.error("Can not load login page from Alarm.com")
           return False
1035314
public String login(String token, Authentication authentication) {
		if (null == token) {
			return login(authentication);
		}
		tokens.put(token, new TokenContainer(authentication));
		return token;
	}
1286438
function getSession (ctx) {
    let signedCookie = ctx.cookies.get(sessionKey, {signed: cookie.signed}) || ''
    signedCookie = signedCookie.split('.')

    return ctx.thunk()(function () {
      if (!storeAvailable) throw new Error('session store is not available')
      if (signedCookie[0]) return store.get(signedCookie[0])
    })(function (err, session) {
      if (err) throw err
      let sessionId
      let originalHash

      if (session) {
        sessionId = signedCookie[0]
        originalHash = signedCookie[1]
        if (hashSession(session, sessionId) !== originalHash) session = null
      }

      if (!session) {
        session = genSession()
        sessionId = genSid(sidSize)
        originalHash = hashSession(session, sessionId)
      }

      return {
        session: session,
        sessionId: sessionId,
        originalHash: originalHash,
        isNew: originalHash !== signedCookie[1]
      }
    })
  }
584802
def get_token(url_base, tenant_id, user, password):
    
    url = 'http://' + url_base + '/v2.0/tokens'
    headers = {'Content-Type': 'application/json'}
    payload = '{"auth":{"tenantId":"' + tenant_id +\
              '","passwordCredentials":{"username":"'\
              + user + '","password":"' + password + '"}}}'
    response = requests.post(url, headers=headers, data=payload)
    if response.status_code != 200:
        print 'error to obtain the token ' + str(response.status_code)
        exit(1)
    response_json = response.json()
    token = response_json['access']['token']['id']
    return token
618148
def step1(self, username, password):
        """"""
        self._check_initialized()
        context = AtvSRPContext(
            str(username), str(password),
            prime=constants.PRIME_2048,
            generator=constants.PRIME_2048_GEN)
        self.session = SRPClientSession(
            context, binascii.hexlify(self._auth_private).decode())
549287
def get_logged_in_account(token_manager=None,
                          app_url=defaults.APP_URL):
    
    headers = token_manager.get_access_token_headers()
    auth_url = environment.get_auth_url(app_url=app_url)
    url = "%s/api/v1/account" % auth_url

    response = requests.get(url,
                            headers=headers)

    if response.status_code == 200:
        return response.json()

    else:
        raise JutException('Error %s; %s' % (response.status_code, response.text))
850253
def authenticate(self):
        """"""
        if self.__token:
            try:
                resp = self._refresh_token()
            except exceptions.TVDBRequestException as err:
                # if a 401 is the cause try to login
                if getattr(err.response, 'status_code', 0) == 401:
                    resp = self._login()
                else:
                    raise
        else:
            resp = self._login()

        self.__token = resp.get('token')
        self._token_timer = timeutil.utcnow()
1351262
def login(self):
        
        response = self._request('Login')
        parser = OneXLogin()
        parser.parse(response)

        self.session_id = response.cookies.get(self.session_id_cookie_name, '')

        if parser.headers.get('RETS-Version') is not None:
            self.version = str(parser.headers.get('RETS-Version'))
            self.client.headers['RETS-Version'] = self.version

        for k, v in parser.capabilities.items():
            self.add_capability(k, v)

        if self.capabilities.get('Action'):
            self._request('Action')
        return True