Esempio n. 1
0
def token_request(uri, post_data):
    """
    This function encapsulates the code used to make the request
    to the (reddit) OAuth2 endpoint that is shared between
    obtaining the first, refreshing and revoking the token.

    The parameters are the endpoint URI and dictionary with the post data
    to be JSONified and sent with the POST request to the URI.
    """
    request_data = urlencode(post_data).encode('utf-8')

    token_request = client_http_request(uri, method='POST', data=request_data)
    token_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    token_request.add_header('User-Agent', rwh.config['APP_USER_AGENT_SERVER'])

    authenticator = HTTPBasicAuthHandler()
    authenticator.add_password(realm='reddit', uri=uri,
                               user=rwh.config['APP_ID'], passwd='')
    authenticated_opener = build_opener(authenticator)

    request_result = authenticated_opener.open(token_request)

    status_code = request_result.getcode()
    result_body = None
    if request_result:
        result_body = request_result.read().decode('utf-8')
    if result_body and (len(result_body.strip()) > 0):
        result_data = parse_json_string(result_body)
    else:
        result_data = None

    return result_data, status_code
Esempio n. 2
0
def get_reddit_username(login_session):
    username_request = client_http_request('https://oauth.reddit.com/api/v1/me',
                                           method='GET')
    username_request.add_header('User-Agent', rwh.config['APP_USER_AGENT_SERVER'])
    username_request.add_header('Authorization', "bearer %s" % login_session.token)
    response = urlopen(username_request)

    http_status = response.getcode()
    response_body = response.read().decode('utf-8')
    if ((http_status == 200) and (len(response_body.strip()) > 0)):
        response_data = parse_json_string(response_body)

        username = response_data['name'] 

        hash_function = sha256()
        hash_function.update(username.encode('utf-8'))

        return hash_function.hexdigest()
    else:
        return None