Lambda#edge redirect gets in a redirect loop - amazon-s3

I have a static website on aws s3. Have setup route 53 and cloud front and everything works smoothly. s3 Bucket is setup to serve index.html as index document.
Now I have added another file called index-en.html that should be served when the request country is any other country and not my home country.
For this I have added a lambda#edge function with the following code:
'use strict';
/* This is an origin request function */
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const headers = request.headers;
/*
* Based on the value of the CloudFront-Viewer-Country header, generate an
* HTTP status code 302 (Redirect) response, and return a country-specific
* URL in the Location header.
* NOTE: 1. You must configure your distribution to cache based on the
* CloudFront-Viewer-Country header. For more information, see
* http://docs.aws.amazon.com/console/cloudfront/cache-on-selected-headers
* 2. CloudFront adds the CloudFront-Viewer-Country header after the viewer
* request event. To use this example, you must create a trigger for the
* origin request event.
*/
let url = 'prochoice.com.tr';
if (headers['cloudfront-viewer-country']) {
const countryCode = headers['cloudfront-viewer-country'][0].value;
if (countryCode === 'TR') {
url = 'prochoice.com.tr';
} else {
url = 'prochoice.com.tr/index-en.html';
}
}
const response = {
status: '302',
statusDescription: 'Found',
headers: {
location: [{
key: 'Location',
value: url,
}],
},
};
callback(null, response);
};
I have also edited cloud front behavior to whitelist Origin and Viewer-country headers and setup the cloudfront Viewer-Request event and lambda Function ARN relation.
However I get a "too many redirect error".
I have 2 questions:
How to correct the "too many redirects error"?
For viewers outside "TR" the default landing page should be index-en.html, from which 2 more pages in english are accessible via navigation menu. So when users request a specific page from page navigation they should be able to access those pages, when no page is requested the default landing page should be served.
Appreciate help.
Thanks.

You are creating a redirect loop because you are sending the viewer back to the same site, same page, no matter what the results of your test.
if (countryCode === 'TR') {
return callback(null, request);
} else {
...
callback(null,request) tells CloudFront to continue processing the request -- not generate a response. Using return before the callback causes the rest of the trigger code not to run.

Related

How to get API call origin in NextJS API endpoint

I have an API set up that receives a token, and I want to store that token in a database. But I also want to store the origin URL.
Let's say my API endpoint is located at https://myapp.com/api/connect
Now, I want to send a token from my website https://mywebsite.net
After I send a token, I want to be able to store the token and the website URL to the database in NextJS code.
My endpoint would store this info to the database:
{
token: someRandomToken
origin: https://mywebsite.net
}
I tried logging the whole req object from the handler to see if that info exist but the console log fills my terminal fast.
Inside Next's Server-Side environment you have access to req.headers.host as well as other headers set by Vercel's or other platforms' Reverse Proxies to tell the actual origin of the request, like this:
/pages/api/some-api-route.ts:
import { NextApiRequest } from "next";
const LOCAL_HOST_ADDRESS = "localhost:3000";
export default async function handler(req: NextApiRequest) {
let host = req.headers?.host || LOCAL_HOST_ADDRESS;
let protocol = /^localhost(:\d+)?$/.test(host) ? "http:" : "https:";
// If server sits behind reverse proxy/load balancer, get the "actual" host ...
if (
req.headers["x-forwarded-host"] &&
typeof req.headers["x-forwarded-host"] === "string"
) {
host = req.headers["x-forwarded-host"];
}
// ... and protocol:
if (
req.headers["x-forwarded-proto"] &&
typeof req.headers["x-forwarded-proto"] === "string"
) {
protocol = `${req.headers["x-forwarded-proto"]}:`;
}
let someRandomToken;
const yourTokenPayload = {
token: someRandomToken,
origin: protocol + "//" + host, // e.g. http://localhost:3000 or https://mywebsite.net
};
// [...]
}
Using Typescript is really helpful when digging for properties as in this case. I couldn't tell if you are using Typescript, but in case you don't, you'll have to remove NextApiRequest.

AWS static website - how to connect subdomains with subfolders

I want to setup S3 static website and connect with my domain (for example domain: example.com).
In this S3 bucket I want to create one particular folder (name content) and many different subfolders with in, then I want to connect these subfolders with appropriate subdomains, so for example
folder content/foo should be available from subdomain foo.example.com,
fodler content/bar should be available from subdomain bar.example.com.
Any content subfolder should be automatically available from subdomain with that same prefix name like folder name.
I will be grateful for any possible solutions for this problem. Should I use redirection option or there is any better solution? Thanks in advance for help.
My solution base on this video:
https://www.youtube.com/watch?v=mls8tiiI3uc
Because above video don’t explain subdomain problem, here is few additional things to do:
to AWS Route53 hostage zone we should add records A with “*.domainname” as record name and edge address as Value
to certificate domains we should add also “*.domainname”- to have certificate for wildcard domain
when setting up Cloudfront distribution we should add to “Alternate domain name (CNAME)“ section “www.domainname” and also “*.domainname”
redirection/forwarding from subdomain to subfolder is realizing via Lambda#Edge function (function should be improve a bit):
'use strict';
exports.handler = (event, context, callback) => {
const path = require("path");
const remove_suffix = ".domain.com";
const host_with_www = "www.domain.com"
const origin_hostname = "www.domain.com.s3-website.eu-west-1.amazonaws.com";
const request = event.Records[0].cf.request;
const headers = request.headers;
const host_header = headers.host[0].value;
if (host_header == host_with_www) {
return callback(null, request);
}
if (host_header.startsWith('www')) {
var new_host_header = host_header.substring(3,host_header.length)
}
if (typeof new_host_header === 'undefined') {
var new_host_header = host_header
}
if (new_host_header.endsWith(remove_suffix)) {
// to support SPA | redirect all(non-file) requests to index.html
const parsedPath = path.parse(request.uri);
if (parsedPath.ext === "") {
request.uri = "/index.html";
}
request.uri =
"/" +
new_host_header.substring(0, new_host_header.length - remove_suffix.length) +
request.uri;
}
headers.host[0].value = origin_hostname;
return callback(null, request);
};
Lambda#Edge is just Lambda function connected with particular Cloudfront distribution
need to add to Cloudfront distribution additional setting for Lambda execution (this setting is needed if we want to have different redirection for different subdomian, instead all redirection will point to main directory or probably to first directory which will be cached - first request to our Cloudfront domain):

HTTP request handler that sends an audio file from another URL as a response

I want to allow users request audio files. The files are hosted on a separate file server. I don't want users to get these files unless they've gone through my server first.
How do I make a function that basically acts as a middle man between the user and the file server. I currently have something like this:
async (req, res) => {
const mediaLink = `https://www.example.com/audio.mp3`;
const mediaResponse = await fetch(mediaLink, {
headers: {
Range: req.headers.range,
}
});
const blob = await mediaResponse.blob(); // I'm guessing here. Idk.
res.send(blob);
}
I tested this in an <audio> tag but the audio never loaded:
<audio controls src="http://localhost:5001/file-server-middleware" />
The correct way to handle such a request would be to pipe the response body back to the client making sure to copy across any relevant headers that may be in the response from the file server. Read up on the HTTP Functions documentation to see what use cases you should be looking out for (e.g. CORS).
async (req, res) => {
const mediaLink = `https://www.example.com/audio.mp3`;
// You may wish to pass through Cache-related headers, such as
// If-None-Match, If-Match, If-Modified-Since, If-Range, If-Unmodified-Since
const mediaResponse = await fetch(mediaLink, {
headers: {
Range: req.headers.range,
}
});
// note: this currently passes the body & status from the file server
// as-is, you may want to send your own body on failed status codes to
// hide the existence of the external server (i.e. custom 404 pages, no
// Nginx error pages, etc)
// mediaResponse.status may be:
// - 200 (sending full file)
// - 206 (sending portion of file)
// - 304 (not modified, if using cache headers)
// - 404 (file not found)
// - 412 (precondition failed, if using cache headers)
// - 416 (range not satisfiable)
// - 5xx (internal server errors from the file server)
res
.status(mediaResponse.status)
.set({
/* ... other headers (e.g. CORS, Cache-Control) ... */
'Content-Type': mediaResponse.headers.get('content-type'),
'Content-Length': mediaResponse.headers.get('content-length'),
'Content-Encoding': mediaResponse.headers.get('content-encoding'),
'Etag': mediaResponse.headers.get('Etag'), // for caching
'Last-Modified': mediaResponse.headers.get('last-modified') // for caching
});
mediaResponse.body.pipe(res);
}
You may also want to look into the various express-compatible proxy modules that can handle the bodies and headers for you. Note that some of these may not function properly if used in a Firebase Cloud Function as the request bodies are automatically consumed for you.

Express js Redirect not rendering page

I am trying to redirect the user that uses my website after he has logged into his account, he will be redirected to a dashboard.
The problem is that I can see a request for the /dashboard route in the Network tab of the browser Inspection Tools, but the page never loads.
This is my code so far.
router.post('/login', function(request, response){
// verify against database and send back response
var userData = {};
userData.email = request.body.email;
userData.password = request.body.password;
userData.rememberPassword = request.body.rememberPassword;
// check if in the database and re-route
var query = database.query('SELECT * FROM users WHERE email = ?', [userData.email], function(error, result){
if(error){
console.log('Error ', error);
}
if(result.length){
// check if the password is correct
if(userData.password === result[0].password){
// redirect to the dashboard
// TODO this piece of code does not redirect correctly
response.redirect('/dashboard'); // < HERE
console.log('Haha');
}
}
else{
// do something when there is are no results
// invalid email status code
response.statusCode = 405;
response.send('');
}
});
});
And this is the route towards the dashboard, and it is being rendered properly when accessed in the browser.
router.get('/dashboard', function(request, response){
response.render(path.resolve(__dirname, 'views', 'dashboard.pug'));
});
Why can't it redirect when the user completes the login process?
Thanks.
The issue can be in the frontend and not in the backend. If you are using AJAX to send the POST request, it is specifically designed to not change your url.
Use window.location.href after AJAX's request has completed to update the URL with the desired path.But the easiest way would be to create a form with action as /login and use the submission to trigger the url change.
To make sure that the problem does not lie with the backend,
Add a logging statement to router.get('/dashboard' to verify if
the control was passed.
Check that the HTTP status code of the /login route is 302 indicating a redirect and location header has the route /dashboard.
Content type of response /dashboard is text/html.If not please set it using res.setHeader("Content-Type", "text/html").

Not able to redirect to client side with token from server(express) side route

I am using 'googleapis' npm package to do token based google authentication.
I am redirected to '/api/auth/success/google' route inside express after google provided authentication and redirects us to the uri stated in google app credentials.
The problem I am facing is that ,I have retrieved the tokens on server side,but I am unable to send those tokens to client side for them to be saved in cookies.
The problem I am facing is because,'/api/auth/success/google' is redirected from google side and not an ajax call from client side.So if I send the tokens back in res,where will it redirect.Also please suggest a way to redirect from server side to client side,along with access_token.
server side code.
//Route reached after google successful login/authentication
app.get('/api/auth/success/google',function(req,res){
console.log("inside redirect");
var code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
if(!err) {
oauth2Client.setCredentials(tokens);
}
res.sendFile('./index.html');
});
})
Client side call
//Google login requested from this function
googleLogin(){
event.preventDefault();
$.ajax({
type : 'POST',
url : baseURL + 'api/authenticate/google',
success: (function(data) {
if (data.redirect) {
document.location.href = data.redirect;
}
}).bind(this)
});
}
//Route handling request of google access
app.post('/api/authenticate/google',function(req,res){
// generate a url that asks permissions for Google+ and Google Calendar scopes
var scopes = [
googlecredentials.SCOPE[0],
googlecredentials.SCOPE[1]
];
var url = oauth2Client.generateAuthUrl({
access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
scope: scopes // If you only need one scope you can pass it as string
});
res.send({ redirect: url });
})
//Google App Credentials
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(googlecredentials.CLIENT_ID, googlecredentials.CLIENT_SECRET, googlecredentials.REDIRECT_URL);
googlecredentials.CLIENT_ID - 858093863410-j9ma1i7lgapupip1ckegc61plrlledtq.apps.googleusercontent.com
REDIRECT_URL - http://localhost:3000/api/auth/success/google where localhost:3000 runs server side
If you send the redirect URL back in the res, the client-side should be able to check for the presence of the redirect URL in the response, and if it exists, push your user to that URL.