♻️ Create guest user in middleware (#927)

This commit is contained in:
Luke Vella 2023-11-04 13:50:15 +00:00 committed by GitHub
parent 25da819774
commit e65850370f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 1 deletions

View file

@ -82,7 +82,7 @@ export const UserProvider = (props: { children?: React.ReactNode }) => {
} }
}, [session.status]); }, [session.status]);
if (!user || !session.data) { if (!user) {
return null; return null;
} }

View file

@ -1,7 +1,9 @@
import { randomid } from "@rallly/backend/utils/nanoid";
import languages from "@rallly/languages"; import languages from "@rallly/languages";
import languageParser from "accept-language-parser"; import languageParser from "accept-language-parser";
import { unsealData } from "iron-session/edge"; import { unsealData } from "iron-session/edge";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { encode } from "next-auth/jwt";
import withAuth from "next-auth/middleware"; import withAuth from "next-auth/middleware";
const supportedLocales = Object.keys(languages); const supportedLocales = Object.keys(languages);
@ -65,6 +67,28 @@ export default withAuth(
value: legacyToken.value, value: legacyToken.value,
httpOnly: false, httpOnly: false,
}); });
} else {
// Create new guest user
const newUser = `user-${randomid()}`;
const token = await encode({
token: {
sub: newUser,
email: null,
},
secret: process.env.SECRET_PASSWORD,
});
const secure = process.env.NODE_ENV === "production";
const prefix = secure ? "__Secure-" : "";
const name = `${prefix}next-auth.session-token`;
res.cookies.set({
name,
value: token,
httpOnly: true,
secure,
sameSite: "lax",
path: "/",
});
} }
} }
} }