Skip to content

Commit

Permalink
Add more logging around Maxmind DB download
Browse files Browse the repository at this point in the history
  • Loading branch information
statico committed Jun 15, 2024
1 parent d6e36ae commit 225f0bb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
17 changes: 16 additions & 1 deletion lib/geoip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ const filename = "GeoLite2-Country.mmdb";
const path = (process.env.DATA_DIR || "/tmp") + "/" + filename;
const url = process.env.MAXMIND_GEOLITE2_COUNTRY_URL;

const debug = (...args: any[]) => {
if (process.env.DEBUG) console.log("[DEBUG]", ...args);
};

const download = async () => {
if (!url) throw "Cannot download Maxmind DB: Missing env var";

Expand All @@ -39,20 +43,31 @@ const download = async () => {
const data = Buffer.concat(chunks);
writeFileSync(path, data);
console.log(`Wrote ${path} (${data.length} bytes)`);
console.log(`stat ${path}: ${JSON.stringify(statSync(path), null, 2)}`);
}
});

console.log(`Downloading ${filename}...`);
debug(`GET ${url}`);
get(url, (res) => {
res.pipe(createGunzip()).pipe(extract);
if (res.statusCode === 200) {
res.pipe(createGunzip()).pipe(extract);
} else {
reject(
`Failed to download Maxmind DB: ${res.statusCode} ${res.statusMessage}`,
);
}
});
});
};

export const getCountryForIP = async (ip: string) => {
if (existsSync(path)) {
debug("Maxmind DB exists", path);
const maxAge = DateTime.now().minus({ weeks: 1 });
debug("Maxmind DB maxAge", maxAge.toISO());
const lastModified = DateTime.fromJSDate(statSync(path).mtime);
debug("Maxmind DB lastModified", lastModified.toISO());
if (lastModified < maxAge) {
console.log("Maxmind DB is older than 1 week - redownloading");
await download();
Expand Down
2 changes: 1 addition & 1 deletion middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function middleware(req: NextRequest) {
const [username, password] = atob(auth.substring(5)).split(":");

if (username !== HARDCODED_USERNAME || password !== secret)
throw new Error(`Invalid credentials from ${ip}`);
throw new Error("Invalid credentials");
return NextResponse.next();
} catch (err) {
console.log(`Authentication error: ${err} from ${ip}`);
Expand Down

0 comments on commit 225f0bb

Please sign in to comment.