Set multi endpoints in S3 fine uploader for AWS - amazon-web-services

The below code works fine for the single endpoint, how to set it for multi endpoints. Please help me.
My requirement is to upload the same file into multiple AWS Buckets.
var uploader = new qq.s3.FineUploader({
//debug: true,
element: document.getElementById('fine-uploader-s3'),
template: 'qq-template-s3',
request: {
endpoint: 'https://s3.amazonaws.com/amazon-bucket',
accessKey: '123456789'
},
signature: {
endpoint: 's3Upload.php'
},
uploadSuccess: {
endpoint: 's3Upload.php?success'
},
iframeSupport: {
localBlankPagePath: '/success.html'
},
retry: {
enableAuto: false // defaults to false
},
cors: {
//all requests are expected to be cross-domain requests
expected: true,
//if you want cookies to be sent along with the request
sendCredentials: true
}
});

Related

Add role based authentication using next-auth in NextJS

I was implementing a role based authentication using next-auth v4 using CognitoProvider which I modified to add a role but the role attribute is not passed in the final session json
import NextAuth from "next-auth/next";
function CognitoProvider(options) {
return {
id: "cognito",
name: "Cognito",
type: "oauth",
wellKnown: `${options.issuer}/.well-known/openid-configuration`,
idToken: true,
profile(profile) {
console.log(profile);
return {
id: profile.sub,
name: profile.name,
email: profile.email,
image: profile.picture,
role: profile["cognito:groups"],
};
},
options,
};
}
export default NextAuth({
providers: [
CognitoProvider({
clientId: process.env.COGNITO_CLIENT_ID,
clientSecret: process.env.COGNITO_CLIENT_SECRET,
issuer: process.env.COGNITO_DOAMIN,
}),
],
callbacks: {
session: (props) => {
console.log(props);
return props.session;
},
},
});
Below is the console log of profile object
role: profile["cognito:groups"]
Actual Object
I have added a user to admin group and wanted him to access a specific route in my NextJS app.
Any help would be appreciated.
You need to configure the jwt and session callbacks to include more data in the session.
From Next-Auth docs:
If you want to make something available you added to the token [...] via the jwt() callback, you have to explicitly forward it here [the session() callback] to make it available to the client.
To add the user's role:
export default NextAuth({
// ...
callbacks: {
jwt({ token, account, profile }) {
if (account) {
// modify token
token.role = profile.role;
}
return token;
},
session({ session, token }) {
// Send properties to the client
if (session.user) {
// modify session
session.user.roles = token.role;
}
return session;
},
},
});
Then in your route, you would get the user's role from the session session.user.role

AWS api gateway working in browser but returning 502 in fiddler

I have a lambda function which would basically authenticate against the password stored in aws secret manager. The secret manager path would be the username and it will have the value for password. password will need to be passed in the header and username in the query. When I access the url https://{myawsurl}.execute-api.{region}.amazonaws.com/demo/{username} in a browser, I get the error password is missing in the header(which is expected). When I hit the url using fiddler I get 502 all the time.
My api gateway is simply a GET to the lambda function below:
const aws = require("aws-sdk");
const sm = new aws.SecretsManager({ region: 'us-east-1' })
const getSecrets = async (SecretId) => {
return await new Promise((resolve, reject) => {
sm.getSecretValue({ SecretId }, (err, result) => {
if (err) {
reject(err);
}
else {
resolve(JSON.parse(result.SecretString));
}
});
});
}
const main = async (event) => {
console.log("Event: ", event);
try {
const username = event.queryStringParameters ? event.queryStringParameters.username : (event.pathParameters ? event.pathParameters.username : null);
if (username === null || username === undefined || username.trim().length === 0) {
if (username === null || username === undefined || username.trim().length === 0) {
return {
statusCode: 400,
headers: {
"Content-Type": "application/json"
},
body: "username is missing in the url. Please add `/?username={username}` or `/{username}` in the url"
};
}
}
const password = event.headers ? event.headers.password : null;
if (password === null || password === undefined || password.trim().length === 0) {
return {
statusCode: 400,
headers: {
"Content-Type": "application/json"
},
body: "password is missing in the header"
};
}
const secrets = await getSecrets(username);
if (password !== secrets.password) {
return {
statusCode: 403,
headers: {
"Content-Type": "application/json"
},
body: "Incorrect username/password"
};
}
return {
statusCode: 200,
headers: {
"Content-Type": "application/json"
},
body: "User is Authenticated"
};
} catch (e) {
return {
statusCode: 404,
headers: {
"Content-Type": "application/json"
},
body: e.message
};
}
}
exports.handler = main;
My fiddler request is below:
GET https://{myawsurl}.execute-api.{region}.amazonaws.com/demo/{username} HTTP/1.1
password: MyTestPassword
I saw other posts where they mentioned about having a statusCode and body being a string. I have those but still getting error...
I added/removed the headers: { "Content-Type": "application/json"}, from the response and it made no difference..
EDIT: One another thing noticed is whenever I access the api gateway url via browser, it gets logged in my api's log group. But when it is accessed using fiddler it doesn't log. Not sure why...
EDIT: After the suggestion from #ArunK, I used Postman and I found it returns the expected response from the api gateway. I assume some settings in Fiddler may be causing this to happen..
Looks like the issue related to the TLS version supported by Fiddler. You need to include tls 1.0 and 1.2 since AWS API Gateway support these TLS Versions.
From the docs:
A security policy is a predefined combination of minimum TLS version
and cipher suite offered by Amazon API Gateway. You can choose either
a TLS version 1.2 or TLS version 1.0 security policy.
Go to Tools -> Options -> Https and verify the following exists under Protocols - <client>;ssl3;tls1.0;tls1.1;tls1.2
More about Fiddler and Modern TLS Versions.

Sending http request from aws lambda to google firebse funcitons

I have set up firebase functions to receive http requests and have verified that the same is working. Now im trying to send http request to firebase from aws lambda function. But there is no response either in aws lambda or in the firebase functions log. This is my aws lambda code:
const postData = JSON.stringify({
"queryresult" : {
"parameters": {
"on": "1",
"device": "1",
"off": ""
}
}
});
const options = {
hostname: 'https://<the firebase function endpoint>',
port: 443,
path: '',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = https.request(options, postData)
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
// Write data to request body
req.write(postData);
req.end();
}
The promise part here is suppose to execute the console logs but it is not getting executed. Is there something that i'm missing here. The host is the URL that we obtain when we deploy a function. Or is there some firebase or aws related plan problem. I'am using the spark plan in firebase. Thankyou.

File Upload in React native using ImagePicker and s3

I am trying to upload the image from the device to s3 directly. I am able to read the image metadata and sending it to the server to generate the pre-signed url for the aws s3. I also have the pre-signed url to with I want to upload the file/image using axios but somehow the image/file is not getting uploaded. Here is my code.
Image data (read by the ImagePicker)
data: "" // image raw data
fileName: "acx.jpg"
fileSize: ""
uri: ""
path: ""
Code for sending the selected image to aws s3.
const options = { headers: { 'Content-Type': fileType}};
axios.put(res.data.signedRequest, data , options);
I'm getting the following respose.
res = {
config:
data: ""
status: 200
StatusText: undefined
...
}
So what should I pass as data in the axios request?
Have you explored this plugin ? It would make the process a lot easier. You could then try
upload = () => {
const file = {
uri: this.state.imageuri,
name: acx.jpg,
type: "image/jpeg"
};
const options = {
keyPrefix: "ts/",
bucket: "celeb-c4u",
region: "eu-west-1",
accessKey: "AKIAI2NHLR7A5W2R3OLA",
secretKey: "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",
successActionStatus: 201
};
return RNS3.put(file, options)
.then(response => {
if (response.status !== 201)
throw new Error("Failed to upload image to S3");
else {
console.log(
"Successfully uploaded image to s3. s3 bucket url: ",
response.body.postResponse.location
);
this.setState({
url: response.body.postResponse.location
});
}
})
.catch(error => {
console.log(error);
});
};

AWS CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. The headers are present

I have been battling with these dreaded CORS issues with AWS for a while now. I thought I had it sorted out and then it turned up again... I have done exactly want I have in the other Lambda functions that work fine.
Why won't it work now?
I have added in the headers in the response to all of the Lambda functions in my handler.js file (I am using serverless to deploy to AWS)
docClient.get(params, function (err, data) {
if (err) {
const response = {
statusCode: 500,
headers: {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": true
},
body: JSON.stringify({
message: 'Failed to fetch service request from the database.',
error: err
}),
};
callback(null, response);
}
else {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": true
}
};
callback(null, response);
}
});
And in the .yml file:
myLambdaFunc:
handler: handler.myLambdaFunc
events:
- http:
path: myLambdaFunc
method: POST
cors: true
I figured out that the problem lies with the docClient.get. I was testing with data where the primary key item being searched for was not in the table.
I wish it didn't tell me that it was a CORS issue because it really wasn't..