def test_parse_token_response(self):
        client = LegacyApplicationClient(self.client_id)

        # Parse code and state
        response = client.parse_request_body_response(self.token_json, scope=self.scope)
        self.assertEqual(response, self.token)
        self.assertEqual(client.access_token, response.get("access_token"))
        self.assertEqual(client.refresh_token, response.get("refresh_token"))
        self.assertEqual(client.token_type, response.get("token_type"))

        # Mismatching state
        self.assertRaises(Warning, client.parse_request_body_response, self.token_json, scope="invalid")
        os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '5'
        token = client.parse_request_body_response(self.token_json, scope="invalid")
        self.assertTrue(token.scope_changed)

        scope_changes_recorded = []
        def record_scope_change(sender, message, old, new):
            scope_changes_recorded.append((message, old, new))

        signals.scope_changed.connect(record_scope_change)
        try:
            client.parse_request_body_response(self.token_json, scope="invalid")
            self.assertEqual(len(scope_changes_recorded), 1)
            message, old, new = scope_changes_recorded[0]
            self.assertEqual(message, 'Scope has changed from "invalid" to "/profile".')
            self.assertEqual(old, ['invalid'])
            self.assertEqual(new, ['/profile'])
        finally:
            signals.scope_changed.disconnect(record_scope_change)
        del os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE']
    def __init__(self, host: str, port: str, user: str, secret: str,
                 verify_ssl: bool) -> None:
        self._host = host
        self._token_file = "%s/%s" % (str(
            self._token_dir), self._token_file_suffix % self._host)
        self._port = port
        self._user = user
        self._secret = secret
        self._verify_ssl = verify_ssl
        if not verify_ssl:
            urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

        # We need to use LegacyClient due to grant_type==password
        self._client = LegacyApplicationClient(None)
        self._client.prepare_request_body(username=self._user,
                                          password=self._secret)

        # Check if token file exists, read it & create OAuthSession with it
        try:
            self._json_token = self.load_token_file_and_update_expire_in()
            LOGGER.debug("Loaded token content: %s", self._json_token)

            self._oauth_session = OAuth2Session(
                self._user,
                client=self._client,
                auto_refresh_url="https://%s:%s%s" %
                (self._host, self._port, self._refresh_endpoint),
                token_updater=lambda x: self.
                store_token_file_and_update_expires_in_abs(to_token_dict(x)),
                token={
                    "access_token": self._json_token["access_token"],
                    "refresh_token": self._json_token["refresh_token"],
                    "expires_in": self._json_token["expires_in"],
                },
            )
        except (FileNotFoundError, KeyError):
            LOGGER.debug(
                "Token file not found or error in token file. Creating new connection."
            )
            self._oauth_session = OAuth2Session(
                self._user,
                client=self._client,
                auto_refresh_url="https://%s:%s%s" %
                (self._host, self._port, self._refresh_endpoint),
                token_updater=lambda x: self.
                store_token_file_and_update_expires_in_abs(to_token_dict(x)),
            )
            # Fetch token
            token_dict = to_token_dict(
                self._oauth_session.fetch_token(
                    token_url="https://%s:%s%s" %
                    (self._host, self._port, self._token_endpoint),
                    username=self._user,
                    password=self._secret,
                    verify=self._verify_ssl,
                ))
            # Initially create the token file
            self.store_token_file_and_update_expires_in_abs(token_dict)
            self._json_token = token_dict
Exemple #3
0
    def test_parse_token_response(self):
        client = LegacyApplicationClient(self.client_id)

        # Parse code and state
        response = client.parse_request_body_response(self.token_json, scope=self.scope)
        self.assertEqual(response, self.token)
        self.assertEqual(client.access_token, response.get("access_token"))
        self.assertEqual(client.refresh_token, response.get("refresh_token"))
        self.assertEqual(client.token_type, response.get("token_type"))

        # Mismatching state
        self.assertRaises(Warning, client.parse_request_body_response, self.token_json, scope="invalid")
Exemple #4
0
    def test_request_body(self):
        client = LegacyApplicationClient(self.client_id)

        # Basic, no extra arguments
        body = client.prepare_request_body(self.username, self.password,
                body=self.body)
        self.assertFormBodyEqual(body, self.body_up)

        # With extra parameters
        body = client.prepare_request_body(self.username, self.password,
                body=self.body, **self.kwargs)
        self.assertFormBodyEqual(body, self.body_kwargs)
    def test_request_body(self):
        client = LegacyApplicationClient(self.client_id)

        # Basic, no extra arguments
        body = client.prepare_request_body(self.username, self.password,
                body=self.body)
        self.assertFormBodyEqual(body, self.body_up)

        # With extra parameters
        body = client.prepare_request_body(self.username, self.password,
                body=self.body, **self.kwargs)
        self.assertFormBodyEqual(body, self.body_kwargs)
def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        if not verifica_login(request):
            oauth = OAuth2Session(client=LegacyApplicationClient(
                client_id=client_id))

            try:
                token = oauth.fetch_token(token_url=api_url + '/o/token/',
                                          username=username,
                                          password=password,
                                          client_id=client_id,
                                          client_secret=client_secret)
            except:
                context = {
                    'title': 'Portal do Conhecimento',
                    'erro':
                    'Nao foi possivel realizar o login. Tente novamente.'
                }

                return render(request, 'knowledgeportal/index.html', context)

            data = json.loads(json.dumps(token))

            request.session['username'] = username
            request.session['access_token'] = data['access_token']
            request.session['refresh_token'] = data['refresh_token']

    return redirect('/')
Exemple #7
0
def session_from_envvars(auth_url=PRODUCTION_AUTH_URL,
                         environ_template=(('username', 'GBDX_USERNAME'),
                                           ('password', 'GBDX_PASSWORD'))):
    """Returns a session with the GBDX authorization token baked in,
    pulling the credentials from environment variables.

    environ_template - An iterable of key, value pairs. The key should
                      be the variables used in the oauth workflow, and
                      the values being the environment variables to
                      pull the configuration from.  Change the
                      template values if your envvars differ from the
                      default, but make sure the keys remain the same.
    """
    def save_token(token):
        s.token = token

    client_id = 'dummyclientid'
    client_secret = 'dummyclientsecret'

    environ = {var: os.environ[envvar] for var, envvar in environ_template}
    s = OAuth2Session(client=LegacyApplicationClient(client_id),
                      auto_refresh_url=auth_url,
                      auto_refresh_kwargs={
                          'client_id': client_id,
                          'client_secret': client_secret
                      },
                      token_updater=save_token)

    s.fetch_token(auth_url, **environ)

    return s
 def _get_token_and_userinfo_password_flow(self, username, password):
     try:
         client_id = settings.KEYCLOAK_CLIENT_ID
         client_secret = settings.KEYCLOAK_CLIENT_SECRET
         token_url = settings.KEYCLOAK_TOKEN_URL
         userinfo_url = settings.KEYCLOAK_USERINFO_URL
         verify_ssl = settings.KEYCLOAK_VERIFY_SSL
         oauth2_session = OAuth2Session(client=LegacyApplicationClient(
             client_id=client_id))
         verify = verify_ssl
         if verify_ssl and hasattr(settings, 'KEYCLOAK_CA_CERTFILE'):
             verify = settings.KEYCLOAK_CA_CERTFILE
         token = oauth2_session.fetch_token(token_url=token_url,
                                            username=username,
                                            password=password,
                                            client_id=client_id,
                                            client_secret=client_secret,
                                            verify=verify)
         userinfo = oauth2_session.get(userinfo_url).json()
         return token, userinfo
     except InvalidGrantError as e:
         # password wasn't valid, just log as a warning
         logger.warning(f"Failed to log in user {username} with "
                        f"password: {e}")
         return None, None
Exemple #9
0
    def __init__(
        self,
        app_login,
        app_password,
        token=None,
        token_updater_clb=None,
        offline=3600,
        scope=".+:/dns-master/.+",
    ):
        self._app_login = app_login
        self._app_password = app_password
        self._token = token
        self._token_updater_clb = token_updater_clb
        self._offline = offline
        self._scope = scope

        # Setup session
        self._session = OAuth2Session(
            client=LegacyApplicationClient(
                client_id=self._app_login,
                scope=self._scope,
            ),
            auto_refresh_url=self.token_url,
            auto_refresh_kwargs={
                "client_id": self._app_login,
                "client_secret": self._app_password,
                "offline": self._offline,
            },
            token_updater=self._token_updater,
            token=self._token,
        )
Exemple #10
0
def _get_token(config):
    token = None
    # Uncomment this if you want to use a stored token
    # try:
    #     with open(TOKEN_FILE_PATH, 'rb') as handle:
    #         logger.info(f'Using token from file {TOKEN_FILE_PATH}.')
    #         token = pickle.load(handle)
    # except Exception as e:
    #     logger.info(f'Failed to get token from {TOKEN_FILE_PATH}.')

    if token is None:
        try:
            logger.info(f'Getting token from {ACCESS_TOKEN_URL}.')
            auth = HTTPBasicAuth(config['client_id'], config['client_secret'])
            client = LegacyApplicationClient(client_id=config['client_id'])
            oauth = OAuth2Session(client=client)
            token = oauth.fetch_token(token_url=ACCESS_TOKEN_URL,
                                      auth=auth,
                                      username=config['username'],
                                      password=config['password'])
            _token_updater(token)

        except Exception as e:
            logger.error(f'Failed to get token. Reason: {e}')
            exit(1)

    return token
Exemple #11
0
    def __init__(self,
                 oauth_domain,
                 username=None,
                 password=None,
                 access_token=None):
        self.domain = oauth_domain
        self.lastresponse = None
        token_url = 'https://%s/rest/login' % oauth_domain
        refresh_url = 'https://%s/rest/login/refresh' % oauth_domain

        if access_token:
            token = {'access_token': access_token, 'token_type': 'Bearer'}
        else:
            token = None

        session = OAuth2Session(client=LegacyApplicationClient('plenty-rest'),
                                auto_refresh_url=refresh_url,
                                token=token,
                                token_updater=self.token_saver)
        self.session = plentymarkets_compliance_fix(session)
        self.token = token

        if not access_token:
            self.token = self.session.fetch_token(token_url=token_url,
                                                  username=username,
                                                  password=password)
 def setUp(self):
     self.token = {
         'token_type': 'Bearer',
         'access_token': 'asdfoiw37850234lkjsdfsdf',
         'refresh_token': 'sldvafkjw34509s8dfsdf',
         'expires_in': 3600,
         'expires_at': fake_time + 3600,
     }
     # use someclientid:someclientsecret to easily differentiate between client and user credentials
     # these are the values used in oauthlib tests
     self.client_id = 'someclientid'
     self.client_secret = 'someclientsecret'
     self.user_username = '******'
     self.user_password = '******'
     self.client_WebApplication = WebApplicationClient(self.client_id,
                                                       code='asdf345xdf')
     self.client_LegacyApplication = LegacyApplicationClient(self.client_id)
     self.client_BackendApplication = BackendApplicationClient(
         self.client_id)
     self.client_MobileApplication = MobileApplicationClient(self.client_id)
     self.clients = [
         self.client_WebApplication,
         self.client_LegacyApplication,
         self.client_BackendApplication,
     ]
     self.all_clients = self.clients + [
         self.client_MobileApplication,
     ]
Exemple #13
0
def get_tokens(api_url: str, username: str, password: str,
               client_id: str = "cf", client_secret: str = "",
               verify_ssl: bool = True) -> Dict[str, str]:
    """
    Private function that authorizes against the UAA OAuth2 endpoint.
    """
    info_url = "{u}/v2/info".format(u=api_url)
    r = requests.get(info_url, verify=verify_ssl)
    if r.status_code != 200:
        logger.debug("failed to fetch Cloud Foundry API info from "
                     "'{u}': {c} => {s}".format(
                         u=info_url, c=r.status_code, s=r.text))
        raise FailedActivity("failed to retrieve Cloud Foundry information, "
                             "cannot proceed further")

    info = r.json()
    authorization_endpoint = info["authorization_endpoint"]
    auth_url = "{u}/oauth/token".format(u=authorization_endpoint)
    client = LegacyApplicationClient(username, password=password)
    s = OAuth2Session(client=client)
    try:
        r = s.fetch_token(auth_url, verify=verify_ssl, username=username,
                          password=password, auth=(client_id, client_secret))
    except OAuth2Error as x:
        logger.debug("failed to auth with the Cloud Foundry API at "
                     "{u}".format(u=auth_url), exc_info=x)
        raise FailedActivity("failed to auth against Cloud Foundry, "
                             "cannot proceed further")

    return r
Exemple #14
0
    def create_password_oauth2_session(self, *args, **kwargs):
        # pylint: disable=line-too-long
        """Create and return an [http://goo.gl/VehoOR|OAuth2] session object to a server with
        [https://goo.gl/N9R62O|resource owner password credentials] authorization grant
        [https://goo.gl/YjNlJf|access token].

        Arguments:
        - ``label``: A case and space insensitive string to identify the OAuth2 session.
        - ``token_url``: The OAuth2 token server URL.
        - ``tenant_id``: The client id obtained during registration with OAuth2 provider.
        - ``tenant_secret``: The client secret obtained during registration with OAuth2 provider.
        - ``username``: The resource owner username.
        - ``password``: The resource owner password.
        - ``base_url``: The server base URL.
        - ``headers``: Default headers dictionary.
        - ``cookies``: Default cookies dictionary.
        - ``timeout``: The connection timeout in seconds.
        - ``proxies``: The proxy URLs dictionary for HTTP and/or HTTPS communication.
        - ``verify``: Set to True if [http://goo.gl/8p7MOG|Requests] should verify the SSL
                      certificate.

        Examples:
        | ${var} = | Create Password OAuth2 Session | label | https://token |
        | ${var} = | Create Password OAuth2 Session | label | https://token | key | secret |
        | ${var} = | Create Password OAuth2 Session | label | https://token | username=usn | password=pwd |
        | ${var} = | Create Password OAuth2 Session | label | https://token | key | secret | usn | pwd |
        """
        # pylint: disable=line-too-long
        return self._create_oauth2_session(LegacyApplicationClient(''), *args,
                                           **kwargs)
    def regenerate_access_token_app_user(self,
                                         user_key: str,
                                         secret_key: str,
                                         scope="spei_admin") -> str:

        try:
            auth = self.__build_http_basic()
            scopes = [scope]
            client = LegacyApplicationClient(client_id=self._client_id)

            oauth = OAuth2Session(client=client)
            token = oauth.fetch_token(token_url=self._environment.token_url,
                                      username=user_key,
                                      password=secret_key,
                                      auth=auth,
                                      scope=scopes)

            key_search = user_key + scope
            token_cached = self._tokens_cached_app_user.get(key_search)
            if token_cached is None and len(
                    self._tokens_cached_app_user
            ) + 1 > self.MAX_APP_USER_SIZE_CACHED:
                for key in self._tokens_cached_app_user:
                    self._tokens_cached_app_user.pop(key)
                    break

            self._tokens_cached_app_user[key_search] = CachedToken(
                user_key, secret_key, token)

            return self.__format_to_header(token.get("access_token"))
        except Exception as ex:
            raise ApiException(
                reason="error to obtain token app user: {0}".format(ex))
Exemple #16
0
def test_oauth():
    client_id = cnconf['client_id']
    client_secret = cnconf['client_secret']
    username = cnconf['username']
    password = cnconf['password']
    token_url = cnconf['token_url']
    redirect_uri = ''
    authorization_response = ''
    scope = ''
    access_token = None
    print(client_id)
    print(client_secret)
    print(token_url)
    oauth = OAuth2Session(client=LegacyApplicationClient(client_id=client_id))
    token = oauth.fetch_token(token_url=token_url,
                              username=username,
                              password=password,
                              client_id=client_id,
                              client_secret=client_secret)
    r = oauth.get(
        'https://reveal-th-preview.smartregister.org/opensrp/rest/plans/e167b3e1-1991-487b-abc7-2e880c3df564'
    )
    print(r.text)
    mrs = json.loads(r.text)

    txt = json.dumps(mrs[0])
    #.encode('utf-8')
    print(txt)
    headers = {'content-type': 'application/json'}
    r = oauth.put(
        'https://reveal-th-preview.smartregister.org/opensrp/rest/plans',
        data=txt,
        headers=headers)
    #r = oauth.post('https://reveal-th-preview.smartregister.org/opensrp/rest/plans', data=mrs)
    print(r)
Exemple #17
0
def session_from_envvars(auth_url='https://geobigdata.io/auth/v1/oauth/token/',
                         environ_template=(('username', 'GBDX_USERNAME'),
                                           ('password', 'GBDX_PASSWORD'),
                                           ('client_id', 'GBDX_CLIENT_ID'),
                                           ('client_secret',
                                            'GBDX_CLIENT_SECRET'))):
    """Returns a session with the GBDX authorization token baked in,
    pulling the credentials from environment variables.

    environ_template - An iterable of key, value pairs. The key should
                      be the variables used in the oauth workflow, and
                      the values being the environment variables to
                      pull the configuration from.  Change the
                      template values if your envvars differ from the
                      default, but make sure the keys remain the same.
    """
    def save_token(token):
        s.token = token

    environ = {var: os.environ[envvar] for var, envvar in environ_template}
    s = OAuth2Session(client=LegacyApplicationClient(environ['client_id']),
                      auto_refresh_url=auth_url,
                      auto_refresh_kwargs={
                          'client_id': environ['client_id'],
                          'client_secret': environ['client_secret']
                      },
                      token_updater=save_token)

    s.fetch_token(auth_url, **environ)

    return s
Exemple #18
0
def fetch_token(username: str, password: str,
                auth_token_url: str,
                auth_client_id: str,
                ) -> OAuth2Token:
    """
    Get OAuth token from auth_token_url and store in config_path_tokenfile
    :return: OAuth2Token with session information or None if any error
    """

    try:
        client: Final[LegacyApplicationClient] = LegacyApplicationClient(client_id=auth_client_id)
        with OAuth2Session(client=client) as oauth_session:
            token: Final[OAuth2Token] = oauth_session.fetch_token(
                token_url=auth_token_url,
                client_id=auth_client_id,
                username=username,
                password=password
            )
            # arcpy.AddMessage(f"Login successful. Got token: {token}")
            return token
    except UnauthorizedClientError:
        arcpy.AddErrorMessage(
            f"Authorisation failed for token url {auth_token_url} as client {auth_client_id}.",
            exc_info=True,
        )
    except InvalidGrantError as e:
        arcpy.AddErrorMessage(f"Login failed. Reason {str(e)}", exc_info=False)
    except Exception:
        arcpy.AddErrorMessage(
            f"Unknown error on authentication for token url {auth_token_url} as client {auth_client_id}.",
            exc_info=True, )
Exemple #19
0
def authorize(user_credentials: dict, api_credentials: dict, feedback=False):
    """
    gets Opisense Token
    :param user_credentials: dict containing 'client_id' , 'client_secret' and 'scope' keys
    :param api_credentials: dict containing 'username' and 'password' keys
    :param feedback: if True, prints HTTP response code in console
    :return: str : Opisense Token
    """
    client_id = api_credentials['client_id']
    client_secret = api_credentials['client_secret']
    scope = api_credentials['scope']
    oauth = OAuth2Session(client=LegacyApplicationClient(client_id=client_id))
    token = oauth.fetch_token(
        token_url='https://identity.opinum.com/connect/token',
        scope=scope,
        username=user_credentials['username'],
        password=user_credentials['password'],
        client_id=client_id,
        client_secret=client_secret,
        auth=False)
    access_token = 'Bearer ' + token['access_token']
    if feedback == True:
        api_filter = oc.ApiFilter('account')
        account = GET(access_token, api_filter).json()
        print('Got a valid token for the account ' + str(account['id']) +
              ' - ' + str(account['name']))
    return access_token
def get_sc_token():
    # Credentials to generate token
    client_id = "Lf7m0371XCbMBlQ0fAFoGRJlfCs2JZpYvLU1uEvd"
    client_secret = ""
    get_token_url = (
        "https://supercoach.heraldsun.com.au/2019/api/afl/classic/v1/access_token"
    )

    # Supercoach credentials
    sc_user = "******"
    sc_pass = getpass.getpass()

    # Create Token
    oauth = OAuth2Session(client=LegacyApplicationClient(client_id=client_id))
    token = oauth.fetch_token(
        token_url=get_token_url,
        username=sc_user,
        password=sc_pass,
        client_id=client_id,
        client_secret=client_secret,
    )

    # Get token value from the Access Token Key
    sc_token = token["access_token"]
    return sc_token
Exemple #21
0
def get_oauth_token():
    """Returns OAuth access token."""
    try:
        logger.debug(settings.CLIENT_ID)
        logger.debug(settings.CLIENT_SECRET)
        logger.debug(settings.USER_NAME)
        logger.debug(settings.PASSWORD)

        logger.debug(settings.OAUTH_TOKEN_URL)
        logger.debug(settings.PATH_TO_CLIENT_CERT)
        logger.debug(settings.PATH_TO_VERIFY_CERT)
        verify_ssl = settings.CALLBACK_SSL_VERIFICATION
        if settings.CALLBACK_SSL_VERIFICATION:
            if settings.PATH_TO_VERIFY_CERT != "":
                verify_ssl = settings.PATH_TO_VERIFY_CERT

        logger.debug(verify_ssl)
        oauth = OAuth2Session(
            client=LegacyApplicationClient(client_id=settings.CLIENT_ID)
        )
        oauth.cert = settings.PATH_TO_CLIENT_CERT
        token = oauth.fetch_token(
            token_url=settings.OAUTH_TOKEN_URL,
            username=settings.USER_NAME,
            password=settings.PASSWORD,
            client_id=settings.CLIENT_ID,
            client_secret=settings.CLIENT_SECRET,
            verify=verify_ssl,
        )
        oauth.close()
        logger.debug("Response from oauth.fetch_token: " + str(token))
        return token
    except Exception:
        raise
Exemple #22
0
    def generate_token(self, user, password):
        """Takes user and password credentials and generates a new token

        :param user: user
        :param password: password
        :return:
            - dictionary containing token data
        :raises:
            - TokenCreateError: If there was an error generating the new token
        """

        logger.debug("(TOKEN_CREATE) :: User: %s" % user)

        session = OAuth2Session(client=LegacyApplicationClient(
            client_id=self.client_id))

        try:
            return dict(
                session.fetch_token(
                    token_url=self.token_url,
                    username=user,
                    password=password,
                    client_id=self.client_id,
                    client_secret=self.client_secret,
                ))
        except OAuth2Error as exception:
            raise TokenCreateError(
                "Error creating user token",
                exception.description,
                exception.status_code,
            )
Exemple #23
0
    def __init__(self, username, password, client_id, client_secret, url):
        self.username = username
        self.password = password
        self.client_id = client_id
        self.client_secret = client_secret
        self._base_url = url

        # Get a token via the Resource Owner Password Credential Grant OAuth2 API
        oauth = OAuth2Session(client=LegacyApplicationClient(
            client_id=client_id))
        self._token = oauth.fetch_token(verify=False,
                                        token_url=self._base_url + "o/token/",
                                        username=username,
                                        password=password,
                                        client_id=client_id,
                                        client_secret=client_secret)
        # Make a client for connecting to the API.
        self._client = OAuth2Session(client_id,
                                     token=self._token,
                                     auto_refresh_url=self._base_url +
                                     "o/token/",
                                     auto_refresh_kwargs={
                                         "client_id": client_id,
                                         "client_secret": client_secret
                                     },
                                     token_updater=self._token_updater)
def authenticate(username, password):
    """
    Returns:
        a dict with:
            pk: the pk of the user
            token: dict containing all the data from the api
                (access_token, refresh_token, expires_at etc.)
            user_data: dict containing user data such as
                first_name, last_name etc.
        if the authentication succeeds
        Raises Unauthorized if the authentication fails
    """
    session = MoJOAuth2Session(client=LegacyApplicationClient(
        client_id=settings.API_CLIENT_ID))

    token = session.fetch_token(token_url=get_request_token_url(),
                                username=username,
                                password=password,
                                auth=HTTPBasicAuth(settings.API_CLIENT_ID,
                                                   settings.API_CLIENT_SECRET),
                                timeout=15,
                                encoding='utf-8')

    user_data = session.get(
        '/users/{username}/'.format(username=username)).json()

    return {'pk': user_data.get('pk'), 'token': token, 'user_data': user_data}
 def setUp(self):
     self.token = {
         "token_type": "Bearer",
         "access_token": "asdfoiw37850234lkjsdfsdf",
         "refresh_token": "sldvafkjw34509s8dfsdf",
         "expires_in": 3600,
         "expires_at": fake_time + 3600,
     }
     # use someclientid:someclientsecret to easily differentiate between client and user credentials
     # these are the values used in oauthlib tests
     self.client_id = "someclientid"
     self.client_secret = "someclientsecret"
     self.user_username = "******"
     self.user_password = "******"
     self.client_WebApplication = WebApplicationClient(self.client_id,
                                                       code=CODE)
     self.client_LegacyApplication = LegacyApplicationClient(self.client_id)
     self.client_BackendApplication = BackendApplicationClient(
         self.client_id)
     self.client_MobileApplication = MobileApplicationClient(self.client_id)
     self.clients = [
         self.client_WebApplication,
         self.client_LegacyApplication,
         self.client_BackendApplication,
     ]
     self.all_clients = self.clients + [self.client_MobileApplication]
Exemple #26
0
 def legacy_app_flow(self):
     """Resource Ownwer Password Credentials Grant Flow
     Reference: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc
     """
     oauth = OAuth2Session(client=LegacyApplicationClient(client_id=self.client_id))
     try:
         if self.endpoint_version == 'v1':
             token = oauth.fetch_token(
                 token_url=self.token_url, 
                 username=self.username,
                 password=self.password, 
                 client_id=self.client_id,
                 client_secret=self.client_secret, 
                 resource=self.resource,
                 verify=self.verify
             )
         else:
             token = oauth.fetch_token(
                 token_url=self.token_url, 
                 username=self.username,
                 password=self.password, 
                 client_id=self.client_id,
                 client_secret=self.client_secret, 
                 scope=self.scope,
                 verify=self.verify
             )
     except InvalidGrantError as e:
         print(e)
         raise Exception('Please use another authorization method. I suggest trying the auth_code_grant() method.') 
     return token['access_token']
Exemple #27
0
    def login(self):
        if self.client and self.token:
            return True

        self.username = self.username or sickrage.app.config.api_username
        self.password = self.password or sickrage.app.config.api_password

        if self.username and self.password:
            oauth = OAuth2Session(client=LegacyApplicationClient(
                client_id=self.client_id))

            try:
                self.token = oauth.fetch_token(token_url=self.token_url,
                                               client_id=self.client_id,
                                               timeout=30,
                                               username=self.username,
                                               password=self.password)

                self.client = OAuth2Session(
                    self.client_id,
                    token=self.token,
                    auto_refresh_url=self.token_url,
                    auto_refresh_kwargs={"client_id": self.client_id},
                    token_updater=self.token_saver)

                return True
            except Exception:
                pass
Exemple #28
0
    def load_client(self):
        if self.API_KEY in self.access_data[self.HEADERS["Host"]]:
            token = self.access_data[self.HEADERS['Host']][self.API_KEY]
        else:
            if self.API_SECRET is None:
                raise APIAuthError(
                    "Refresh token is expired. To obtain new token, please, specify API SECRET argument"
                )
            oauth = OAuth2Session(client=LegacyApplicationClient(
                client_id=CLIENT_ID))
            token = oauth.fetch_token(token_url="https://%s/%s/" %
                                      (self.HEADERS['Host'], "api/o/token"),
                                      username=self.API_KEY,
                                      password=self.API_SECRET,
                                      client_id=CLIENT_ID,
                                      client_secret=CLIENT_SECRET)
            self._token_update_handler(token)

        client = OAuth2Session(CLIENT_ID,
                               token=token,
                               auto_refresh_kwargs={
                                   "client_id": CLIENT_ID,
                                   "client_secret": CLIENT_SECRET
                               },
                               auto_refresh_url="https://%s/%s/" %
                               (self.HEADERS['Host'], "api/o/token"),
                               token_updater=self._token_update_handler)
        retry = Retry(total=3, read=3, connect=3)
        adapter = HTTPAdapter(max_retries=retry)
        client.mount('http://', adapter)
        client.mount('https://', adapter)
        # client = requests.Session()
        # client.auth = httpsBasicAuth(self.API_KEY, self.API_SECRET)
        return client
Exemple #29
0
def download_http_oath2(url, target_dir, credentials, timeout=60):
    import requests
    from requests_oauthlib import OAuth2Session
    from oauthlib.oauth2 import LegacyApplicationClient
    from oauthlib.oauth2.rfc6749 import tokens

    assert credentials['grant_type'] == "ResourceOwnerPasswordCredentialsGrant"

    session = OAuth2Session(client=LegacyApplicationClient(client_id=credentials['client_id']))
    token = session.fetch_token(token_url=credentials['token_url'], username=credentials['username'],
                                password=credentials['password'], client_id=credentials['client_id'],
                                client_secret=credentials['client_secret'])
    try:
        r = session.get(url, timeout=timeout, stream=True)
        r.raise_for_status()
        local_file = os.path.join(target_dir, os.path.basename(urlparse(r.url).path))
        if "content-disposition" in [k.lower() for k in r.headers.keys()]:
            matches = re.findall("filename=\"?([^\"]+)\"?", r.headers["content-disposition"])
            if len(matches) > 0:
                local_file = os.path.join(target_dir, matches[-1])
        with open(local_file, 'wb') as output:
            for block in r.iter_content(1048576):  # use 1MB blocks
                output.write(block)
    except Exception as e:
        raise DownloadError('Error downloading %s (Reason: %s)' % (url, e))
    return local_file
Exemple #30
0
 def authorize(self):
     token_url = self._BASE_URL + "oauth2/token"
     client = LegacyApplicationClient(client_id=self.client_id)
     self.oauth = OAuth2Session(client=client, scope=['read_station'])
     self.oauth.fetch_token(token_url=token_url,
         username=self.username, password=self.password,
         client_id=self.client_id, client_secret=self.client_secret)
Exemple #31
0
 def __init__(self, client_id, username, password):
     self._username = username
     self._password = password
     self._client_id = client_id
     client = LegacyApplicationClient(client_id=client_id)
     self._session = OAuth2Session(client=client)
     self._token = self._fetch_token()
Exemple #32
0
 def __init__(self, username, password):
     client = LegacyApplicationClient(client_id='meine-tonies')
     self.session = _TonieOAuth2Session(client=client)
     self.session.fetch_token(token_url=self.TOKEN_URL,
                              username=username,
                              password=password)
     self._households = {}
    def test_prepare_request_body(self):
        """
        see issue #585
            https://github.com/oauthlib/oauthlib/issues/585
        """
        client = LegacyApplicationClient(self.client_id)

        # scenario 1, default behavior to not include `client_id`
        r1 = client.prepare_request_body(username=self.username, password=self.password)
        self.assertIn(r1, ('grant_type=password&username=%s&password=%s' % (self.username, self.password, ),
                           'grant_type=password&password=%s&username=%s' % (self.password, self.username, ),
                          ))

        # scenario 2, include `client_id` in the body
        r2 = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True)
        r2_params = dict(urlparse.parse_qsl(r2, keep_blank_values=True))
        self.assertEqual(len(r2_params.keys()), 4)
        self.assertEqual(r2_params['grant_type'], 'password')
        self.assertEqual(r2_params['username'], self.username)
        self.assertEqual(r2_params['password'], self.password)
        self.assertEqual(r2_params['client_id'], self.client_id)

        # scenario 3, include `client_id` + `client_secret` in the body
        r3 = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True, client_secret=self.client_secret)
        r3_params = dict(urlparse.parse_qsl(r3, keep_blank_values=True))
        self.assertEqual(len(r3_params.keys()), 5)
        self.assertEqual(r3_params['grant_type'], 'password')
        self.assertEqual(r3_params['username'], self.username)
        self.assertEqual(r3_params['password'], self.password)
        self.assertEqual(r3_params['client_id'], self.client_id)
        self.assertEqual(r3_params['client_secret'], self.client_secret)

        # scenario 4, `client_secret` is an empty string
        r4 = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True, client_secret='')
        r4_params = dict(urlparse.parse_qsl(r4, keep_blank_values=True))
        self.assertEqual(len(r4_params.keys()), 5)
        self.assertEqual(r4_params['grant_type'], 'password')
        self.assertEqual(r4_params['username'], self.username)
        self.assertEqual(r4_params['password'], self.password)
        self.assertEqual(r4_params['client_id'], self.client_id)
        self.assertEqual(r4_params['client_secret'], '')

        # scenario 4b`,` client_secret is `None`
        r4b = client.prepare_request_body(username=self.username, password=self.password, include_client_id=True, client_secret=None)
        r4b_params = dict(urlparse.parse_qsl(r4b, keep_blank_values=True))
        self.assertEqual(len(r4b_params.keys()), 4)
        self.assertEqual(r4b_params['grant_type'], 'password')
        self.assertEqual(r4b_params['username'], self.username)
        self.assertEqual(r4b_params['password'], self.password)
        self.assertEqual(r4b_params['client_id'], self.client_id)