Beispiel #1
0
def menbib_oauth_finish(**kwargs):
    user = get_current_user()
    if not user:
        raise HTTPError(http.FORBIDDEN)
    node = Node.load(session.data.get('menbib_auth_nid'))
    result = finish_auth()

    user.add_addon('menbib')
    user.save()
    user_settings = user.get_addon('menbib')
    user_settings.owner = user
    user_settings.access_token = result.access_token
    user_settings.refresh_token = result.refresh_token
    user_settings.token_type = result.token_type
    user_settings.expires_in = result.expires_in
    user_settings.save()

    flash('Successfully authorized Mendeley', 'success')

    if node:
        del session.data['menbib_auth_nid']
        if node.has_addon('menbib'):
            node_addon = node.get_addon('menbib')
            node_addon.set_user_auth(user_settings)
            node_addon.save()
        return redirect(node.web_url_for('node_setting'))

    return redirect(web_url_for('user_addons'))
Beispiel #2
0
def dropbox_oauth_finish(auth, **kwargs):
    """View called when the Oauth flow is completed. Adds a new DropboxUserSettings
    record to the user and saves the user's access token and account info.
    """
    if not auth.logged_in:
        raise HTTPError(http.FORBIDDEN)
    user = auth.user

    node = Node.load(session.data.get('dropbox_auth_nid'))
    result = finish_auth(node)
    # If result is a redirect response, follow the redirect
    if isinstance(result, BaseResponse):
        return result
    # Make sure user has dropbox enabled
    user.add_addon('dropbox')
    user.save()
    user_settings = user.get_addon('dropbox')
    user_settings.owner = user
    user_settings.access_token = result.access_token
    user_settings.dropbox_id = result.dropbox_id
    client = get_client_from_user_settings(user_settings)
    user_settings.dropbox_info = client.account_info()
    user_settings.save()

    flash('Successfully authorized Dropbox', 'success')
    if node:
        del session.data['dropbox_auth_nid']
        # Automatically use newly-created auth
        if node.has_addon('dropbox'):
            node_addon = node.get_addon('dropbox')
            node_addon.set_user_auth(user_settings)
            node_addon.save()
        return redirect(node.web_url_for('node_setting'))
    return redirect(web_url_for('user_addons'))
Beispiel #3
0
def googledrive_oauth_start(auth, **kwargs):
    """View function that does OAuth Authorization
    and returns access token"""
    # Run through the OAuth flow and retrieve credentials
    # Store the node ID on the session in order to get the correct redirect URL
    # upon finishing the flow
    user = auth.user
    nid = kwargs.get('nid') or kwargs.get('pid')
    node = models.Node.load(nid) if nid else None
    node_addon = user.get_addon('googledrive')

    # Fail if node provided and user not contributor
    if node and not node.is_contributor(user):
        raise HTTPError(http.FORBIDDEN)

    # If user has already authorized google drive, flash error message
    if node_addon and node_addon.has_auth:
        flash('You have already authorized Google Drive for this account', 'warning')
        return redirect(web_url_for('user_addons'))

    client = GoogleAuthClient()
    authorization_url, state = client.start()

    session.data['googledrive_auth_state'] = state
    if nid:
        session.data['googledrive_auth_nid'] = nid

    return redirect(authorization_url)
Beispiel #4
0
def dropbox_oauth_finish(auth, **kwargs):
    """View called when the Oauth flow is completed. Adds a new DropboxUserSettings
    record to the user and saves the user's access token and account info.
    """
    if not auth.logged_in:
        raise HTTPError(http.FORBIDDEN)
    user = auth.user

    node = Node.load(session.data.get('dropbox_auth_nid'))
    result = finish_auth(node)
    # If result is a redirect response, follow the redirect
    if isinstance(result, BaseResponse):
        return result
    # Make sure user has dropbox enabled
    user.add_addon('dropbox')
    user.save()
    user_settings = user.get_addon('dropbox')
    user_settings.owner = user
    user_settings.access_token = result.access_token
    user_settings.dropbox_id = result.dropbox_id
    client = get_client_from_user_settings(user_settings)
    user_settings.dropbox_info = client.account_info()
    user_settings.save()

    flash('Successfully authorized Dropbox', 'success')
    if node:
        del session.data['dropbox_auth_nid']
        # Automatically use newly-created auth
        if node.has_addon('dropbox'):
            node_addon = node.get_addon('dropbox')
            node_addon.set_user_auth(user_settings)
            node_addon.save()
        return redirect(node.web_url_for('node_setting'))
    return redirect(web_url_for('user_addons'))
Beispiel #5
0
def box_oauth_finish(auth, **kwargs):
    """View called when the Oauth flow is completed. Adds a new BoxUserSettings
    record to the user and saves the user's access token and account info.
    """
    user = auth.user
    node = Node.load(session.data.pop('box_auth_nid', None))

    # Handle request cancellations from Box's API
    if request.args.get('error'):
        flash('Box authorization request cancelled.')
        if node:
            return redirect(node.web_url_for('node_setting'))
        return redirect(web_url_for('user_addons'))

    result = finish_auth()

    # If result is a redirect response, follow the redirect
    if isinstance(result, BaseResponse):
        return result

    client = BoxClient(CredentialsV2(
        result['access_token'],
        result['refresh_token'],
        settings.BOX_KEY,
        settings.BOX_SECRET,
    ))

    about = client.get_user_info()
    oauth_settings = BoxOAuthSettings.load(about['id'])

    if not oauth_settings:
        oauth_settings = BoxOAuthSettings(user_id=about['id'], username=about['name'])
        oauth_settings.save()

    oauth_settings.refresh_token = result['refresh_token']
    oauth_settings.access_token = result['access_token']
    oauth_settings.expires_at = datetime.utcfromtimestamp(time.time() + 3600)

    # Make sure user has box enabled
    user.add_addon('box')
    user.save()

    user_settings = user.get_addon('box')
    user_settings.oauth_settings = oauth_settings

    user_settings.save()

    flash('Successfully authorized Box', 'success')

    if node:
        # Automatically use newly-created auth
        if node.has_addon('box'):
            node_addon = node.get_addon('box')
            node_addon.set_user_auth(user_settings)
            node_addon.save()
        return redirect(node.web_url_for('node_setting'))
    return redirect(web_url_for('user_addons'))
Beispiel #6
0
def googledrive_oauth_finish(auth, **kwargs):
    """View called when the Oauth flow is completed. Adds a new GoogleDriveUserSettings
    record to the user and saves the user's access token and account info.
    """
    user = auth.user
    node = Node.load(session.data.pop('googledrive_auth_nid', None))

    # Handle request cancellations from Google's API
    if request.args.get('error'):
        flash('Google Drive authorization request cancelled.')
        if node:
            return redirect(node.web_url_for('node_setting'))
        return redirect(web_url_for('user_addons'))

    user.add_addon('googledrive')
    user.save()

    code = request.args.get('code')
    user_settings = user.get_addon('googledrive')

    state = session.data.pop('googledrive_auth_state')
    if state != request.args.get('state'):
        raise HTTPError(http.BAD_REQUEST)

    if code is None:
        raise HTTPError(http.BAD_REQUEST)

    auth_client = GoogleAuthClient()
    token = auth_client.finish(code)
    info = auth_client.userinfo(token['access_token'])

    # Attempt to attach an existing oauth settings model
    oauth_settings = GoogleDriveOAuthSettings.load(info['sub'])
    # Create a new oauth settings model
    if not oauth_settings:
        oauth_settings = GoogleDriveOAuthSettings()
        oauth_settings.user_id = info['sub']
        oauth_settings.save()
    user_settings.oauth_settings = oauth_settings

    user_settings.username = info['name']
    user_settings.access_token = token['access_token']
    user_settings.refresh_token = token['refresh_token']
    user_settings.expires_at = datetime.utcfromtimestamp(token['expires_at'])
    user_settings.save()

    flash('Successfully authorized Google Drive', 'success')
    if node:
        if node.has_addon('googledrive'):
            node_addon = node.get_addon('googledrive')
            node_addon.set_user_auth(user_settings)
            node_addon.save()
        return redirect(node.web_url_for('node_setting'))
    return redirect(web_url_for('user_addons'))
Beispiel #7
0
def menbib_oauth_start(**kwargs):
    user = get_current_user()
    nid = kwargs.get('pid') or kwargs.get('nid')
    if nid:
        session.data['menbib_auth_nid'] = nid
    if not user:
        raise HTTPError(http.FORBIDDEN)
    if user.has_addon('menbib') and user.get_addon('menbib').has_auth:
        flash('You have already authorized Mendeley for this account', 'warning')
        return redirect(web_url_for('user_addons'))

    return redirect(get_auth_flow())
Beispiel #8
0
def dropbox_oauth_start(auth, **kwargs):
    user = auth.user
    # Store the node ID on the session in order to get the correct redirect URL
    # upon finishing the flow
    nid = kwargs.get('nid') or kwargs.get('pid')
    if nid:
        session.data['dropbox_auth_nid'] = nid
    if not user:
        raise HTTPError(http.FORBIDDEN)
    # If user has already authorized dropbox, flash error message
    if user.has_addon('dropbox') and user.get_addon('dropbox').has_auth:
        flash('You have already authorized Dropbox for this account', 'warning')
        return redirect(web_url_for('user_addons'))
    # Force the user to reapprove the dropbox authorization each time. Currently the
    # URI component force_reapprove is not configurable from the dropbox python client.
    # Issue: https://github.com/dropbox/dropbox-js/issues/160
    return redirect(get_auth_flow().start() + '&force_reapprove=true')
Beispiel #9
0
def dropbox_oauth_start(**kwargs):
    user = get_current_user()
    # Store the node ID on the session in order to get the correct redirect URL
    # upon finishing the flow
    nid = kwargs.get('nid') or kwargs.get('pid')
    if nid:
        session.data['dropbox_auth_nid'] = nid
    if not user:
        raise HTTPError(http.FORBIDDEN)
    # If user has already authorized dropbox, flash error message
    if user.has_addon('dropbox') and user.get_addon('dropbox').has_auth:
        flash('You have already authorized Dropbox for this account', 'warning')
        return redirect(web_url_for('user_addons'))
    # Force the user to reapprove the dropbox authorization each time. Currently the
    # URI component force_reapprove is not configurable from the dropbox python client.
    # Issue: https://github.com/dropbox/dropbox-js/issues/160
    return redirect(get_auth_flow().start() + '&force_reapprove=true')
Beispiel #10
0
def finish_auth():
    """View helper for finishing the Dropbox Oauth2 flow. Returns the
    access_token, dropbox_id, and url_state.

    Handles various errors that may be raised by the Dropbox client.
    """
    try:
        access_token, dropbox_id, url_state = get_auth_flow().finish(request.args)
    except DropboxOAuth2Flow.BadRequestException:
        raise HTTPError(http.BAD_REQUEST)
    except DropboxOAuth2Flow.BadStateException:
        # Start auth flow again
        return redirect(api_url_for('dropbox_oauth_start'))
    except DropboxOAuth2Flow.CsrfException:
        raise HTTPError(http.FORBIDDEN)
    except DropboxOAuth2Flow.NotApprovedException:  # User canceled flow
        flash('Did not approve token.', 'info')
        return redirect(web_url_for('user_addons'))
    except DropboxOAuth2Flow.ProviderException:
        raise HTTPError(http.FORBIDDEN)
    return AuthResult(access_token, dropbox_id, url_state)
Beispiel #11
0
def box_oauth_start(auth, **kwargs):
    user = auth.user
    # Store the node ID on the session in order to get the correct redirect URL
    # upon finishing the flow
    nid = kwargs.get('nid') or kwargs.get('pid')

    node = Node.load(nid)

    if node and not node.is_contributor(user):
        raise HTTPError(http.FORBIDDEN)

    csrf_token = security.random_string(10)
    session.data['box_oauth_state'] = csrf_token

    if nid:
        session.data['box_auth_nid'] = nid

    # If user has already authorized box, flash error message
    if user.has_addon('box') and user.get_addon('box').has_auth:
        flash('You have already authorized Box for this account', 'warning')
        return redirect(web_url_for('user_addons'))

    return redirect(get_auth_flow(csrf_token))
Beispiel #12
0
def menbib_get_page_info(node_addon, auth, **kwargs):

    folder = request.args.get('folder')

    if node_addon.user_settings is None:
        flash('Authorize Mendeley add-on in Settings', 'warning')
        raise HTTPError(http.FORBIDDEN)
    node = node_addon.owner
    user_settings = node_addon.user_settings
    client = get_node_addon_client(node_addon)
    client.from_settings(user_settings)
    client.refresh_access_token()
    user_folders = client.folders()
    user_library = client.library()
    user_folders_id = []
    user_folders_name = []

    for idx in range(0, len(user_folders)):
        user_folders_id.append(user_folders[idx]['id'])
        user_folders_name.append(user_folders[idx]['name'])

    if folder is not None:
        idx = user_folders_name.index(folder)
        folder_documentId = client.folder_details(user_folders_id[idx])
        documentId = folder_documentId['document_ids']
    else:
        documentId = user_library['document_ids']

    doc_meta = []

    for idx in range(0, len(documentId)):
        meta = client.document_details(documentId[idx])
        author = []
        second_line = ''
        for idy in range(0,len(meta['authors'])):
            author.append({
            'family':meta['authors'][idy]['surname'],
            'given': meta['authors'][idy]['forename'],
            })
            second_line = second_line + meta['authors'][idy]['forename'] + ' ' \
                           + meta['authors'][idy]['surname'] + ', '
        second_line = second_line[:-2]
        second_line = second_line + ' (' + str(meta.get('year','0')) + ')'

        third_line = meta['published_in'] + ' ' \
                  + meta.get('volume', '') + ' '  \
                  + '(' + meta.get('issue', '') + ')' + ' p. ' + \
          meta.get('pages', '')

        doc_meta.append({
            "author": author,
            "id": meta['id'],
            "issued": {
            "date-parts": [
                [
                    meta.get('year','0'),
                    meta.get('month','0'),
                    meta.get('day','0'),
                ]
            ]
            },
            "title": meta.get('title',"").replace('.',''),
            "type": meta.get('type',"").lower(),
            "abstract": meta.get('abstract',""),
            "publisher": meta.get('published_in',""),
            "volume": meta.get('volume',""),
            "page": meta.get('pages',""),
            "url": meta.get('url'," "),
            "second_line": second_line,
            "third_line": third_line.replace('()', '').strip(' p. '),
             })

    data = _view_project(node, auth, primary=True)

    rv = _page_content(node, node_addon)
    rv.update({
        'addon_page_js': user_settings.config.include_js.get('page'),
        'addon_page_css': user_settings.config.include_css.get('page'),
        'items': doc_meta,
        'citation_styles': menbib_settings.CITATION_STYLES,
        'export_formats': menbib_settings.EXPORT_FORMATS,
        'folder_names': user_folders_name,
    })
    rv.update(user_settings.config.to_json())
    rv.update(data)

    return rv