clerk / javascript

Official JavaScript repository for Clerk authentication
https://clerk.com
MIT License
1.19k stars 272 forks source link

@clerk/express getAuth #4469

Closed wyvern800 closed 2 weeks ago

wyvern800 commented 1 month ago

Preliminary Checks

Reproduction

#

Publishable key

pk_test_ZXhvdGljLWNyYWItNzUuY2xlcmsuYWNjb3VudHMuZGV2JA

Description

Steps to reproduce:

Try calling 'getAuth' from the lib, in dev mode

Expected behavior: will only return: { ... [1] sessionId: 'example session id, [1] userId: 'example user id', [1]

seems like everything is null, it was supposed to come with a userId and a sessionId.

Actual behavior: will only return: { [1] sessionClaims: null, [1] sessionId: null, [1] userId: null, [1] actor: null, [1] orgId: null, [1] orgRole: null, [1] orgSlug: null, [1] orgPermissions: null, [1] __experimental_factorVerificationAge: null, [1] getToken: [Function: getToken], [1] has: [Function: has], [1] debug: [Function (anonymous)], [1]

seems like everything is null, it was supposed to come with a userId and a sessionId.

Environment

System:
    OS: Windows 10 10.0.19045
    CPU: (16) x64 AMD Ryzen 7 5700X 8-Core Processor
    Memory: 8.42 GB / 31.91 GB
  Binaries:
    Node: 20.17.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.4 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 10.9.0 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Chromium (129.0.2792.65)
    Internet Explorer: 11.0.19041.4355
  npmPackages:
    @clerk/clerk-sdk-node: ^5.0.50 => 5.0.58
    @clerk/express: ^1.2.3 => 1.3.7
    axios: ^1.7.7 => 1.7.7
    concurrently: ^9.0.1 => 9.0.1
    cors: ^2.8.5 => 2.8.5
    date-fns: ^4.1.0 => 4.1.0
    discord.js: ^14.0.0 => 14.16.3
    dotenv: ^10.0.0 => 10.0.0
    express: ^4.17.1 => 4.21.1
    express-rate-limit: ^7.4.1 => 7.4.1
    firebase-admin: ^12.6.0 => 12.7.0
    node-cache: ^5.1.2 => 5.1.2
    node-cron: ^3.0.3 => 3.0.3
    nodemon: ^3.1.7 => 3.1.7
wobsoriano commented 4 weeks ago

Hello! I'm sorry you're experiencing this issue. I just tested it locally and was able to get the correct results.

Screenshot 2024-11-04 at 11 12 33 AM

How are you using it? Could you provide a basic reproduction?

Also, I notice you're using @clerk/clerk-sdk-node. We advise migrating to @clerk/backend for pure Node projects or @clerk/express for Express projects.

wobsoriano commented 3 weeks ago

Hi @wyvern800! Just following up on your reported issue - were you able to replicate it again or has the problem been resolved on your end?

wyvern800 commented 3 weeks ago

Still having the issue, it started outta nowhere

wobsoriano commented 3 weeks ago

Thanks for the update @wyvern800! Would you be able to provide a minimal repro using our quickstart template?

wyvern800 commented 2 weeks ago

I am using the same setup as in the quickstart template:

as you can see here:, but when I access the route, it stays blank: image

image

import express from "express";
import path from "path";
import cors from "cors";
import { commands } from "../../utils/commands.js";
import { parseRoutes, getRoutes } from "../middlewares/routeCapturer.js";
import { clerkMiddleware, getAuth } from "@clerk/express";
import "dotenv/config";
import Clerk from "../../utils/clerk.js";
import ResponseBase from "../../utils/responses.js";
import {
  getGuildsByOwnerOrUser,
  getAllGuilds,
} from "../../database/repository.js";
import { config } from "dotenv";
import rateLimit from "express-rate-limit";
import { protectedRouteMiddleware } from "../../src/middlewares/clerkAuth.js";
import { createClerkClient } from '@clerk/backend';

config();

export const createServer = (client) => {
  const app = express();
  const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY, publishableKey: process.env.CLERK_PUBLISHABLE_KEY });
  console.log(clerkClient)

  const port = process.env.PORT || 3000;

  const limiter = rateLimit({
    windowMs: parseInt(process.env.MAX_REQ_TIME, 10),
    max: parseInt(process.env.LIMIT_REQUESTS, 10),
  });

  app.use(
    cors({
      origin: process.env.ENV === "dev" ? "*" : "https://www.tldkp.online",
      methods: ["GET", "POST", "OPTIONS"],
      allowedHeaders: ["Content-Type", "Authorization"],
      optionsSuccessStatus: 200,
    })
  );

  // Serve static files from the React app build
  const __dirname = path.resolve();
  app.use(express.static(path.join(__dirname, "frontend", "build")));

  // Create a router for your /api routes
  const apiRouter = express.Router();
  apiRouter.use(express.json());

  apiRouter.use(
    cors({
      origin: process.env.ENV === "dev" ? "*" : "https://www.tldkp.online",
      methods: ["GET", "POST"],
      allowedHeaders: ["Content-Type", "Authorization"],
      optionsSuccessStatus: 200,
    })
  );

  // Middleware to parse the routes to display as default endpoint
  parseRoutes(apiRouter);

  apiRouter.get(
    "/",
    (req, res) => {
      res.status(200).json(getRoutes());
    },
    "Endpoint that shows all the api endpoints"
  );

  apiRouter.get(
    "/commands",
    (req, res) => {
      return new ResponseBase(res).success(
        commands.map((command) => ({
          name: command.name,
          description: command.description,
          options: command.options,
          commandCategory: command.commandCategory,
          new: command.new,
        }))
      );
    },
    "Endpoint that shows all the commands from the bot service"
  );

  apiRouter.get(
    "/health",
    (req, res) => {
      if (client) {
        const status = client.user.presence.status; // Get the bot's status
        if (status === "online") {
          return new ResponseBase(res).success("Bot is healthy");
        } else {
          return new ResponseBase(res).error("Bot is unhealthy!");
        }
      } else {
        return new ResponseBase(res).successEmpty();
      }
    },
    "Endpoint that shows bot status"
  );

  apiRouter.use(limiter);

  // clerkMiddleware is required to be set in the middleware chain before req.auth is used
  apiRouter.use(clerkMiddleware({ clerkClient, debug: true, enableHandshake: true }));

  // Protected route middleware

  apiRouter.get("/dashboard", async (req, res) => {
    res.json(req.auth)
    const { userDiscordId } = req;

    // Gets the data
    if (userDiscordId) {
      await getGuildsByOwnerOrUser(userDiscordId).then((guild) => {
        return new ResponseBase(res).success(guild);
      });
    }
  });

  apiRouter.get("/admin", async (req, res) => {
    const { userDiscordId } = req;

    if (userDiscordId) {
      const adminDiscordIds = process.env.ADMINS?.split(",");
      const isAdmin = adminDiscordIds.includes(userDiscordId);

      const allGuilds = await getAllGuilds();

      if (isAdmin) {
        return new ResponseBase(res).success({ isAdmin, guilds: allGuilds });
      } else {
        return new ResponseBase(res).notAllowed("Unauthorized");
      }
    }
  });

  apiRouter.use((err, req, res, next) => {
    return new ResponseBase(res).notAllowed("Unauthenticated!");
  });

  app.use("/api", apiRouter);

  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "frontend", "build", "index.html"));
  });

  app.listen(port, () => {
    console.log(`[Express] HTTP Server running on port ${port}`);
  });

  return app;
};
wyvern800 commented 2 weeks ago

I've discovered the issue My system for some reason didnt have the correct time set that was causing the issue but that wasnt supposed to happen on dev environment, since the log told Imagem the issue is I use two systems and in linux the time was correct, but not on windows dualboot thanks god, after some long reseaerches but u see there is something said: Clerk will attempt to account for the clock skew in development. that is not happening maybe there is a way to tag clerk as dev mode on its initialization?

wyvern800 commented 2 weeks ago

Yeah, everything is working fine now.

wobsoriano commented 2 weeks ago

Awesome!