Nik-Novak / steam-next-auth

NextAuth / AuthJS V5 Steam Provider
MIT License
2 stars 0 forks source link

Callback not working #2

Open ancyloce opened 2 weeks ago

ancyloce commented 2 weeks ago

Hello @Nik-Novak

I hope this message finds you well. I'm encountering an issue while using the library you developed. Below is the code I am working with:

env.local

NEXTAUTH_STEAM_SECRET="----------------------------"
NEXTAUTH_URL="http://localhost:7800"

app/api/auth/fuckoffnextauth/[provider]/route.ts

import { NextRequest } from 'next/server';

export type RouteURL = '/api/auth/fuckoffnextauth/[provider]';
type Params = { params: { provider: string } };

export async function GET(
  req: NextRequest,
  { params }: Params,
): Promise<Response> {
  const provider = params.provider;
  const { searchParams } = new URL(req.url);
  searchParams.set('code', '123'); //inject a fake code to make nextauth v5 happy
  return Response.redirect(
    `${process.env.NEXTAUTH_URL}/api/auth/callback/${provider}?${searchParams.toString()}`,
  ); //this should be your normal nextauth callback url
}

export async function POST(req: NextRequest): Promise<Response> {
  return Response.json({ token: '123' }); //fake token endpoint
}

//You can hardcode provider to be 'steam'

app/api/auth/[...nextauth]/route.ts

import { handlers } from '@/auth';

export const { GET, POST } = handlers;

auth.config.ts

import type { NextAuthConfig } from 'next-auth';
import { CustomAccount } from '@/next-auth';
import { parseCallback } from '@/lib/utils';

export const authRoutes = ['/mine', '/settings', '/user'];

export const authConfig = {
  debug: process.env.NODE_ENV === 'development',
  secret: process.env.AUTH_SECRET,
  trustHost: true,
  pages: {
    signIn: '/signin',
  },
  basePath: '/api/auth',
  session: {
    strategy: 'jwt',
  },
  providers: [],
  callbacks: {
    authorized({ auth, request }) {
      console.log('authorized', auth);
      console.log('==============================>');
      const isLoggedIn = !!auth?.user;
      const isOnDashboard = authRoutes.some((route) => {
        const pathname = request.nextUrl.pathname.toLowerCase();
        if (pathname === '/') {
          return true;
        } else {
          return pathname.startsWith(route);
        }
      });

      if (isOnDashboard) {
        return isLoggedIn;
      } else if (isLoggedIn) {
        const callbackUrl = parseCallback(request.nextUrl);
        return Response.redirect(new URL(callbackUrl || '/', request.nextUrl));
      }

      return true;
    },
    async jwt({ token, user, account }) {
      console.log('jwt', user);
      if (user) {
        token.id = user.id;
        token.account = user.account;
      }
      return token;
    },
    async session({ session, token }) {
      console.log('session', token);
      if (token.account) {
        session.account = token.account as CustomAccount;
      }
      return session;
    },
    async redirect({ url, baseUrl }) {
      console.log('redirect', url);
      return url.startsWith(baseUrl) ? url : baseUrl;
    },
  },
} satisfies NextAuthConfig;

auth.ts

import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { authConfig } from './auth.config';
import z from 'zod';
import { PHONE_REGEX } from '@/lib/globals';
import { getMine, signIn as signInApi } from '@/services/server/auth';
import SteamProvider from 'steam-next-auth';

export const { handlers, auth, signIn, signOut } = NextAuth((req) => ({
  ...authConfig,
  providers: [
    SteamProvider(req as any, {
      clientSecret: process.env.AUTH_STEAM_SECRET!,
      callbackUrl: `${process.env.AUTH_URL}/api/auth/fuckoffnextauth`,
    }),
    Credentials({
      credentials: {
        phone: { label: 'phone, type: 'text' },
        password: { label: 'password', type: 'password' },
      },
      async authorize(credentials) {
        // get credentials
        const { success, data, error } = z
          .object({})
          .safeParse(credentials);

        // if zod validation fails
        if (!success) {
          throw new Error(JSON.stringify(error?.errors));
        }

        try {
          const resp = await signInApi(data);

          if (!resp?.success) return null;

          const mineResp = await getMine(resp?.data?.token);

          if (!mineResp?.success) return null;

          const user = mineResp?.data;

          return {
            ...user,
            name: user?.displayName,
            email: user?.phone,
            picture: user?.avatarUrl,
            account: {
              custom_id: user?.phone,
              user,
              token: resp?.data?.token,
              session: resp?.data,
            },
          };
        } catch (error) {
          throw new Error(JSON.stringify(error));
        }
      },
    }),
  ],
}));

actions.ts

export async function steam() {
  await signIn('steam');
}

Thank you for your assistance.

Best regards

ancyloce commented 2 weeks ago
 ✓ Compiled /api/auth/fuckoffnextauth/[provider] in 531ms (2956 modules)
 GET /api/auth/fuckoffnextauth/steam?openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=http
s%3A%2F%2Fsteamcommunity.com%2Fopenid%2Flogin&openid.claimed_id=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561199702565607&o
penid.identity=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561199702565607&openid.return_to=http%3A%2F%2Flocalhost%3A7800%2Fa
pi%2Fauth%2Ffuckoffnextauth%2Fsteam&openid.response_nonce=2024-06-14T11%3A21%3A06ZKdkbBeu9vpAyQwED%2B%2FEPCVdfoSY%3D&openid.assoc_ha
ndle=1234567890&openid.signed=signed%2Cop_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle&openid.sig=JVQS4H6%2FPH7io68A3zxOQ1Lfi%2Fo%3D 302 in 623ms
[auth][warn][debug-enabled] Read more: https://warnings.authjs.dev#debug-enabled
redirect http://localhost:7800/signin?callbackUrl=http%3A%2F%2Flocalhost%3A7800%2F
 POST /api/auth/fuckoffnextauth/steam 200 in 26ms