Google cloud reCAPTCHA Enterprise showing invalid argument error - google-cloud-platform

devs.
I am migrating my Recaptcha V2 to the Recaptcha enterprise using the below link.
https://cloud.google.com/recaptcha-enterprise/docs/using-features
the frontend integration part work and the Recaptcha checkbox part are showing.
On the backend side after the user submit the form passing the Recaptcha test. to verify the Recaptcha test, I call google REST API to create an assessment.
I am using this link.
https://cloud.google.com/recaptcha-enterprise/docs/create-assessment#rest-api
code of the function to verify user response.
def verify_captcha_response(self, recaptcha_response):
"""
Verify the Google Recaptcha V2 response of the request
- if recatacha response value is more than the value set
on google recaptcha admin.
- if request fail error will be raise and no response will be accept
"""
if not recaptcha_response:
return False
if isinstance(recaptcha_response, list):
recaptcha_response = recaptcha_response[0]
url = "https://recaptchaenterprise.googleapis.com/v1/projects/%s/assessments?key=%s" % ("Project id", settings.RECAPTCHA_SITE_KEY)
recaptcha_secret_key = settings.RECAPTCHA_SECRET_KEY,
headers={'Content-Type': 'application/json'}
data = {
"event":{
"token": recaptcha_response,
"siteKey": recaptcha_secret_key,
"expectedAction": "login"
}
}
response = requests.post(url, headers=headers,
data=data)
result = response.json()
if not result['success']:
if 'timeout-or-duplicate' in result['error-codes']:
raise forms.ValidationError(msg.RECAPTCHA_FAILED)
return False
return True
The response I am getting.
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT"
}
}
but as per the documentation, I am passing all the arguments.
Thank you.

Related

AWS API Gateway Post Requests

I created an api with AWS Api Gateway and when I try to execute a POST request I get a 403 vs when I do GET request it returns 200 and returns the data I expect.
data = json.dumps({'to': 'USD', 'from': 'CNY', 'start': '2022-03-01', 'end': '2022-12-01'})
requests.get(url,headers = headers,data=data).json()
headers = {'Content-type': 'application/json'}
data = json.dumps({'to': 'USD', 'from': 'CNY', 'start': '2022-03-01', 'end': '2022-12-01'})
requests.post(url,headers = headers,data=data).json()
>>> {'message': 'Missing Authentication Token'}
How do I authenticate to get a 200 for a post requests ?

How to create an account/login using google api client in django for android

I want to implement the same scenario for use in Android Kotlin which is given in this url.
For Web Application
I have created login with google for web application by follow this link. Here is my Google Login View in views.py for access token (as one user have explained here )
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
And It's working for me as I expected.
For Android Application
Now, Somehow I have managed a code for this google scenario.
Here is my Google Client login View.view.py code
class GoogleClientView(APIView):
def post(self, request):
token = {'id_token': request.data.get('id_token')}
print(token)
try:
# Specify the CLIENT_ID of the app that accesses the backend:
idinfo = id_token.verify_oauth2_token(token['id_token'], requests.Request(), CLIENT_ID)
print(idinfo)
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
raise ValueError('Wrong issuer.')
return Response(idinfo)
except ValueError as err:
# Invalid token
print(err)
content = {'message': 'Invalid token'}
return Response(content)
When I am requesting POST method with IdToken then this is providing below information and ofcourse we need this.
{
// These six fields are included in all Google ID Tokens.
"iss": "https://accounts.google.com",
"sub": "110169484474386276334",
"azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"iat": "1433978353",
"exp": "1433981953",
// These seven fields are only included when the user has granted the "profile" and
// "email" OAuth scopes to the application.
"email": "testuser#gmail.com",
"email_verified": "true",
"name" : "Test User",
"picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
"given_name": "Test",
"family_name": "User",
"locale": "en"
}
Till here, everything is working good for me.But here I want to create account/login for a the user using above info and when account/login is created then need a key in return response.
below What I had tried
class GoogleClientView(APIView):
permission_classes = [AllowAny]
adapter_class = GoogleOAuth2Adapter
callback_url = 'https://example.com/user/accounts/google/login/callback/'
client_class = OAuth2Client
def post(self, request):
token = {'id_token': request.data.get('id_token')}
print(token)
try:
# Specify the CLIENT_ID of the app that accesses the backend:
idinfo = id_token.verify_oauth2_token(token['id_token'], requests.Request(), CLIENT_ID)
print(idinfo)
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
raise ValueError('Wrong issuer.')
return Response(idinfo)
except ValueError as err:
# Invalid token
print(err)
content = {'message': 'Invalid token'}
return Response(content)
Again It seems it's not creating any account/login for user and no key is getting in response.
So, for creating account/login, How can I implement the code?
Please ask for more information If I forgot to put any.

Test cases for Django Rest Framework; struggling to get a correct response

Update: Solved my own problem: I've learnt that Django creates its own test database, and as such, it needs to be populated with data. Ran my importer in my test cases and it all worked. So, if you're also wondering why you're tests don't work, check that you've got some data in the test db!
End Update
I am writing tests for my Django Rest Framework API but I am struggling to get my code to return a 200 OK. At the moment, my test case continually returns a 404 Not Found.
I'm in the early stages of writing tests, and have a lot to learn. I'm currently following https://www.django-rest-framework.org/api-guide/testing/
I'm trying to test an endpoint at the following URL
# Not shown here, is that all URLs here will be prepended with /api/v1
path('case/<int:pk>/', EntireCaseView.as_view(), name='case'),
I have an object in my database with an ID (primary key) of 1. I can successful query the API by going to http://localhost:8000/api/v1/case/1/
I receive a valid JSON response (Trampe is a rabbit)
{
"id": 1,
"total_points": 5000,
"passing_points": 3700,
"budget": 5000,
"description": "Saving Trampe from Trauma",
"name": "Trampe",
"signalment": "8yr, intact male, mixed breed.",
"problem": "Respiratory difficulty",
"image": {
"id": 1,
"file": "http://localhost:8000/media/images/trampe.jpg",
"description": "A lovely picture of Trampe"
},
My API requires authentication, and as such I am providing authentication in my test case.
class CaseTests(APITestCase):
def test_status_code(self):
"""
ensure that case/1 returns 200 OK
"""
# Create a test user
test_user = User(username='jim', password='monkey123', email='jim#jim.com')
test_user.save()
# build a factory and get our user Jim
factory = APIRequestFactory()
user = User.objects.get(username='jim')
# Get our view to test and the url, too
view = EntireCaseView.as_view()
url = reverse('case', kwargs={'pk': '1'})
print(url.__str__())
# Make an authenticated request to the view...
request = factory.get(url)
print(request.get_full_path())
force_authenticate(request, user=user)
response = view(request, "1")
print(response.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
Of interest here (at least to me) are the lines
url = reverse('case', kwargs={'pk': '1'})
and
response = view(request, "1")
If I leave out either the kwargs argument in url =r everse('case', kwargs={'pk': '1'}) or the "1" in response = view(request, "1") I will receive an error saying that the get() method requires 2 positional arguments but only given.
Here is the signature of the get() method in my view.
class EntireCaseView(APIView):
def get(self, request, pk):
If I run my test, Django reports that it fails because of a 404.
self.assertEqual(response.status_code, status.HTTP_200_OK)
AssertionError: 404 != 200
What I am trying to work out is why this is the case. Printing print(url.__str__()) outputs /api/v1/case/1/ as does print(request.get_full_path())
So in summary, I am trying to understand why I'm receiving this 404, and ultimately, how I can test this, and other endpoints.
Any and all help is appreciated.
Cheers,
C

Instagram Invalid Response Error - 400

I have the following code.
params = {'client_id':settings.SOCIAL_AUTH_INSTAGRAM_KEY,
'client_secret':settings.SOCIAL_AUTH_INSTAGRAM_SECRET,
'aspect':'media',
'object':'tag',
'object_id':instance.hashtag,
'callback_url':
'http://subdomain.domain.net:8000/campaigns/hook'}
response = requests.post('https://api.instagram.com/v1/subscriptions',
data=params)
And I get response
'{"meta":{"error_type":"APISubscriptionError","code":400,"error_message":"Invalid
response"}}'
My domain is reachable from outside. Any ideas?
This was because Instagram sends a GET request to my callback_url
and wants me to response with hub.challenge parameter like below
if self.request.GET:
response = request.GET.get('hub.challenge')
return HttpResponse(response)

KeyError: access token

I have already test this before and it's work. Now the error back again and I didn't do any changes on my social app.
Here are my codes:
def get_profile(request, token=None):
args = {
'client_id': settings.FACEBOOK_APP_ID,
'client_secret': settings.FACEBOOK_APP_SECRET,
'redirect_uri': request.build_absolute_uri(reverse('social:fb_callback')),
'code': token,
}
target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read()
response = cgi.parse_qs(target)
access_token = response['access_token'][-1]
return access_token
Obviously, your request is not successful and the response doesn't have an access token. According to facebook docs, when a request isn't good, it returns a response with an error element, something like:
{
error: {
message: "Missing redirect_uri parameter.",
type: "OAuthException",
code: 191
}
}
So, in your function, you should do something like:
class FacebookAccessException(Exception): pass
def get_profile(request, token=None):
...
response = json.loads(urllib_response)
if 'error' in response:
raise FacebookAccessException(response['error']['message'])
access_token = response['access_token'][-1]
return access_token
PS:
Try to use better urllib. You should try Requests.