Return 'auth token' string, if the user credentials are already stored
9689
def has_credentials_stored():
    

    try:
        with open(credentials_file, 'r') as f:
            token = f.readline().strip()
            id = f.readline().strip()

            return token
    except Exception, e:
        return False
877849
def get_token(self):
        
        if self.token == None:
            self.token = self.authenticate(self.username, self.password)
        try:
            return str(self.token,'utf-8')
        except TypeError:
            return self.token
467628
def check_auth(self, username, password):
        '''  '''
        return username == self.queryname and password == self.querypw
601182
def authenticate_credentials(self, payload):
        """"""
        username = payload.get('preferred_username') or payload.get('username')

        if username is None:
            raise exceptions.AuthenticationFailed('JWT must include a preferred_username or username claim!')
        else:
            try:
                user, __ = get_user_model().objects.get_or_create(username=username)
                attributes_updated = False
                for claim, attr in self.get_jwt_claim_attribute_map().items():
                    payload_value = payload.get(claim)

                    if getattr(user, attr) != payload_value and payload_value is not None:
                        setattr(user, attr, payload_value)
                        attributes_updated = True

                if attributes_updated:
                    user.save()
            except:
                msg = 'User retrieval failed.'
                logger.exception(msg)
                raise exceptions.AuthenticationFailed(msg)

        return user
511317
def _get_credentials(self):
        
        uri = URITemplate(self.baseuri + '/{username}/credentials').expand(
            username=self.username)

        resp = self.session.post(uri)

        self.handle_http_error(
            resp,
            custom_messages={
                401: "Token is not authorized",
                404: "Token does not have upload scope",
                429: "Too many requests"})
        return resp
883550
def get_user_password (self, url):
        
        for auth in self["authentication"]:
            if auth['pattern'].match(url):
                return (auth['user'], auth['password'])
        return (None, None)
294947
def _generateForTokenSecurity(self,
                                  username, password,
                                  tokenUrl,
                                  expiration=None,
                                  client='requestip'):
        

        query_dict = {'username': username,
                      'password': password,
                      'expiration':str(_defaultTokenExpiration),
                      'client': client,
                      'f': 'json'}
        if client == "referer":
            query_dict['referer'] = self._referer_url
        if expiration is not None:
            query_dict['expiration'] = expiration

        secHandler = None
        if self.cookiejar is not None:
            secHandler = self
            if secHandler is not None:
                secHandler._method = "HANDLER"
        token = self._post(url=tokenUrl,
                           param_dict=query_dict,
                           securityHandler=secHandler,
                           proxy_port=self._proxy_port,
                           proxy_url=self._proxy_url)
        if self.cookiejar is not None:
            if secHandler is not None:
                secHandler._method = "TOKEN"
        if 'error' in token:
            self._token = None
            self._token_created_on = None
            self._token_expires_on = None
            self._expires_in = None

            return token
        elif 'status' in token:
            self._token = None
            self._token_created_on = None
            self._token_expires_on = None
            self._expires_in = None
            #print token['message']
            return token

        else:
            self._token = token['token']
            self._token_created_on = datetime.datetime.now()
            self._token_expires_on = datetime.datetime.fromtimestamp(token['expires'] /1000) - \
                datetime.timedelta(seconds=1)
            self._expires_in = (self._token_expires_on - self._token_created_on).total_seconds()
            return token['token']
869390
def _authstr(self, auth):
        """"""
        if type(auth) is dict:
            return '{' + ','.join(["{0}:{1}".format(k, auth[k]) for k in sorted(auth.keys())]) + '}'
        return auth
388282
def auth(self):
        """"""
        response = requests.post(
            parse.urljoin(self.base_url, '/api/auth'),
            timeout=self.timeout,
            data={'username': self.username, 'password': self.password})
        response.raise_for_status()
        json = response.json()
        if 'jwt' not in json:
            raise ValueError("Not authorized: didn't receive token, check username or password.")
        self.jwt = json['jwt']
        return json
1155681
def access_token(self):
        """"""
        if self.cache_token:
            return self.access_token_ or \
                   self._resolve_credential('access_token')
        return self.access_token_
220959
def construct_auth (self):
        """"""
        if self.auth:
            return
        _user, _password = self.get_user_password()
        if _user is not None and _password is not None:
            self.auth = (_user, _password)
1023604
def get_token_credentials(cls, username, request):
        
        try:
            user = cls.get_item(username=username)
        except Exception as ex:
            log.error(str(ex))
            forget(request)
        else:
            if user:
                return user.api_key.token
813277
def auth(self):
        
        username = self._settings["username"]

        if not username:
            raise ValueError("Username was not configured in %s" % CONFIG_FILE)

        if self._settings["use_keyring"]:
            password = self.keyring_get_password(username)
            if not password:
                self.keyring_set_password(username)
                password = self.keyring_get_password(username)
        else:
            password = self._settings["password"]

        return self._settings["username"], password
747793
def _get_auth_header(self):
        '''  '''
        realm = 'realm="{realm}"'.format(realm=self.realm)
        params = ['{k}="{v}"'.format(k=k, v=quote(str(v), safe=''))
                  for k, v in self.oauth_params.items()]
        return 'OAuth ' + ','.join([realm] + params)
416725
def token_auth(self, token):
        
        if not token:
            return

        self.headers.update({
            'Authorization': 'token {0}'.format(token)
            })
        # Unset username/password so we stop sending them
        self.auth = None
1046502
def mk_token(self, load):
        '''
        
        '''
        if not self.authenticate_eauth(load):
            return {}

        if self._allow_custom_expire(load):
            token_expire = load.pop('token_expire', self.opts['token_expire'])
        else:
            _ = load.pop('token_expire', None)
            token_expire = self.opts['token_expire']

        tdata = {'start': time.time(),
                 'expire': time.time() + token_expire,
                 'name': self.load_name(load),
                 'eauth': load['eauth']}

        if self.opts['keep_acl_in_token']:
            acl_ret = self.__get_acl(load)
            tdata['auth_list'] = acl_ret

        groups = self.get_groups(load)
        if groups:
            tdata['groups'] = groups

        return self.tokens["{0}.mk_token".format(self.opts['eauth_tokens'])](self.opts, tdata)
235862
def _get_credentials(self, request):
        
        authorization = request.headers.get('Authorization')
        if not authorization:
            return None
        try:
            authmeth, authbytes = authorization.split(' ', 1)
        except ValueError:  # not enough values to unpack
            return None
        if authmeth.lower() != 'apikey':
            return None

        if six.PY2 or isinstance(authbytes, bytes):
            try:
                auth = authbytes.decode('utf-8')
            except UnicodeDecodeError:
                auth = authbytes.decode('latin-1')
        else:
            auth = authbytes

        try:
            username, api_key = auth.split(':', 1)
        except ValueError:  # not enough values to unpack
            return None
        return username, api_key