Esempio n. 1
0
 def __init__(self,
              app=None,
              base_url=None,
              consumer_key=None,
              consumer_secret=None,
              **kwargs):
     RauthServiceMixin.__init__(self, app=app, base_url=base_url)
     OAuth2Service.__init__(self,
                            consumer_key=consumer_key,
                            consumer_secret=consumer_secret,
                            **kwargs)
Esempio n. 2
0
    def request(self, method, url, access_token=None, **kwargs):
        '''
        Make a request using an `access_token` obtained via the
            :func:`authorized_handler`.

        If no access_token is provided and a
        :func:`RauthServiceMixin.tokengetter` **was** provided, the
        :func:`RauthServiceMixin.tokengetter` will be called.

        :param method: Same as :func:`rauth.OAuth2Service.request`.
        :param url: Same as :func:`rauth.OAuth2Service.request`, except when a
            `base_url` was provided to the constructor, in which case the URL
            should be any valid endpoint after being :func:`urljoin` ed with
            the `base_url`.
        :param access_token: The `access_token` required to make requests
            against this service.
        :param kwargs: Any `kwargs` that can be passed to
            :func:`OAuth2Service.request`.
        '''
        url = self._expand_url(url)

        if access_token is None and self.tokengetter_f is not None:
            access_token = self.tokengetter_f()

        # add in the access_token
        if 'params' not in kwargs:
            kwargs['params'] = {'access_token': access_token}
        elif 'access_token' not in kwargs['params']:
            # TODO: handle if the user sends bytes -> properly append 'access_token'
            kwargs['params']['access_token'] = access_token

        # call the parent implementation
        return RauthResponse(OAuth2Service.request(self, method, url, **kwargs))
Esempio n. 3
0
    def request(self, method, url, access_token=None, **kwargs):
        '''
        Make a request using an `access_token` obtained via the
            :func:`authorized_handler`.

        If no access_token is provided and a
        :func:`RauthServiceMixin.tokengetter` **was** provided, the
        :func:`RauthServiceMixin.tokengetter` will be called.

        :param method: Same as :func:`rauth.OAuth2Service.request`.
        :param url: Same as :func:`rauth.OAuth2Service.request`, except when a
            `base_url` was provided to the constructor, in which case the URL
            should be any valid endpoint after being :func:`urljoin` ed with
            the `base_url`.
        :param access_token: The `access_token` required to make requests
            against this service.
        :param kwargs: Any `kwargs` that can be passed to
            :func:`OAuth2Service.request`.
        '''
        url = self._expand_url(url)

        if access_token is None and self.tokengetter_f is not None:
            access_token = self.tokengetter_f()

        # add in the access_token
        if 'params' not in kwargs:
            kwargs['params'] = {'access_token': access_token}
        elif 'access_token' not in kwargs['params']:
            # TODO: handle if the user sends bytes -> properly append 'access_token'
            kwargs['params']['access_token'] = access_token

        # call the parent implementation
        return RauthResponse(OAuth2Service.request(self, method, url,
                                                   **kwargs))
	def __init__(self, request_token=None):
		facebook = Facebook()
        	self.service = OAuth2Service(name=facebook.name,
                         authorize_url=facebook.authorize_url,
                         access_token_url=facebook.access_token_url,
                         client_id=facebook.client_id,
                         client_secret=facebook.client_secret,
			 scope=facebook.scope,
                         base_url=facebook.base_url)
Esempio n. 5
0
 def test_init_with_access_token(self):
     service = OAuth2Service(
         'example',
         consumer_key='123',
         consumer_secret='456',
         access_token_url='http://example.com/access_token',
         authorize_url='http://example.com/authorize',
         access_token='321')
     self.assertEqual(service.access_token, '321')
Esempio n. 6
0
 def __init__(self):
     super(GoogleSignIn, self).__init__('google')
     self.service = OAuth2Service(
         name='google',
         client_id=self.consumer_id,
         client_secret=self.consumer_secret,
         authorize_url="https://accounts.google.com/o/oauth2/v2/auth",
         base_url="https://www.googleapis.com/oauth2/v3/userinfo",
         access_token_url="https://www.googleapis.com/oauth2/v4/token")
Esempio n. 7
0
 def __init__(self):
     super(FacebookSignIn, self).__init__('facebook')
     ##OAuth2Service
     self.service = OAuth2Service(
         name='facebook',
         client_id=self.consumer_id,
         client_secret=self.consumer_secret,
         authorize_url='https://graph.facebook.com/oauth/authorize',
         access_token_url='https://graph.facebook.com/oauth/access_token',
         base_url='https://graph.facebook.com/')
Esempio n. 8
0
    def setUp(self):
        RauthTestCase.setUp(self)

        # mock service for testing
        service = OAuth2Service(
            'example',
            consumer_key='123',
            consumer_secret='456',
            access_token_url='http://example.com/access_token',
            authorize_url='http://example.com/authorize')
        self.service = service
Esempio n. 9
0
 def __init__(self, consumer_key, consumer_secret, pin=None):
     self.redu = OAuth2Service(
         name='redu',
         authorize_url='http://redu.com.br/oauth/authorize',
         access_token_url='http://redu.com.br/oauth/token',
         consumer_key=consumer_key,
         consumer_secret=consumer_secret)
     self.consumer_key = consumer_key
     self.consumer_secret = consumer_secret
     if pin:
         self.initClient(pin)
Esempio n. 10
0
def github_oauth(app):
    from rauth.service import OAuth2Service

    github = OAuth2Service(
        name='github',
        base_url='https://api.github.com/',
        authorize_url='https://github.com/login/oauth/authorize',
        access_token_url='https://github.com/login/oauth/access_token',
        client_id=app.config['GITHUB_CONSUMER_KEY'],
        client_secret=app.config['GITHUB_CONSUMER_SECRET'],
    )
    return github
Esempio n. 11
0
def get_foursquare_service_container():
    """
    Return a service wrapper that provides
    OAuth 2.0 flow methods.
    """
    client_id = application.config['FOURSQUARE_CLIENT_ID']
    client_secret = application.config['FOURSQUARE_CLIENT_SECRET']
    service_container = OAuth2Service(client_id=client_id,
                                client_secret=client_secret,
                                name='foursquare',
                                authorize_url='https://foursquare.com/oauth2/authenticate',
                                access_token_url='https://foursquare.com/oauth2/access_token',
                                base_url='https://api.foursquare.com/v2/')
    return service_container
Esempio n. 12
0
 def __init__(self,client_secret,client_id,authorization_url,redirect_url):
     
     self.client_secret = client_secret
     self.client_id = client_id
     self.authorization_url = authorization_url
     self.redirect_url = redirect_url
     
     self.apiObj = OAuth2Service(client_id=self.client_id,client_secret=self.client_secret,authorize_url=self.authorization_url) 
     authorize_url = self.apiObj.get_authorize_url()
     print('Visit this URL in your browser: {url}'.format(url=authorize_url))
     webbrowser.open(authorize_url)
     
     url_with_code = input('Copy URL from your browser\'s address bar: ')
     self.access_token = re.search('\#access_token=([^&]*)', url_with_code).group(1)
     self.headers = {'Authorization': 'Bearer '+self.access_token}
Esempio n. 13
0
def setup_github(state):
    gh.BASE_URL = 'https://api.github.com/'
    gh.oauth = OAuth2Service(
        name='github',
        base_url=gh.BASE_URL,
        authorize_url='https://github.com/login/oauth/authorize',
        access_token_url='https://github.com/login/oauth/access_token',
        client_id=state.app.config['GITHUB_CLIENT_ID'],
        client_secret=state.app.config['GITHUB_CLIENT_SECRET'],
        session_obj=GHOAuthSession,
    )
    gh.AppSession = lambda: GHAppSession(
        gh.BASE_URL,
        client_id=state.app.config['GITHUB_CLIENT_ID'],
        client_secret=state.app.config['GITHUB_CLIENT_SECRET'],
    )
Esempio n. 14
0
    def setUp(self):
        RauthTestCase.setUp(self)

        self.access_token_url = 'https://example.com/access'
        self.authorize_url = 'https://example.com/authorize'
        self.base_url = 'https://example/api/'

        self.service = OAuth2Service(self.client_id,
                                     self.client_secret,
                                     access_token_url=self.access_token_url,
                                     authorize_url=self.authorize_url,
                                     base_url=self.base_url)

        self.session = self.service.get_session(self.access_token)

        # patches
        self.session.request = self.fake_request
        self.service.get_session = self.fake_get_session
Esempio n. 15
0
    def fake_request(self,
                     method,
                     url,
                     mock_request,
                     bearer_auth=False,
                     **kwargs):
        mock_request.return_value = self.response

        url = self.session._set_url(url)

        service = OAuth2Service(self.client_id,
                                self.client_secret,
                                access_token_url=self.access_token_url,
                                authorize_url=self.authorize_url,
                                base_url=self.base_url)

        session = service.get_session(self.access_token)
        r = session.request(method,
                            url,
                            bearer_auth=bearer_auth,
                            **deepcopy(kwargs))

        kwargs.setdefault('params', {})

        if is_basestring(kwargs.get('params', {})):
            kwargs['params'] = dict(parse_qsl(kwargs['params']))

        if bearer_auth and self.access_token is not None:
            bearer_token = 'Bearer {token}'.format(token=self.access_token)
            bearer_header = {'Authorization': bearer_token}
            kwargs.setdefault('headers', {})
            kwargs['headers'].update(bearer_header)
        else:
            kwargs['params'].update({'access_token': self.access_token})

        mock_request.assert_called_with(method,
                                        url,
                                        timeout=OAUTH2_DEFAULT_TIMEOUT,
                                        **kwargs)
        return r
Esempio n. 16
0
def linkedin(request):
    try:
        app = AppData.objects.filter(nome="Linkedin")[0]
    except:
        return HttpResponse(
            "Devi prima impostare i dettagli della tua Applicazione")

    Objlinkedin = OAuth2Service(
        client_id=app.app_id,
        client_secret=app.app_secret,
        name='linkedin',
        authorize_url='https://www.linkedin.com/uas/oauth2/authorization',
        access_token_url='https://www.linkedin.com/uas/oauth2/accessToken',
        base_url='http://www.linkedin.com/v1/')

    try:
        data = {
            'code': request.GET["code"],
            'grant_type': 'authorization_code',
            'redirect_uri': 'http://dev.artirion.com/linkedin'
        }

        session = Objlinkedin.get_raw_access_token(data=data)
        response = session.json()
        return HttpResponse(
            "Copia l'access token: <textarea style='width:400px; height:200px;' readonly='true'>%s</textarea>"
            % response["access_token"])

    except:
        params = {
            'scope': 'r_network rw_nus',
            'state': binascii.b2a_hex(os.urandom(15)),
            'response_type': 'code',
            'redirect_uri': 'http://dev.artirion.com/linkedin',
        }
        authorize_url = Objlinkedin.get_authorize_url(**params)
        return HttpResponseRedirect(authorize_url)
Esempio n. 17
0
 def __init__(self, app=None, base_url=None, consumer_key=None, consumer_secret=None, **kwargs):
     OAuth2Service.__init__(self, consumer_key=consumer_key, consumer_secret=consumer_secret, **kwargs)
     RauthServiceMixin.__init__(self, app=app, base_url=base_url)
Esempio n. 18
0
app.debug = True
app.config.from_object(__name__)
db = SQLAlchemy(app)

# setup logging, with default level of INFO and higher
handler = RotatingFileHandler('console.log', maxBytes=1000000, backupCount=5)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)

app.secret_key = '\x03R\xe8!\xfdZ\x87*\xe9\x07sVI\x88|tt"\xdcb\xab=\xf8;'

# rauth OAuth 2.0 service wrapper
graph_url = 'https://graph.facebook.com/'
facebook = OAuth2Service(name='facebook',
                         authorize_url='https://www.facebook.com/dialog/oauth',
                         access_token_url=graph_url + 'oauth/access_token',
                         client_id=app.config['FB_CLIENT_ID'],
                         client_secret=app.config['FB_CLIENT_SECRET'],
                         base_url=graph_url)


# models
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    fb_id = db.Column(db.String(120))

    def __init__(self, username, fb_id):
        self.username = username
        self.fb_id = fb_id

    def __repr__(self):
Esempio n. 19
0
import requests
import datetime

from flask import (Flask, flash, request, redirect, render_template, url_for,
                   session)
from rauth.service import OAuth2Service
from record import Tag, Record
from knowledgegraph import KnowledgeGraph

tag = Tag()
kg = KnowledgeGraph()
# Use your own values in your real application
github = OAuth2Service(
    name='github',
    base_url='https://api.github.com/',
    access_token_url='https://github.com/login/oauth/access_token',
    authorize_url='https://github.com/login/oauth/authorize',
    client_id='38f88bfb83a0908e0103',
    client_secret='7f0c4c5d52972e1d767d0145c6e02ce54342ade3',
)
SECRET_KEY = '\xfb\x12\xdf\xa1@i\xd6>V\xc0\xbb\x8fp\x16#Z\x0b\x81\xeb\x16'
utils = Utils()
app = Flask(__name__)
app.secret_key = SECRET_KEY

extensionManager = ExtensionManager()
args_history = {}


@app.route('/', methods=['GET', 'POST'])
def index():
    print request.args.get('column', '')
Esempio n. 20
0
                                                 params=params,
                                                 **req_kwargs)


class GHOAuthSession(OAuth2Session):
    """An OAuth2 session for user authentication, with a nice UA header"""
    def __init__(self, *args, **kwargs):
        super(GHOAuthSession, self).__init__(*args, **kwargs)
        useragentify(self)


gh_oauth = OAuth2Service(
    name='github',
    base_url=GH_BASE_URL,
    authorize_url='https://github.com/login/oauth/authorize',
    access_token_url='https://github.com/login/oauth/access_token',
    client_id=app.config['GITHUB_CLIENT_ID'],
    client_secret=app.config['GITHUB_CLIENT_SECRET'],
    session_obj=GHOAuthSession,
)
AppSession = lambda: GHAppSession(
    GH_BASE_URL,
    client_id=app.config['GITHUB_CLIENT_ID'],
    client_secret=app.config['GITHUB_CLIENT_SECRET'],
)


@kale.dbgetter
def get_mongodb():
    return mongo.db
    def auth_user(self, username, password, req=None):
        """
        Tries to find email and identity of the user from OAuth2 provider. If it
        doesn't find any of them, returns (None, None)

        @param username: Isn't used in this function
        @type username: str

        @param password: Isn't used in this function
        @type password: str

        @param req: request
        @type req: invenio.webinterface_handler_wsgi.SimulatedModPythonRequest

        @rtype: str|NoneType, str|NoneType
        """
        from invenio.webinterface_handler import wash_urlargd
        from invenio.access_control_config import CFG_OAUTH2_CONFIGURATIONS
        from rauth.service import OAuth2Service
        from invenio.access_control_config import CFG_OAUTH2_PROVIDERS

        self.__init_req(req)

        args = wash_urlargd(req.form, {
            'code': (str, ''),
            'provider': (str, '')
        })

        req.g['oauth2_provider_name'] = args['provider']

        if not req.g['oauth2_provider_name']:
            # If provider name isn't given
            req.g['oauth2_msg'] = 21
            return None, None

        # Some providers doesn't construct return uri properly.
        # Since the callback uri is:
        # /youraccount/login?login_method=oauth2&provider=something
        # they may return to:
        # /youraccount/login?login_method=oauth2&provider=something?code=#
        # instead of
        # /youraccount/login?login_method=oauth2&provider=something&code=#
        if '?' in req.g['oauth2_provider_name']:
            (req.g['oauth2_provider_name'], args['code']) = \
        (
            req.g['oauth2_provider_name'][:req.g['oauth2_provider_name'].index('?')],
            req.g['oauth2_provider_name'][req.g['oauth2_provider_name'].index('?') + 1 + len("code="):]
            )

        if not req.g['oauth2_provider_name'] in CFG_OAUTH2_PROVIDERS:
            req.g['oauth2_msg'] = 22
            return None, None

        # Load the configurations to construct OAuth2 service
        config = CFG_OAUTH2_CONFIGURATIONS[req.g['oauth2_provider_name']]

        req.g['oauth2_debug'] = config.get('debug', 0)

        provider = OAuth2Service(name=req.g['oauth2_provider_name'],
                                 client_id=config['consumer_key'],
                                 client_secret=config['consumer_secret'],
                                 access_token_url=config['access_token_url'],
                                 authorize_url=config['authorize_url'])

        data = dict(
            code=args['code'],
            client_id=config['consumer_key'],
            client_secret=config['consumer_secret'],
            grant_type="authorization_code",
            # Construct redirect uri without having '/' character at the
            # left most of SITE_SECURE_URL
            redirect_uri=CFG_SITE_URL + '/youraccount/login?' +
            urlencode({
                'login_method': 'oauth2',
                'provider': req.g['oauth2_provider_name']
            }))
        headers = dict(Accept="application/json")
        kwargs = dict(data=data, headers=headers)
        # Get the access token
        r = provider.get_raw_access_token(method='POST', **kwargs)

        keys = ['access_token', 'orcid']
        try:
            access_token, orcid = process_token_request(r, json.loads, *keys)
            token_content = {'access_token': access_token, 'orcid': orcid}
        except:
            req.g['oauth2_msg'] = 22
            return None, None

        req.g['oauth2_access_token'] = token_content['access_token']

        if req.g['oauth2_debug']:
            req.g['oauth2_debug_msg'] = str(token_content) + "<br/>"

        if req.g['oauth2_provider_name'] == 'orcid':
            req.g['oauth2_orcid'] = token_content['orcid']
            email, identity = self._get_user_email_and_id_from_orcid(req)
        else:
            # Some providers send the user information and access token together.
            email, identity = self._get_user_email_and_id(token_content, req)

        if not identity:
            profile = provider.request(
                'GET', config['request_url'].format(
                    access_token=token_content['access_token'], id=identity))
            req.g['oauth2_access_token'] = token_content['access_token']

            if req.g['oauth2_debug']:
                req.g['oauth2_debug_msg'] += str(profile.content)

            email, identity = self._get_user_email_and_id(profile.content, req)

        if identity:
            # If identity is found, add the name of the provider at the
            # beginning of the identity because different providers may have
            # different users with same id.
            identity = "%s:%s" % (req.g['oauth2_provider_name'], identity)
        else:
            req.g['oauth2_msg'] = 23

        if req.g['oauth2_debug']:
            req.g['oauth2_msg'] = "<code>%s</code>" % req.g[
                'oauth2_debug_msg'].replace("\n", "<br/>")
            return None, None

        return email, identity
Esempio n. 22
0
import requests
import json
from random import shuffle, randint
from rauth.service import OAuth2Service
from urllib.parse import unquote
import datetime

REC_URL = app.config["BASE_REC_URL"]

#URL_DATABASE = "http://127.0.0.1:8080"
URL_DATABASE = "https://es-booking-service.herokuapp.com"

graph_url = 'https://graph.facebook.com/'
facebook = OAuth2Service(name='facebook',
                         authorize_url='https://www.facebook.com/dialog/oauth',
                         access_token_url=graph_url + 'oauth/access_token',
                         client_id=app.config["FACEBOOK_APP_ID"],
                         client_secret=app.config["FACEBOOK_APP_SECRET"],
                         base_url=graph_url)


@app.route('/')
def index():

    return redirect(url_for('getRecomended'))


@app.route('/facebook/login')
def login():
    redirect_uri = url_for('authorized', _external=True)
    params = {'redirect_uri': redirect_uri, 'scope': 'user_likes '}
    # print(facebook.get_authorize_url(**params))
Esempio n. 23
0
from rauth.service import OAuth2Service

# Get a real consumer key & secret from:
# https://github.com/settings/applications/new
github = OAuth2Service(
    client_id='8ae4946cc5a9af76f6d7',
    client_secret='48aeb2b3c9226ae2b698eef4d7e6310473ccafa7',
    name='github',
    authorize_url='https://github.com/login/oauth/authorize',
    access_token_url='https://github.com/login/oauth/access_token',
    base_url='https://api.github.com/')

print 'Visit this URL in your browser: ' + github.get_authorize_url()

# This is a bit cumbersome, but you need to copy the code=something (just the
# `something` part) out of the URL that's redirected to AFTER you login and
# authorize the demo application
code = raw_input('Enter code parameter (code=something) from URL: ')

# create a dictionary for the data we'll post on the get_access_token request
data = dict(code=code, redirect_uri='https://github.com/litl/rauth/')

# retrieve the authenticated session
session = github.get_auth_session(data=data)

# make a request using the authenticated session
user = session.get('user').json()

print 'currently logged in as: ' + user['login']
Esempio n. 24
0
from rauth.service import OAuth2Service

import re
import webbrowser

# Get a real consumer key & secret from:
# https://developers.facebook.com/apps

facebook = OAuth2Service(
    client_id='440483442642551',
    client_secret='cd54f1ace848fa2a7ac89a31ed9c1b61',
    name='facebook',
    authorize_url='https://graph.facebook.com/oauth/authorize',
    access_token_url='https://graph.facebook.com/oauth/access_token',
    base_url='https://graph.facebook.com/')

redirect_uri = 'https://www.facebook.com/connect/login_success.html'

params = {
    'scope': 'read_stream',
    'response_type': 'token',
    'redirect_uri': redirect_uri
}

authorize_url = facebook.get_authorize_url(**params)

print 'Visit this URL in your browser: ' + authorize_url
webbrowser.open(authorize_url)

url_with_code = raw_input('Copy URL from your browser\'s address bar: ')
access_token = re.search('\#access_token=([^&]*)', url_with_code).group(1)
Esempio n. 25
0
from newslynx.lib.serialize import jsonify
from newslynx.lib import dates
from newslynx.views.decorators import load_user, load_org
from newslynx.views.util import obj_or_404, delete_response
from newslynx.lib import url

# blueprint
bp = Blueprint('auth_facebook', __name__)

# auth flow
if settings.FB_ENABLED:
    _graph_url = 'https://graph.facebook.com/'
    fb_oauth = OAuth2Service(
        name='facebook',
        authorize_url='https://www.facebook.com/dialog/oauth',
        access_token_url=_graph_url + 'oauth/access_token',
        client_id=settings.FACEBOOK_APP_ID,
        client_secret=settings.FACEBOOK_APP_SECRET,
        base_url=_graph_url)

# oauth utilities #


def fb_extend_oauth_token(temp_access_token):
    url = _graph_url + "oauth/access_token"
    params = {
        'grant_type': 'fb_exchange_token',
        'client_id': settings.FACEBOOK_APP_ID,
        'client_secret': settings.FACEBOOK_APP_SECRET,
        'fb_exchange_token': temp_access_token
    }
Esempio n. 26
0
from rauth.service import OAuth2Service

# Get a real consumer key & secret from:
# https://code.google.com/apis/console/
google = OAuth2Service(
    name='google',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    consumer_key='',
    consumer_secret='')

redirect_uri = 'https://github.com/litl/rauth/'

print 'Visit this URL in your browser: ' + google.get_authorize_url(
    redirect_uri=redirect_uri, scope='profile email')

# This is a bit cumbersome, but you need to copy the code=something (just the
# `something` part) out of the URL that's redirected to AFTER you login and
# authorize the demo application
code = raw_input('Enter code parameter (code=something) from URL: ')

# create a dictionary for the data we'll post on the get_access_token request
data = dict(code=code,
            grant_type='authorization_code',
            redirect_uri=redirect_uri)

# retrieve the access token
access_token = \
    google.get_access_token('POST', data=data).content['access_token']

# make a request using the access token
Esempio n. 27
0
from flask import Flask, flash, request, redirect, render_template, url_for
from flask.ext.sqlalchemy import SQLAlchemy

from rauth.service import OAuth2Service

website = 'http://davidadlersapp.appspot.com/'
fbid = '287745697930531'
fbsecr = '244b438e67524756fcdaedb24a54e8c5'
newssfeedurl = 'https://graph.facebook.com/me/home?access_token='

# rauth OAuth 2.0 service wrapper
graph_url = 'https://graph.facebook.com/'
facebook = OAuth2Service(name='facebook',
                         authorize_url='https://www.facebook.com/dialog/oauth',
                         access_token_url=graph_url + 'oauth/access_token',
                         consumer_key='440483442642551',
                         consumer_secret='cd54f1ace848fa2a7ac89a31ed9c1b61')

# Flask config
SQLALCHEMY_DATABASE_URI = 'sqlite:///facebook.db'
SECRET_KEY = '\xfb\x12\xdf\xa1@i\xd6>V\xc0\xbb\x8fp\x16#Z\x0b\x81\xeb\x16'
DEBUG = True

# Flask setup
app = Flask(__name__)
app.config.from_object(__name__)
db = SQLAlchemy(app)


# models
Esempio n. 28
0
import os
from flask import (Flask, flash, request, redirect, render_template, url_for,
                   session)
from rauth.service import OAuth2Service

application = Flask(__name__)

github = OAuth2Service(
    name='github',
    base_url='https://api.github.com/',
    access_token_url='https://github.com/login/oauth/access_token',
    authorize_url='https://github.com/login/oauth/authorize',
    client_id=os.environ.get('GITHUB_CLIENT_ID'),
    client_secret=os.environ.get('GITHUB_CLIENT_SECRET'),
)


@application.route("/")
def index():
    return render_template('login.html')


@application.route('/about')
def about():
    if session.has_key('token'):
        auth = github.get_session(token=session['token'])
        resp = auth.get('/user')
        if resp.status_code == 200:
            user = resp.json()

        return render_template('about.html', user=user)
Esempio n. 29
0
def rauthoauth2_fixed_init(self, fapp=None, base_url=None, consumer_key=None, consumer_secret=None, **kwargs):
    # P This line is the fix. The property 'name' is referenced before it is set in the stock code
    self.name = kwargs['name']
    RauthServiceMixin.__init__(self, app=fapp, base_url=base_url)
    OAuth2Service.__init__(self, consumer_key=consumer_key, consumer_secret=consumer_secret, **kwargs)
Esempio n. 30
0
 def __init__(self, app=None, base_url=None, consumer_key=None, consumer_secret=None, **kwargs):
     self.name=kwargs['name']
     RauthServiceMixin.__init__(self, app=app, base_url=base_url)
     OAuth2Service.__init__(self, self.consumer_key, self.consumer_secret, **kwargs)
Esempio n. 31
0
 def __init__(self, app=None, base_url=None, client_id=None, client_secret=None, **kwargs):
     RauthServiceMixin.__init__(self, app=app, base_url=base_url)
     OAuth2Service.__init__(self, client_id=client_id, client_secret=client_secret,
                            base_url=base_url, **kwargs)
Esempio n. 32
0
# Flask config
SQLALCHEMY_DATABASE_URI = 'sqlite:///github.db'
SECRET_KEY = '\xfb\x12\xdf\xa1@i\xd6>V\xc0\xbb\x8fp\x16#Z\x0b\x81\xeb\x16'
DEBUG = True

# Flask setup
app = Flask(__name__)
app.config.from_object(__name__)
db = SQLAlchemy(app)

# Use your own values in your real application
github = OAuth2Service(
    name='github',
    base_url='https://api.github.com/',
    access_token_url='https://github.com/login/oauth/access_token',
    authorize_url='https://github.com/login/oauth/authorize',
    client_id='09be269976304f03264a',
    client_secret='3f51d253a9f992d9030ae923602a6445798fb80d',
)


# models
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    login = db.Column(db.String(80), unique=True)
    name = db.Column(db.String(120))

    def __init__(self, login, name):
        self.login = login
        self.name = name
Esempio n. 33
0
from rauth.service import OAuth2Service
import re
import webbrowser
from urllib2 import *
# Get a real consumer key & secret from:
# https://developers.facebook.com/apps

website = 'http://davidadlersapp.appspot.com/'
fbid = '287745697930531'
fbsecr = '244b438e67524756fcdaedb24a54e8c5'
newssfeedurl = 'https://graph.facebook.com/me/home?access_token='

facebook = OAuth2Service(
    name='facebook',
    authorize_url='https://graph.facebook.com/oauth/authorize',
    access_token_url='https://graph.facebook.com/oauth/access_token',
    consumer_key=fbid,
    consumer_secret=fbsecr)

redirect_uri = 'https://www.facebook.com/connect/login_success.html'
authorize_url = facebook.get_authorize_url(redirect_uri=redirect_uri,
                                           scope='read_stream',
                                           response_type='token')

print 'Visit this URL in your browser: \n' + authorize_url
#webbrowser.open(authorize_url);

raw_input()
url_with_code = urlopen(authorize_url).geturl()
#url_with_code = raw_input("Copy URL from your browser's address bar: ")
print url_with_code
Esempio n. 34
0
 def __create_service(self):
     '''Create a OAuth2 Service from the _serv_params populate by constructore'''
     self._service = OAuth2Service(**self._serv_params)
Esempio n. 35
0
with open("../../../res/misc/spotify-client-id.txt", 'r') as f:
    SPOTIFY_CLIENT_ID = f.read().replace('\n', '')

with open("../../../res/misc/spotify-client-secret.txt", 'r') as f:
    SPOTIFY_CLIENT_SECRET = f.read().replace('\n', '')

SPOTIFY_REDIRECT_URI = "http://localhost:6814"

# Try to read file save
spotify_saver = Saver(".cache-rauth-spotify.json")

spotify = OAuth2Service(
    client_id=SPOTIFY_CLIENT_ID,
    client_secret=SPOTIFY_CLIENT_SECRET,
    name="spotify",
    authorize_url="https://accounts.spotify.com/authorize",
    access_token_url="https://accounts.spotify.com/api/token",
    base_url="https://api.spotify.com/v1/",
)

# If there is no save
if spotify_saver.get("code", None) is None:
    params = {
        "scope": "user-read-currently-playing",
        "response_type": "code",
        "redirect_uri": SPOTIFY_REDIRECT_URI
    }

    # Read the HTML template
    template = "<html><body>The program successfully received the code! You can now close this tab.</body></html>"
    try: