Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

Auth with Google and GitHub (#405)

Marc Klingenf8d3258829f6
diff --git a/.env.cloud.example b/.env.cloud.example
index 1a5a572c31..2949f60407 100644
--- a/.env.cloud.example
+++ b/.env.cloud.example
@@ -32,4 +32,10 @@ SALT="salt"
# NEXT_PUBLIC_POSTHOG_KEY=
# Id of demo project to automatically assign new users to
-# NEXT_PUBLIC_DEMO_PROJECT_ID=
\ No newline at end of file
+# NEXT_PUBLIC_DEMO_PROJECT_ID=
+
+# Auth, each group is optional
+AUTH_GOOGLE_CLIENT_ID=
+AUTH_GOOGLE_CLIENT_SECRET=
+AUTH_GITHUB_CLIENT_ID=
+AUTH_GITHUB_CLIENT_SECRET=
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index 5c8e0a3a17..5aacb5ba81 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10194,6 +10194,16 @@
"integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==",
"dev": true
},
+ "node_modules/nodemailer": {
+ "version": "6.9.6",
+ "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.6.tgz",
+ "integrity": "sha512-s7pDtWwe5fLMkQUhw8TkWB/wnZ7SRdd9HRZslq/s24hlZvBP3j32N/ETLmnqTpmj4xoBZL9fOWyCIZ7r2HORHg==",
+ "optional": true,
+ "peer": true,
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
"node_modules/nopt": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/nopt/-/nopt-6.0.0.tgz",
diff --git a/src/components/layouts/layout.tsx b/src/components/layouts/layout.tsx
index e8a995c891..a05a520456 100644
--- a/src/components/layouts/layout.tsx
+++ b/src/components/layouts/layout.tsx
@@ -40,7 +40,8 @@ export default function Layout(props: PropsWithChildren) {
const [sidebarOpen, setSidebarOpen] = useState(false);
const router = useRouter();
const session = useSession();
- const runtimeEnv = api.runtimeEnv.all.useQuery();
+ const enableExperimentalFeatures =
+ api.environment.enableExperimentalFeatures.useQuery().data;
const projectId = router.query.projectId as string | undefined;
const navigation = ROUTES.filter(
@@ -49,7 +50,7 @@ export default function Layout(props: PropsWithChildren) {
.filter(
({ featureFlag }) =>
featureFlag === undefined ||
- runtimeEnv.data?.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES === "true" ||
+ enableExperimentalFeatures ||
session.data?.user?.featureFlags[featureFlag],
)
.map(({ pathname, ...rest }) => ({
diff --git a/src/env.mjs b/src/env.mjs
index 30dc21fadf..fc510eb8a7 100644
--- a/src/env.mjs
+++ b/src/env.mjs
@@ -33,6 +33,11 @@ export const env = createEnv({
required_error:
"A strong Salt is required to encrypt API keys securely. See: https://langfuse.com/docs/deployment/self-host#deploy-the-container",
}),
+ // AUTH
+ AUTH_GOOGLE_CLIENT_ID: z.string().optional(),
+ AUTH_GOOGLE_CLIENT_SECRET: z.string().optional(),
+ AUTH_GITHUB_CLIENT_ID: z.string().optional(),
+ AUTH_GITHUB_CLIENT_SECRET: z.string().optional(),
},
/**
@@ -68,5 +73,10 @@ export const env = createEnv({
LANGFUSE_NEW_USER_SIGNUP_WEBHOOK:
process.env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK,
SALT: process.env.SALT,
+ // AUTH
+ AUTH_GOOGLE_CLIENT_ID: process.env.AUTH_GOOGLE_CLIENT_ID,
+ AUTH_GOOGLE_CLIENT_SECRET: process.env.AUTH_GOOGLE_CLIENT_SECRET,
+ AUTH_GITHUB_CLIENT_ID: process.env.AUTH_GITHUB_CLIENT_ID,
+ AUTH_GITHUB_CLIENT_SECRET: process.env.AUTH_GITHUB_CLIENT_SECRET,
},
});
diff --git a/src/features/feature-flags/components/FeatureFlagToggle.tsx b/src/features/feature-flags/components/FeatureFlagToggle.tsx
index 185586093b..891aa60cde 100644
--- a/src/features/feature-flags/components/FeatureFlagToggle.tsx
+++ b/src/features/feature-flags/components/FeatureFlagToggle.tsx
@@ -9,10 +9,10 @@ export const FeatureFlagToggle = (props: {
whenLoading?: React.ReactNode;
}) => {
const session = useSession();
- const runtimeEnv = api.runtimeEnv.all.useQuery();
+ const enableExperimentalFeatures =
+ api.environment.enableExperimentalFeatures.useQuery().data;
- if (runtimeEnv.data?.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES === "true")
- return props.whenEnabled ?? <></>;
+ if (enableExperimentalFeatures) return props.whenEnabled ?? <></>;
const flags = session.data?.user?.featureFlags;
const isEnabled = flags !== undefined && flags[props.featureFlag];
diff --git a/src/pages/api/auth/signup.ts b/src/pages/api/auth/signup.ts
index f6bda2570d..6708004861 100644
--- a/src/pages/api/auth/signup.ts
+++ b/src/pages/api/auth/signup.ts
@@ -36,7 +36,7 @@ export default async function handler(
console.log(
"Signup: Error creating user",
error.message,
- body.email,
+ body.email.toLowerCase(),
body.name,
);
res.status(422).json({ message: error.message });
diff --git a/src/pages/auth/sign-in.tsx b/src/pages/auth/sign-in.tsx
index 9b1f150e0c..34ac640e8f 100644
--- a/src/pages/auth/sign-in.tsx
+++ b/src/pages/auth/sign-in.tsx
@@ -1,3 +1,4 @@
+import { type GetServerSideProps } from "next";
import { LangfuseIcon } from "@/src/components/LangfuseLogo";
import { Button } from "@/src/components/ui/button";
import {
@@ -11,32 +12,68 @@ import {
import { Input } from "@/src/components/ui/input";
import { env } from "@/src/env.mjs";
import { zodResolver } from "@hookform/resolvers/zod";
+import { FcGoogle } from "react-icons/fc";
+import { FaGithub } from "react-icons/fa";
import { signIn } from "next-auth/react";
import Head from "next/head";
import Link from "next/link";
import { useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
+import { usePostHog } from "posthog-js/react";
-const formSchema = z.object({
+const credentialAuthForm = z.object({
email: z.string().email(),
password: z.string().min(8, {
message: "Password must be at least 8 characters long",
}),
});
-export default function SignIn() {
- const [formError, setFormError] = useState<string | null>(null);
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
+type PageProps = {
+ authProviders: {
+ credentials: boolean;
+ google: boolean;
+ github: boolean;
+ };
+};
+
+// eslint-disable-next-line @typescript-eslint/require-await
+export const getServerSideProps: GetServerSideProps<PageProps> = async () => {
+ return {
+ props: {
+ authProviders: {
+ google:
+ env.AUTH_GOOGLE_CLIENT_ID !== undefined &&
+ env.AUTH_GOOGLE_CLIENT_SECRET !== undefined,
+ github:
+ env.AUTH_GITHUB_CLIENT_ID !== undefined &&
+ env.AUTH_GITHUB_CLIENT_SECRET !== undefined,
+ credentials: true,
+ },
+ },
+ };
+};
+
+export default function SignIn(props: PageProps) {
+ const [credentialsFormError, setCredentialsFormError] = useState<
+ string | null
+ >(null);
+
+ const posthog = usePostHog();
+
+ // Credentials
+ const credentialsForm = useForm<z.infer<typeof credentialAuthForm>>({
+ resolver: zodResolver(credentialAuthForm),
defaultValues: {
email: "",
password: "",
},
});
-
- async function onSubmit(values: z.infer<typeof formSchema>) {
- setFormError(null);
+ async function onCredentialsSubmit(
+ values: z.infer<typeof credentialAuthForm>,
+ ) {
+ setCredentialsFormError(null);
+ posthog.capture("sign_in:credentials_form_submit");
const result = await signIn("credentials", {
email: values.email,
password: values.password,
@@ -44,7 +81,7 @@ export default function SignIn() {
redirect: false,
});
if (result?.error) {
- setFormError(result.error);
+ setCredentialsFormError(result.error);
}
}
@@ -62,56 +99,92 @@ export default function SignIn() {
</div>
<div className="mt-14 sm:mx-auto sm:w-full sm:max-w-[480px]">
- <div className="bg-white px-6 py-12 shadow sm:rounded-lg sm:px-12">
- <Form {...form}>
- <form
- className="space-y-6"
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
- onSubmit={form.handleSubmit(onSubmit)}
- >
- <FormField
- control={form.control}
- name="email"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Email</FormLabel>
- <FormControl>
- <Input placeholder="[email protected]" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="password"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Password</FormLabel>
- <FormControl>
- <Input type="password" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <Button
- type="submit"
- className="w-full"
- loading={form.formState.isSubmitting}
+ <div className="divide-y bg-white p-6 py-6 shadow sm:rounded-lg sm:px-12">
+ {props.authProviders.credentials ? (
+ <Form {...credentialsForm}>
+ <form
+ className="space-y-6 py-6"
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ onSubmit={credentialsForm.handleSubmit(onCredentialsSubmit)}
>
- Sign in
- </Button>
- {formError ? (
- <div className="text-center text-sm font-medium text-destructive">
- {formError}, contact support if this error is unexpected.
- </div>
- ) : null}
- </form>
- </Form>
+ <FormField
+ control={credentialsForm.control}
+ name="email"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Email</FormLabel>
+ <FormControl>
+ <Input placeholder="[email protected]" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={credentialsForm.control}
+ name="password"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Password</FormLabel>
+ <FormControl>
+ <Input type="password" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <Button
+ type="submit"
+ className="w-full"
+ loading={credentialsForm.formState.isSubmitting}
+ >
+ Sign in
+ </Button>
+ {credentialsFormError ? (
+ <div className="text-center text-sm font-medium text-destructive">
+ {credentialsFormError}, contact support if this error is
+ unexpected.
+ </div>
+ ) : null}
+ </form>
+ </Form>
+ ) : null}
+
+ {
+ // any authprovider from props is enanbles
+ Object.values(props.authProviders).some((enabled) => enabled) ? (
+ <div className="flex flex-row flex-wrap items-center justify-center gap-4 py-6">
+ {props.authProviders.google ? (
+ <Button
+ onClick={() => {
+ posthog.capture("sign_in:google_button_click");
+ void signIn("google");
+ }}
+ variant="secondary"
+ >
+ <FcGoogle className="mr-3" size={18} />
+ Sign in with Google
+ </Button>
+ ) : null}
+ {props.authProviders.github ? (
+ <Button
+ onClick={() => {
+ posthog.capture("sign_in:github_button_click");
+ void signIn("github");
+ }}
+ variant="secondary"
+ >
+ <FaGithub className="mr-3" size={18} />
+ Sign in with Github
+ </Button>
+ ) : null}
+ </div>
+ ) : null
+ }
</div>
- {env.NEXT_PUBLIC_SIGN_UP_DISABLED !== "true" ? (
+ {env.NEXT_PUBLIC_SIGN_UP_DISABLED !== "true" &&
+ props.authProviders.credentials ? (
<p className="mt-10 text-center text-sm text-gray-500">
No account yet?{" "}
<Link
diff --git a/src/server/api/root.ts b/src/server/api/root.ts
index 430a5b8fdd..ac93487498 100644
--- a/src/server/api/root.ts
+++ b/src/server/api/root.ts
@@ -9,7 +9,7 @@ import { projectMembersRouter } from "@/src/features/rbac/server/projectMembersR
import { userRouter } from "@/src/server/api/routers/users";
import { publishTracesRouter } from "@/src/features/public-traces/server/publishTracesRouter";
import { datasetRouter } from "@/src/features/datasets/server/dataset-router";
-import { runtimeEnvRouter } from "@/src/server/api/routers/runtimeEnv";
+import { environmentRouter } from "@/src/server/api/routers/environment";
/**
* This is the primary router for your server.
@@ -27,7 +27,7 @@ export const appRouter = createTRPCRouter({
projectMembers: projectMembersRouter,
publishTraces: publishTracesRouter,
datasets: datasetRouter,
- runtimeEnv: runtimeEnvRouter,
+ environment: environmentRouter,
});
// export type definition of API
diff --git a/src/server/api/routers/environment.ts b/src/server/api/routers/environment.ts
new file mode 100644
index 0000000000..50f5f69ef3
--- /dev/null
+++ b/src/server/api/routers/environment.ts
@@ -0,0 +1,8 @@
+import { env } from "@/src/env.mjs";
+import { createTRPCRouter, publicProcedure } from "@/src/server/api/trpc";
+
+export const environmentRouter = createTRPCRouter({
+ enableExperimentalFeatures: publicProcedure.query(
+ () => env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES === "true",
+ ),
+});
diff --git a/src/server/api/routers/runtimeEnv.ts b/src/server/api/routers/runtimeEnv.ts
deleted file mode 100644
index c81b5619c0..0000000000
--- a/src/server/api/routers/runtimeEnv.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { env } from "@/src/env.mjs";
-import { createTRPCRouter, publicProcedure } from "@/src/server/api/trpc";
-
-export const runtimeEnvRouter = createTRPCRouter({
- all: publicProcedure.query(() => {
- return {
- LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES:
- env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES,
- };
- }),
-});
diff --git a/src/server/auth.ts b/src/server/auth.ts
index f796710cbe..f1671bf27b 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -7,11 +7,16 @@ import {
} from "next-auth";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { prisma } from "@/src/server/db";
-import CredentialsProvider from "next-auth/providers/credentials";
import { verifyPassword } from "@/src/features/auth/lib/emailPassword";
import { parseFlags } from "@/src/features/feature-flags/utils";
import { env } from "@/src/env.mjs";
+// Providers
+import { type Provider } from "next-auth/providers";
+import CredentialsProvider from "next-auth/providers/credentials";
+import GoogleProvider from "next-auth/providers/google";
+import GitHubProvider from "next-auth/providers/github";
+
// Use secure cookies on https hostnames, exception for Vercel which sets NEXTAUTH_URL without the protocol
const useSecureCookies =
env.NEXTAUTH_URL.startsWith("https://") || process.env.VERCEL === "1";
@@ -33,6 +38,68 @@ const cookieName = (name: string) =>
: "",
].join("");
+const providers: Provider[] = [
+ CredentialsProvider({
+ name: "credentials",
+ credentials: {
+ email: {
+ label: "Email",
+ type: "email",
+ placeholder: "[email protected]",
+ },
+ password: { label: "Password", type: "password" },
+ },
+ async authorize(credentials, _req) {
+ if (!credentials) throw new Error("No credentials");
+
+ const dbUser = await prisma.user.findUnique({
+ where: {
+ email: credentials.email.toLowerCase(),
+ },
+ });
+
+ if (!dbUser) throw new Error("Invalid credentials");
+ if (dbUser.password === null) throw new Error("Invalid credentials");
+
+ const isValidPassword = await verifyPassword(
+ credentials.password,
+ dbUser.password,
+ );
+ if (!isValidPassword) throw new Error("Invalid credentials");
+
+ const userObj: User = {
+ id: dbUser.id,
+ name: dbUser.name,
+ email: dbUser.email,
+ image: dbUser.image,
+ emailVerified: dbUser.emailVerified,
+ featureFlags: parseFlags(dbUser.featureFlags),
+ projects: [],
+ };
+
+ return userObj;
+ },
+ }),
+];
+
+if (env.AUTH_GOOGLE_CLIENT_ID && env.AUTH_GOOGLE_CLIENT_SECRET)
+ providers.push(
+ GoogleProvider({
+ clientId: env.AUTH_GOOGLE_CLIENT_ID,
+ clientSecret: env.AUTH_GOOGLE_CLIENT_SECRET,
+ allowDangerousEmailAccountLinking: true,
+ }),
+ );
+
+if (env.AUTH_GITHUB_CLIENT_ID && env.AUTH_GITHUB_CLIENT_SECRET)
+ providers.push(
+ GitHubProvider({
+ clientId: env.AUTH_GITHUB_CLIENT_ID,
+ clientSecret: env.AUTH_GITHUB_CLIENT_SECRET,
+ allowDangerousEmailAccountLinking: true,
+ }),
+ );
+
/**
* Options for NextAuth.js used to configure adapters, providers, callbacks, etc.
*
@@ -87,63 +154,7 @@ export const authOptions: NextAuthOptions = {
},
},
adapter: PrismaAdapter(prisma),
- providers: [
- /**
- * ...add more providers here.
- *
- * Most other providers require a bit more work than the Discord provider. For example, the
- * GitHub provider requires you to add the `refresh_token_expires_in` field to the Account
- * model. Refer to the NextAuth.js docs for the provider you want to use. Example:
- *
- * @see https://next-auth.js.org/providers/github
- */
- CredentialsProvider({
- // The name to display on the sign in form (e.g. "Sign in with...")
- name: "credentials",
- // `credentials` is used to generate a form on the sign in page.
- // You can specify which fields should be submitted, by adding keys to the `credentials` object.
- // e.g. domain, username, password, 2FA token, etc.
- // You can pass any HTML attribute to the <input> tag through the object.
- credentials: {
- email: {
- label: "Email",
- type: "email",
- placeholder: "[email protected]",
- },
- password: { label: "Password", type: "password" },
- },
- async authorize(credentials, _req) {
- if (!credentials) throw new Error("No credentials");
-
- const dbUser = await prisma.user.findUnique({
- where: {
- email: credentials.email.toLowerCase(),
- },
- });
-
- if (!dbUser) throw new Error("Invalid credentials");
- if (dbUser.password === null) throw new Error("Invalid credentials");
-
- const isValidPassword = await verifyPassword(
- credentials.password,
- dbUser.password,
- );
- if (!isValidPassword) throw new Error("Invalid credentials");
-
- const userObj: User = {
- id: dbUser.id,
- name: dbUser.name,
- email: dbUser.email,
- image: dbUser.image,
- emailVerified: dbUser.emailVerified,
- featureFlags: parseFlags(dbUser.featureFlags),
- projects: [],
- };
-
- return userObj;
- },
- }),
- ],
+ providers,
pages: {
signIn: "/auth/sign-in",
},
@@ -173,6 +184,31 @@ export const authOptions: NextAuthOptions = {
options: cookieOptions,
},
},
+ events: {
+ createUser: async (message) => {
+ const { user } = message;
+ console.log("Sending new user signup webhook");
+ console.log(user);
+ if (
+ env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK &&
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
+ ) {
+ await fetch(env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK, {
+ method: "POST",
+ body: JSON.stringify({
+ name: user.name,
+ email: user.email,
+ cloudRegion: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
+ userId: user.id,
+ // referralSource: ...
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+ },
+ },
};
/**