File size: 901 Bytes
60e766b
 
374bf33
 
 
 
60e766b
 
374bf33
 
 
 
 
 
 
 
60e766b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { cookies, headers } from "next/headers";

function looksLikeAnonId(value: string): boolean {
  return value.length >= 8 && value.length <= 128;
}

export async function getAnonId(): Promise<string> {
  const store = await cookies();
  const cookieAnon = store.get("anon_id")?.value ?? "";
  if (looksLikeAnonId(cookieAnon)) return cookieAnon;

  const h = await headers();
  const headerAnon = h.get("x-anon-id")?.trim() ?? "";
  if (looksLikeAnonId(headerAnon)) return headerAnon;

  return "";
}

export async function getNickname(): Promise<string> {
  const store = await cookies();
  return store.get("nickname")?.value ?? "anon";
}

export async function getClientIp(): Promise<string> {
  const h = await headers();
  const forwarded = h.get("x-forwarded-for");
  if (forwarded) {
    return forwarded.split(",")[0]?.trim() || "unknown";
  }
  return h.get("x-real-ip") ?? "unknown";
}