Example #1
0
def twitter_process(request):
    """Process the Twitter redirect"""
    if 'denied' in request.GET:
        return AuthenticationDenied("User denied authentication")

    settings = request.registry.settings
    request_token = oauth.Token.from_string(request.session['token'])
    verifier = request.GET.get('oauth_verifier')
    if not verifier:
        raise ThirdPartyFailure("Oauth verifier not returned")
    request_token.set_verifier(verifier)

    # Create the consumer and client, make the request
    consumer = oauth.Consumer(settings['velruse.twitter.consumer_key'],
                              settings['velruse.twitter.consumer_secret'])

    client = oauth.Client(consumer, request_token)
    resp, content = client.request(ACCESS_URL, "POST")
    if resp['status'] != '200':
        raise ThirdPartyFailure("Status %s: %s" % (resp['status'], content))
    access_token = dict(parse_qs(content))

    # Setup the normalized contact info
    profile = {}
    profile['accounts'] = [{
        'domain':'twitter.com',
        'userid':access_token['user_id'][0]
    }]
    profile['displayName'] = access_token['screen_name'][0]
    profile['end_point'] = get_came_from(request)

    cred = {'oauthAccessToken': access_token['oauth_token'][0],
            'oauthAccessTokenSecret': access_token['oauth_token_secret'][0]}
    return TwitterAuthenticationComplete(profile=profile,
                                         credentials=cred)
Example #2
0
    def process(self, request):
        """Handle incoming redirect from OpenID Provider"""
        log_debug = self.log_debug
        if log_debug:
            log.debug('Handling processing of response from server')

        openid_session = request.session.get('openid_session', None)
        del request.session['openid_session']
        if not openid_session:
            raise ThirdPartyFailure("No OpenID Session has begun.")

        # Setup the consumer and parse the information coming back
        oidconsumer = consumer.Consumer(openid_session, self.openid_store)
        return_to = request.route_url(self.process_url)
        info = oidconsumer.complete(request.params, return_to)

        if info.status in [consumer.FAILURE, consumer.CANCEL]:
            raise AuthenticationDenied("OpenID failure")
        elif info.status == consumer.SUCCESS:
            openid_identity = info.identity_url
            if info.endpoint.canonicalID:
                # If it's an i-name, use the canonicalID as its secure even if
                # the old one is compromised
                openid_identity = info.endpoint.canonicalID

            user_data = extract_openid_data(
                identifier=openid_identity,
                sreg_resp=sreg.SRegResponse.fromSuccessResponse(info),
                ax_resp=ax.FetchResponse.fromSuccessResponse(info),
            )

            user_data['end_point'] = get_came_from(request)
            # Did we get any OAuth info?
            oauth = info.extensionResponse(
                'http://specs.openid.net/extensions/oauth/1.0', False)
            cred = {}
            if oauth and 'request_token' in oauth:
                access_token = self._get_access_token(oauth['request_token'])
                if access_token:
                    cred.update(access_token)

                # See if we need to update our profile data with an OAuth call
                self._update_profile_data(request, user_data, cred)

            # Delete the temporary token data used for the OpenID auth
            return self.AuthenticationComplete(profile=user_data,
                                               credentials=cred)
        else:
            raise ThirdPartyFailure("OpenID failed.")
Example #3
0
    def process(self, request):
        """Handle incoming redirect from OpenID Provider"""
        log_debug = self.log_debug
        if log_debug:
            log.debug("Handling processing of response from server")

        openid_session = request.session.get("openid_session", None)
        del request.session["openid_session"]
        if not openid_session:
            raise ThirdPartyFailure("No OpenID Session has begun.")

        # Setup the consumer and parse the information coming back
        oidconsumer = consumer.Consumer(openid_session, self.openid_store)
        return_to = request.route_url(self.process_url)
        info = oidconsumer.complete(request.params, return_to)

        if info.status in [consumer.FAILURE, consumer.CANCEL]:
            raise AuthenticationDenied("OpenID failure")
        elif info.status == consumer.SUCCESS:
            openid_identity = info.identity_url
            if info.endpoint.canonicalID:
                # If it's an i-name, use the canonicalID as its secure even if
                # the old one is compromised
                openid_identity = info.endpoint.canonicalID

            user_data = extract_openid_data(
                identifier=openid_identity,
                sreg_resp=sreg.SRegResponse.fromSuccessResponse(info),
                ax_resp=ax.FetchResponse.fromSuccessResponse(info),
            )

            user_data["end_point"] = get_came_from(request)
            # Did we get any OAuth info?
            oauth = info.extensionResponse("http://specs.openid.net/extensions/oauth/1.0", False)
            cred = {}
            if oauth and "request_token" in oauth:
                access_token = self._get_access_token(oauth["request_token"])
                if access_token:
                    cred.update(access_token)

                # See if we need to update our profile data with an OAuth call
                self._update_profile_data(request, user_data, cred)

            # Delete the temporary token data used for the OpenID auth
            return self.AuthenticationComplete(profile=user_data, credentials=cred)
        else:
            raise ThirdPartyFailure("OpenID failed.")
Example #4
0
def github_login(request):
    """Initiate a github login"""
    config = request.registry.settings
    came_from = get_came_from(request)
    redirect_uri = request.route_url('github_process')
    if came_from:
        qs = urlencode({'end_point': came_from})
        if not '?' in redirect_uri:
            redirect_uri += '?'
        redirect_uri += qs
    scope = config.get('velruse.github.authorize',
                       request.POST.get('scope', ''))
    gh_url = flat_url('https://github.com/login/oauth/authorize',
                      scope=scope,
                      client_id=config['velruse.github.consumer_key'],
                      redirect_uri=redirect_uri)
    return HTTPFound(location=gh_url)
Example #5
0
def github_login(request):
    """Initiate a github login"""
    config = request.registry.settings
    came_from = get_came_from(request)
    redirect_uri = request.route_url('github_process')
    if came_from:
        qs = urlencode({'end_point':came_from })
        if not '?' in redirect_uri:
            redirect_uri += '?'
        redirect_uri += qs  
    scope = config.get('velruse.github.authorize',
                       request.POST.get('scope', ''))
    gh_url = flat_url('https://github.com/login/oauth/authorize',
                      scope=scope,
                      client_id=config['velruse.github.consumer_key'],
                      redirect_uri=redirect_uri)
    return HTTPFound(location=gh_url)
Example #6
0
def github_process(request):
    """Process the github redirect"""
    config = request.registry.settings
    code = request.GET.get('code')
    if not code:
        reason = request.GET.get('error', 'No reason provided.')
        return AuthenticationDenied(reason)

    # Now retrieve the access token with the code
    access_url = flat_url(
        'https://github.com/login/oauth/access_token',
        client_id=config['velruse.github.consumer_key'],
        client_secret=config['velruse.github.consumer_secret'],
        redirect_uri=request.route_url('github_process'),
        code=code)
    r = requests.get(access_url)
    if r.status_code != 200:
        raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content))
    access_token = parse_qs(r.content)['access_token'][0]

    # Retrieve profile data
    graph_url = flat_url('https://github.com/api/v2/json/user/show',
                         access_token=access_token)
    r = requests.get(graph_url)
    if r.status_code != 200:
        raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content))
    data = loads(r.content)['user']

    profile = {}
    profile['accounts'] = [{
        'domain': 'github.com',
        'username': data['login'],
        'userid': data['id']
    }]
    profile['displayName'] = data['name']
    profile['preferredUsername'] = data['login']
    profile['end_point'] = get_came_from(request)

    # We don't add this to verifiedEmail because ppl can change email addresses
    # without verifying them
    if 'email' in data:
        profile['emails'] = [{'value': data['email']}]

    cred = {'oauthAccessToken': access_token}
    return GithubAuthenticationComplete(profile=profile, credentials=cred)
Example #7
0
def github_process(request):
    """Process the github redirect"""
    config = request.registry.settings
    code = request.GET.get('code')
    if not code:
        reason = request.GET.get('error', 'No reason provided.')
        return AuthenticationDenied(reason)

    # Now retrieve the access token with the code
    access_url = flat_url('https://github.com/login/oauth/access_token',
                          client_id=config['velruse.github.consumer_key'],
                          client_secret=config['velruse.github.consumer_secret'],
                          redirect_uri=request.route_url('github_process'),
                          code=code)
    r = requests.get(access_url)
    if r.status_code != 200:
        raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content))
    access_token = parse_qs(r.content)['access_token'][0]

    # Retrieve profile data
    graph_url = flat_url('https://github.com/api/v2/json/user/show',
                         access_token=access_token)
    r = requests.get(graph_url)
    if r.status_code != 200:
        raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content))
    data = loads(r.content)['user']

    profile = {}
    profile['accounts'] = [{
        'domain':'github.com',
        'username':data['login'],
        'userid':data['id']
    }]
    profile['displayName'] = data['name']
    profile['preferredUsername'] = data['login']
    profile['end_point'] = get_came_from(request)

    # We don't add this to verifiedEmail because ppl can change email addresses
    # without verifying them
    if 'email' in data:
        profile['emails'] = [{'value':data['email']}]

    cred = {'oauthAccessToken': access_token}
    return GithubAuthenticationComplete(profile=profile,
                                        credentials=cred)
Example #8
0
def twitter_login(request):
    """Initiate a Twitter login"""
    settings = request.registry.settings

    # Create the consumer and client, make the request
    consumer = oauth.Consumer(settings['velruse.twitter.consumer_key'],
                              settings['velruse.twitter.consumer_secret'])
    came_from = get_came_from(request)
    redirect_uri = request.route_url('twitter_process')
    if came_from:
        qs = urlencode({'end_point': came_from})
        if not '?' in redirect_uri:
            redirect_uri += '?'
        redirect_uri += qs
    sigmethod = oauth.SignatureMethod_HMAC_SHA1()
    params = {'oauth_callback': redirect_uri}

    # We go through some shennanigans here to specify a callback url
    oauth_request = oauth.Request.from_consumer_and_token(consumer,
                                                          http_url=REQUEST_URL,
                                                          parameters=params)
    oauth_request.sign_request(sigmethod, consumer, None)
    r = requests.get(REQUEST_URL, headers=oauth_request.to_header())

    if r.status_code != 200:
        raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content))
    request_token = oauth.Token.from_string(r.content)

    request.session['token'] = r.content

    # Send the user to twitter now for authorization
    if asbool(settings.get('velruse.twitter.authorize')):
        req_url = 'https://api.twitter.com/oauth/authorize'
    else:
        req_url = 'https://api.twitter.com/oauth/authenticate'
    oauth_request = oauth.Request.from_token_and_callback(token=request_token,
                                                          http_url=req_url)
    return HTTPFound(location=oauth_request.to_url())
Example #9
0
def twitter_login(request):
    """Initiate a Twitter login"""
    settings = request.registry.settings

    # Create the consumer and client, make the request
    consumer = oauth.Consumer(settings['velruse.twitter.consumer_key'],
                              settings['velruse.twitter.consumer_secret'])
    came_from = get_came_from(request)
    redirect_uri = request.route_url('twitter_process')
    if came_from:
        qs = urlencode({'end_point':came_from })
        if not '?' in redirect_uri:
            redirect_uri += '?'
        redirect_uri += qs 
    sigmethod = oauth.SignatureMethod_HMAC_SHA1()
    params = {'oauth_callback': redirect_uri}

    # We go through some shennanigans here to specify a callback url
    oauth_request = oauth.Request.from_consumer_and_token(consumer,
        http_url=REQUEST_URL, parameters=params)
    oauth_request.sign_request(sigmethod, consumer, None)
    r = requests.get(REQUEST_URL, headers=oauth_request.to_header())

    if r.status_code != 200:
        raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content))
    request_token = oauth.Token.from_string(r.content)

    request.session['token'] = r.content

    # Send the user to twitter now for authorization
    if asbool(settings.get('velruse.twitter.authorize')):
        req_url = 'https://api.twitter.com/oauth/authorize'
    else:
        req_url = 'https://api.twitter.com/oauth/authenticate'
    oauth_request = oauth.Request.from_token_and_callback(
        token=request_token, http_url=req_url)
    return HTTPFound(location=oauth_request.to_url())
Example #10
0
def twitter_process(request):
    """Process the Twitter redirect"""
    if 'denied' in request.GET:
        return AuthenticationDenied("User denied authentication")

    settings = request.registry.settings
    request_token = oauth.Token.from_string(request.session['token'])
    verifier = request.GET.get('oauth_verifier')
    if not verifier:
        raise ThirdPartyFailure("Oauth verifier not returned")
    request_token.set_verifier(verifier)

    # Create the consumer and client, make the request
    consumer = oauth.Consumer(settings['velruse.twitter.consumer_key'],
                              settings['velruse.twitter.consumer_secret'])

    client = oauth.Client(consumer, request_token)
    resp, content = client.request(ACCESS_URL, "POST")
    if resp['status'] != '200':
        raise ThirdPartyFailure("Status %s: %s" % (resp['status'], content))
    access_token = dict(parse_qs(content))

    # Setup the normalized contact info
    profile = {}
    profile['accounts'] = [{
        'domain': 'twitter.com',
        'userid': access_token['user_id'][0]
    }]
    profile['displayName'] = access_token['screen_name'][0]
    profile['end_point'] = get_came_from(request)

    cred = {
        'oauthAccessToken': access_token['oauth_token'][0],
        'oauthAccessTokenSecret': access_token['oauth_token_secret'][0]
    }
    return TwitterAuthenticationComplete(profile=profile, credentials=cred)
Example #11
0
    def login(self, request):
        log_debug = self.log_debug
        if log_debug:
            log.debug('Handling OpenID login')

        # Load default parameters that all Auth Responders take
        openid_url = request.params.get('openid_identifier')

        # Let inherited consumers alter the openid identifier if desired
        openid_url = self._lookup_identifier(request, openid_url)

        if not openid_url:
            log.error('Velruse: no openid_url')
            raise MissingParameter('No openid_identifier was found')

        openid_session = {}
        oidconsumer = consumer.Consumer(openid_session, self.openid_store)

        try:
            if log_debug:
                log.debug('About to try OpenID begin')
            authrequest = oidconsumer.begin(openid_url)
        except consumer.DiscoveryFailure:
            if log_debug:
                log.debug('OpenID begin DiscoveryFailure')
            raise

        if authrequest is None:
            if log_debug:
                log.debug('OpenID begin returned empty')
            raise ThirdPartyFailure("OpenID begin returned nothing")

        if log_debug:
            log.debug('Updating authrequest')

        # Update the authrequest
        self._update_authrequest(request, authrequest)

        return_to = request.route_url(self.process_url)
        came_from = get_came_from(request)
        if came_from:
            qs = urlencode({'return_to': came_from})
            if not '?' in return_to:
                return_to += '?'
            return_to += qs

        # OpenID 2.0 lets Providers request POST instead of redirect, this
        # checks for such a request.
        if authrequest.shouldSendRedirect():
            if log_debug:
                log.debug('About to initiate OpenID redirect')
            realm = self.realm
            if not self.realm:
                realm = return_to
            redirect_url = authrequest.redirectURL(realm=realm,
                                                   return_to=return_to,
                                                   immediate=False)
            request.session['openid_session'] = openid_session
            return HTTPFound(location=redirect_url)
        else:
            if log_debug:
                log.debug('About to initiate OpenID POST')
            html = authrequest.htmlMarkup(
                realm=return_to,
                return_to=return_to,
                immediate=False,
                form_tag_attrs={
                    "claimed_id":
                    "http://specs.openid.net/auth/2.0/identifier_select",
                    "identity":
                    "http://specs.openid.net/auth/2.0/identifier_select",
                })
            request.session['openid_session'] = openid_session
            return Response(body=html)
Example #12
0
                if items:
                    for item in items:
                        if item[0] == dn:
                            data = item[1]
                            break
            except Exception, e:
                pass
    if not verified_login:
        reason = "Cannot verify the credentials with any of the ldap servers %s." % url
        return AuthenticationDenied(reason)
    profile = {}
    email, emails = '', data.get('mail', '')
    if emails:
        if isinstance(emails, list):
            email = emails[0]
        else:
            email = emails
    profile['accounts'] = [{
        'domain':'ldap',
        'username': username,
        'userid': username,
    }]
    if email:
        profile['verifiedEmail'] = email
        profile['emails'] = [{'value':email}]
    profile['displayName'] = username
    profile['end_point'] = get_came_from(request)
    cred = {'oauthAccessToken': '', 'oauthAccessTokenSecret': ''} 
    #return LdapAuthenticationComplete(profile=profile, credentials=cred)
    return AuthenticationComplete(profile=profile, credentials=cred)
Example #13
0
    def login(self, request):
        log_debug = self.log_debug
        if log_debug:
            log.debug("Handling OpenID login")

        # Load default parameters that all Auth Responders take
        openid_url = request.params.get("openid_identifier")

        # Let inherited consumers alter the openid identifier if desired
        openid_url = self._lookup_identifier(request, openid_url)

        if not openid_url:
            log.error("Velruse: no openid_url")
            raise MissingParameter("No openid_identifier was found")

        openid_session = {}
        oidconsumer = consumer.Consumer(openid_session, self.openid_store)

        try:
            if log_debug:
                log.debug("About to try OpenID begin")
            authrequest = oidconsumer.begin(openid_url)
        except consumer.DiscoveryFailure:
            if log_debug:
                log.debug("OpenID begin DiscoveryFailure")
            raise

        if authrequest is None:
            if log_debug:
                log.debug("OpenID begin returned empty")
            raise ThirdPartyFailure("OpenID begin returned nothing")

        if log_debug:
            log.debug("Updating authrequest")

        # Update the authrequest
        self._update_authrequest(request, authrequest)

        return_to = request.route_url(self.process_url)
        came_from = get_came_from(request)
        if came_from:
            qs = urlencode({"return_to": came_from})
            if not "?" in return_to:
                return_to += "?"
            return_to += qs

        # OpenID 2.0 lets Providers request POST instead of redirect, this
        # checks for such a request.
        if authrequest.shouldSendRedirect():
            if log_debug:
                log.debug("About to initiate OpenID redirect")
            realm = self.realm
            if not self.realm:
                realm = return_to
            redirect_url = authrequest.redirectURL(realm=realm, return_to=return_to, immediate=False)
            request.session["openid_session"] = openid_session
            return HTTPFound(location=redirect_url)
        else:
            if log_debug:
                log.debug("About to initiate OpenID POST")
            html = authrequest.htmlMarkup(
                realm=return_to,
                return_to=return_to,
                immediate=False,
                form_tag_attrs={
                    "claimed_id": "http://specs.openid.net/auth/2.0/identifier_select",
                    "identity": "http://specs.openid.net/auth/2.0/identifier_select",
                },
            )
            request.session["openid_session"] = openid_session
            return Response(body=html)
Example #14
0
                if items:
                    for item in items:
                        if item[0] == dn:
                            data = item[1]
                            break
            except Exception, e:
                pass
    if not verified_login:
        reason = "Cannot verify the credentials with any of the ldap servers %s." % url
        return AuthenticationDenied(reason)
    profile = {}
    email, emails = '', data.get('mail', '')
    if emails:
        if isinstance(emails, list):
            email = emails[0]
        else:
            email = emails
    profile['accounts'] = [{
        'domain': 'ldap',
        'username': username,
        'userid': username,
    }]
    if email:
        profile['verifiedEmail'] = email
        profile['emails'] = [{'value': email}]
    profile['displayName'] = username
    profile['end_point'] = get_came_from(request)
    cred = {'oauthAccessToken': '', 'oauthAccessTokenSecret': ''}
    #return LdapAuthenticationComplete(profile=profile, credentials=cred)
    return AuthenticationComplete(profile=profile, credentials=cred)