def __get_oauth_url(self, url, method):
        """ Generate oAuth1.0a URL """
        oauth = OAuth(url=url,
                      consumer_key=self.consumer_key,
                      consumer_secret=self.consumer_secret,
                      version=self.version,
                      method=method)

        return oauth.get_oauth_url()
Esempio n. 2
0
def oauth_dance(app_name, consumer_key, consumer_secret, token_filename=None):
    """
    Perform the OAuth dance with some command-line prompts. Return the
    oauth_token and oauth_token_secret.

    Provide the name of your app in `app_name`, your consumer_key, and
    consumer_secret. This function will open a web browser to let the
    user Allow your app to access their Twitter account. PIN
    authentication is used.

    If a token_filename is given, the oauth tokens will be written to
    the file.
    """
    print("Hi there! We're gonna get you all set up to use %s." % app_name)
    twitter = Twitter(auth=OAuth('', '', consumer_key, consumer_secret),
                      format='',
                      api_version=None)
    oauth_token, oauth_token_secret = parse_oauth_tokens(
        twitter.oauth.request_token())
    print("""
In the web browser window that opens please choose to Allow
access. Copy the PIN number that appears on the next page and paste or
type it here:
""")
    oauth_url = ('http://api.twitter.com/oauth/authorize?oauth_token=' +
                 oauth_token)
    print("Opening: %s\n" % oauth_url)

    try:
        r = webbrowser.open(oauth_url)
        time.sleep(2)  # Sometimes the last command can print some
        # crap. Wait a bit so it doesn't mess up the next
        # prompt.
        if not r:
            raise Exception()
    except:
        print("""
Uh, I couldn't open a browser on your computer. Please go here to get
your PIN:

""" + oauth_url)
    oauth_verifier = _input("Please enter the PIN: ").strip()
    twitter = Twitter(auth=OAuth(oauth_token, oauth_token_secret, consumer_key,
                                 consumer_secret),
                      format='',
                      api_version=None)
    oauth_token, oauth_token_secret = parse_oauth_tokens(
        twitter.oauth.access_token(oauth_verifier=oauth_verifier))
    if token_filename:
        write_token_file(token_filename, oauth_token, oauth_token_secret)
        print()
        print("That's it! Your authorization keys have been written to %s." %
              (token_filename))
    return oauth_token, oauth_token_secret
Esempio n. 3
0
    def __init__(self, configFilename):
        self.configFilename = configFilename
        self.config = load_config(self.configFilename)

        global ACTIVE_PREFIXES
        ACTIVE_PREFIXES = PREFIXES[self.config.get('irc', 'prefixes')]

        oauth_file = self.config.get('twitter', 'oauth_token_file')
        if not os.path.exists(oauth_file):
            oauth_dance("IRC Bot", CONSUMER_KEY, CONSUMER_SECRET, oauth_file)
        oauth_token, oauth_secret = read_token_file(oauth_file)

        self.twitter = Twitter(
            auth=OAuth(
                oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET),
            api_version='1',
            domain='api.twitter.com')

        self.irc = irclib.IRC()
        self.irc.add_global_handler('privmsg', self.handle_privmsg)
        self.irc.add_global_handler('ctcp', self.handle_ctcp)
        self.ircServer = self.irc.server()

        self.sched = Scheduler(
            (SchedTask(self.process_events, 1),
             SchedTask(self.check_statuses, 120)))
        self.lastUpdate = (datetime.utcnow() - timedelta(minutes=10)).utctimetuple()
Esempio n. 4
0
    def __init__(self, oauth_token=None, oauth_token_secret=None):
        self.config = config
        self.oauth_client = None
        self.http_client = httplib2.Http()

        if (oauth_token and oauth_token_secret):
            self.oauth_client = OAuth(token=oauth_token,
                                      secret=oauth_token_secret).client()
Esempio n. 5
0
File: views.py Progetto: svven/web
def oauth_callback(provider_name):
    if not current_user.is_anonymous():
        return redirect(url_for('home.page'))
    oauth = OAuth.get_provider(provider_name)
    try:
        user_credentials = oauth.callback()
        if user_credentials is None:
            raise
    except Exception, e:
        current_app.logger.exception(e)
        flash('Oops, could not authenticate you, sorry.', 'danger')
        return redirect(url_for('front.page'))
Esempio n. 6
0
    def get(self):
        gh_code = self.get_query_argument('code', None)
        if not gh_code:
            return self.redirect('/')

        gh_oauth = OAuth(gh_code)
        yield gh_oauth.set_access_token()

        if not gh_oauth.access_token:
            return self.redirect('/')

        user_data = yield gh_oauth.get_user_data()

        login = user_data['login']
        user = yield User.get(login=login)

        if not user:
            user = User(login, data=user_data, gh_token=gh_oauth.access_token)
            yield user.put()

        self.set_secure_cookie('token', user.token)
        self.redirect('/')
Esempio n. 7
0
    def get(self):
        gh_code = self.get_query_argument('code', None)
        if not gh_code:
            return self.redirect('/')

        gh_oauth = OAuth(gh_code)
        yield gh_oauth.set_access_token()

        if not gh_oauth.access_token:
            return self.redirect('/')

        user_data = yield gh_oauth.get_user_data()

        login = user_data['login']
        user = yield User.get(login=login)

        if not user:
            user = User(login, data=user_data, gh_token=gh_oauth.access_token)
            yield user.put()

        self.set_secure_cookie('token', user.token)
        self.redirect('/')
Esempio n. 8
0
	def __init__(self):
		Thread.__init__(self)
		log('Engine started', 'CCO')
		self.OAuth = OAuth('api.crew.dreamhack.se')
		self.start()
		self.thankyous = ['Aren\'t you just the best! :D\n\nYou\'ve scucessfully subscribed to Crew Corners mailinglist for new events!',
						'You can put a Trojan on my Hard Drive anytime because You\'ve scucessfully subscribed to Crew Corners mailinglist for new events!',
						'Are you Google? Because you have everything I\'m searching for and ontop of that, You\'ve scucessfully subscribed to Crew Corners mailinglist for new events!',
						'You got me stuck on Caps Lock, if you know what I mean. Oh and You\'ve scucessfully subscribed to Crew Corners mailinglist for new events!',
						'Your beauty rivals the graphics of Crysis... And You\'ve scucessfully subscribed to Crew Corners mailinglist for new events!',
						'You must be Windows 95 because you gots me so unstable that i\'ve accidenatly subscribed you to the Crew Corners mailing list!',
						'If you won\'t let me buy you a drink, at least let me fix your laptop and subscribe you to the Crew Corners mailinglist?',
						'Isn\'t your e-mail address [email protected]? Oh well.. Here\'s a subscription to the CCO mailing list',
						'What\'s a nice girl like you doing in a chatroom like this? Oh subsciiiibing? ok.. In that case, you\'re subscribed to CCO mailinglist! ;)',
						'I think you could be an integral part of my project life cycle. Because you\'re in my Mailinglist for Crew Corner ;)',
						'I\'ll bet my hard drive is the biggest you\'ve ever seen!! I mean.. erm.. Subscription? sure CCO mailinglist here you go!',
						'Your homepage or mine? Oh mine? Sure.. in that case, you\'re on my list of mails to CCO',
						'Want to come see my HARD Disk? I promise it isn\'t 3.5 inches and it ain\'t floppy... But since I\'m shy we\'ll start off with a mialing list for CCO ok?',
						'How about we go home and you handle my exception? Oh shoot, no exceptions my my core :S But a addition to the mailing list has been done for you!']
Esempio n. 9
0
        return delta.total_seconds()

    def _get_next_alarm(self):
        today = datetime.now()
        today_alarm = datetime(today.year, today.month, today.day, 18, 40, 0)
        if (today_alarm - today - timedelta(seconds=15)).days >= 0:
            return today_alarm
        else:
            return today_alarm + timedelta(days=1)

    def run(self):
        if self.chat_client.connect():
            self.chat_client.process(block=False)
            while True:
                sleep(self._get_secs_to(self._get_next_alarm()))
                self.send_alarm()
        else:
            raise RuntimeError("Unable to connect!")


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO,
                        format='%(levelname)-8s %(message)s',
                        stream=sys.stdout)
    oauth = OAuth()
    oauth.read_cfg('oauth.cfg')
    jid = '*****@*****.**'
    chat_client = ChatClient(jid, oauth)
    medbot = MedBot(chat_client, 'Buddy')
    medbot.run()
Esempio n. 10
0
            track_details['followers'] = followers
            # try except to catch Spotify max retries error
            try:
                # get audio features
                attribute_info(sp, mood, track_uri, track_details)
            except:
                print("Connection refused by the server...")
                print("sleeping for 5 seconds...")
                time.sleep(5)
                print("Slept for 5 seconds, time to continue...")
                continue

    return track_dict


sp = OAuth()
token = sp.get_token()

if token:
    # get angry songs
    track_dict = {}
    sp = spotipy.Spotify(auth=token)
    print(type(sp))
    track_dict = get_songs(sp, 0, num_angry, angry,
                           track_dict)  # get info about angry songs
    print(len(track_dict))

    # turn dictionary of songs into a dataframe
    df = pd.DataFrame.from_dict(track_dict, orient='index')
    df.rename(columns={'Unnamed: 0': 'track_uri'}, inplace=True)
    print(df)
Esempio n. 11
0
    import secrets
    GOOGLE_CLIENT_ID = secrets.GOOGLE_CLIENT_ID
    GOOGLE_CLIENT_SECRET = secrets.GOOGLE_CLIENT_SECRET
    SECRET_KEY = secrets.SECRET_KEY
    FAKED_SECRETS = False
except ImportError:
    logging.critical("Unable to find secrets.py. Cannot force authentication")
    GOOGLE_CLIENT_ID = 'dummy google client id'
    GOOGLE_CLIENT_SECRET = 'dummy google client secret'
    SECRET_KEY = 'dummy secret key'
    FAKED_SECRETS = True


REDIRECT_URI = '/oauth2callback'

oauth = OAuth()
google = oauth.remote_app(
        'google',
        base_url='https://www.google.com/accounts/',
        authorize_url='https://accounts.google.com/o/oauth2/auth',
        request_token_url=None,
        request_token_params={
            'scope': 'https://www.googleapis.com/auth/userinfo.email',
            'response_type': 'code'
        },
        access_token_params={'grant_type': 'authorization_code'},
        access_token_url='https://accounts.google.com/o/oauth2/token',
        access_token_method='POST',
        consumer_key=GOOGLE_CLIENT_ID,
        consumer_secret=GOOGLE_CLIENT_SECRET,
        )
Esempio n. 12
0
class CCO(Thread):
	def __init__(self):
		Thread.__init__(self)
		log('Engine started', 'CCO')
		self.OAuth = OAuth('api.crew.dreamhack.se')
		self.start()
		self.thankyous = ['Aren\'t you just the best! :D\n\nYou\'ve scucessfully subscribed to Crew Corners mailinglist for new events!',
						'You can put a Trojan on my Hard Drive anytime because You\'ve scucessfully subscribed to Crew Corners mailinglist for new events!',
						'Are you Google? Because you have everything I\'m searching for and ontop of that, You\'ve scucessfully subscribed to Crew Corners mailinglist for new events!',
						'You got me stuck on Caps Lock, if you know what I mean. Oh and You\'ve scucessfully subscribed to Crew Corners mailinglist for new events!',
						'Your beauty rivals the graphics of Crysis... And You\'ve scucessfully subscribed to Crew Corners mailinglist for new events!',
						'You must be Windows 95 because you gots me so unstable that i\'ve accidenatly subscribed you to the Crew Corners mailing list!',
						'If you won\'t let me buy you a drink, at least let me fix your laptop and subscribe you to the Crew Corners mailinglist?',
						'Isn\'t your e-mail address [email protected]? Oh well.. Here\'s a subscription to the CCO mailing list',
						'What\'s a nice girl like you doing in a chatroom like this? Oh subsciiiibing? ok.. In that case, you\'re subscribed to CCO mailinglist! ;)',
						'I think you could be an integral part of my project life cycle. Because you\'re in my Mailinglist for Crew Corner ;)',
						'I\'ll bet my hard drive is the biggest you\'ve ever seen!! I mean.. erm.. Subscription? sure CCO mailinglist here you go!',
						'Your homepage or mine? Oh mine? Sure.. in that case, you\'re on my list of mails to CCO',
						'Want to come see my HARD Disk? I promise it isn\'t 3.5 inches and it ain\'t floppy... But since I\'m shy we\'ll start off with a mialing list for CCO ok?',
						'How about we go home and you handle my exception? Oh shoot, no exceptions my my core :S But a addition to the mailing list has been done for you!']

	def login(self):
		tokens = self.OAuth.get() # Defaults to requesting the tokens
		if len(tokens) <= 0:
			return None
		print tokens
		core['cco']['access_key'] = tokens['oauth_token']
		core['cco']['access_secret'] = tokens['oauth_token_secret']
		return True

	def run(self):
		if not 'CCO_events' in core['pickle']:
			core['pickle']['CCO_events'] = []

		if core['cco']['access_key'] == '':
			if not self.login():
				log('Could not login, no keys defined', 'CCO')
				return None

		while 1:
			new = []
			#log('Getting eventlist','CCO')
			for e in getEvents(self.OAuth.get('/1/event/get/all')):
				if not e in core['pickle']['CCO_events']:
					new.append(e)
					core['pickle']['CCO_events'].append(e)
					log('New event: ' + str(e),'CCO')

			if 'email' in core['pickle_ignore']:
				if not 'mailinglist' in core['pickle']:
					core['pickle']['mailinglist'] = {}
				if not 'cco' in core['pickle']['mailinglist']:
					core['pickle']['mailinglist']['cco'] = []

				for person in core['pickle_ignore']['email'].getmailinglist():
					body = ''
					person, msg = person
					if len(person) <= 0 or '@' not in person: continue

					## generate a nicer subject and message body.
					if len(new) == 1: m, t = 'A new event', 'A new event on CC'
					else: m, t = 'New events', 'New events on CC'

					## Generate Eventlist
					l = ''
					for item in new: l += ' - ' + item + '\n'

					if person in core['pickle']['mailinglist']['cco']:
						continue
					else:
						core['pickle']['mailinglist']['cco'].append(person)
						if 'hello world' in msg.lower():
							body += 'You had me at "Hello World." <3\nYou\'re subscribed to the CCO mailing list for new events ;)'
						else:
							body += self.thankyous[randint(0, 1000)%len(self.thankyous)-1]
						#core['pickle_ignore']['email'].send(person, 'You are now on CCO new event mailinglist', body)
					
					if len(l) > 0:
						body += '\n\nNew events:\n' + l
					elif len(l) == 0 and len(body) > 0:
						body += '\n\n\n\nTo unsubscribe, send a e-mail (containing what ever) to: [email protected]!'

					if len(body) > 0:
						pass #core['pickle_ignore']['email'].send(person, t, body)

			sleep(60)
from flask import Flask
from oauth import OAuth

# Create application object
app = Flask(__name__)
app.config.from_object('flask_social_auth.default')

oauth = OAuth()
facebook = oauth.remote_app('facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key=app.config.get('FACEBOOK_APP_ID'),
    consumer_secret=app.config.get('FACEBOOK_APP_SECRET'),
    request_token_params={'scope': 'email'}
)
twitter = oauth.remote_app('twitter',
    base_url='https://api.twitter.com/1/',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authenticate',
    consumer_key=app.config.get('TWITTER_CONSUMER_KEY'),
    consumer_secret=app.config.get('TWITTER_CONSUMER_SECRET')
)
google = oauth.remote_app('google',
    base_url=None,
    request_token_url=None, #this should only exist for OAuth1.0
    access_token_url='https://accounts.google.com/o/oauth2/token',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    consumer_key=app.config.get('GOOGLE_CLIENT_ID'),
Esempio n. 14
0
def main():
    auth = OAuth(oauth_filename)
    if not auth.is_login() or auth.get_expire_time() < datetime.datetime.now():
        username = input('user name or email address: ')
        password = input('password: '******'r') as f:
            cache_list = json.load(f)
    else:
        cache_list = []
    cache_list = set(cache_list)
    exp_json = requests.get('https://www.bilibili.com/plus/account/exp.php',
                            cookies=cookies).json()
    coins_left = 5 - int(exp_json['number'] / 10)
    page = 1
    while True:
        params = {'callback': 'abc', 'pn': page, 'ps': 100, 'jsonp': 'jsonp'}
        history_json = json.loads(
            requests.get('https://api.bilibili.com/x/v2/history',
                         params=params,
                         cookies=cookies,
                         headers={
                             'Referer':
                             'https://www.bilibili.com'
                             '/account/history'
                         }).text[4:-1])
        for video in history_json['data']:
            bvid = video['bvid']
            aid = video.get('aid', bv_to_av(bvid))
            copyright = video['copyright']
            headers = {'Referer': f'https://www.bilibili.com/video/av{aid}'}
            if aid not in cache_list:
                params = {'callback': 'abc', 'jsonp': 'jsonp', 'aid': aid}
                coin_json = json.loads(
                    requests.get(
                        'https://api.bilibili.com/x/web-interface/archive/coins',
                        params=params,
                        cookies=cookies,
                        headers=headers).text[4:-1])
                available_coins = 3 - copyright - coin_json['data']['multiply']
                throw_coins = min(coins_left, available_coins)
                if throw_coins > 0:
                    params = {
                        'aid': aid,
                        'multiply': throw_coins,
                        'select_like': 0,
                        'cross_domain': True,
                        'csrf': cookies['bili_jct']
                    }
                    requests.post(
                        'https://api.bilibili.com/x/web-interface/coin/add',
                        data=params,
                        cookies=cookies,
                        headers=headers)
                    print('throw %d coins to av%d' % (throw_coins, aid))
                if throw_coins == 0 or throw_coins == available_coins:
                    cache_list.add(aid)
                coins_left -= throw_coins
                if coins_left == 0:
                    with open(cache_coin_av_list, 'w') as f:
                        json.dump(list(cache_list), f)
                    return
        if len(history_json['data']) == 0:
            with open(cache_coin_av_list, 'w') as f:
                json.dump(list(cache_list), f)
            return
        page += 1
Esempio n. 15
0
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)

        # Create a dataview control
        self.dvc = dv.DataViewCtrl(self,
                                   style=wx.BORDER_THEME
                                   | dv.DV_ROW_LINES
                                   | dv.DV_VERT_RULES
                                   | dv.DV_MULTIPLE)

        self.model = DataModel([])
        self.dvc.AssociateModel(self.model)

        self.dvc.AppendTextColumn("path", 1, width=170)
        self.dvc.AppendTextColumn("title",
                                  2,
                                  width=300,
                                  mode=dv.DATAVIEW_CELL_EDITABLE)
        self.dvc.AppendProgressColumn("progress", 3, width=130)
        self.dvc.AppendTextColumn("status",
                                  4,
                                  width=300,
                                  mode=dv.DATAVIEW_CELL_EDITABLE)

        # set the Sizer property (same as SetSizer)
        self.Sizer = wx.BoxSizer(wx.VERTICAL)
        self.Sizer.Add(self.dvc, 1, wx.EXPAND)

        b2 = wx.Button(self, label="Add files")
        self.Bind(wx.EVT_BUTTON, self.OnAddRow, b2)
        self.button_add = b2

        b3 = wx.Button(self, label="Delete selected")
        b3.Enable(False)
        self.Bind(wx.EVT_BUTTON, self.OnDeleteRows, b3)
        self.button_delete = b3

        b5 = wx.Button(self, label="Start upload")
        b5.Enable(False)
        self.Bind(wx.EVT_BUTTON, self.start_upload, b5)
        self.button_upload_start = b5

        b6 = wx.Button(self, label="Stop upload")
        b6.Enable(False)
        self.Bind(wx.EVT_BUTTON, self.stop_upload, b6)
        self.button_upload_stop = b6

        self.in_progress = False
        self.files_in_progress = 0

        btnbox = wx.BoxSizer(wx.HORIZONTAL)
        btnbox.Add(b2, 0, wx.LEFT | wx.RIGHT, 5)
        btnbox.Add(b3, 0, wx.LEFT | wx.RIGHT, 5)
        btnbox.Add(b5, 0, wx.LEFT | wx.RIGHT, 5)
        btnbox.Add(b6, 0, wx.LEFT | wx.RIGHT, 5)
        self.Sizer.Add(btnbox, 0, wx.TOP | wx.BOTTOM, 5)

        # Bind some events so we can see what the DVC sends us
        self.Bind(dv.EVT_DATAVIEW_ITEM_START_EDITING, self.on_before_edit,
                  self.dvc)
        # self.Bind(dv.EVT_DATAVIEW_ITEM_EDITING_DONE, self.OnEditingDone, self.dvc)
        # self.Bind(dv.EVT_DATAVIEW_ITEM_VALUE_CHANGED, self.OnValueChanged, self.dvc)

        self.Bind(dv.EVT_DATAVIEW_ITEM_ACTIVATED, self.RightClick, self.dvc)

        parent.Bind(wx.EVT_CLOSE, self.OnClose)
        self.parent = parent

        # worker stuff
        self.enclosure_queue = Queue()

        self.worker = None
        # drop
        file_drop_target = MyFileDropTarget(self.on_drop)
        self.SetDropTarget(file_drop_target)

        auth = OAuth(self)
        self.oauth = auth
        if not auth.ShowModal():
            self.parent.Close()
Esempio n. 16
0
from django.shortcuts import render, redirect, HttpResponse
from django.conf import settings
from django.template import loader
from oauth import OAuth

oauthWrapper = OAuth(settings.NCTU_APP_CLIENT_ID, settings.NCTU_APP_CLIENT_SECRET, settings.NCTU_APP_REDIRECT_URI)

def login(request):
    # check for token from nctu oauth redirection
	if OAuth.get_profile(request) == None:
		return oauthWrapper.authorize()
	return redirect('/')
Esempio n. 17
0
from pprint import pprint

from api import Foursquare
from oauth import OAuth

if __name__ == '__main__':

    # say hello and ask for foursquare email/phone
    print('Foursquare API')
    print('--------------\n')
    username = raw_input(
        'Email associated with your Foursquare account: ').strip()

    # build oauth obj, do oauth_dance if oath_token not available
    oauth_fname = '%s.token' % username
    if not os.path.exists(oauth_fname):
        raise Exception('need to do OAuth token getting blaaaah...')
    else:
        oauth_token = open(oauth_fname, 'r').readlines()[0]
        oauth_token = oauth_token.strip()
    auth = OAuth(oauth_token)

    # make our foursquare object
    fsq = Foursquare(auth=auth)

    # foursquare api requests
    phil_id = 5804431
    me = fsq.users()
    my_friends = fsq.users.friends(id=phil_id)
    pprint(me)
Esempio n. 18
0
File: views.py Progetto: svven/web
def oauth_authorize(provider_name):
    if not current_user.is_anonymous():
        return redirect(url_for('home.page'))
    oauth = OAuth.get_provider(provider_name)
    return oauth.authorize()
Esempio n. 19
0
        return delta.total_seconds()

    def _get_next_alarm(self):
        today = datetime.now()
        today_alarm = datetime(today.year, today.month, today.day, 18, 40, 0)
        if (today_alarm - today - timedelta(seconds=15)).days >= 0:
            return today_alarm
        else:
            return today_alarm + timedelta(days=1)

    def run(self):
        if self.chat_client.connect():
            self.chat_client.process(block=False)
            while True:
                sleep(self._get_secs_to(self._get_next_alarm()))
                self.send_alarm()
        else:
            raise RuntimeError("Unable to connect!")


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO,
                        format='%(levelname)-8s %(message)s',
                        stream=sys.stdout)
    oauth = OAuth()
    oauth.read_cfg('oauth.cfg')
    jid = '*****@*****.**'
    chat_client = ChatClient(jid, oauth)
    medbot = MedBot(chat_client, 'Buddy')
    medbot.run()
Esempio n. 20
0
    if options['refresh'] and options['action'] not in ('friends', 'public',
                                                        'replies'):
        print >> sys.stderr, "You can only refresh the friends, public, or replies actions."
        print >> sys.stderr, "Use 'twitter -h' for help."
        return 1

    oauth_filename = os.path.expanduser(options['oauth_filename'])

    if (options['action'] == 'authorize'
            or not os.path.exists(oauth_filename)):
        oauth_dance("the Command-Line Tool", CONSUMER_KEY, CONSUMER_SECRET,
                    options['oauth_filename'])

    oauth_token, oauth_token_secret = read_token_file(oauth_filename)

    twitter = Twitter(auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY,
                                 CONSUMER_SECRET),
                      secure=options['secure'],
                      api_version='1',
                      domain='api.twitter.com')

    try:
        Action()(twitter, options)
    except NoSuchActionError, e:
        print >> sys.stderr, e
        raise SystemExit(1)
    except TwitterError, e:
        print >> sys.stderr, str(e)
        print >> sys.stderr, "Use 'twitter -h' for help."
        raise SystemExit(1)
Esempio n. 21
0
def login(request):
    # check for token from nctu oauth redirection
	if OAuth.get_profile(request) == None:
		return oauthWrapper.authorize()
	return redirect('/')
Esempio n. 22
0
    GOOGLE_CLIENT_ID = 'dummy google client id'
    GOOGLE_CLIENT_SECRET = 'dummy google client secret'
    SECRET_KEY = 'dummy secret key'
    FAKED_SECRETS = True

REDIRECT_URI = '/oauth2callback'

_auth_whitelist = set()
try:
    import auth_whitelist
    _auth_whitelist = set(auth_whitelist.auth_whitelist)
except ImportError:
    # Auth whitelist is optional. No biggie if it's not there.
    pass

oauth = OAuth()
google = oauth.remote_app(
    'google',
    base_url='https://www.google.com/accounts/',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    request_token_url=None,
    request_token_params={
        'scope': 'https://www.googleapis.com/auth/userinfo.email',
        'response_type': 'code'
    },
    access_token_params={'grant_type': 'authorization_code'},
    access_token_url='https://accounts.google.com/o/oauth2/token',
    access_token_method='POST',
    consumer_key=GOOGLE_CLIENT_ID,
    consumer_secret=GOOGLE_CLIENT_SECRET,
)