CoolFace
Apppublic

Exched/DeepSeek_Coder

sourceHugging Facemitupdated 11mo agoView on Hugging Face
0likes
auth.ts73 linesDownload Raw Back to lib
1import { User } from "@/types";2import { NextResponse } from "next/server";3import { cookies, headers } from "next/headers";4import MY_TOKEN_KEY from "./get-cookie-name";5 6// UserResponse = type User & { token: string };7type UserResponse = User & { token: string };8 9export const isAuthenticated = async (): // req: NextRequest10Promise<UserResponse | NextResponse<unknown> | undefined> => {11  const authHeaders = await headers();12  const cookieStore = await cookies();13  const token = cookieStore.get(MY_TOKEN_KEY())?.value14    ? `Bearer ${cookieStore.get(MY_TOKEN_KEY())?.value}`15    : authHeaders.get("Authorization");16 17  if (!token) {18    return NextResponse.json(19      {20        ok: false,21        message: "Wrong castle fam :(",22      },23      {24        status: 401,25        headers: {26          "Content-Type": "application/json",27        },28      }29    );30  }31 32  const user = await fetch("https://huggingface.co/api/whoami-v2", {33    headers: {34      Authorization: token,35    },36    method: "GET",37  })38    .then((res) => res.json())39    .catch(() => {40      return NextResponse.json(41        {42          ok: false,43          message: "Invalid token",44        },45        {46          status: 401,47          headers: {48            "Content-Type": "application/json",49          },50        }51      );52    });53  if (!user || !user.id) {54    return NextResponse.json(55      {56        ok: false,57        message: "Invalid token",58      },59      {60        status: 401,61        headers: {62          "Content-Type": "application/json",63        },64      }65    );66  }67 68  return {69    ...user,70    token: token.replace("Bearer ", ""),71  };72};73