Skip to content

Commit

Permalink
Integrate NextAuth
Browse files Browse the repository at this point in the history
  • Loading branch information
jevakallio committed Oct 24, 2023
1 parent bcd4ff5 commit 418e2b5
Show file tree
Hide file tree
Showing 4 changed files with 183 additions and 7 deletions.
10 changes: 10 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# The Next.js app needs to know where to reach the PartyKit server
NEXT_PUBLIC_PARTYKIT_HOST="127.0.0.1:1999"

# To enable authentication, generate a NEXTAUTH_SECRET here: https://generate-secret.vercel.app/32 (only required for localhost)
NEXTAUTH_SECRET=

# To enable GitHub login, create a GitHub OAuth application
GITHUB_CLIENT_ID=
GITHUB_SECRET=

58 changes: 58 additions & 0 deletions app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import NextAuth, { type NextAuthOptions } from "next-auth";
import type { User } from "@/party/utils/auth";
import GitHubProvider from "next-auth/providers/github";

const GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID;
const GITHUB_SECRET = process.env.GITHUB_SECRET;

if (!GITHUB_CLIENT_ID)
throw new Error("GITHUB_CLIENT_ID not defined in environment");

if (!GITHUB_SECRET)
throw new Error("GITHUB_CLIENT_SECRET not defined in environment");

export const authOptions: NextAuthOptions = {
providers: [
GitHubProvider({
clientId: GITHUB_CLIENT_ID,
clientSecret: GITHUB_SECRET,
}),
],
callbacks: {
async redirect({ url, baseUrl }) {
// Allows relative callback URLs
if (url.startsWith("/")) return `${baseUrl}${url}`;
// Allows callback URLs on the same origin
else if (new URL(url).origin === baseUrl) return url;
return baseUrl;
},
signIn(params) {
return true;
},

session({ session, token, user }) {
return {
...session,
user: {
...session.user,
username: token.username,
} as User,
};
},

jwt({ token, profile, trigger }) {
const username =
profile && "login" in profile ? profile.login : profile?.email;

if (trigger === "signIn") {
return { ...token, username };
}

return token;
},
},
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
121 changes: 114 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"react": "^18",
"react-dom": "^18",
"next": "13.5.4",
"next-auth": "^4.24.3",
"partysocket": "0.0.9"
},
"devDependencies": {
Expand Down

0 comments on commit 418e2b5

Please sign in to comment.