Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

upgrade v5 auth.js #47

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 1 addition & 6 deletions apps/nextjs/src/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */

import NextAuth from "next-auth";

import { authOptions } from "@saasfly/auth";

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
export { GET, POST } from "@saasfly/auth"
82 changes: 37 additions & 45 deletions apps/nextjs/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { redirect } from "next/navigation";
import { NextRequest, NextResponse } from "next/server";
import { match as matchLocale } from "@formatjs/intl-localematcher";
import {NextRequest, NextResponse} from "next/server";
import {match as matchLocale} from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
import { getToken } from "next-auth/jwt";
import { withAuth } from "next-auth/middleware";

import { i18n } from "~/config/i18n-config";
import {i18n} from "~/config/i18n-config";
import {auth} from "@saasfly/auth";

const noNeedProcessRoute = [".*\\.png", ".*\\.jpg", ".*\\.opengraph-image.png"];

Expand Down Expand Up @@ -87,50 +85,44 @@ export default async function middleware(request: NextRequest) {
return authMiddleware(request, null);
}

const authMiddleware = withAuth(
async function middlewares(req) {
const token = await getToken({ req });
const isAuth = !!token;
const isAdmin = token?.isAdmin;
const isAuthPage = /^\/[a-zA-Z]{2,}\/(login|register)/.test(
// @ts-ignore
const authMiddleware = auth((req,res) => {
// @ts-ignore
const token = auth(req, res);
const isAuth = !!token;
// @ts-ignore
const isAdmin = token?.isAdmin;
// @ts-ignore
const isAuthPage = /^\/[a-zA-Z]{2,}\/(login|register)/.test(
req.nextUrl.pathname,
);
const isAuthRoute = /^\/api\/trpc\//.test(req.nextUrl.pathname);
const locale = getLocale(req);
);
const isAuthRoute = /^\/api\/trpc\//.test(req.nextUrl.pathname);
const locale = getLocale(req);

if (isAuthRoute && isAuth) {
return NextResponse.next();
}
if (req.nextUrl.pathname.startsWith("/admin/dashboard")) {
if (!isAuth || !isAdmin)
return NextResponse.redirect(new URL(`/admin/login`, req.url));
return NextResponse.next();
if (isAuthRoute && isAuth) {
return NextResponse.next();
}
if (req.nextUrl.pathname.startsWith("/admin/dashboard")) {
if (!isAuth || !isAdmin)
return NextResponse.redirect(new URL(`/admin/login`, req.url));
return NextResponse.next();
}
if (isAuthPage) {
if (isAuth) {
return NextResponse.redirect(new URL(`/${locale}/dashboard`, req.url));
}
if (isAuthPage) {
if (isAuth) {
return NextResponse.redirect(new URL(`/${locale}/dashboard`, req.url));
}
return null;
return null;
}
if (!isAuth) {
let from = req.nextUrl.pathname;
if (req.nextUrl.search) {
from += req.nextUrl.search;
}
if (!isAuth) {
let from = req.nextUrl.pathname;
if (req.nextUrl.search) {
from += req.nextUrl.search;
}
return NextResponse.redirect(
return NextResponse.redirect(
new URL(`/${locale}/login?from=${encodeURIComponent(from)}`, req.url),
);
}
},
{
callbacks: {
authorized() {
return true;
},
},
},
);

);
}
})
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
5 changes: 3 additions & 2 deletions packages/api/src/router/customer.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { getServerSession } from "next-auth/next";
import { z } from "zod";

import { authOptions } from "@saasfly/auth";
import { db, SubscriptionPlan } from "@saasfly/db";

import { createTRPCRouter, protectedProcedure } from "../trpc";
import {auth} from "@saasfly/auth/auth";

const updateUserNameSchema = z.object({
name: z.string(),
Expand All @@ -21,7 +21,8 @@ export const customerRouter = createTRPCRouter({
.input(updateUserNameSchema)
.mutation(async ({ input }) => {
const { userId } = input;
const session = await getServerSession(authOptions);
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-assignment
const session = await auth();
if (!session?.user || userId !== session?.user.id) {
return { success: false, reason: "no auth" };
}
Expand Down
8 changes: 4 additions & 4 deletions packages/api/src/router/k8s.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { TRPCError } from "@trpc/server";
import { getServerSession } from "next-auth/next";
import { z } from "zod";

import { authOptions } from "@saasfly/auth";
import { db, SubscriptionPlan } from "@saasfly/db";

import { createTRPCRouter, protectedProcedure } from "../trpc";
import {auth} from "@saasfly/auth/";

const k8sClusterCreateSchema = z.object({
id: z.number().optional(),
Expand All @@ -19,7 +18,8 @@ const k8sClusterDeleteSchema = z.object({

export const k8sRouter = createTRPCRouter({
getClusters: protectedProcedure.query(async (opts) => {
const session = await getServerSession(authOptions);
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-assignment
const session = await auth();
const userId = opts.ctx.userId! as string;
if (!session) {
return;
Expand All @@ -35,7 +35,7 @@ export const k8sRouter = createTRPCRouter({
.mutation(async ({ ctx, input }) => {
const userId = ctx.userId! as string;

const session = await getServerSession(authOptions);
const session = await auth();
if (!session) {
throw new TRPCError({
code: "UNAUTHORIZED",
Expand Down
5 changes: 4 additions & 1 deletion packages/api/src/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { getToken, type JWT } from "next-auth/jwt";
import { ZodError } from "zod";

import { transformer } from "./transformer";
import {env} from "./env.mjs";
import {auth} from "@saasfly/auth";

interface CreateContextOptions {
req?: NextRequest;
Expand Down Expand Up @@ -48,5 +50,6 @@ export const protectedProcedure = procedure.use(async (opts) => {

async function handler(req: NextRequest): Promise<JWT | null> {
// if using `NEXTAUTH_SECRET` env variable, we detect it, and you won't actually need to `secret`
return await getToken({ req });
// @ts-ignore
return await auth();
}
7 changes: 7 additions & 0 deletions packages/auth/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// import NextAuth from "next-auth"
// import GitHub from "next-auth/providers/github"

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
// export const { handlers, signIn, signOut, auth } = NextAuth({
// providers: [GitHub]
// })