Esempio n. 1
0
class ITwitterLoginSettings(Interface):
    
    twitter_consumer_key = schema.TextLine(title=_(u'Twiter Consumer Key'), 
                                description=_(u'The App ID/API Key you got when creating the app at https://dev.twitter.com/apps/new'))
    
    twitter_consumer_secret = schema.TextLine(title=_(u'Twitter Consumer Secret'), 
                                    description=_(u'The App Secret Key you got when creating the app at https://dev.twitter.com/apps/new'))

    twitter_access_token = schema.TextLine(title=_(u'Twitter Access Token'), 
                                    description=_(u'The Access Token of your app you got when creating the app at https://dev.twitter.com/apps/new'))

    twitter_access_token_secret = schema.TextLine(title=_(u'Twitter Access Token Secret'), 
                                    description=_(u'The Access Token Secret of your app you got when creating the app at https://dev.twitter.com/apps/new'))
Esempio n. 2
0
    def __call__(self):
        registry = getUtility(IRegistry)
        TWITTER_CONSUMER_KEY = registry.get('cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_key').encode()
        TWITTER_CONSUMER_SECRET = registry.get('cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_secret').encode()

        # Create an Oauth Consumer
        oauth_consumer = oauth.Consumer(key=TWITTER_CONSUMER_KEY,
                                        secret=TWITTER_CONSUMER_SECRET)

        oauth_client = oauth.Client(oauth_consumer)

        # Set the callback URL. Be sure that callback urls are allowed in
        # Twitter App configuration. Do not leave blank the field of the
        # callback url when creating the app, otherwise this login method
        # *will not work*.
        return_args = ''
        if self.request.get('came_from', None) is not None:
            return_args = {'came_from': self.request.get('came_from')}
            return_args = '?' + urllib.urlencode(return_args)

        pps = getMultiAdapter(
            (self.context, self.request),
            name='plone_portal_state'
        )
        portal_url = pps.portal_url()

        url = portal_url + '/@@twitter-login-verify' + return_args

        args = {
            'oauth_callback': url,
        }
        body = urllib.urlencode(args)
        resp, content = oauth_client.request(
            TWITTER_REQUEST_TOKEN_URL, 'POST',
            body=body
        )

        if resp.get('status', '999') != '200':
            msg = _(u"Error getting the authorization token from Twitter. "
                    u"Try again please"
            )
            IStatusMessage(self.request).add(msg, type="error")
            self.request.response.redirect(self.context.absolute_url())
            return u""
        else:
            # The request was successful, so save the token in the session
            # and redirect the user to Twitter
            request_token = dict(parse_qsl(content))
            sdm = getToolByName(self.context, "session_data_manager")
            session = sdm.getSessionData(create=True)
            session[AuthorizationTokenKeys.oauth_token] = request_token['oauth_token']
            session[AuthorizationTokenKeys.oauth_token_secret] = request_token['oauth_token_secret']
            session[AuthorizationTokenKeys.oauth_callback_confirmed] = request_token['oauth_callback_confirmed']
            session.save()

            args = {
                'oauth_token': request_token['oauth_token'],
            }

            self.request.response.redirect(
                "%s?%s" % (TWITTER_AUTH_URL, urllib.urlencode(args),)
            )
Esempio n. 3
0
    def __call__(self):
        registry = getUtility(IRegistry)
        TWITTER_CONSUMER_KEY = registry.get('cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_key').encode()
        TWITTER_CONSUMER_SECRET = registry.get('cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_secret').encode()

        oauth_token = self.request.get('oauth_token')
        oauth_verifier = self.request.get('oauth_verifier')

        sdm = getToolByName(self.context, "session_data_manager")
        session = sdm.getSessionData(create=False)

        # Check if the provided oauth_token and the one we have from the
        # previous step are the same.
        if oauth_token != session[AuthorizationTokenKeys.oauth_token]:
            msg = _(u"Your oauth token is not correct. Please try again")
            IStatusMessage(self.request).add(msg, type="error")
            self.request.response.redirect(self.context.absolute_url())
            return u""

        # Check if the provided verifier is OK, querying Twitter API.
        token = oauth.Token(
            session[AuthorizationTokenKeys.oauth_token],
            session[AuthorizationTokenKeys.oauth_token_secret],
        )
        consumer = oauth.Consumer(
            key=TWITTER_CONSUMER_KEY,
            secret=TWITTER_CONSUMER_SECRET
        )
        client = oauth.Client(consumer, token)
        args = {
            'oauth_verifier': oauth_verifier,
        }
        body = urllib.urlencode(args)
        resp, content = client.request(TWITTER_ACCESS_TOKEN_URL, 'POST', body)
        if resp.get('status', '999') != '200':
            msg = _(u"Error authenticating with Twitter. Please try again.")
            IStatusMessage(self.request).add(msg, type="error")
            self.request.response.redirect(self.context.absolute_url())
            return u""

        # Save the data in the session so that the extraction plugin can
        # authenticate the user to Plone and save the oauth_token
        # for future queries to Twitter API
        access_token = dict(parse_qsl(content))
        session = sdm.getSessionData(create=False)
        session[SessionKeys.user_id] = str(access_token['user_id'])
        session[SessionKeys.screen_name] = access_token['screen_name']
        session[SessionKeys.oauth_token] = access_token['oauth_token']
        session[SessionKeys.oauth_token_secret] = access_token['oauth_token_secret']

        # Query Twitter API for user data
        token = oauth.Token(
            session[SessionKeys.oauth_token],
            session[SessionKeys.oauth_token_secret],
        )
        consumer = oauth.Consumer(
            key=TWITTER_CONSUMER_KEY,
            secret=TWITTER_CONSUMER_SECRET
        )
        client = oauth.Client(consumer, token)
        args = {
            'user_id': session[SessionKeys.user_id]
        }
        body = urllib.urlencode(args)
        url = TWITTER_USER_DATA_URL + '?' + body
        resp, content = client.request(url, 'GET')
        if resp.get('status', '999') != '200':
            msg = _(u"Error getting user information. Please try again.")
            IStatusMessage(self.request).add(msg, type="error")
            self.request.response.redirect(self.context.absolute_url())
            return u""

        us = json.loads(content)
        session[SessionKeys.screen_name] = us.get(u'screen_name', '')
        session[SessionKeys.name] = us.get(u'name', session[SessionKeys.screen_name])
        session[SessionKeys.profile_image_url] = us.get(u'profile_image_url', '')
        session[SessionKeys.description] = us.get(u'description', '')
        session[SessionKeys.location] = us.get(u'location')
        session.save()

        # Add user data into our plugin storage:
        acl = self.context.acl_users
        acl_plugins = acl.plugins
        ids = acl_plugins.listPluginIds(IExtractionPlugin)
        for id in ids:
            plugin = getattr(acl_plugins, id)
            if ICSTwitterPlugin.providedBy(plugin):
                if plugin._storage.get(session[SessionKeys.user_id], None) is None:
                    user_data = {
                        'screen_name': session[SessionKeys.screen_name],
                        'fullname': session[SessionKeys.name],
                        'profile_image_url': session[SessionKeys.profile_image_url],
                        'description': session[SessionKeys.description],
                        'location': session[SessionKeys.location]
                    }
                    plugin._storage[session[SessionKeys.user_id]] = user_data

        msg = pmf(u"Welcome. You are now logged in.")
        IStatusMessage(self.request).add(msg, type="info")

        return_args = ''
        if self.request.get('came_from', None) is not None:
            return_args = {'came_from': self.request.get('came_from')}
            return_args = '?' + urllib.urlencode(return_args)

        return_url = self.context.absolute_url() + '/logged_in' + return_args
        self.request.response.redirect(return_url)
    def __call__(self):
        registry = getUtility(IRegistry)
        TWITTER_CONSUMER_KEY = registry.get(
            'cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_key'
        ).encode()
        TWITTER_CONSUMER_SECRET = registry.get(
            'cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_secret'
        ).encode()

        # Create an Oauth Consumer
        oauth_consumer = oauth.Consumer(key=TWITTER_CONSUMER_KEY,
                                        secret=TWITTER_CONSUMER_SECRET)

        oauth_client = oauth.Client(oauth_consumer)

        # Set the callback URL. Be sure that callback urls are allowed in Twitter
        # App configuration. Do not leave blank the field of the callback url
        # when creating the app, otherwise this login method *will not work*.
        return_args = ''
        if self.request.get('came_from', None) is not None:
            return_args = {'came_from': self.request.get('came_from')}
            return_args = '?' + urllib.urlencode(return_args)

        args = {
            'oauth_callback':
            self.context.absolute_url() + '/@@twitter-login-verify' +
            return_args,
        }
        body = urllib.urlencode(args)
        resp, content = oauth_client.request(TWITTER_REQUEST_TOKEN_URL,
                                             'POST',
                                             body=body)

        if resp.get('status', '999') != '200':
            IStatusMessage(self.request).add(_(
                u"Error getting the authorization token from Twitter. Try again please"
            ),
                                             type="error")
            self.request.response.redirect(self.context.absolute_url())
            return u""
        else:
            # The request was successful, so save the token in the session
            # and redirect the user to Twitter
            request_token = dict(parse_qsl(content))
            session = ISession(self.request)
            session[AuthorizationTokenKeys.
                    oauth_token] = request_token['oauth_token']
            session[AuthorizationTokenKeys.
                    oauth_token_secret] = request_token['oauth_token_secret']
            session[AuthorizationTokenKeys.
                    oauth_callback_confirmed] = request_token[
                        'oauth_callback_confirmed']
            session.save()

            args = {
                'oauth_token': request_token['oauth_token'],
            }

            self.request.response.redirect("%s?%s" % (
                TWITTER_AUTH_URL,
                urllib.urlencode(args),
            ))
    def __call__(self):
        registry = getUtility(IRegistry)
        TWITTER_CONSUMER_KEY = registry.get(
            'cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_key'
        ).encode()
        TWITTER_CONSUMER_SECRET = registry.get(
            'cs.auth.twitter.controlpanel.ITwitterLoginSettings.twitter_consumer_secret'
        ).encode()

        session = ISession(self.request)
        token = oauth.Token(
            session[AuthorizationTokenKeys.oauth_token],
            session[AuthorizationTokenKeys.oauth_token_secret],
        )
        consumer = oauth.Consumer(key=TWITTER_CONSUMER_KEY,
                                  secret=TWITTER_CONSUMER_SECRET)
        client = oauth.Client(consumer, token)
        resp, content = client.request(TWITTER_ACCESS_TOKEN_URL, 'GET')
        if resp.get('status', '999') != '200':
            IStatusMessage(self.request).add(
                _(u"Error authenticating with Twitter. Please try again."),
                type="error")
            self.request.response.redirect(self.context.absolute_url())
            return u""

        access_token = dict(parse_qsl(content))
        # Save the data in the session so that the extraction plugin can
        # authenticate the user to Plone
        session = ISession(self.request)
        session[SessionKeys.user_id] = str(access_token['user_id'])
        session[SessionKeys.screen_name] = access_token['screen_name']
        session[SessionKeys.oauth_token] = access_token['oauth_token']
        session[SessionKeys.
                oauth_token_secret] = access_token['oauth_token_secret']

        api = Api(consumer_key=TWITTER_CONSUMER_KEY,
                  consumer_secret=TWITTER_CONSUMER_SECRET,
                  access_token_key=session[AuthorizationTokenKeys.oauth_token],
                  access_token_secret=session[
                      AuthorizationTokenKeys.oauth_token_secret])

        us = api.GetUser(str(access_token['user_id']))
        session[SessionKeys.name] = us.name
        session[SessionKeys.profile_image_url] = us.profile_image_url
        session[SessionKeys.description] = us.description
        session[SessionKeys.location] = us.location
        session.save()

        # Add user data into our plugin storage:
        acl = self.context.acl_users
        acl_plugins = acl.plugins
        ids = acl_plugins.listPluginIds(IExtractionPlugin)
        for id in ids:
            plugin = getattr(acl_plugins, id)
            if ICSTwitterPlugin.providedBy(plugin):
                if plugin._storage.get(session[SessionKeys.user_id],
                                       None) is None:
                    user_data = {
                        'screen_name': session[SessionKeys.screen_name],
                        'fullname': session[SessionKeys.name],
                        'profile_image_url':
                        session[SessionKeys.profile_image_url],
                        'description': session[SessionKeys.description],
                        'location': session[SessionKeys.location]
                    }
                    plugin._storage[session[SessionKeys.user_id]] = user_data

        IStatusMessage(self.request).add(_(u"Welcome. You are now logged in."),
                                         type="info")

        return_args = ''
        if self.request.get('came_from', None) is not None:
            return_args = {'came_from': self.request.get('came_from')}
            return_args = '?' + urllib.urlencode(return_args)

        self.request.response.redirect(self.context.absolute_url() +
                                       '/logged_in' + return_args)
Esempio n. 6
0
from zope import schema
from zope.interface import Interface
from plone.app.registry.browser.controlpanel import ControlPanelFormWrapper
from plone.app.registry.browser.controlpanel import RegistryEditForm
from plone.z3cform import layout

from cs.auth.twitter import TWMessageFactory as _

class ITwitterLoginSettings(Interface):
    
    twitter_consumer_key = schema.TextLine(title=_(u'Twiter Consumer Key'), 
                                description=_(u'The App ID/API Key you got when creating the app at https://dev.twitter.com/apps/new'))
    
    twitter_consumer_secret = schema.TextLine(title=_(u'Twitter Consumer Secret'), 
                                    description=_(u'The App Secret Key you got when creating the app at https://dev.twitter.com/apps/new'))

    twitter_access_token = schema.TextLine(title=_(u'Twitter Access Token'), 
                                    description=_(u'The Access Token of your app you got when creating the app at https://dev.twitter.com/apps/new'))

    twitter_access_token_secret = schema.TextLine(title=_(u'Twitter Access Token Secret'), 
                                    description=_(u'The Access Token Secret of your app you got when creating the app at https://dev.twitter.com/apps/new'))


class TwitterLoginControlPanelForm(RegistryEditForm):
    schema = ITwitterLoginSettings

TwitterLoginControlPanelView = layout.wrap_form(TwitterLoginControlPanelForm, ControlPanelFormWrapper)
TwitterLoginControlPanelView.label = _(u"Twitter Login settings")
Esempio n. 7
0
        title=_(u'Twiter Consumer Key'),
        description=_(u'The App ID/API Key you got when creating the app at '
                      u'https://dev.twitter.com/apps/new')
        )

    twitter_consumer_secret = schema.TextLine(
        title=_(u'Twitter Consumer Secret'),
        description=_(u'The App Secret Key you got when creating the app at '
                      u'https://dev.twitter.com/apps/new'))

    twitter_access_token = schema.TextLine(
        title=_(u'Twitter Access Token'),
        description=_(u'The Access Token of your app you got when creating'
                      u'the app at https://dev.twitter.com/apps/new')
        )

    twitter_access_token_secret = schema.TextLine(
        title=_(u'Twitter Access Token Secret'),
        description=_(u'The Access Token Secret of your app you got when '
                      u'creating the app at https://dev.twitter.com/apps/new'))


class TwitterLoginControlPanelForm(RegistryEditForm):
    schema = ITwitterLoginSettings

TwitterLoginControlPanelView = layout.wrap_form(
    TwitterLoginControlPanelForm,
    ControlPanelFormWrapper)

TwitterLoginControlPanelView.label = _(u"Twitter Login settings")