-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.js
95 lines (83 loc) · 2.16 KB
/
handler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"use strict";
const util = require("util");
const Cookie = require("cookie");
const Reader = require("mmdb-reader");
const DOMAIN = "testbixtrim.tk";
// edgeRedirect solves the Cloudfront website use-case
/*
Typical Cloudfront event structure to consume:
{
"Records": [
{
"cf": {
"request": {
"uri": "/test",
"headers": {
"cloudfront-viewer-country": [
{
key: "Cloudfromt-Viewer-Country",
value: "FR"
}
]
}
}
}
}
]
}
*/
module.exports.edgeRedirect = (event, context, callback) => {
const request = event.Records[0].cf.request;
const headers = request.headers;
const uri = request.uri;
const countryCode = headers["cloudfront-viewer-country"][0].value;
// const domain = request.headers.host.replace('http://','').replace('https://','');
console.log(`Country detected: '${countryCode}'`);
if(uri.trim() === "/"){
let response = {
status: "302",
statusDescription: "Found",
headers: {
location: [
{
key: "Location",
value: `https://${DOMAIN}/en`
}
]
}
};
if (countryCode == "GE") {
response.headers.location[0].value = `https://${DOMAIN}/ka`
}
callback(null,response);
}else{
callback(null,request);
}
};
// countryLookup solves all non-CloudFront use-cases, such as mobile
module.exports.countryLookup = (
{ requestContext },
ctx,
callback
) => {
let ip =
requestContext &&
requestContext.identity &&
requestContext.identity.sourceIp
? requestContext.identity.sourceIp
: callback(null, { statusCode: 422, body: "Unprocessable Request" });
Reader.open(__dirname + "/data/GeoLite2-Country.mmdb", (error, reader) => {
if (error) {
callback(error);
}else {
let { iso_code, is_in_european_union } = reader.lookup(ip).country;
callback(null, {
statusCode: 200,
body: JSON.stringify({
iso_code,
is_in_european_union: is_in_european_union || false
})
});
}
});
};