Python Linked API throwing error with Python 2.7 - python-2.7

This code to fetch skills from linkedin is working fine with python 2.6
from linkedin import helper
from liclient import LinkedInAPI
import json
AUTH_TOKEN='{"oauth_token_secret": "TOKEN SECRET", "oauth_authorization_expires_in": "0", "oauth_token": "OAUTH TOKEN", "oauth_expires_in": "0"}'
consumer_key = 'CONSUMER KEY'
consumer_secret = 'CONSUMER SECRET'
APIClient =LinkedInAPI(consumer_key, consumer_secret)
request_token = APIClient.get_request_token()
field_selector_string = ['skills']
results = APIClient.get_user_profile(json.loads(AUTH_TOKEN), field_selector_string)
Skills = results[0].skills
print Skills
But when I run same code with python 2.7 gettting this error
Traceback (most recent call last):
File "linkedintest.py", line 10, in <module>
results = APIClient.get_user_profile(json.loads(AUTH_TOKEN), field_selector_string)
File "/var/www/shine/liclient/__init__.py", line 82, in get_user_profile
resp, content = client.request(url, 'GET')
File "/var/www/shine/liclient/oauth2/__init__.py", line 603, in request
req.sign_request(self.method, self.consumer, self.token)
File "/var/www/shine/liclient/oauth2/__init__.py", line 357, in sign_request
self['oauth_signature'] = signature_method.sign(self, consumer, token)
File "/var/www/shine/liclient/oauth2/__init__.py", line 683, in sign
hashed = hmac.new(key, raw, sha)
File "/usr/lib/python2.7/hmac.py", line 133, in new
return HMAC(key, msg, digestmod)
File "/usr/lib/python2.7/hmac.py", line 72, in __init__
self.outer.update(key.translate(trans_5C))
TypeError: character mapping must return integer, None or unicode

Try this:
from linkedin import helper
from liclient import LinkedInAPI
import json
AUTH_TOKEN='{"oauth_token_secret": "TOKEN SECRET", "oauth_authorization_expires_in": "0", "oauth_token": "OAUTH TOKEN", "oauth_expires_in": "0"}'
# converting unicode dict to str dict
AUTH_TOKEN=json.loads(AUTH_TOKEN)
AUTH_TOKEN_DICT = {}
for auth in AUTH_TOKEN:
AUTH_TOKEN_STR[str(auth)] = str(AUTH_TOKEN[auth])
consumer_key = 'CONSUMER KEY'
consumer_secret = 'CONSUMER SECRET'
APIClient =LinkedInAPI(consumer_key, consumer_secret)
request_token = APIClient.get_request_token()
field_selector_string = ['skills']
results = APIClient.get_user_profile(AUTH_TOKEN_DICT, field_selector_string)
Skills = results[0].skills
print Skills

Related

Is there any error with local moto server and cognito-idp in boto3 with awssrp?

I have a local moto server and am verifying cognito-idp in boto3 with awssrp, but I get an error.
The error message is.
Traceback (most recent call last):
File "/tests/get_token.py", line 71, in <module>
token_res = get_cognito_token(cognito_user_name, cognito_user_password)
File "/tests/get_token.py", line 63, in get_cognito_token
tokens = response.authenticate_user()
File "/Users/myuser/.pyenv/versions/3.9.14/lib/python3.9/site-packages/warrant/aws_srp.py", line 210, in authenticate_user
tokens = boto_client.respond_to_auth_challenge(
File "/Users/myuser/.pyenv/versions/3.9.14/lib/python3.9/site-packages/botocore/client.py", line 530, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/Users/myuser/.pyenv/versions/3.9.14/lib/python3.9/site-packages/botocore/client.py", line 960, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.errorfactory.UserNotFoundException: An error occurred (UserNotFoundException) when calling the RespondToAuthChallenge operation: User does not exist.
The code is as follows.
create user and sign up code no error...
create_user.py
import boto3
import json
cognito_client = boto3.client('cognito-idp', region_name="us-east-1", endpoint_url='http://localhost:5000')
response = cognito_client.create_user_pool(
PoolName='local_pool'
)
# print(response)
cl_pool_id = response['UserPool']['Id']
print(f"response_code:{response['ResponseMetadata']['HTTPStatusCode']}")
print(f"pool_id:{response['UserPool']['Id']}")
create_user_res = cognito_client.create_user_pool_client(
UserPoolId=cl_pool_id,
ClientName='local_user7',
ExplicitAuthFlows=[
# 'ADMIN_NO_SRP_AUTH',
# 'CUSTOM_AUTH_FLOW_ONLY',
# 'USER_PASSWORD_AUTH',
'ALLOW_ADMIN_USER_PASSWORD_AUTH',
# 'ALLOW_CUSTOM_AUTH',
'ALLOW_USER_PASSWORD_AUTH',
'ALLOW_USER_SRP_AUTH',
'ALLOW_REFRESH_TOKEN_AUTH',
],
)
cl_client_id = create_user_res['UserPoolClient']['ClientId']
print(f"client_id:{cl_client_id}")
cognito_user_name = "dummy7"
cognito_user_email = "dummy7#dummy.jp"
cognito_user_password = "P#ssw0rd"
create_user_res = cognito_client.admin_create_user(
UserPoolId=cl_pool_id,
Username=cognito_user_name,
UserAttributes=[
{
'Name': 'email',
'Value': cognito_user_email
},
{
'Name': 'email_verified',
'Value': "true"
},
],
MessageAction='SUPPRESS',
)
print(f"create_user_res:{create_user_res}")
set_user_pass = cognito_client.admin_set_user_password(
UserPoolId=cl_pool_id,
Username=cognito_user_name,
Password=cognito_user_password,
Permanent=True
)
print(f"set_user_pass_res:{set_user_pass}")
list_users = cognito_client.list_users(
UserPoolId=cl_pool_id,
)
print(f"list_users:{list_users}")
user_pool_client = cognito_client.describe_user_pool_client(
UserPoolId=cl_pool_id,
ClientId=cl_client_id,
)
print(f"user_pool_client:{user_pool_client}")
authenticate code with error.
get_token.py
import ast
import base64
import boto3
import json
import logging
import os
import re
from warrant.aws_srp import AWSSRP
pool_id = "us-east-1_8d32eabf665f214687c6ba15282a4ad20d36fdae19d630"
client_id = "jp4v9277l6pca2v5ei2v0p5ayh"
cognito_user_name = "dummy7"
cognito_user_email = "dummy7#dummy.jp"
cognito_user_password = "P#ssw0rd"
cognito_client = boto3.client('cognito-idp', region_name="us-east-1", endpoint_url='http://localhost:5000')
def get_cognito_token(username, password):
response = AWSSRP(
username=cognito_user_name,
password=cognito_user_password,
pool_id=pool_id,
client_id=client_id,
client=cognito_client,
)
print(f"response:{response}")
print(f"response_dir:{dir(response)}")
# print(f"response_vars:{vars(response)}")
tokens = response.authenticate_user()
result = tokens["AuthenticationResult"]
return result
token_res = get_cognito_token(cognito_user_name, cognito_user_password)
print(f"token_res:{token_res}")
error I search various things from the contents, but moto server itself seems to support srp as well.
I tried password authentication with moto server, which is not srp, for a user that has already been created, and it authenticated without problems.
I would like to know if anyone has succeeded in mocking with moto server using srp.

Web API (Python, Flask) with middleware and JWT for requests authentication raises DecodeError('Signature verification failed')

I'm having trouble decoding a token that I receive through the header of my request.
Application:
from flask import Flask
from flask import jsonify
from flask_restplus import Resource, Api
from helpers.load import get_env as _
from middleware.environment_middleware import EnvironmentMiddleware
from flask_jwt_extended import JWTManager
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = _('DATABASE_URI')
app.config['SQLALCHEMY_DATABASE_URI'] = _('DATABASE_URI')
app.config['SECRET_KEY'] = _('SECRET_KEY')
app.config['JWT_SECRET_KEY'] = _('JWT_SECRET')
app.wsgi_app = EnvironmentMiddleware(app.wsgi_app)
jwt = JWTManager(app)
api = Api(app)
jwt._set_error_handler_callbacks(api)
Middleware Class:
from werkzeug.wrappers import Request, Response, ResponseStream
from helpers.load import load_db_env
from flask_jwt_extended import get_jwt_identity, jwt_required, verify_jwt_in_request
import jwt
class EnvironmentMiddleware():
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
request = Request(environ)
if request.headers:
params = load_db_env(request.headers.get('Whitelabel'))
jwt.decode(request.headers.get('Authorization').replace('Bearer ', ''), params['JWT_SECRET'], algorithm='HS256')
return self.app(environ, start_response)
res = Response(u'Unauthorized.', mimetype='application/json', status=401)
return res(environ, start_response)
load_db_env brings a dict with all params from my database according with the 'whitelabel' parameter including the JWT_SECRET and my environ brings all Response data, headers, etc that I need for authentication.
But for some reason I can't decode and find the informations inside the Bearer Token from the request for validate and identify the user.
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/bela/dev/bela/lib/python3.8/site-packages/jwt/api_jwt.py", line 63, in decode
decoded = super(PyJWT, self).decode(jwt, key, verify, algorithms,
File "/home/bela/dev/bela/lib/python3.8/site-packages/jwt/api_jws.py", line 115, in decode
self._verify_signature(payload, signing_input, header, signature,
File "/home/bela/dev/bela/lib/python3.8/site-packages/jwt/api_jws.py", line 186, in _verify_signature
raise DecodeError('Signature verification failed')
jwt.exceptions.DecodeError: Signature verification failed
I hope I was clear, I'm from Brazil and my english is not the best.
Obrigada! :*

Login via Airflow Web Authentication shows an error page

I enabled a Web Authentication for Airflow by following instructions at http://airflow.apache.org/security.html#web-authentication (and restarted the web server)
Logging in seems to work but what I see is an error page with this error message:
File "/usr/local/lib/python2.7/dist-packages/airflow/contrib/auth/backends/password_auth.py", line 154, in login
user = authenticate(session, username, password)
File "/usr/local/lib/python2.7/dist-packages/airflow/contrib/auth/backends/password_auth.py", line 131, in authenticate
if not user.authenticate(password):
File "/usr/local/lib/python2.7/dist-packages/airflow/contrib/auth/backends/password_auth.py", line 72, in authenticate
return check_password_hash(self._password, plaintext)
File "/usr/local/lib/python2.7/dist-packages/flask_bcrypt.py", line 67, in check_password_hash
return Bcrypt().check_password_hash(pw_hash, password)
File "/usr/local/lib/python2.7/dist-packages/flask_bcrypt.py", line 193, in check_password_hash
return safe_str_cmp(bcrypt.hashpw(password, pw_hash), pw_hash)
File "/usr/local/lib/python2.7/dist-packages/bcrypt/__init__.py", line 81, in hashpw
original_salt, salt = salt, _normalize_re.sub(b"$2b$", salt)
TypeError: expected string or buffer
Any idea/insight on this issue?
As mentioned here, using the following worked for me when I had the same error:
import airflow
from airflow import models, settings
from airflow.contrib.auth.backends.password_auth import PasswordUser
from flask_bcrypt import generate_password_hash
user = PasswordUser(models.User())
user.username = 'some'
user.email = 'some#email.com'
user._password = generate_password_hash('password', 12).decode('utf-8')
session = settings.Session()
session.add(user)
session.commit()
session.close()

Adwords API UserListService results in attribute error on calling mutate

I am Adding a new User List using Google AdWords API userListService,I have passed all the required inputs and the adword client instance got created successfully.
But while calling the mutate method it is throwing an attribute error
"AttributeError: class HttpTransport has no attribute '_HttpTransport__get_request_url'"
Please find the StackTrace:
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 5\helpers\pydev\pydevd.py", line 2411, in
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 5\helpers\pydev\pydevd.py", line 1802, in run
launch(file, globals, locals) # execute the script
File "D:/Python Studies/SVN Code/Work In Progress/Source Code/doubleclick-Dmp-Integration/DmpIntegrationApplication/dmpintegration/dmpex/adwords.py", line 93, in
main(adwords_client)
File "D:/Python Studies/SVN Code/Work In Progress/Source Code/doubleclick-Dmp-Integration/DmpIntegrationApplication/dmpintegration/dmpex/adwords.py", line 33, in main
result = user_list_service.mutate(operations)
File "C:\Python27\lib\site-packages\googleads\common.py", line 720, in MakeSoapRequest
*[_PackForSuds(arg, self.suds_client.factory) for arg in args])
File "C:\Python27\lib\site-packages\suds\client.py", line 542, in call
return client.invoke(args, kwargs)
File "C:\Python27\lib\site-packages\suds\client.py", line 602, in invoke
result = self.send(soapenv)
File "C:\Python27\lib\site-packages\suds\client.py", line 637, in send
reply = transport.send(request)
File "C:\Python27\lib\site-packages\googleads\util.py", line 92, in PatchedHttpTransportSend
url = http_transport._HttpTransport__get_request_url(request)
AttributeError: class HttpTransport has no attribute '_HttpTransport__get_request_url'
Here is my code:
import uuid
from googleads import adwords
from googleads import oauth2
def main(client):
# Initialize appropriate service.
user_list_service = client.GetService(
'AdwordsUserListService', version='v201702')
# Construct operations and add a user list.
operations = [
{
'operator': 'ADD',
'operand': {
'xsi_type': 'BasicUserList',
'name': 'Mars cruise customers #%s' % uuid.uuid4(),
'description': 'A list of mars cruise customers in the last
year',
'membershipLifeSpan': '365',
'conversionTypes': [
{
'name': ('Mars cruise customers #%s'
% uuid.uuid4())
}
],
# Optional field.
'status': 'OPEN',
}
}
]
result = user_list_service.mutate(operations)
if __name__ == '__main__':
CLIENT_ID = 'xxx'
CLIENT_SECRET = 'xxx'
REFRESH_TOKEN = 'xxx'
DEVELOPER_TOKEN = 'xxx'
USER_AGENT = 'xxx'
CLIENT_CUSTOMER_ID = 'xxx'
oauth2_client = oauth2.GoogleRefreshTokenClient(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN)
adwords_client = adwords.AdWordsClient(DEVELOPER_TOKEN, oauth2_client, USER_AGENT,client_customer_id=CLIENT_CUSTOMER_ID)
main(adwords_client)

"TypeError: cannot concatenate 'str' and 'NoneType' objects" in Python Google Adwords API Client

I can't use the download reports feature with the Python client. I'm using with adwords-15.9.0 with v201306. It always fails with:
$ ./classifications.py
Traceback (most recent call last):
File "./classifications.py", line 48, in <module>
download_report(client, client_id)
File "./classifications.py", line 32, in download_report
file_path = report_downloader.DownloadReportWithAwql(report_query, 'CSV', file_path=path)
File "/Users/mike/.virtualenvs/xxx/lib/python2.7/site-packages/adspygoogle/adwords/ReportDownloader.py", line 127, in DownloadReportWithAwql
fileobj) or file_path
File "/Users/mike/.virtualenvs/xxx/lib/python2.7/site-packages/adspygoogle/adwords/ReportDownloader.py", line 169, in __DownloadAdHocReportWithAwql
return self.__DownloadReport(payload, return_micros, fileobj)
File "/Users/mike/.virtualenvs/xxx/lib/python2.7/site-packages/adspygoogle/adwords/ReportDownloader.py", line 184, in __DownloadReport
headers = self.__GenerateHeaders(return_micros)
File "/Users/mike/.virtualenvs/xxx/lib/python2.7/site-packages/adspygoogle/adwords/ReportDownloader.py", line 282, in __GenerateHeaders
self._headers['oauth2credentials'].apply(headers)
File "/Users/mike/.virtualenvs/xxx/lib/python2.7/site-packages/oauth2client/client.py", line 533, in apply
headers['Authorization'] = 'Bearer ' + self.access_token
TypeError: cannot concatenate 'str' and 'NoneType' objects
Example scripts get_report_fields.py and get_campaign_stats.py work fine but download_criteria_report.py and download_criteria_report_with_awql.py fail with the same error.
Any ideas?
My code:
#!/usr/bin/env python
import csv
import os
import MySQLdb as mdb
from adspygoogle.adwords.AdWordsClient import AdWordsClient
MATCH_TYPES = {
'b': 'Broad',
'e': 'Exact',
'p': 'Phrase',
}
DEVICE_TYPES = {
'c': 'Desktop',
'm': 'Mobile',
't': 'Tablet',
}
REPORT_TYPE = 'CREATIVE_CONVERSION_REPORT'
def download_report(client, client_id):
# Initialize appropriate service.
report_downloader = client.GetReportDownloader(version='v201306')
# Create report query.
report_query = ('SELECT AdGroupId', 'CampaignId', 'CreativeId FROM CREATIVE_CONVERSION_REPORT DURING LAST_7_DAYS')
path = '/tmp/report_%d.csv' % client_id
file_path = report_downloader.DownloadReportWithAwql(report_query, 'CSV', file_path=path)
print 'Report was downloaded to \'%s\'.' % file_path
if __name__ == '__main__':
client = AdWordsClient()
conn = mdb.connect('xxx.us-east-1.rds.amazonaws.com', 'xxx', 'xxx', 'xxx');
with conn:
cur = conn.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT * FROM xxx.adwords_accounts")
rows = cur.fetchall()
for row in rows:
client_id = row['id']
client.SetClientCustomerId(client_id)
download_report(client, client_id)
Something's wrong with your authentication as indicated by the OAuth2Credentials object's attribute access_token being None.
If you didn't already, take a look at the use_oath2.py example to see how authentication via OAuth2 is handled. You will also need to create a Google API Console application to obtain a client ID and secret.
It's a known bug. Fixed in v15.9.1