예제 #1
0
def facebook_process(request):
    """Process the facebook redirect"""
    if request.GET.get('state') != request.session.get('facebook_state'):
        raise CSRFError(
            "CSRF Validation check failed. Request state %s is "
            "not the same as session state %s" %
            (request.GET.get('state'), request.session.get('state')))
    del request.session['facebook_state']

    code = request.GET.get('code')
    if not code:
        reason = request.GET.get('error_reason', 'No reason provided.')
        return AuthenticationDenied(reason)

    cfg = ptah.get_settings(ptahcrowd.CFG_ID_AUTH, request.registry)

    client_id = cfg['facebook_id']
    client_secret = cfg['facebook_secret']

    # Now retrieve the access token with the code
    access_url = '{0}?{1}'.format(
        'https://graph.facebook.com/oauth/access_token',
        url_encode({
            'client_id': client_id,
            'client_secret': client_secret,
            'redirect_uri': request.route_url('facebook_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 = urlparse.parse_qs(r.content)['access_token'][0]

    entry = Storage.get_by_token(access_token)
    if entry is not None:
        return FacebookAuthenticationComplete(entry)

    # Retrieve profile data
    graph_url = '{0}?{1}'.format('https://graph.facebook.com/me',
                                 url_encode({'access_token': access_token}))
    r = requests.get(graph_url)
    if r.status_code != 200:
        raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content))

    profile = json.loads(r.content)

    id = profile['id']
    name = profile['name']
    email = profile.get('email', '')
    verified = profile.get('verified', False)

    entry = Storage.create(access_token,
                           'facebook',
                           uid='{0}:{1}'.format('facebook', id),
                           name=name,
                           email=email,
                           verified=verified,
                           profile=profile)
    return FacebookAuthenticationComplete(entry)
예제 #2
0
def facebook_process(request):
    """Process the facebook redirect"""
    if request.GET.get('state') != request.session.get('facebook_state'):
        raise CSRFError("CSRF Validation check failed. Request state %s is "
                        "not the same as session state %s" % (
                        request.GET.get('state'), request.session.get('state')
                        ))
    del request.session['facebook_state']

    code = request.GET.get('code')
    if not code:
        reason = request.GET.get('error_reason', 'No reason provided.')
        return AuthenticationDenied(reason)

    cfg = ptah.get_settings(ptahcrowd.CFG_ID_AUTH, request.registry)

    client_id = cfg['facebook_id']
    client_secret = cfg['facebook_secret']

    # Now retrieve the access token with the code
    access_url = '{0}?{1}'.format(
        'https://graph.facebook.com/oauth/access_token',
        url_encode({'client_id': client_id,
                    'client_secret': client_secret,
                    'redirect_uri': request.route_url('facebook_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 = urlparse.parse_qs(r.content)['access_token'][0]

    entry = Storage.get_by_token(access_token)
    if entry is not None:
        return FacebookAuthenticationComplete(entry)

    # Retrieve profile data
    graph_url = '{0}?{1}'.format('https://graph.facebook.com/me',
                                 url_encode({'access_token': access_token}))
    r = requests.get(graph_url)
    if r.status_code != 200:
        raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content))

    profile = json.loads(r.content)

    id = profile['id']
    name = profile['name']
    email = profile.get('email','')
    verified = profile.get('verified', False)

    entry = Storage.create(access_token, 'facebook',
                           uid = '{0}:{1}'.format('facebook', id),
                           name = name,
                           email = email,
                           verified = verified,
                           profile = profile)
    return FacebookAuthenticationComplete(entry)
예제 #3
0
def github_process(request):
    """Process the github redirect"""
    code = request.GET.get('code')
    if not code:
        reason = request.GET.get('error', 'No reason provided.')
        return AuthenticationDenied(reason)

    cfg = ptah.get_settings(ptahcrowd.CFG_ID_AUTH, request.registry)

    client_id = cfg['github_id']
    client_secret = cfg['github_secret']

    # Now retrieve the access token with the code
    access_url = '{0}?{1}'.format(
        'https://github.com/login/oauth/access_token',
        url_encode({
            'client_id': client_id,
            'client_secret': client_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))

    try:
        access_token = urlparse.parse_qs(r.content)['access_token'][0]
    except:
        return AuthenticationDenied("Can't get access_token.")

    entry = Storage.get_by_token(access_token)
    if entry is not None:
        return GithubAuthenticationComplete(entry)

    # Retrieve profile data
    graph_url = '{0}?{1}'.format('https://github.com/api/v2/json/user/show',
                                 url_encode({'access_token': access_token}))
    r = requests.get(graph_url)
    if r.status_code != 200:
        raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content))

    profile = json.loads(r.content)

    entry = Storage.create(access_token,
                           'github',
                           uid='github:{0}'.format(profile['user']['id']),
                           name=profile['user']['name'],
                           email=profile['user'].get('email') or '',
                           profile=profile)

    return GithubAuthenticationComplete(entry)
예제 #4
0
def github_process(request):
    """Process the github redirect"""
    code = request.GET.get('code')
    if not code:
        reason = request.GET.get('error', 'No reason provided.')
        return AuthenticationDenied(reason)

    cfg = ptah.get_settings(ptahcrowd.CFG_ID_AUTH, request.registry)

    client_id = cfg['github_id']
    client_secret = cfg['github_secret']

    # Now retrieve the access token with the code
    access_url ='{0}?{1}'.format(
        'https://github.com/login/oauth/access_token',
        url_encode({'client_id': client_id,
                    'client_secret': client_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))

    try:
        access_token = urlparse.parse_qs(r.content)['access_token'][0]
    except:
        return AuthenticationDenied("Can't get access_token.")

    entry = Storage.get_by_token(access_token)
    if entry is not None:
        return GithubAuthenticationComplete(entry)

    # Retrieve profile data
    graph_url = '{0}?{1}'.format(
        'https://github.com/api/v2/json/user/show',
        url_encode({'access_token': access_token}))
    r = requests.get(graph_url)
    if r.status_code != 200:
        raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content))

    profile = json.loads(r.content)

    entry = Storage.create(access_token, 'github',
                           uid = 'github:{0}'.format(profile['user']['id']),
                           name = profile['user']['name'],
                           email = profile['user'].get('email') or '',
                           profile = profile)

    return GithubAuthenticationComplete(entry)
예제 #5
0
def facebook_process(request):
    """Process the facebook redirect"""
    print request.GET

    # get session
    st = request.GET.get('state').split(',')[-1]
    manager = ptah.sockjs.get_session_manager(request.registry)
    try:
        session = manager.get(st)
    except:
        raise HTTPBadRequest("No session")

    code = request.GET.get('code')
    if not code:
        raise HTTPBadRequest("No reason")

    # auth
    cfg = ptah.get_settings(CFG_ID_AUTH, request.registry)

    client_id = cfg['facebook_id']
    client_secret = cfg['facebook_secret']

    # Now retrieve the access token with the code
    access_url = '{0}?{1}'.format(
        'https://graph.facebook.com/oauth/access_token',
        url_encode({
            'client_id': client_id,
            'client_secret': client_secret,
            'redirect_uri': request.route_url('facebook_process'),
            'code': code
        }))

    r = requests.get(access_url)
    if r.status_code != 200:
        raise HTTPBadRequest("Status %s: %s" % (r.status_code, r.content))

    access_token = urlparse.parse_qs(r.content)['access_token'][0]

    with ptah.sa_session() as sa:
        user = User.get_bytoken(access_token)
        if user is not None:
            protocol = session.protocols.get('gallery')
            protocol.auth(user)

            response = request.response
            response.content_type = 'text/html'
            response.body = close
            return response

    # Retrieve profile data
    graph_url = '{0}?{1}'.format('https://graph.facebook.com/me',
                                 url_encode({'access_token': access_token}))
    r = requests.get(graph_url)
    if r.status_code != 200:
        raise HTTPBadRequest("Status %s: %s" % (r.status_code, r.content))

    profile = ptah.json.loads(r.content)

    id = profile['id']
    name = profile['name']
    email = profile.get('email', '').lower()

    with ptah.sa_session() as sa:
        sa.query(User).filter(User.email == email).delete()

        user = User(token=access_token,
                    source='facebook',
                    name=name,
                    email=email)
        sa.add(user)
        sa.flush()

        protocol = session.protocols.get('gallery')
        protocol.auth(user)

        response = request.response
        response.content_type = 'text/html'
        response.body = close
        return response
예제 #6
0
파일: app.py 프로젝트: fschulze/troublebox
 def iter_items(self):
     # make a copy for modification
     data = dict(self.data)
     if 'server_name' in data:
         yield Info('Server Name', data.pop('server_name'))
     platform = data.pop('platform', None)
     if platform:
         yield Info('Platform', platform)
     if 'level' in data:
         yield Info('Level', data.pop('level'))
     data.pop('timestamp', None)
     if 'transaction' in data:
         yield Info('Transaction', data.pop('transaction'))
     request = dict(data.pop('request', {}))
     if 'method' in request:
         yield Info('Request Method', request.get('method'))
     if 'url' in request:
         yield Info(
             'Request URL',
             Markup(url_template(url=request['url'], title=request['url'])))
     if request.get('query_string'):
         qs = request.get('query_string')
         try:
             qs = urlparse.parse_qs(qs)
             yield Info(
                 'Request Query String',
                 Markup(tabled_dict_template(value=qs, pformat=pformat)))
         except Exception:
             yield Info('Request Query String', qs)
     if platform == 'python' and 'values' in data.get('exception', {}):
         exception = dict(data.pop('exception'))
         values = exception.pop('values', [])
         num_values = len(values)
         if num_values > 1:
             title_fmt = 'Exception {}/%s' % num_values
         else:
             title_fmt = 'Exception'
         for index, value in enumerate(values, start=1):
             if 'stacktrace' in value and 'frames' in value['stacktrace']:
                 frames = value['stacktrace'].pop('frames')
                 if not value['stacktrace']:
                     del value['stacktrace']
                 yield Info(title_fmt.format(index) + ' Frames',
                            Markup(''.join(render_frame(x)
                                           for x in frames)),
                            toggle=True,
                            toggled=index > 1)
             yield Info(
                 value.pop('type', None),
                 Markup(pre_wrap_template(value=value.pop('value', None))))
             yield Info(
                 title_fmt.format(index) + ' Info',
                 Markup(tabled_dict_template(value=value, pformat=pformat)))
         # in case there are more items
         if exception:
             yield Info(
                 'Exception Meta',
                 Markup(
                     tabled_dict_template(value=exception,
                                          pformat=pformat)))
     if 'logentry' in data:
         yield Info(
             'Log Entry',
             Markup(
                 tabled_dict_template(value=data.pop('logentry'),
                                      pformat=pformat)))
     if 'logger' in data:
         yield Info('Logger', data.pop('logger'))
     if request:
         yield Info(
             'Request',
             Markup(tabled_dict_template(value=request, pformat=pformat)))
     for key, value in sorted(data.items()):
         yield Info(key, Markup(pre_template(value=pformat(value))))
예제 #7
0
def facebook_process(request):
    """Process the facebook redirect"""
    print request.GET

    # get session
    st = request.GET.get('state').split(',')[-1]
    manager = ptah.sockjs.get_session_manager(request.registry)
    try:
        session = manager.get(st)
    except:
        raise HTTPBadRequest("No session")

    code = request.GET.get('code')
    if not code:
        raise HTTPBadRequest("No reason")

    # auth
    cfg = ptah.get_settings(CFG_ID_AUTH, request.registry)

    client_id = cfg['facebook_id']
    client_secret = cfg['facebook_secret']

    # Now retrieve the access token with the code
    access_url = '{0}?{1}'.format(
        'https://graph.facebook.com/oauth/access_token',
        url_encode({'client_id': client_id,
                    'client_secret': client_secret,
                    'redirect_uri': request.route_url('facebook_process'),
                    'code': code}))

    r = requests.get(access_url)
    if r.status_code != 200:
        raise HTTPBadRequest("Status %s: %s" % (r.status_code, r.content))

    access_token = urlparse.parse_qs(r.content)['access_token'][0]

    with ptah.sa_session() as sa:
        user = User.get_bytoken(access_token)
        if user is not None:
            protocol = session.protocols.get('gallery')
            protocol.auth(user)
            
            response = request.response
            response.content_type = 'text/html'
            response.body = close
            return response

    # Retrieve profile data
    graph_url = '{0}?{1}'.format('https://graph.facebook.com/me',
                                 url_encode({'access_token': access_token}))
    r = requests.get(graph_url)
    if r.status_code != 200:
        raise HTTPBadRequest("Status %s: %s" % (r.status_code, r.content))

    profile = ptah.json.loads(r.content)

    id = profile['id']
    name = profile['name']
    email = profile.get('email','').lower()

    with ptah.sa_session() as sa:
        sa.query(User).filter(User.email == email).delete()

        user = User(
            token = access_token,
            source = 'facebook',
            name = name, email = email)
        sa.add(user)
        sa.flush()

        protocol = session.protocols.get('gallery')
        protocol.auth(user)

        response = request.response
        response.content_type = 'text/html'
        response.body = close
        return response