Esempio n. 1
0
def s3_add_user_account(auth, **kwargs):
    """Verifies new external account credentials and adds to user's list"""
    try:
        access_key = request.json['access_key']
        secret_key = request.json['secret_key']
    except KeyError:
        raise HTTPError(httplib.BAD_REQUEST)

    if not (access_key and secret_key):
        return {
            'message': 'All the fields above are required.'
        }, httplib.BAD_REQUEST

    user_info = utils.get_user_info(access_key, secret_key)
    if not user_info:
        return {
            'message':
            ('Unable to access account.\n'
             'Check to make sure that the above credentials are valid, '
             'and that they have permission to list buckets.')
        }, httplib.BAD_REQUEST

    if not utils.can_list(access_key, secret_key):
        return {
            'message':
            ('Unable to list buckets.\n'
             'Listing buckets is required permission that can be changed via IAM'
             )
        }, httplib.BAD_REQUEST

    account = None
    try:
        account = ExternalAccount(
            provider=SHORT_NAME,
            provider_name=FULL_NAME,
            oauth_key=access_key,
            oauth_secret=secret_key,
            provider_id=user_info.id,
            display_name=user_info.display_name,
        )
        account.save()
    except ValidationError:
        # ... or get the old one
        account = ExternalAccount.objects.get(provider=SHORT_NAME,
                                              provider_id=user_info.id)
    assert account is not None

    if not auth.user.external_accounts.filter(id=account.id).exists():
        auth.user.external_accounts.add(account)

    # Ensure S3 is enabled.
    auth.user.get_or_add_addon('s3', auth=auth)
    auth.user.save()

    return {}
Esempio n. 2
0
def s3_add_user_account(auth, **kwargs):
    """Verifies new external account credentials and adds to user's list"""
    try:
        access_key = request.json['access_key']
        secret_key = request.json['secret_key']
    except KeyError:
        raise HTTPError(httplib.BAD_REQUEST)

    if not (access_key and secret_key):
        return {
            'message': 'All the fields above are required.'
        }, httplib.BAD_REQUEST

    user_info = utils.get_user_info(access_key, secret_key)
    if not user_info:
        return {
            'message': ('Unable to access account.\n'
                'Check to make sure that the above credentials are valid, '
                'and that they have permission to list buckets.')
        }, httplib.BAD_REQUEST

    if not utils.can_list(access_key, secret_key):
        return {
            'message': ('Unable to list buckets.\n'
                'Listing buckets is required permission that can be changed via IAM')
        }, httplib.BAD_REQUEST

    account = None
    try:
        account = ExternalAccount(
            provider=SHORT_NAME,
            provider_name=FULL_NAME,
            oauth_key=access_key,
            oauth_secret=secret_key,
            provider_id=user_info.id,
            display_name=user_info.display_name,
        )
        account.save()
    except ValidationError:
        # ... or get the old one
        account = ExternalAccount.objects.get(
            provider=SHORT_NAME,
            provider_id=user_info.id
        )
    assert account is not None

    if not auth.user.external_accounts.filter(id=account.id).exists():
        auth.user.external_accounts.add(account)

    # Ensure S3 is enabled.
    auth.user.get_or_add_addon('s3', auth=auth)
    auth.user.save()

    return {}
Esempio n. 3
0
def disconnect(external_account_id, institution_id, user):
    """disconnect OAuth"""
    account = ExternalAccount.load(external_account_id)

    if not account:
        raise Http404

    rdm_addon_option = get_rdm_addon_option(institution_id, account.provider)
    if not rdm_addon_option.external_accounts.filter(id=account.id).exists():
        raise Http404

    app = flask.Flask(__name__)
    with app.test_client() as c:
        # Create dummy Flask communication.
        # revoke_oauth_access method goes through flask
        # in order to confirm the user is logged in.
        c.get('/')
        # iterate AddonUserSettings for addons
        for user_settings in user.get_oauth_addons():
            if user_settings.oauth_provider.short_name == account.provider:
                user_settings.revoke_oauth_access(account, Auth(user))
                user_settings.save()

        # # only after all addons have been dealt with can we remove it from the user
        rdm_addon_option.external_accounts.remove(account)
        rdm_addon_option.save()
        user.external_accounts.remove(account)
        user.save()
    return HttpResponse('')
Esempio n. 4
0
def add_account(json_request, institution_id, addon_name):
    host = json_request['host']
    api_token = json_request['api_token']

    provider = DataverseProvider()
    # check authentication
    client.connect_or_error(host, api_token)
    # acquire authentication account information
    try:
        provider.account = ExternalAccount(
            provider=provider.short_name,
            provider_name=provider.name,
            display_name=host,
            oauth_key=host,
            oauth_secret=api_token,
            provider_id=api_token,
        )
        provider.account.save()
    except ValidationError:
        # ... or get the old one
        provider.account = ExternalAccount.objects.get(
            provider=provider.short_name, provider_id=api_token)
    rdm_addon_option = get_rdm_addon_option(institution_id, addon_name)
    if not rdm_addon_option.external_accounts.filter(
            id=provider.account.id).exists():
        rdm_addon_option.external_accounts.add(provider.account)

    return {}, httplib.OK
Esempio n. 5
0
def get_targets(delta, addon_short_name):
    # NOTE: expires_at is the  access_token's expiration date,
    # NOT the refresh token's
    return ExternalAccount.find(
        Q('expires_at', 'lt', timezone.now() - delta) &
        Q('date_last_refreshed', 'lt', timezone.now() - delta) &
        Q('provider', 'eq', addon_short_name)
    )
Esempio n. 6
0
    def get_object(self):
        user_settings = self.get_addon_settings(check_object_permissions=False)
        account_id = self.kwargs['account_id']

        account = ExternalAccount.load(account_id)
        if not (account and user_settings.external_accounts.filter(id=account.id).exists()):
            raise NotFound('Requested addon unavailable')
        return account
Esempio n. 7
0
    def get_object(self):
        user_settings = self.get_addon_settings(check_object_permissions=False)
        account_id = self.kwargs['account_id']

        account = ExternalAccount.load(account_id)
        if not (account and user_settings.external_accounts.filter(id=account.id).exists()):
            raise NotFound('Requested addon unavailable')
        return account
Esempio n. 8
0
def add_account(json_request, institution_id, addon_name):
    try:
        access_key = json_request['access_key']
        secret_key = json_request['secret_key']
    except KeyError:
        raise HTTPError(httplib.BAD_REQUEST)

    if not (access_key and secret_key):
        return {
            'message': 'All the fields above are required.'
        }, httplib.BAD_REQUEST

    user_info = get_user_info(access_key, secret_key)
    if not user_info:
        return {
            'message': ('Unable to access account.\n'
                'Check to make sure that the above credentials are valid, '
                'and that they have permission to list buckets.')
        }, httplib.BAD_REQUEST

    if not can_list(access_key, secret_key):
        return {
            'message': ('Unable to list buckets.\n'
                'Listing buckets is required permission that can be changed via IAM')
        }, httplib.BAD_REQUEST

    account = None
    try:
        account = ExternalAccount(
            provider=SHORT_NAME,
            provider_name=FULL_NAME,
            oauth_key=access_key,
            oauth_secret=secret_key,
            provider_id=user_info.id,
            display_name=user_info.display_name,
        )
        account.save()
    except ValidationError:
        # ... or get the old one
        account = ExternalAccount.objects.get(
            provider=SHORT_NAME,
            provider_id=user_info.id
        )
        if account.oauth_key != access_key or account.oauth_secret != secret_key:
            account.oauth_key = access_key
            account.oauth_secret = secret_key
            account.save()
    assert account is not None

    rdm_addon_option = get_rdm_addon_option(institution_id, addon_name)
    if not rdm_addon_option.external_accounts.filter(id=account.id).exists():
        rdm_addon_option.external_accounts.add(account)

    return {}, httplib.OK
Esempio n. 9
0
 def __init__(self, account=None, host=None, username=None, password=None):
     super(WEKOProvider, self).__init__(account=account)
     if account:
         self.account = account
     elif not account and host and password and username:
         self.account = ExternalAccount(display_name=username,
                                        oauth_key=password,
                                        oauth_secret=host,
                                        provider_id='{}:{}:{}'.format(
                                            REPOID_BASIC_AUTH, host,
                                            username),
                                        profile_url=host,
                                        provider=self.short_name,
                                        provider_name=self.name)
     else:
         self.account = None
Esempio n. 10
0
def dataverse_add_user_account(auth, **kwargs):
    """Verifies new external account credentials and adds to user's list"""
    user = auth.user
    provider = DataverseProvider()

    host = request.json.get('host').rstrip('/')
    api_token = request.json.get('api_token')

    # Verify that credentials are valid
    client.connect_or_error(host, api_token)

    # Note: `DataverseSerializer` expects display_name to be a URL
    try:
        provider.account = ExternalAccount(
            provider=provider.short_name,
            provider_name=provider.name,
            display_name=host,       # no username; show host
            oauth_key=host,          # hijacked; now host
            oauth_secret=api_token,  # hijacked; now api_token
            provider_id=api_token,   # Change to username if Dataverse allows
        )
        provider.account.save()
    except ValidationError:
        # ... or get the old one
        provider.account = ExternalAccount.objects.get(
            provider=provider.short_name,
            provider_id=api_token
        )

    if not user.external_accounts.filter(id=provider.account.id).exists():
        user.external_accounts.add(provider.account)

    user_addon = auth.user.get_addon('dataverse')
    if not user_addon:
        user.add_addon('dataverse')
    user.save()

    # Need to ensure that the user has dataverse enabled at this point
    user.get_or_add_addon('dataverse', auth=auth)
    user.save()

    return {}
Esempio n. 11
0
def oauth_disconnect(external_account_id, auth):
    account = ExternalAccount.load(external_account_id)
    user = auth.user

    if account is None:
        raise HTTPError(http.NOT_FOUND)

    if not user.external_accounts.filter(id=account.id).exists():
        raise HTTPError(http.FORBIDDEN)

    # iterate AddonUserSettings for addons
    for user_settings in user.get_oauth_addons():
        if user_settings.oauth_provider.short_name == account.provider:
            user_settings.revoke_oauth_access(account)
            user_settings.save()

    # ExternalAccount.remove_one(account)
    # # only after all addons have been dealt with can we remove it from the user
    user.external_accounts.remove(account)
    user.save()
Esempio n. 12
0
    def _import_auth(auth, node_addon, user_addon, **kwargs):
        """Import add-on credentials from the currently logged-in user to a node.
        """
        external_account = ExternalAccount.load(
            request.json['external_account_id'])

        if not user_addon.external_accounts.filter(
                id=external_account.id).exists():
            raise HTTPError(http_status.HTTP_403_FORBIDDEN)

        try:
            node_addon.set_auth(external_account, user_addon.owner)
        except PermissionsError:
            raise HTTPError(http_status.HTTP_403_FORBIDDEN)

        node_addon.save()

        return {
            'result': Serializer().serialize_settings(node_addon, auth.user),
            'message': 'Successfully imported access token from profile.',
        }
Esempio n. 13
0
    def _import_auth(auth, node_addon, user_addon, **kwargs):
        """Import add-on credentials from the currently logged-in user to a node.
        """
        external_account = ExternalAccount.load(
            request.json['external_account_id']
        )

        if not user_addon.external_accounts.filter(id=external_account.id).exists():
            raise HTTPError(http.FORBIDDEN)

        try:
            node_addon.set_auth(external_account, user_addon.owner)
        except PermissionsError:
            raise HTTPError(http.FORBIDDEN)

        node_addon.save()

        return {
            'result': Serializer().serialize_settings(node_addon, auth.user),
            'message': 'Successfully imported access token from profile.',
        }
Esempio n. 14
0
def gitlab_add_user_account(auth, **kwargs):
    """Verifies new external account credentials and adds to user's list"""

    host = request.json.get('host').rstrip('/')
    access_token = request.json.get('access_token')

    client = GitLabClient(access_token=access_token, host=host)
    try:
        user_info = client.user()
    except:
        # TODO: does gitlab even throw errors?
        raise

    if user_info.get('message') == '401 Unauthorized':
        raise HTTPError(http.UNAUTHORIZED)

    try:
        account = ExternalAccount(
            provider='gitlab',
            provider_name='GitLab',
            display_name=user_info['username'],
            oauth_key=access_token,
            oauth_secret=host,  # Hijacked to allow multiple hosts
            provider_id=user_info['web_url'],  # unique for host/username
        )
        account.save()
    except ValidationError:
        # ... or get the old one
        account = ExternalAccount.objects.get(provider='gitlab',
                                              provider_id=user_info['web_url'])
        if account.oauth_key != access_token:
            account.oauth_key = access_token
            account.save()

    user = auth.user
    if not user.external_accounts.filter(id=account.id).exists():
        user.external_accounts.add(account)

    user.get_or_add_addon('gitlab', auth=auth)
    user.save()

    return {}
Esempio n. 15
0
def gitlab_add_user_account(auth, **kwargs):
    """Verifies new external account credentials and adds to user's list"""

    host = request.json.get('host').rstrip('/')
    access_token = request.json.get('access_token')

    client = GitLabClient(access_token=access_token, host=host)
    try:
        user_info = client.user()
    except:
        # TODO: does gitlab even throw errors?
        raise

    if user_info.get('message') == '401 Unauthorized':
        raise HTTPError(http.UNAUTHORIZED)

    try:
        account = ExternalAccount(
            provider='gitlab',
            provider_name='GitLab',
            display_name=user_info['username'],
            oauth_key=access_token,
            oauth_secret=host,  # Hijacked to allow multiple hosts
            provider_id=user_info['web_url'],   # unique for host/username
        )
        account.save()
    except ValidationError:
        # ... or get the old one
        account = ExternalAccount.objects.get(
            provider='gitlab', provider_id=user_info['web_url']
        )
        if account.oauth_key != access_token:
            account.oauth_key = access_token
            account.save()

    user = auth.user
    if not user.external_accounts.filter(id=account.id).exists():
        user.external_accounts.add(account)

    user.get_or_add_addon('gitlab', auth=auth)
    user.save()

    return {}
Esempio n. 16
0
def gitlab_add_user_account(auth, **kwargs):
    """Verifies new external account credentials and adds to user's list"""

    host = request.json.get('host').rstrip('/')
    access_token = request.json.get('access_token')

    client = GitLabClient(access_token=access_token, host=host)

    user = client.user()

    try:
        account = ExternalAccount(
            provider='gitlab',
            provider_name='GitLab',
            display_name=user.username,
            oauth_key=access_token,
            oauth_secret=host,  # Hijacked to allow multiple hosts
            provider_id=user.web_url,  # unique for host/username
        )
        account.save()
    except ValidationError:
        # ... or get the old one
        account = ExternalAccount.objects.get(provider='gitlab',
                                              provider_id=user.web_url)
        if account.oauth_key != access_token:
            account.oauth_key = access_token
            account.save()

    user = auth.user
    if not user.external_accounts.filter(id=account.id).exists():
        user.external_accounts.add(account)

    user.get_or_add_addon('gitlab', auth=auth)
    user.save()

    return {}
Esempio n. 17
0
def gitlab_add_user_account(auth, **kwargs):
    """Verifies new external account credentials and adds to user's list"""

    host = request.json.get('host').rstrip('/')
    access_token = request.json.get('access_token')

    client = GitLabClient(access_token=access_token, host=host)

    user = client.user()

    try:
        account = ExternalAccount(
            provider='gitlab',
            provider_name='GitLab',
            display_name=user.username,
            oauth_key=access_token,
            oauth_secret=host,  # Hijacked to allow multiple hosts
            provider_id=user.web_url,   # unique for host/username
        )
        account.save()
    except ValidationError:
        # ... or get the old one
        account = ExternalAccount.objects.get(
            provider='gitlab', provider_id=user.web_url
        )
        if account.oauth_key != access_token:
            account.oauth_key = access_token
            account.save()

    user = auth.user
    if not user.external_accounts.filter(id=account.id).exists():
        user.external_accounts.add(account)

    user.get_or_add_addon('gitlab', auth=auth)
    user.save()

    return {}