http error 400 with "meetup" API - django

I'm trying to hook my website to Meetup.com.
Instructions
Everything works when I request authorization. However when I try to get the access token, I keep getting:
http error 400: bad request.
Here is my code:
def meetupauth(request):
r =request.REQUEST
code = r['code']
state = r['state']
consumer = OAuthConsumer.objects.filter(apiservice_id=LINKEDINAPI)[0]
url_str = {'client_id' : consumer.token, 'client_secret' : consumer.tokensecret, 'grant_type' : 'authorization_code', 'redirect_uri' : 'http://127.0.0.1:8000/apiservice/meetupauth', 'code' : code}
#url_str = (('client_id' , consumer.token), ('client_secret' , consumer.tokensecret), ('grant_type' , 'authorization_code'), ('redirect_uri' , 'http://127.0.0.1:8000/apiservice/meetupauth'), ('code' , code))
url_string = urllib.urlencode(url_str)
req = urllib2.Request(meetup_access_token_url, url_string)
resp = urllib2.urlopen(req)
return redirect("/dashboard/")
This is the error:
HTTPError at /apiservice/meetupauth
HTTP Error 400: Bad Request
Request Method: GET
Request URL: http://127.0.0.1:8000/apiservice/meetupauth?code=acd62b4e1f28e3454c322d6b00136443&state=
Django Version: 1.4
Exception Type: HTTPError
Exception Value: HTTP Error 400: Bad Request

Dumb mistake.
the code is:
consumer = OAuthConsumer.objects.filter(apiservice_id=LINKEDINAPI)[0]
it should have been
consumer = OAuthConsumer.objects.filter(apiservice_id=MEETUPAPI)[0]

Related

AWS Lambda function url call gives 502 Bad gateway

I'm getting started with AWS lambda and created a basic java handler like below.
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Map;
// Handler value: example.Handler
public class Handler implements RequestHandler<Map<String,String>, String>{
Gson gson = new GsonBuilder().setPrettyPrinting().create();
#Override
public String handleRequest(Map<String,String> event, Context context)
{
LambdaLogger logger = context.getLogger();
String response = "200 OK";
// log execution details
logger.log("ENVIRONMENT VARIABLES: " + gson.toJson(System.getenv()));
logger.log("CONTEXT: " + gson.toJson(context));
// process event
logger.log("EVENT: " + gson.toJson(event));
logger.log("EVENT TYPE: " + event.getClass());
return response;
}
}
When I'm testing the lambda function via AWS portal, it is working fine. But when I'm triggering the same using function URL like below, I'm getting a 502: Bad Gateway error.
curl --location --request POST 'https://xyz.lambda-url.region.on.aws?message=HelloWorld' \
--header 'Content-Type: application/json' \
--data-raw '{
"some-key": "some-value"
}'
An error occurred during JSON parsing: java.lang.RuntimeException
java.lang.RuntimeException: An error occurred during JSON parsing
Caused by: java.io.UncheckedIOException: com.amazonaws.lambda.thirdparty.com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.String out of START_OBJECT token
at [Source: (ByteArrayInputStream); line: 1, column: 84] (through reference chain: java.util.LinkedHashMap["headers"])
at com.amazonaws.services.lambda.runtime.serialization.factories.JacksonFactory$InternalSerializer.fromJson(JacksonFactory.java:184)
Caused by: com.amazonaws.lambda.thirdparty.com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.String out of START_OBJECT token
at [Source: (ByteArrayInputStream); line: 1, column: 84] (through reference chain: java.util.LinkedHashMap["headers"])
I've mentioned the Auth type of Function URL to NONE as well. Is there anything I'm missing here? Thanks in advance.
According to aws docs, even though you specify AuthType as NONE, your function's resource-based policy is always in effect and must grant public access before your function URL can receive requests.
You can re-verify your lambda role policy if it has public access and also with AuthType set to NONE.

AWS API Gateway Invoke URL link works in browser but not with XMLHttpRequest

Whenever I use the following to try and load the json:
'''
<script>
function shutDown() {
let request = new XMLHttpRequest();
request.open("GET", "https://er2uqo9cyc.execute-api.us-east-1.amazonaws.com/testing/ec2");
request.send();
request.onload = () => {
console.log(request);
if (request.status == 200) {
console.log(JSON.parse(request.response));
} else {
console.log('error ${request.status} ${request.statusText}');
}
}
}
</script>
'''
I get the following error in the console of my browser, and no JSON:
'''
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (styles.css, line 0)
[Error] Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin. Status code: 200
[Error] XMLHttpRequest cannot load https://er2uqo9cyc.execute-api.us-east-1.amazonaws.com/testing/ec2 due to access control checks.
[Error] Failed to load resource: Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin. Status code: 200 (ec2, line 0)
'''
Why isn't it working with XMLHttpRequest?

S3 : Java SDK : Delete Object tags throws "You must provide the Content-Length HTTP header" error

I am having trouble deleting tags on existing key.
SDK Version : compile('software.amazon.awssdk:s3:2.17.2')
Java version : 1.8
Error : software.amazon.awssdk.services.s3.model.S3Exception: You must provide the Content-Length HTTP header.
Code snippet:
DeleteObjectTaggingRequest deleteObjectTaggingRequest = DeleteObjectTaggingRequest.builder()
.bucket(bucketName)
.key(key)
.build();
s3Client.deleteObjectTagging(deleteObjectTaggingRequest);
Stack trace:
2021-07-22 17:12:46.365 ERROR 13564 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is software.amazon.awssdk.services.s3.model.S3Exception: You must provide the Content-Length HTTP header. (Service: S3, Status Code: 411, Request ID: 1626991966461970, Extended Request ID: 12789133)] with root cause
software.amazon.awssdk.services.s3.model.S3Exception: You must provide the Content-Length HTTP header. (Service: S3, Status Code: 411, Request ID: , Extended Request ID: )
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handleErrorResponse(AwsXmlPredicatedResponseHandler.java:156) ~[aws-xml-protocol-2.17.2.jar:na]
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handleResponse(AwsXmlPredicatedResponseHandler.java:106) ~[aws-xml-protocol-2.17.2.jar:na]
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handle(AwsXmlPredicatedResponseHandler.java:84) ~[aws-xml-protocol-2.17.2.jar:na]
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handle(AwsXmlPredicatedResponseHandler.java:42) ~[aws-xml-protocol-2.17.2.jar:na]
Any help on this would be greatly appreciated. Thank you

django channel set up routing

I'm learning how to setup a websocket connection with django-channel, i've got this setup in routing.py
from channels import route
from gallery import socket as sock
channel_routing = [
# Wire up websocket channels to our consumers:
route("websocket.connect", sock.ws_connect, path=r"^/render-status/$"),
route("websocket.receive", sock.ws_receive, , path=r"^/render-status/$"),
]
and the following javascript
// When we're using HTTPS, use WSS too.
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
var ws_path = ws_scheme + '://' + window.location.host + '/render-status/';
console.log("Connecting to " + ws_path)
var socket = new ReconnectingWebSocket(ws_path);
socket.onmessage = function(message) {
console.log("Got message: " + message.data);
var data = JSON.parse(message.data);
// if action is started, add new item to table
if (data.action == "started") {
}
// if action is completed, just update the status
else if (data.action == "completed"){
}
};
var message = {
action: "incomplete",
job_name: "10",
};
socket.send(JSON.stringify(message));
tried it out and there's a failure in connecting (from the console)
colorpicker2.js:565 Connecting to ws://127.0.0.1:8000/render-status/
reconnecting-websocket.min.js:1 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
at a.send (http://127.0.0.1:8000/static/js/reconnecting-websocket.min.js:1:2611)
at HTMLDocument.<anonymous> (http://127.0.0.1:8000/static/js/colorpicker2.js:584:11)
at k (http://127.0.0.1:8000/static/js/jquery.js:15:16962)
at Object.fireWith [as resolveWith] (http://127.0.0.1:8000/static/js/jquery.js:15:17720)
at Function.ready (http://127.0.0.1:8000/static/js/jquery.js:15:12435)
at HTMLDocument.D (http://127.0.0.1:8000/static/js/jquery.js:15:9840)
send # reconnecting-websocket.min.js:1
(anonymous) # colorpicker2.js:584
k # jquery.js:15
fireWith # jquery.js:15
ready # jquery.js:15
D # jquery.js:15
reconnecting-websocket.min.js:1 WebSocket connection to 'ws://127.0.0.1:8000/render-status/' failed: Error during WebSocket handshake: Unexpected response code: 404
open # reconnecting-websocket.min.js:1
a # reconnecting-websocket.min.js:1
(anonymous) # colorpicker2.js:566
k # jquery.js:15
fireWith # jquery.js:15
ready # jquery.js:15
D # jquery.js:15
22reconnecting-websocket.min.js:1 WebSocket connection to 'ws://127.0.0.1:8000/render-status/' failed: Error during WebSocket handshake: Unexpected response code: 404
open # reconnecting-websocket.min.js:1
(anonymous) # reconnecting-websocket.min.js:1
I've also checked the documentation https://channels.readthedocs.io/en/stable/routing.html just to be sure this is how you set a path.
Your routing is correct, but you are sending the message too soon, while the socket is still trying to connect. Use the onopen callback to ensure the message is sent only after the connection was established:
socket.onopen = function() {
var message = {
action: "incomplete",
job_name: "10",
};
socket.send(JSON.stringify(message));
}

AMAZON SNS import Parse Server Data as JSON

I am shifting my self-hosted parse to Amazon SNS and have followed all instructions on this link properly:
https://aws.amazon.com/blogs/mobile/migrating-from-parse-push-to-amazon-sns/
Now on step 4: Import Parse Push data when i run the java code
java -jar SNSImportTool.jar -s -f <PATH_TO_EXPORTED_PARSE_INSTALLATION_.JSON_FILE>
--apnsName <APNS_PLATFORM_APP_NAME_STEP_3.2.9>
--gcmName <GCM_PLATFORM_APP_NAME_STEP_3.2.9>
--topicName <SNS_TOPIC_NAME_STEP_3.2.10>
--awsaccess <AWS_KEY_ID_STEP_3.3>
--awssecret <SECRET_ACCESS_KEY_STEP_3.3>
i get the following output:
===========================================
Import from Parse to Amazon SNS
===========================================
Verify platform application: app/GCM/appname_MOBILEHUB_111111
Verify platform application: app/APNS/appname_MOBILEHUB_111111
Created 1 channel topics:SNS
Processing token APA91bEApdQ5PFqX77X53LZZevzw9ghwxuhvBwPu5E4Z1og1TTYTLFHv3oF5-AMszqZDfSBWCH4dn_zYK4Emx21j-30k6u0SGQ4KHbAWuuYbPCzSRm-9hvU
Could not create endpoint: Invalid parameter: PlatformApplicationArn Reason: Wrong number of slashes in relative portion of the ARN. (Service: AmazonSNS; Status Code: 400; Error Code: InvalidParameter; Request ID: 12b597de-1a46-5168-b1af-c661430db91f)
Processing token d806a7e6701df9250d8162e47b15ff78b857b285de38113d1b7f504ea92d46b5
Could not create endpoint: PlatformApplication does not exist (Service: AmazonSNS; Status Code: 404; Error Code: NotFound; Request ID: 419d4827-9238-5d46-a584-1998cb74e16e)
to clarify, for items in json that have deviceType as android i get the following error:
Invalid parameter: PlatformApplicationArn Reason: Wrong number of slashes in relative portion of the ARN
and deviceType as ios i get the following error:
Could not create endpoint: PlatformApplication does not exist
my json file looks like this:
{"results":[{ "channels" : ["SNS"], "_id" : "000f0KsszOH1", "_updated_at" : "2017-06-11T00:03:10.712+0000" , "UniqueId" : "79bb118ec2b71c3f", "appIdentifier" : "com.leApp", "parseVersion" : "1.8.0", "timeZone" : "Asia/Riyadh", "installationId" : "f05f3d8a-f045-35fe-a268-855eda3b2c78", "appVersion" : "2.2.8", "deviceType" : "ios", "_created_at" : "2015-12-15T12:49:23.954+0000", "pushType" : "gcm","deviceToken" : "APA99bEApdQ5PFqX77X53LYYevzw4ghwxuhvBwPu4C3Z1og1TTYTLFHv3oF5-AMszqZDfSBWCH4dn_zYK4Emx21j-30k6u0SGQ4KHbAWuuYbPCzSRm-9hvU", "localeIdentifier" : "en-GB" }]}
please advise how to fix these errors.