Exemple #1
0
    def any(self, provider_name):

        # Log the user in.
        result = authomatic.login(Webapp2Adapter(self), provider_name)

        if result:
            if result.user:
                result.user.update()
                self.response.write('<h1>Hi {}</h1>'.format(result.user.name))

                # Save the user name and ID to cookies that we can use it in other handlers.
                self.response.set_cookie('user_id', result.user.id)
                self.response.set_cookie('user_name',
                                         urllib.quote(result.user.name))

                if result.user.credentials:
                    # Serialize credentials and store it as well.
                    serialized_credentials = result.user.credentials.serialize(
                    )
                    self.response.set_cookie('credentials',
                                             serialized_credentials)

            elif result.error:
                self.response.set_cookie('error',
                                         urllib.quote(result.error.message))

            self.redirect('/')
Exemple #2
0
    def any(self, provider_name='', result_format=None):
        # It all begins with login.
        def clean_session(result):  # XXX
            self.session.pop(auth.prefix, None)

        result = auth.login(Webapp2Adapter(self),
                            provider_name,
                            session=self.session,
                            session_saver=self.session.on_update,
                            callback=clean_session)
        if not result:
            # Do not write anything to the response if there is no result!
            return

        if result.user:
            if not result.error:
                try:
                    self.fetch_user_info(result)
                except BaseError as e:
                    result.error = e
                except Exception as e:
                    result.error = GenericError(e)

            if not result.error:
                self.login_successful(result)

        self.respond(self.state_dict(error=result.error), result_format)
Exemple #3
0
 def any(self, provider_name):
     result = authomatic.login(Webapp2Adapter(self), provider_name)
     if result:
         apis = []
         if result.user:
             result.user.update()
             if result.user.credentials:
                 apis = config.config.get(provider_name, {}).get('_apis', {})
         
         nice_provider_name = config.config.get(provider_name, {}).get('_name') or provider_name.capitalize()
         
         render(self, result, result.popup_js(custom=dict(apis=apis, provider_name=nice_provider_name)))
Exemple #4
0
    def any(self, provider_name):
        #make sure we're not already logged in! don't waste api calls!
        user = oAuthUser.fromCookie()
        #redirect = getRedirect()
        self.response.delete_cookie('user_redirect')
        if user:
            if user.name and user.provider:
                self.response.delete_cookie('error')
                self.redirect('/')

        # It all begins with login.
        result = authomatic.login(Webapp2Adapter(self), provider_name)

        # Do not write anything to the response if there is no result!
        if result:
            if result.user:
                result.user.update()
                if result.user.name:
                    # Save the user name and ID to cookies that we can use it in other handlers.
                    self.response.set_cookie('user_id', result.user.id)
                    self.response.set_cookie('user_name',
                                             urllib.quote(result.user.name))
                    self.response.set_cookie('user_email', result.user.email)
                    self.response.set_cookie('user_provider', provider_name)
                    self.response.delete_cookie('error')
                elif result.user.email:
                    # Use the first part of the email as the user's name
                    self.response.set_cookie('user_id', result.user.id)
                    self.response.set_cookie(
                        'user_name',
                        urllib.quote(result.user.email.split('@')[0]))
                    self.response.set_cookie('user_email', result.user.email)
                    self.response.set_cookie('user_provider', provider_name)
                    self.response.delete_cookie('error')
                else:
                    self.response.set_cookie('error',
                                             'No user name available!')
                if result.user.credentials:
                    # Serialize credentials and store it as well.
                    serialized_credentials = result.user.credentials.serialize(
                    )
                    self.response.set_cookie('credentials',
                                             serialized_credentials)
                self.redirect('/')
            elif result.error:
                self.response.set_cookie('error',
                                         urllib.quote(result.error.message))
                self.response.out.write(str(result.error.message))
    def any(self):
        """
        Autentica un utente tramite il suo account facebook.
        Se e' la prima volta che l'utente accede tramite facebook, viene creato un nuovo oggetto User
        per memorizzare i suoi dati.
        (per il corretto funzionamento della libreria authomatic,
        il metodo deve accettare sia richieste GET che POST)
        :return:
        """
        result = authomatic.login(Webapp2Adapter(self), 'facebook')

        if result:
            if result.error:
                self.renderMessage(result.error.message)
                pass
            elif result.user:
                if not (result.user.name and result.user.id):
                    result.user.update()

                if result.user.credentials:
                    url = self.buildApiUrl(result.user.id,
                                           result.user.credentials.token)
                    response = result.provider.access(url)

                    if response.status == 200:
                        data = response.data
                        if not self.checkUserExistence(data['id']):
                            userData = self.createUser(data['id'], data)
                            self.checkUserCreation(userData)
                            pass
                        try:
                            time.sleep(1)
                            self.login(data['id'])
                            self.redirect('/')
                        except (InvalidAuthIdError, InvalidPasswordError) as e:
                            logging.info(
                                'Login failed for user %s because of %s',
                                data['name'], type(e))
                            self.renderMessage('Login failed!')

                    pass

        pass
Exemple #6
0
    def get(self, provider_name):

        result = authomatic.login(Webapp2Adapter(self), provider_name)

        if result:
            if result.error:
                error_message = result.error.message
                raise(Exception('Login failed to [%s]. Error was [%s].' % (provider_name, error_message)))
            elif result.user:
                if not (result.user.name and result.user.id):
                    logging.debug('No name or id. Getting.')
                    result.user.update()
                logging.info('user = [%s, %s, %s]', result.user.name, result.user.id, result.user.email)
                self.session['user_email'] = result.user.email
                next_url = self.session.get('next_url') or '/'
                logging.debug('redirecting to %s', next_url)
                return self.redirect(str(next_url))
            else:
                raise(Exception('Login to [%(provider_name)s] succeeded, but no user was returned.' % vars()))
Exemple #7
0
    def login(self, provider_name):

        result = authomatic.login(Webapp2Adapter(self),
                                  provider_name,
                                  callback=self.callback)

        if result:
            if result.user:
                user_response = result.user.update()
                if user_response:
                    self.response.write('<br /><br />status = {}<br />'.format(
                        user_response.status))

                self.response.write('<br /><br />Hi {}<br />'.format(
                    result.user.name))
                self.response.write('your ID is {}<br />'.format(
                    result.user.id))
                self.response.write('your email is {}<br />'.format(
                    result.user.email))
            elif result.error:
                self.response.write('ERROR {}<br />'.format(
                    result.error.message))
Exemple #8
0
 def any(self, provider_name):
             
     # It all begins with login.
     result = authomatic.login(Webapp2Adapter(self), provider_name)
     
     # Do not write anything to the response if there is no result!
     if result:
         # If there is result, the login procedure is over and we can write to response.
         self.response.write('<a href="..">Home</a>')
         
         if result.error:
             # Login procedure finished with an error.
             self.response.write('<h2>Damn that error: {}</h2>'.format(result.error.message))
         
         elif result.user:
             # Hooray, we have the user!
             
             # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,
             # We need to update the user to get more info.
             if not (result.user.name and result.user.id):
                 result.user.update()
             
             # Welcome the user.
             self.response.write('<h1>Hi {}</h1>'.format(result.user.name))
             self.response.write('<h2>Your id is: {}</h2>'.format(result.user.id))
             self.response.write('<h2>Your email is: {}</h2>'.format(result.user.email))
             
             # Seems like we're done, but there's more we can do...
             
             # If there are credentials (only by AuthorizationProvider),
             # we can _access user's protected resources.
             if result.user.credentials:
                 
                 # Each provider has it's specific API.
                 if result.provider.name == 'fb':
                     self.response.write('Your are logged in with Facebook.<br />')
                     
                     # We will access the user's 5 most recent statuses.
                     url = 'https://graph.facebook.com/{}?fields=feed.limit(5)'
                     url = url.format(result.user.id)
                     
                     # Access user's protected resource.
                     response = result.provider.access(url)
                     
                     if response.status == 200:
                         # Parse response.
                         statuses = response.data.get('feed').get('data')
                         error = response.data.get('error')
                         
                         if error:
                             self.response.write('Damn that error: {}!'.format(error))
                         elif statuses:
                             self.response.write('Your 5 most recent statuses:<br />')
                             for message in statuses:
                                 
                                 text = message.get('message')
                                 date = message.get('created_time')
                                 
                                 self.response.write('<h3>{}</h3>'.format(text))
                                 self.response.write('Posted on: {}'.format(date))
                     else:
                         self.response.write('Damn that unknown error!<br />')
                         self.response.write('Status: {}'.format(response.status))
                     
                 if result.provider.name == 'tw':
                     self.response.write('Your are logged in with Twitter.<br />')
                     
                     # We will get the user's 5 most recent tweets.
                     url = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
                     
                     # You can pass a dictionary of querystring parameters.
                     response = result.provider.access(url, {'count': 5})
                                             
                     # Parse response.
                     if response.status == 200:
                         if type(response.data) is list:
                             # Twitter returns the tweets as a JSON list.
                             self.response.write('Your 5 most recent tweets:')
                             for tweet in response.data:
                                 text = tweet.get('text')
                                 date = tweet.get('created_at')
                                 
                                 self.response.write('<h3>{}</h3>'.format(text))
                                 self.response.write('Tweeted on: {}'.format(date))
                                 
                         elif response.data.get('errors'):
                             self.response.write('Damn that error: {}!'.\
                                                 format(response.data.get('errors')))
                     else:
                         self.response.write('Damn that unknown error!<br />')
                         self.response.write('Status: {}'.format(response.status))
Exemple #9
0
import webapp2
import urllib
from authomatic import Authomatic
from authomatic.adapters import Webapp2Adapter
from config import CONFIG 

authomatic = Authomatic(config=CONFIG, secret='some random secret string')

class SnsAuth(webapp2.RequestHandler):
  def get(self)
    result = authomatic.login(Webapp2Adapter(self), 'fb')
    if result:
      self.response.write('l s')
app = webapp2.WSGIApplication([('/fb', SnsAuth)], debug=True)
Exemple #10
0
    def any(self, provider_name):

        #promote out of the iframe post parameters into session variables
        referer = self.requestParam('referer')
        if referer is None:
            referer = self.session.get('referer', None)
        if referer is None or (self.request.referer is not None
                               and "positiondial.com" in urlparse(
                                   self.request.referer).netloc):
            if self.requestParam(
                    'referer') is None or "positiondial.com" not in urlparse(
                        self.requestParam('referer')).netloc:
                referer = self.request.referer
        if type(referer) is unicode:
            referer = referer.encode('UTF-8')
        self.session['referer'] = referer
        visitorid = self.session.get('visitorid', None)
        # It all begins with login.
        if provider_name == 'ptw':
            self.redirect("/login/tw?" + self.request.query)
            return

        result = authomatic.login(Webapp2Adapter(self), provider_name)

        # Do not write anything to the response if there is no result!
        if result:
            # If there is result, the login procedure is over and we can write to response.

            if result.error:
                # Login procedure finished with an error.
                self.abort(404)

            elif result.user:
                creds = authomatic.credentials(result.user.credentials)
                # Test auto tweet

                # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,
                # We need to update the user to get more info.
                if not (result.user.name and result.user.id):
                    result.user.update()
                visitorquery = model.Visitor.query().filter(
                    model.Visitor.identities.external_id == result.user.id,
                    model.Visitor.identities.provider == provider_name)
                visitor = visitorquery.get()
                newvisitor = getById('Visitor', visitorid)

                #merge new visitor to existing visitor and remove
                if newvisitor != visitor:
                    if visitor is not None:
                        if newvisitor is not None:
                            mergevisitors(visitor, newvisitor)
                    else:  #shouldn't ever get here unless you've a messed up account like mine
                        visitor = newvisitor

                if visitor is None:
                    visitor = model.Visitor()

                pdprovideridentity = None
                provideridentity = None

                for identity in visitor.identities:
                    if identity.provider == provider_name:
                        provideridentity = identity
                    if identity.provider == 'pd':
                        pdprovideridentity = identity

                if provideridentity is None:
                    provideridentity = model.Identity(provider=provider_name)
                    visitor.identities.append(provideridentity)

                #if we found this provider, update the details
                provideridentity.name = result.user.name
                provideridentity.external_id = result.user.id
                provideridentity.email = result.user.email

                #if there's no positiondial account, create one
                if pdprovideridentity is None:
                    try:
                        randompass = id_generator(size=16)
                        user_data = self.user_model.create_user(
                            result.user.name, [],
                            password_raw=randompass,
                            email=provideridentity.email,
                            verified=False)
                        if user_data[0]:
                            user = user_data[1]
                            pdprovideridentity = model.Identity(provider='pd')
                            pdprovideridentity.name = user.auth_ids[0]
                            pdprovideridentity.external_id = user.get_id()
                            pdprovideridentity.email = user.email
                            visitor.identities.append(pdprovideridentity)
                    except Exception as e:
                        logging.exception(e)
                        pass

                #if there's no nickname (visitor name) take it from this identity
                if visitor.name is None:
                    visitor.name = provideridentity.name

                if type(visitor.referer) is unicode:
                    visitor.referer = visitor.referer.encode('UTF-8')

                #now save
                try:
                    visitor.put()
                except Exception as e:
                    replacementvisitor = model.Visitor(id=visitor.key.id())
                    mergevisitors(replacementvisitor, visitor)
                    replacementvisitor.put()
                    logging.debug(e)

                if result.provider.name == 'tw':
                    self.session['twittertoken'] = creds.token
                    self.session['twittersecret'] = creds.token_secret
                    self.session['twitterloggedin'] = True

                if result.provider.name == 'fb':
                    self.session['facebookloggedin'] = True

                self.session['visitorid'] = visitor.key.id()
                self.session['username'] = visitor.name
                self.redirect(referer)
                logging.info("Redirecting login to " + referer)
                self.session['referer'] = None
                return

                # Seems like we're done, but there's more we can do...

                # If there are credentials (only by AuthorizationProvider),
                # we can _access user's protected resources.
                if result.user.credentials:

                    # Each provider has it's specific API.
                    if result.provider.name == 'fb':
                        self.response.write(
                            'Your are logged in with Facebook.<br />')

                        # We will access the user's 5 most recent statuses.
                        url = 'https://graph.facebook.com/{}?fields=feed.limit(5)'
                        url = url.format(result.user.id)

                        # Access user's protected resource.
                        response = result.provider.access(url)

                        if response.status == 200:
                            # Parse response.
                            statuses = response.data.get('feed').get('data')
                            error = response.data.get('error')

                            if error:
                                self.response.write(
                                    u'Damn that error: {}!'.format(error))
                            elif statuses:
                                self.response.write(
                                    'Your 5 most recent statuses:<br />')
                                for message in statuses:

                                    text = message.get('message')
                                    date = message.get('created_time')

                                    self.response.write(
                                        u'<h3>{}</h3>'.format(text))
                                    self.response.write(
                                        u'Posted on: {}'.format(date))
                        else:
                            self.response.write(
                                'Damn that unknown error!<br />')
                            self.response.write(u'Status: {}'.format(
                                response.status))

                    if result.provider.name == 'tw':
                        self.response.write(
                            'Your are logged in with Twitter.<br />')

                        # We will get the user's 5 most recent tweets.
                        url = 'https://api.pdtwitter.com/1.1/statuses/user_timeline.json'

                        # You can pass a dictionary of querystring parameters.
                        response = result.provider.access(url, {'count': 5})

                        # Parse response.
                        if response.status == 200:
                            if type(response.data) is list:
                                # Twitter returns the tweets as a JSON list.
                                self.response.write(
                                    'Your 5 most recent tweets:')
                                for tweet in response.data:
                                    text = tweet.get('text')
                                    date = tweet.get('created_at')

                                    self.response.write(u'<h3>{}</h3>'.format(
                                        text.replace(u'\u2013', '[???]')))
                                    self.response.write(
                                        u'Tweeted on: {}'.format(date))

                            elif response.data.get('errors'):
                                self.response.write(u'Damn that error: {}!'.\
                                                    format(response.data.get('errors')))
                        else:
                            self.response.write(
                                'Damn that unknown error!<br />')
                            self.response.write(u'Status: {}'.format(
                                response.status))
Exemple #11
0
    def any(self, provider_name):

        result = authomatic.login(Webapp2Adapter(self), provider_name)

        if result:
            self.response.write("""<!DOCTYPE html><html>
            <head>
                <script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?skin=sunburst"></script>
            </head>
            """)

            self.response.write('<body>')
            self.response.write('<a href="..">Home</a> | ')
            self.response.write(
                '<a href="../login/{}">Retry</a>'.format(provider_name))

            if result.error:
                self.response.write('<h4>ERROR: {}</h4>'.format(
                    result.error.message))

                self.response.write('<h3>error to dict</h3>')
                self.response.write('<pre class="prettyprint">{}</pre>'.format(
                    result.error.to_dict()))

            elif result.user:
                response = result.user.update()
                if response:
                    self.response.write(
                        '<h3>User refresh status: {}</h3>'.format(
                            response.status))
                    self.response.write(
                        '<pre class="prettyprint">{}</pre>'.format(
                            response.content))

                    self.response.write('<h3>Access-Control-Allow-Origin</h3>')
                    self.response.write(
                        '<pre class="prettyprint">{}</pre>'.format(
                            response.getheader('Access-Control-Allow-Origin')))

                    self.response.write('<h3>User headers</h3>')
                    self.response.write(
                        '<pre class="prettyprint">{}</pre>'.format(
                            response.getheaders()))

                self.response.write('<h3>User</h3>')
                if result.user.picture:
                    self.response.write(
                        '<img src="{}" width="100" height="100" />'.format(
                            result.user.picture))

                loop(self, result.user)

                if result.user.credentials:
                    # loop through credentials attrs
                    self.response.write('<h3>Credentials</h3>')
                    self.response.write('<h5>expiration time: {}</h5>'.format(
                        result.user.credentials.expiration_time))
                    self.response.write('<h5>expiration date: {}</h5>'.format(
                        result.user.credentials.expiration_date))
                    loop(self, result.user.credentials)

                    self.response.write('<h3>Serialized credentials</h3>')
                    serialized_credentials = result.user.credentials.serialize(
                    )
                    endpoint_url = '/login/?type=elements&url=http://example.com&credentials=' + serialized_credentials
                    self.response.write(
                        '<a href="{}" target="_blank">{}</a>'.format(
                            endpoint_url, serialized_credentials))

                    json_input = """
                    {{"credentials": "{}",
                    "url": "http://example.com",
                    "method": "GET",
                    "params": {{"a": 1, "b": 2}},
                    "headers": {{"c": 3, "d": 4}}}}
                    """.format(result.user.credentials.serialize())

                    self.response.write('<h3>JSON Request elements</h3>')
                    re = authomatic.request_elements(json_input=json_input,
                                                     return_json=True)
                    self.response.write(
                        '<pre class="prettyprint">{}</pre>'.format(re))

                    # refresh credentials
                    response = result.user.credentials.refresh(force=True)

                    if response:
                        self.response.write(
                            '<h3>Refresh status: {}</h3>'.format(
                                response.status))
                        self.response.write(
                            '<pre class="prettyprint">{}</pre>'.format(
                                response.content))

                self.response.write(
                    '<pre id="ui" class="prettyprint">{}</pre>'.format(
                        cgi.escape(result.user.content or '')))

                self.response.write("""
                <script type="text/javascript">
                    ui = document.getElementById('ui');
                    try {{
                        ui.innerHTML = JSON.stringify({0}, undefined, 4);
                    }} catch(e) {{
                        console.log('XML');
                    }}
                        
                </script>
                """.format(result.user.content.replace('\n', ' ')) if result.
                                    user.content else '')

            self.response.write('<h3>Result js callback HTML</h3>')
            self.response.write('<pre class="prettyprint">{}</pre>'\
                                .format(cgi.escape(result.js_callback('callback', indent=4,
                                                                      custom=dict(foo='bar', baz="bing")))))

            self.response.write('</body></html>')
Exemple #12
0
    def any(self, provider_name):

        # It all begins with login.
        result = authomatic.login(Webapp2Adapter(self), provider_name)

        # Do not write anything to the response if there is no result!
        if result:
            # If there is result, the login procedure is over and we can write to response.
            self.response.write('<a href="..">Home</a>')

            if result.error:
                # Login procedure finished with an error.
                self.response.write('<h2>Damn that error: {}</h2>'.format(
                    result.error.message))

            elif result.user:
                # Hooray, we have the user!

                # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,
                # We need to update the user to get more info.
                if not (result.user.name and result.user.id):
                    result.user.update()

                # Welcome the user.
                user_name = result.user.name
                user_id = result.user.id
                #self.response.write(result.user.credentials)
                self.redirect('/pick')
                # Seems like we're done, but there's more we can do...

                # If there are credentials (only by AuthorizationProvider),
                # we can _access user's protected resources.
                if result.user.credentials:

                    # Each provider has it's specific API.
                    if result.provider.name == 'fb':
                        self.response.write(
                            'Your are logged in with Facebook.<br />')

                        # We will access the user's 5 most recent statuses.

                        url = 'https://graph.facebook.com/me/friends'
                        # Access user's protected resource.
                        response = result.provider.access(url)
                        #self.response.write(response.data['data'][4])

                        if response.status == 200:
                            # Parse response.
                            friends = {}
                            user_friends = response.data['data']
                            for item in user_friends:
                                friends[item['id']] = item['name']

                            user = User.get_or_insert(user_id,
                                                      id=user_id,
                                                      name=user_name)
                            if self.session['number'] != None:
                                user.number = self.session['number']
                            user.friends = str(friends)
                            user.put()

                            self.session['id'] = user_id
                            self.session['name'] = user_name

                            error = response.data.get('error')

                            if error:
                                self.response.write(
                                    'Damn that error: {}!'.format(error))
                        else:
                            self.response.write(
                                'Damn that unknown error!<br />')
                            self.response.write('Status: {}'.format(
                                response.status))