コード例 #1
0
ファイル: facebook.py プロジェクト: aaronpk/silo.pub
def callback():
    callback_uri = url_for('.callback', _external=True)
    result = process_authenticate_callback(callback_uri)
    if 'error' in result:
        flash(result['error'], category='danger')
        return redirect(url_for('views.index'))
    account = Account.query.filter_by(
        service='facebook', user_id=result['user_id']).first()

    if not account:
        account = Account(service='facebook', user_id=result['user_id'],
                          username=result['user_id'])
        db.session.add(account)

    account.user_info = result['user_info']
    account.token = result['token']

    account.update_sites([Facebook(
        url='https://www.facebook.com/{}'.format(account.user_id),
        # overloading "domain" to really mean "user's canonical url"
        domain='facebook.com/{}'.format(account.user_id),
        site_id=account.user_id)])

    db.session.commit()
    flash('Authorized {}: {}'.format(account.username, ', '.join(
        s.domain for s in account.sites)))
    util.set_authed(account.sites)

    return redirect(url_for('views.setup_account', service=SERVICE_NAME,
                            user_id=account.user_id))
コード例 #2
0
ファイル: github.py プロジェクト: kylewm/silo.pub
def process_callback(callback_uri):
    code = request.args.get('code')
    state = request.args.get('state')
    error = request.args.get('error')
    error_desc = request.args.get('error_description', '')

    if error:
        return {'error': 'GitHub auth canceled or failed with error: {}, '
                'description: {}'.format(error, error_desc)}

    if not validate_csrf(state):
        return {'error': 'csrf token mismatch in GitHub callback.'}

    r = requests.post('https://github.com/login/oauth/access_token', data={
        'client_id': current_app.config['GITHUB_CLIENT_ID'],
        'client_secret': current_app.config['GITHUB_CLIENT_SECRET'],
        'code': code,
        'redirect_uri': callback_uri,
        'state': state,
    })

    payload = parse_qs(r.text)
    current_app.logger.debug('auth responses from GitHub %s', payload)
    access_token = payload['access_token'][0]

    r = requests.get('https://api.github.com/user', headers={
        'Authorization': 'token ' + access_token,
    })

    user_info = r.json()
    user_id = str(user_info.get('id'))

    account = Account.query.filter_by(
        service='github', user_id=user_id).first()

    if not account:
        account = Account(service='github', user_id=user_id)
        db.session.add(account)

    account.username = user_info.get('login')
    account.token = access_token
    account.user_info = user_info

    account.update_sites([GitHub(
        url='https://github.com/{}'.format(account.username),
        # overloading "domain" to really mean "user's canonical url"
        domain='github.com/{}'.format(account.username),
        site_id=account.user_id)])

    db.session.commit()
    util.set_authed(account.sites)

    return {'account': account}
コード例 #3
0
ファイル: flickr.py プロジェクト: kylewm/silo.pub
def process_callback(callback_uri):
    verifier = request.args.get('oauth_verifier')
    request_token = request.args.get('oauth_token')
    if not verifier or not request_token:
        # user declined
        return {'error': 'Flickr authorization declined'}

    request_token_secret = session.get('oauth_token_secret')
    oauth = OAuth1Session(
        client_key=current_app.config['FLICKR_CLIENT_KEY'],
        client_secret=current_app.config['FLICKR_CLIENT_SECRET'],
        resource_owner_key=request_token,
        resource_owner_secret=request_token_secret)
    oauth.parse_authorization_response(request.url)
    # get the access token and secret
    r = oauth.fetch_access_token(ACCESS_TOKEN_URL)
    current_app.logger.debug('response from access token: %r', r)

    token = r.get('oauth_token')
    secret = r.get('oauth_token_secret')
    user_id = r.get('user_nsid')
    username = r.get('fullname')

    r = call_api_method('GET', 'flickr.people.getInfo', {'user_id': user_id},
                        token, secret)
    user_info = r.json()

    account = Account.query.filter_by(service=SERVICE_NAME,
                                      user_id=user_id).first()

    if not account:
        account = Account(service=SERVICE_NAME, user_id=user_id)
        db.session.add(account)

    account.username = username
    account.user_info = user_info
    account.token = token
    account.token_secret = secret

    account.update_sites([
        Flickr(url='https://flickr.com/{}'.format(account.user_id),
               domain='flickr.com/{}'.format(account.user_id),
               site_id=account.user_id)
    ])

    db.session.commit()
    flash('Authorized {}: {}'.format(
        account.username, ', '.join(s.domain for s in account.sites)))
    util.set_authed(account.sites)
    return {'account': account}
コード例 #4
0
ファイル: blogger.py プロジェクト: aaronpk/silo.pub
def callback():
    redirect_uri = url_for('.callback', _external=True)
    result = process_authenticate_callback(redirect_uri)

    if 'error' in result:
        flash(result['error'], category='danger')
        return redirect(url_for('views.index'))

    # find or create the account
    user_id = result['user_id']
    account = Account.lookup_by_user_id(SERVICE_NAME, user_id)

    if not account:
        account = Account(service=SERVICE_NAME, user_id=user_id)
        db.session.add(account)

    account.username = result['username']
    account.user_info = result['user_info']
    account.token = result['token']
    account.refresh_token = result['refresh']
    account.expiry = result['expiry']

    r = requests.get(API_BLOGS_URL, headers={
        'Authorization': 'Bearer ' + account.token,
    })

    if util.check_request_failed(r):
        return redirect(url_for('views.index'))

    payload = r.json()
    blogs = payload.get('items', [])

    # find or create the sites
    sites = []
    for blog in blogs:
        sites.append(Blogger(
            url=blog.get('url'),
            domain=util.domain_for_url(blog.get('url')),
            site_id=blog.get('id'),
            site_info=blog))
    account.update_sites(sites)

    db.session.commit()
    flash('Authorized {}: {}'.format(account.username, ', '.join(
        s.domain for s in account.sites)))
    util.set_authed(account.sites)

    return redirect(url_for('views.setup_account',
                            service=SERVICE_NAME,
                            user_id=account.user_id))
コード例 #5
0
ファイル: flickr.py プロジェクト: kylewm/silo.pub
def process_callback(callback_uri):
    verifier = request.args.get('oauth_verifier')
    request_token = request.args.get('oauth_token')
    if not verifier or not request_token:
        # user declined
        return {'error': 'Flickr authorization declined'}

    request_token_secret = session.get('oauth_token_secret')
    oauth = OAuth1Session(
        client_key=current_app.config['FLICKR_CLIENT_KEY'],
        client_secret=current_app.config['FLICKR_CLIENT_SECRET'],
        resource_owner_key=request_token,
        resource_owner_secret=request_token_secret)
    oauth.parse_authorization_response(request.url)
    # get the access token and secret
    r = oauth.fetch_access_token(ACCESS_TOKEN_URL)
    current_app.logger.debug('response from access token: %r', r)

    token = r.get('oauth_token')
    secret = r.get('oauth_token_secret')
    user_id = r.get('user_nsid')
    username = r.get('fullname')

    r = call_api_method('GET', 'flickr.people.getInfo', {
        'user_id': user_id
    }, token, secret)
    user_info = r.json()

    account = Account.query.filter_by(
        service=SERVICE_NAME, user_id=user_id).first()

    if not account:
        account = Account(service=SERVICE_NAME, user_id=user_id)
        db.session.add(account)

    account.username = username
    account.user_info = user_info
    account.token = token
    account.token_secret = secret

    account.update_sites([Flickr(
        url='https://flickr.com/{}'.format(account.user_id),
        domain='flickr.com/{}'.format(account.user_id),
        site_id=account.user_id)])

    db.session.commit()
    flash('Authorized {}: {}'.format(account.username, ', '.join(
        s.domain for s in account.sites)))
    util.set_authed(account.sites)
    return {'account': account}
コード例 #6
0
ファイル: tumblr.py プロジェクト: kylewm/silo.pub
def process_callback(callback_uri):
    verifier = request.args.get('oauth_verifier')
    request_token = request.args.get('oauth_token')
    if not verifier or not request_token:
        # user declined
        return {'error': 'Tumblr authorization declined'}

    request_token_secret = session.get('oauth_token_secret')
    oauth = OAuth1Session(
        client_key=current_app.config['TUMBLR_CLIENT_KEY'],
        client_secret=current_app.config['TUMBLR_CLIENT_SECRET'],
        resource_owner_key=request_token,
        resource_owner_secret=request_token_secret)
    oauth.parse_authorization_response(request.url)
    # get the access token and secret
    r = oauth.fetch_access_token(ACCESS_TOKEN_URL)
    token = r.get('oauth_token')
    secret = r.get('oauth_token_secret')

    info_resp = oauth.get(USER_INFO_URL).json()
    user_info = info_resp.get('response', {}).get('user')
    user_id = username = user_info.get('name')

    account = Account.query.filter_by(
        service='tumblr', user_id=user_id).first()

    if not account:
        account = Account(service='tumblr', user_id=user_id)
        db.session.add(account)

    account.username = username
    account.user_info = user_info
    account.token = token
    account.token_secret = secret

    sites = []
    for blog in user_info.get('blogs', []):
        sites.append(Tumblr(
            url=blog.get('url'),
            domain=util.domain_for_url(blog.get('url')),
            site_id=blog.get('name'),
            site_info=blog))
    account.update_sites(sites)

    db.session.commit()
    util.set_authed(account.sites)
    return {'account': account}
コード例 #7
0
def process_callback(callback_uri):
    verifier = request.args.get('oauth_verifier')
    request_token = request.args.get('oauth_token')
    if not verifier or not request_token:
        # user declined
        return {'error': 'Tumblr authorization declined'}

    request_token_secret = session.get('oauth_token_secret')
    oauth = OAuth1Session(
        client_key=current_app.config['TUMBLR_CLIENT_KEY'],
        client_secret=current_app.config['TUMBLR_CLIENT_SECRET'],
        resource_owner_key=request_token,
        resource_owner_secret=request_token_secret)
    oauth.parse_authorization_response(request.url)
    # get the access token and secret
    r = oauth.fetch_access_token(ACCESS_TOKEN_URL)
    token = r.get('oauth_token')
    secret = r.get('oauth_token_secret')

    info_resp = oauth.get(USER_INFO_URL).json()
    user_info = info_resp.get('response', {}).get('user')
    user_id = username = user_info.get('name')

    account = Account.query.filter_by(service='tumblr',
                                      user_id=user_id).first()

    if not account:
        account = Account(service='tumblr', user_id=user_id)
        db.session.add(account)

    account.username = username
    account.user_info = user_info
    account.token = token
    account.token_secret = secret

    sites = []
    for blog in user_info.get('blogs', []):
        sites.append(
            Tumblr(url=blog.get('url'),
                   domain=util.domain_for_url(blog.get('url')),
                   site_id=blog.get('name'),
                   site_info=blog))
    account.update_sites(sites)

    db.session.commit()
    util.set_authed(account.sites)
    return {'account': account}
コード例 #8
0
ファイル: tumblr.py プロジェクト: aaronpk/silo.pub
def callback():
    try:
        callback_uri = url_for(".callback", _external=True)
        result = process_authenticate_callback(callback_uri)
        if "error" in result:
            flash(result["error"], category="danger")
            return redirect(url_for("views.index"))

        account = Account.query.filter_by(service="tumblr", user_id=result["user_id"]).first()

        if not account:
            account = Account(service="tumblr", user_id=result["user_id"])
            db.session.add(account)

        account.username = result["username"]
        account.user_info = result["user_info"]
        account.token = result["token"]
        account.token_secret = result["secret"]

        sites = []
        for blog in result["user_info"].get("blogs", []):
            sites.append(
                Tumblr(
                    url=blog.get("url"),
                    domain=util.domain_for_url(blog.get("url")),
                    site_id=blog.get("name"),
                    site_info=blog,
                )
            )
        account.update_sites(sites)

        db.session.commit()
        flash("Authorized {}: {}".format(account.username, ", ".join(s.domain for s in account.sites)))
        util.set_authed(account.sites)
        return redirect(url_for("views.setup_account", service=SERVICE_NAME, user_id=account.user_id))

    except:
        current_app.logger.exception("During Tumblr authorization callback")
        flash(html.escape(str(sys.exc_info()[0])), "danger")
        return redirect(url_for("views.index"))
コード例 #9
0
ファイル: goodreads.py プロジェクト: aaronpk/silo.pub
def callback():
    try:
        callback_uri = url_for('.callback', _external=True)
        result = process_authenticate_callback(callback_uri)

        if 'error' in result:
            flash(result['error'], category='danger')
            return redirect(url_for('views.index'))

        account = Account.query.filter_by(
            service=SERVICE_NAME, user_id=result['user_id']).first()
        if not account:
            account = Account(service=SERVICE_NAME, user_id=result['user_id'])
            db.session.add(account)

        account.username = result['username']
        account.token = result['token']
        account.token_secret = result['secret']
        account.user_info = fetch_user_info(account.user_id)

        url = 'https://www.goodreads.com/user/show/' + account.user_id

        account.update_sites([Goodreads(
            url=url,
            domain='goodreads.com/' + account.user_id,
            site_id=account.user_id)])

        db.session.commit()
        flash('Authorized {} ({}): {}'.format(
            account.user_id, account.username, ', '.join(
                site.url for site in account.sites)))
        util.set_authed(account.sites)
        return redirect(url_for('views.setup_account', service=SERVICE_NAME,
                                user_id=account.user_id))
    except:
        current_app.logger.exception('goodreads authorization callback')
        flash(html.escape(str(sys.exc_info()[0])), 'danger')
        return redirect(url_for('views.index'))
コード例 #10
0
ファイル: twitter.py プロジェクト: kylewm/silo.pub
def process_callback(callback_uri):
    verifier = request.args.get('oauth_verifier')
    if not verifier:
        # user declined
        return {'error': 'Twitter authorization declined'}

    request_token = session.get('oauth_token')
    request_token_secret = session.get('oauth_token_secret')
    oauth_session = OAuth1Session(
        client_key=current_app.config['TWITTER_CLIENT_KEY'],
        client_secret=current_app.config['TWITTER_CLIENT_SECRET'],
        resource_owner_key=request_token,
        resource_owner_secret=request_token_secret,
        callback_uri=callback_uri)
    oauth_session.parse_authorization_response(request.url)
    # get the access token and secret
    r = oauth_session.fetch_access_token(ACCESS_TOKEN_URL)
    access_token = r.get('oauth_token')
    access_token_secret = r.get('oauth_token_secret')

    current_app.logger.debug('request token: %s, secret: %s', request_token,
                             request_token_secret)
    current_app.logger.debug('access token: %s, secret: %s', access_token,
                             access_token_secret)

    auth = OAuth1(client_key=current_app.config['TWITTER_CLIENT_KEY'],
                  client_secret=current_app.config['TWITTER_CLIENT_SECRET'],
                  resource_owner_key=access_token,
                  resource_owner_secret=access_token_secret)

    user_info = requests.get(VERIFY_CREDENTIALS_URL, auth=auth).json()

    if 'errors' in user_info:
        return {
            'error': 'Error fetching credentials %r' % user_info.get('errors')
        }

    user_id = user_info.get('id_str')
    username = user_info.get('screen_name')

    current_app.logger.debug('verified credentials. user_id=%s, username=%s',
                             user_id, username)
    current_app.logger.debug('user_info: %r', user_info)

    account = Account.query.filter_by(service='twitter',
                                      user_id=user_id).first()

    if not account:
        account = Account(service='twitter', user_id=user_id)
        db.session.add(account)

    account.username = username
    account.user_info = user_info
    account.token = access_token
    account.token_secret = access_token_secret

    account.update_sites([
        Twitter(url='https://twitter.com/{}'.format(account.username),
                domain='twitter.com/{}'.format(account.username),
                site_id=account.user_id)
    ])

    db.session.commit()
    util.set_authed(account.sites)
    return {'account': account}
コード例 #11
0
def process_callback(callback_uri):
    client_id = current_app.config['WORDPRESS_CLIENT_ID']
    client_secret = current_app.config['WORDPRESS_CLIENT_SECRET']

    code = request.args.get('code')
    error = request.args.get('error')
    error_desc = request.args.get('error_description')
    csrf = request.args.get('state', '')

    if error:
        return {
            'error':
            'Wordpress authorization canceled or failed with '
            'error: {}, and description: {}'.format(error, error_desc)
        }

    if not validate_csrf(csrf):
        return {'error': 'csrf token mismatch in wordpress callback.'}

    r = requests.post(API_TOKEN_URL,
                      data={
                          'client_id': client_id,
                          'redirect_uri': callback_uri,
                          'client_secret': client_secret,
                          'code': code,
                          'grant_type': 'authorization_code',
                      })

    if r.status_code // 100 != 2:
        error_obj = r.json()
        return {
            'error':
            'Error ({}) requesting access token: {}, description: {}'.format(
                r.status_code, error_obj.get('error'),
                error_obj.get('error_description')),
        }

    payload = r.json()
    current_app.logger.info('WordPress token endpoint repsonse: %r', payload)

    access_token = payload.get('access_token')
    blog_url = payload.get('blog_url')
    blog_id = str(payload.get('blog_id'))

    r = requests.get(API_ME_URL,
                     headers={'Authorization': 'Bearer ' + access_token})
    current_app.logger.info('User info response %s', r)

    if r.status_code // 100 != 2:
        error_obj = r.json()
        return {
            'error':
            'Error fetching user info: {}, description: {}'.format(
                error_obj.get('error'), error_obj.get('error_description'))
        }

    user_info = r.json()
    user_id = str(user_info.get('ID'))
    username = user_info.get('username')

    account = Account.query.filter_by(service=SERVICE_NAME,
                                      user_id=user_id).first()
    if not account:
        account = Account(service=SERVICE_NAME, user_id=user_id)
    account.username = username
    account.user_info = user_info

    current_app.logger.info('Fetching site info %s',
                            API_SITE_URL.format(blog_id))
    r = requests.get(API_SITE_URL.format(blog_id),
                     headers={'Authorization': 'Bearer ' + access_token})
    current_app.logger.info('Site info response %s', r)

    if r.status_code // 100 != 2:
        error_obj = r.json()
        return {
            'error':
            'Error ({}) fetching site info: {}, description: {}'.format(
                r.status_code, error_obj.get('error'),
                error_obj.get('error_description'))
        }

    site = Wordpress.query.filter_by(account=account, site_id=blog_id).first()
    if not site:
        site = Wordpress(site_id=blog_id)
        account.sites.append(site)

    site.site_info = r.json()
    site.url = blog_url
    site.domain = util.domain_for_url(blog_url)
    site.token = access_token

    db.session.add(account)
    db.session.commit()

    util.set_authed([site])
    return {
        'account': account,
        'site': site,
    }
コード例 #12
0
ファイル: github.py プロジェクト: kylewm/silo.pub
def process_callback(callback_uri):
    code = request.args.get('code')
    state = request.args.get('state')
    error = request.args.get('error')
    error_desc = request.args.get('error_description', '')

    if error:
        return {
            'error':
            'GitHub auth canceled or failed with error: {}, '
            'description: {}'.format(error, error_desc)
        }

    if not validate_csrf(state):
        return {'error': 'csrf token mismatch in GitHub callback.'}

    r = requests.post('https://github.com/login/oauth/access_token',
                      data={
                          'client_id':
                          current_app.config['GITHUB_CLIENT_ID'],
                          'client_secret':
                          current_app.config['GITHUB_CLIENT_SECRET'],
                          'code':
                          code,
                          'redirect_uri':
                          callback_uri,
                          'state':
                          state,
                      })

    payload = parse_qs(r.text)
    current_app.logger.debug('auth responses from GitHub %s', payload)
    access_token = payload['access_token'][0]

    r = requests.get('https://api.github.com/user',
                     headers={
                         'Authorization': 'token ' + access_token,
                     })

    user_info = r.json()
    user_id = str(user_info.get('id'))

    account = Account.query.filter_by(service='github',
                                      user_id=user_id).first()

    if not account:
        account = Account(service='github', user_id=user_id)
        db.session.add(account)

    account.username = user_info.get('login')
    account.token = access_token
    account.user_info = user_info

    account.update_sites([
        GitHub(
            url='https://github.com/{}'.format(account.username),
            # overloading "domain" to really mean "user's canonical url"
            domain='github.com/{}'.format(account.username),
            site_id=account.user_id)
    ])

    db.session.commit()
    util.set_authed(account.sites)

    return {'account': account}
コード例 #13
0
def process_callback(callback_uri):
    code = request.args.get('code')
    state = request.args.get('state')
    error = request.args.get('error')
    error_desc = request.args.get('error_description', '')

    if error:
        return {
            'error':
            'Facebook auth canceled or failed with error: {}, '
            'description: {}'.format(error, error_desc)
        }

    if not validate_csrf(state):
        return {'error': 'csrf token mismatch in Facebook callback.'}

    r = requests.get('https://graph.facebook.com/oauth/access_token',
                     params={
                         'client_id':
                         current_app.config['FACEBOOK_CLIENT_ID'],
                         'client_secret':
                         current_app.config['FACEBOOK_CLIENT_SECRET'],
                         'redirect_uri':
                         callback_uri,
                         'code':
                         code,
                         'scope':
                         PERMISSION_SCOPES,
                     })

    if r.status_code // 100 != 2:
        error_obj = r.json()
        error = error_obj.get('error')
        error_desc = error_obj.get('error_description')
        return {
            'error':
            'Error ({}) requesting access token: {}, '
            'description: {}'.format(r.status_code, error, error_desc)
        }

    payload = json.loads(r.text)
    current_app.logger.debug('auth responses from Facebook %s', payload)
    current_app.logger.debug('raw response %s', r.text)
    access_token = payload['access_token']

    r = requests.get('https://graph.facebook.com/v2.5/me',
                     params={
                         'access_token': access_token,
                         'fields': 'id,name,picture',
                     })

    if r.status_code // 100 != 2:
        error_obj = r.json()
        error = error_obj.get('error')
        error_desc = error_obj.get('error_description')
        return {
            'error':
            'Error ({}) requesting authed user info: {}, '
            'description: {}'.format(r.status_code, error, error_desc)
        }

    user_info = r.json()
    current_app.logger.debug('authed user info from Facebook %s', user_info)

    user_id = user_info.get('id')
    account = Account.query.filter_by(service='facebook',
                                      user_id=user_id).first()

    if not account:
        account = Account(service='facebook',
                          user_id=user_id,
                          username=user_id)
        db.session.add(account)

    account.user_info = user_info
    account.token = access_token

    account.update_sites([
        Facebook(
            url='https://www.facebook.com/{}'.format(account.user_id),
            # overloading "domain" to really mean "user's canonical url"
            domain='facebook.com/{}'.format(account.user_id),
            site_id=account.user_id)
    ])

    db.session.commit()
    util.set_authed(account.sites)
    return {'account': account}
コード例 #14
0
ファイル: facebook.py プロジェクト: kylewm/silo.pub
def process_callback(callback_uri):
    code = request.args.get('code')
    state = request.args.get('state')
    error = request.args.get('error')
    error_desc = request.args.get('error_description', '')

    if error:
        return {'error': 'Facebook auth canceled or failed with error: {}, '
                'description: {}'.format(error, error_desc)}

    if not validate_csrf(state):
        return {'error': 'csrf token mismatch in Facebook callback.'}

    r = requests.get('https://graph.facebook.com/oauth/access_token', params={
        'client_id': current_app.config['FACEBOOK_CLIENT_ID'],
        'client_secret': current_app.config['FACEBOOK_CLIENT_SECRET'],
        'redirect_uri': callback_uri,
        'code': code,
        'scope': PERMISSION_SCOPES,
    })

    if r.status_code // 100 != 2:
        error_obj = r.json()
        error = error_obj.get('error')
        error_desc = error_obj.get('error_description')
        return {'error': 'Error ({}) requesting access token: {}, '
                'description: {}' .format(r.status_code, error, error_desc)}

    payload = json.loads(r.text)
    current_app.logger.debug('auth responses from Facebook %s', payload)
    current_app.logger.debug('raw response %s', r.text)
    access_token = payload['access_token']

    r = requests.get('https://graph.facebook.com/v2.5/me', params={
        'access_token': access_token,
        'fields': 'id,name,picture',
    })

    if r.status_code // 100 != 2:
        error_obj = r.json()
        error = error_obj.get('error')
        error_desc = error_obj.get('error_description')
        return {'error': 'Error ({}) requesting authed user info: {}, '
                'description: {}' .format(r.status_code, error, error_desc)}

    user_info = r.json()
    current_app.logger.debug('authed user info from Facebook %s', user_info)

    user_id = user_info.get('id')
    account = Account.query.filter_by(
        service='facebook', user_id=user_id).first()

    if not account:
        account = Account(service='facebook', user_id=user_id,
                          username=user_id)
        db.session.add(account)

    account.user_info = user_info
    account.token = access_token

    account.update_sites([Facebook(
        url='https://www.facebook.com/{}'.format(account.user_id),
        # overloading "domain" to really mean "user's canonical url"
        domain='facebook.com/{}'.format(account.user_id),
        site_id=account.user_id)])

    db.session.commit()
    util.set_authed(account.sites)
    return {'account': account}
コード例 #15
0
ファイル: twitter.py プロジェクト: kylewm/silo.pub
def process_callback(callback_uri):
    verifier = request.args.get('oauth_verifier')
    if not verifier:
        # user declined
        return {'error': 'Twitter authorization declined'}

    request_token = session.get('oauth_token')
    request_token_secret = session.get('oauth_token_secret')
    oauth_session = OAuth1Session(
        client_key=current_app.config['TWITTER_CLIENT_KEY'],
        client_secret=current_app.config['TWITTER_CLIENT_SECRET'],
        resource_owner_key=request_token,
        resource_owner_secret=request_token_secret,
        callback_uri=callback_uri)
    oauth_session.parse_authorization_response(request.url)
    # get the access token and secret
    r = oauth_session.fetch_access_token(ACCESS_TOKEN_URL)
    access_token = r.get('oauth_token')
    access_token_secret = r.get('oauth_token_secret')

    current_app.logger.debug('request token: %s, secret: %s',
                             request_token, request_token_secret)
    current_app.logger.debug('access token: %s, secret: %s',
                             access_token, access_token_secret)

    auth = OAuth1(
        client_key=current_app.config['TWITTER_CLIENT_KEY'],
        client_secret=current_app.config['TWITTER_CLIENT_SECRET'],
        resource_owner_key=access_token,
        resource_owner_secret=access_token_secret)

    user_info = requests.get(VERIFY_CREDENTIALS_URL, auth=auth).json()

    if 'errors' in user_info:
        return {'error': 'Error fetching credentials %r'
                % user_info.get('errors')}

    user_id = user_info.get('id_str')
    username = user_info.get('screen_name')

    current_app.logger.debug('verified credentials. user_id=%s, username=%s',
                             user_id, username)
    current_app.logger.debug('user_info: %r', user_info)

    account = Account.query.filter_by(
        service='twitter', user_id=user_id).first()

    if not account:
        account = Account(service='twitter', user_id=user_id)
        db.session.add(account)

    account.username = username
    account.user_info = user_info
    account.token = access_token
    account.token_secret = access_token_secret

    account.update_sites([Twitter(
        url='https://twitter.com/{}'.format(account.username),
        domain='twitter.com/{}'.format(account.username),
        site_id=account.user_id)])

    db.session.commit()
    util.set_authed(account.sites)
    return {'account': account}
コード例 #16
0
ファイル: goodreads.py プロジェクト: kylewm/silo.pub
def process_callback(callback_uri):
    if request.args.get('authorize') != '1':
        return {'error': 'Goodreads user declined'}

    request_token = session.get('oauth_token')
    request_token_secret = session.get('oauth_token_secret')

    if request_token != request.args.get('oauth_token'):
        return {'error': 'oauth_token does not match'}

    oauth_session = OAuth1Session(
        client_key=current_app.config['GOODREADS_CLIENT_KEY'],
        client_secret=current_app.config['GOODREADS_CLIENT_SECRET'],
        resource_owner_key=request_token,
        resource_owner_secret=request_token_secret,
        callback_uri=callback_uri,
        # Goodreads does not use a verifier, put something here so that
        # the library doesn't error
        verifier='unused')
    oauth_session.parse_authorization_response(request.url)
    # get the access token and secret
    r = oauth_session.fetch_access_token(ACCESS_TOKEN_URL)
    access_token = r.get('oauth_token')
    access_token_secret = r.get('oauth_token_secret')

    r = oauth_session.get('https://www.goodreads.com/api/auth_user')

    if r.status_code // 100 != 2:
        return {
            'error': 'unexpected response from auth.user. status={}, body={}'
            .format(r.status_code, r.text)
        }

    # EXAMPLE RESPONSE
    """<?xml version="1.0" encoding="UTF-8"?>
    <GoodreadsResponse>
      <Request>
        <authentication>true</authentication>
          <key><![CDATA[qRuT5Xit4xERHQGzyq9QSw]]></key>
        <method><![CDATA[api_auth_user]]></method>
      </Request>
      <user id="4544167">
      <name>Kyle Mahan</name>
      <link><![CDATA[https://www.goodreads.com/user/show/4544167-kyle?utm_medium=api]]></link>
    </user>
    </GoodreadsResponse>"""

    root = ETree.fromstring(r.content)
    user = root.find('user')
    user_id = user.attrib['id']
    user_name = user.findtext('name')

    account = Account.query.filter_by(
        service=SERVICE_NAME, user_id=user_id).first()
    if not account:
        account = Account(service=SERVICE_NAME, user_id=user_id)
        db.session.add(account)

    account.username = user_name
    account.token = access_token
    account.token_secret = access_token_secret
    account.user_info = fetch_user_info(account.user_id)

    url = 'https://www.goodreads.com/user/show/' + account.user_id

    account.update_sites([Goodreads(
        url=url,
        domain='goodreads.com/' + account.user_id,
        site_id=account.user_id)])

    db.session.commit()
    util.set_authed(account.sites)
    return {'account': account}
コード例 #17
0
ファイル: wordpress.py プロジェクト: aaronpk/silo.pub
def callback():
    state = request.args.get('state', '')
    csrf, purpose = state.split('|', 1)

    # wordpress only allows us one redirect url, so use the state parameter to
    # hack it to redirect to another one
    if purpose == 'id':
        return redirect(url_for(
            'micropub.indieauth_callback',
            code=request.args.get('code'),
            error=request.args.get('error'),
            error_description=request.args.get('error_description'),
            state=state))

    redirect_uri = url_for('wordpress.callback', _external=True)
    result = process_authenticate_callback(redirect_uri)

    if 'error' in result:
        flash(result['error'], category='danger')
        return redirect(url_for('views.index'))

    access_token = result['token']
    username = result['username']
    user_id = result['user_id']
    user_info = result['user_info']
    blog_id = result['blog_id']
    blog_url = result['blog_url']

    account = Account.query.filter_by(
        service=SERVICE_NAME, user_id=user_id).first()
    if not account:
        account = Account(service=SERVICE_NAME, user_id=user_id)
    account.username = username
    account.user_info = user_info

    current_app.logger.info(
        'Fetching site info %s', API_SITE_URL.format(blog_id))
    r = requests.get(API_SITE_URL.format(blog_id), headers={
        'Authorization': 'Bearer ' + access_token})
    current_app.logger.info('Site info response %s', r)

    if r.status_code // 100 != 2:
        error_obj = r.json()
        flash('Error ({}) fetching site info: {}, description: {}'.format(
            r.status_code, error_obj.get('error'),
            error_obj.get('error_description')), 'danger')
        return redirect(url_for('views.index'))

    site = Wordpress.query.filter_by(
        account=account, site_id=blog_id).first()
    if not site:
        site = Wordpress(site_id=blog_id)
        account.sites.append(site)

    site.site_info = r.json()
    site.url = blog_url
    site.domain = util.domain_for_url(blog_url)
    site.token = access_token

    db.session.add(account)
    db.session.commit()

    flash('Authorized {}: {}'.format(account.username, site.domain))
    util.set_authed([site])

    return redirect(url_for('views.setup_site', service=SERVICE_NAME,
                            domain=site.domain))
コード例 #18
0
ファイル: blogger.py プロジェクト: kylewm/silo.pub
def process_callback(redirect_uri):
    code = request.args.get('code')
    error = request.args.get('error')

    if error:
        return {'error': 'Blogger authorization canceled or '
                'failed with error: {}' .format(error)}

    if not validate_csrf(request.args.get('state')):
        return {'error': 'csrf token mismatch in blogger callback.'}

    r = requests.post(API_TOKEN_URL, data={
        'code': code,
        'client_id': current_app.config['GOOGLE_CLIENT_ID'],
        'client_secret': current_app.config['GOOGLE_CLIENT_SECRET'],
        'redirect_uri': redirect_uri,
        'grant_type': 'authorization_code',
    })

    if util.check_request_failed(r):
        return {'error': 'failed to validate access token'}

    current_app.logger.info('Got Blogger access token response: %s', r.text)

    payload = r.json()
    access_token = payload.get('access_token')
    expires_in = payload.get('expires_in')
    refresh_token = payload.get('refresh_token')

    if expires_in:
        expiry = datetime.datetime.utcnow() + datetime.timedelta(
            seconds=int(expires_in))
    else:
        expiry = None

    current_app.logger.info(
        'Got Blogger access token: %s. expiry: %s. refresh token: %s',
        access_token, expiry, refresh_token)

    r = requests.get(API_SELF_URL, headers={
        'Authorization': 'Bearer ' + access_token,
    })

    if util.check_request_failed(r):
        return {'error': 'failed to fetch {}'.format(API_SELF_URL)}

    payload = r.json()
    username = user_id = payload.get('id')

    # find or create the account
    account = Account.lookup_by_user_id(SERVICE_NAME, user_id)

    if not account:
        account = Account(service=SERVICE_NAME, user_id=user_id)
        db.session.add(account)

    account.username = username
    account.user_info = payload
    account.token = access_token
    account.refresh_token = refresh_token
    account.expiry = expiry

    r = requests.get(API_BLOGS_URL, headers={
        'Authorization': 'Bearer ' + account.token,
    })

    if util.check_request_failed(r):
        return redirect(url_for('views.index'))

    payload = r.json()
    blogs = payload.get('items', [])

    # find or create the sites
    sites = []
    for blog in blogs:
        sites.append(Blogger(
            url=blog.get('url'),
            domain=util.domain_for_url(blog.get('url')),
            site_id=blog.get('id'),
            site_info=blog))
    account.update_sites(sites)

    db.session.commit()
    util.set_authed(account.sites)
    return {'account': account}
コード例 #19
0
def process_callback(callback_uri):
    if request.args.get('authorize') != '1':
        return {'error': 'Goodreads user declined'}

    request_token = session.get('oauth_token')
    request_token_secret = session.get('oauth_token_secret')

    if request_token != request.args.get('oauth_token'):
        return {'error': 'oauth_token does not match'}

    oauth_session = OAuth1Session(
        client_key=current_app.config['GOODREADS_CLIENT_KEY'],
        client_secret=current_app.config['GOODREADS_CLIENT_SECRET'],
        resource_owner_key=request_token,
        resource_owner_secret=request_token_secret,
        callback_uri=callback_uri,
        # Goodreads does not use a verifier, put something here so that
        # the library doesn't error
        verifier='unused')
    oauth_session.parse_authorization_response(request.url)
    # get the access token and secret
    r = oauth_session.fetch_access_token(ACCESS_TOKEN_URL)
    access_token = r.get('oauth_token')
    access_token_secret = r.get('oauth_token_secret')

    r = oauth_session.get('https://www.goodreads.com/api/auth_user')

    if r.status_code // 100 != 2:
        return {
            'error':
            'unexpected response from auth.user. status={}, body={}'.format(
                r.status_code, r.text)
        }

    # EXAMPLE RESPONSE
    """<?xml version="1.0" encoding="UTF-8"?>
    <GoodreadsResponse>
      <Request>
        <authentication>true</authentication>
          <key><![CDATA[qRuT5Xit4xERHQGzyq9QSw]]></key>
        <method><![CDATA[api_auth_user]]></method>
      </Request>
      <user id="4544167">
      <name>Kyle Mahan</name>
      <link><![CDATA[https://www.goodreads.com/user/show/4544167-kyle?utm_medium=api]]></link>
    </user>
    </GoodreadsResponse>"""

    root = ETree.fromstring(r.content)
    user = root.find('user')
    user_id = user.attrib['id']
    user_name = user.findtext('name')

    account = Account.query.filter_by(service=SERVICE_NAME,
                                      user_id=user_id).first()
    if not account:
        account = Account(service=SERVICE_NAME, user_id=user_id)
        db.session.add(account)

    account.username = user_name
    account.token = access_token
    account.token_secret = access_token_secret
    account.user_info = fetch_user_info(account.user_id)

    url = 'https://www.goodreads.com/user/show/' + account.user_id

    account.update_sites([
        Goodreads(url=url,
                  domain='goodreads.com/' + account.user_id,
                  site_id=account.user_id)
    ])

    db.session.commit()
    util.set_authed(account.sites)
    return {'account': account}