Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: implement social logins google and github (#819)

Aman Agarwal885ee9007178
diff --git a/docker-compose.yml b/docker-compose.yml
index 32ebd268..9418e519 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -26,6 +26,15 @@ services:
SQLITE_DATABASE_URL: file:/app/client/data/data.db
PORT: ${PORT:-3000}
DOCKER_PORT: ${PORT:-3000}
+ # OAuth Environment Variables
+ GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}
+ GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}
+ GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}
+ GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}
+
+ env_file:
+ - path: .env
+ required: false
ports:
- "${PORT:-3000}:${DOCKER_PORT:-3000}"
depends_on:
diff --git a/docs/latest/oauth-authentication.mdx b/docs/latest/oauth-authentication.mdx
new file mode 100644
index 00000000..f4c2f6cb
--- /dev/null
+++ b/docs/latest/oauth-authentication.mdx
@@ -0,0 +1,237 @@
+---
+title: 'OAuth Authentication Setup'
+description: 'Configure Google and GitHub OAuth authentication for OpenLIT using NextAuth.js'
+icon: 'shield-check'
+---
+
+This guide walks you through setting up OAuth authentication with Google and GitHub providers in OpenLIT using [NextAuth.js](https://next-auth.js.org/).
+
+## Overview
+
+OpenLIT supports OAuth authentication through NextAuth.js with these providers:
+- **Google OAuth** - Sign in with Google accounts
+- **GitHub OAuth** - Sign in with GitHub accounts
+- **Email/Password** - Traditional credentials-based authentication
+
+NextAuth.js automatically handles:
+- OAuth 2.0 authorization flow
+- Token management and refresh
+- User session management
+- Security best practices
+
+When users sign in via OAuth, OpenLIT automatically:
+- Creates new user accounts if they don't exist
+- Links OAuth accounts to existing email-based accounts
+- Syncs profile information (name, profile picture)
+- Runs user setup and database configuration
+
+## Google OAuth Setup
+
+### 1. Create Google Cloud Project
+
+<Steps>
+ <Step title="Access Google API Console">
+ Visit the [Google API Console](https://console.cloud.google.com/) to create OAuth 2.0 credentials.
+ </Step>
+
+ <Step title="Create or Select Project">
+ - Click on the project dropdown at the top
+ - Click "New Project" or select an existing project
+ - Give your project a meaningful name like "OpenLIT Authentication"
+ </Step>
+
+ <Step title="Enable Required APIs">
+ - Navigate to "APIs & Services" > "Library"
+ - Search for and enable "Google+ API" or "People API"
+ - This allows access to user profile information
+ </Step>
+</Steps>
+
+### 2. Configure OAuth Consent Screen
+
+<Steps>
+ <Step title="Setup Consent Screen">
+ - Navigate to "APIs & Services" > "OAuth consent screen"
+ - Choose "External" for user type (unless you have Google Workspace)
+ - Fill in required information:
+ - **App name**: OpenLIT
+ - **User support email**: Your email address
+ - **Developer contact information**: Your email address
+ </Step>
+
+ <Step title="Add Test Users (Development)">
+ - For testing, add email addresses that can access your app
+ - Production apps will be available to all users once published
+ </Step>
+</Steps>
+
+### 3. Create OAuth Credentials
+
+<Steps>
+ <Step title="Create Web Application Credentials">
+ - Navigate to "APIs & Services" > "Credentials"
+ - Click "Create Credentials" > "OAuth client ID"
+ - Select "Web application"
+ </Step>
+
+ <Step title="Configure Redirect URIs">
+ As per [NextAuth.js Google provider documentation](https://next-auth.js.org/providers/google):
+
+ - **Authorized JavaScript origins**:
+ ```
+ http://localhost:3000
+ https://yourdomain.com
+ ```
+ - **Authorized redirect URIs**:
+ ```
+ http://localhost:3000/api/auth/callback/google
+ https://yourdomain.com/api/auth/callback/google
+ ```
+
+ <Warning>
+ The redirect URIs must match exactly, including the port number (3000 in your case).
+ </Warning>
+ </Step>
+
+ <Step title="Save Credentials">
+ - Click "Create"
+ - Copy the **Client ID** and **Client Secret**
+ - Store them securely for environment configuration
+ </Step>
+</Steps>
+
+## GitHub OAuth Setup
+
+### 1. Create GitHub OAuth App
+
+<Steps>
+ <Step title="Access GitHub Developer Settings">
+ Go to [GitHub Settings](https://github.com/settings/apps) > Developer settings > OAuth Apps
+ </Step>
+
+ <Step title="Register New OAuth Application">
+ Click "New OAuth App" and configure:
+ - **Application name**: OpenLIT
+ - **Homepage URL**: `http://localhost:3000` (development) or `https://yourdomain.com` (production)
+ - **Authorization callback URL**:
+ ```
+ http://localhost:3000/api/auth/callback/github
+ ```
+
+ <Note>
+ As per [NextAuth.js GitHub provider documentation](https://next-auth.js.org/providers/github), GitHub only allows one callback URL per Client ID/Secret.
+ </Note>
+ </Step>
+
+ <Step title="Generate Client Secret">
+ - Click "Register application"
+ - Copy the **Client ID**
+ - Click "Generate a new client secret"
+ - Copy the **Client Secret** immediately (it won't be shown again)
+ </Step>
+</Steps>
+
+### 2. GitHub App Permissions (Optional)
+
+<Note>
+If creating a GitHub App instead of OAuth App, set "Email addresses" permission to read-only to access private email addresses as mentioned in the [NextAuth.js documentation](https://next-auth.js.org/providers/github).
+</Note>
+
+## Environment Configuration
+
+```.env.production
+# NextAuth Configuration
+NEXTAUTH_URL=https://yourdomain.com
+NEXTAUTH_SECRET=your-production-secret
+
+# Google OAuth
+GOOGLE_CLIENT_ID=your-google-client-id
+GOOGLE_CLIENT_SECRET=your-google-client-secret
+
+# GitHub OAuth
+GITHUB_CLIENT_ID=your-github-client-id
+GITHUB_CLIENT_SECRET=your-github-client-secret
+```
+
+### Production Setup
+
+<Steps>
+ <Step title="Update OAuth App URLs">
+ Update both Google and GitHub OAuth apps with production URLs:
+ - **Google**: Add `https://yourdomain.com` to origins and `https://yourdomain.com/api/auth/callback/google` to redirect URIs
+ - **GitHub**: Update callback URL to `https://yourdomain.com/api/auth/callback/github`
+ </Step>
+
+ <Step title="HTTPS Requirement">
+ Ensure your production domain has a valid SSL certificate. OAuth providers require HTTPS in production.
+ </Step>
+</Steps>
+
+## Features & Behavior
+
+### User Management
+
+- **New Users**: Automatically created when signing in via OAuth for the first time
+- **Existing Users**: OAuth accounts are linked to existing email-based accounts
+- **Profile Sync**: Name and profile picture are synced from OAuth providers
+- **Database Setup**: New users get proper database configurations and permissions
+
+### Session Management
+
+NextAuth.js handles all session management including:
+- JWT token creation and validation
+- Session persistence across browser sessions
+- Automatic token refresh when needed
+- Secure cookie configuration
+
+## Troubleshooting
+
+### Common Issues
+
+<AccordionGroup>
+ <Accordion title="OAuth button not appearing">
+ **Solutions**:
+ - Check that environment variables are set correctly
+ - Ensure `.env` file is in the correct directory (`src/client/`) for development
+ - You can create a `.env` file to in the same directory as the `docker-compose.yml` file with the creds
+ </Accordion>
+
+ <Accordion title="Redirect URI mismatch error">
+ **Solutions**:
+ - Verify redirect URIs match exactly in OAuth app settings
+ - Check port numbers (3001 vs 3000)
+ - Ensure protocol matches (http/https)
+ </Accordion>
+
+ <Accordion title="Invalid client error">
+ **Solutions**:
+ - Verify client credentials are copied correctly
+ - Check for extra spaces or characters in environment variables
+ - Ensure you're using credentials from the correct OAuth app
+ </Accordion>
+
+ <Accordion title="NEXTAUTH_URL mismatch">
+ **Solutions**:
+ - Set `NEXTAUTH_URL=http://localhost:3000` for development
+ - Set `NEXTAUTH_URL=https://yourdomain.com` for production
+ - Ensure the URL matches your actual application URL
+ </Accordion>
+</AccordionGroup>
+
+## Useful Links
+
+- [NextAuth.js Google Provider](https://next-auth.js.org/providers/google)
+- [NextAuth.js GitHub Provider](https://next-auth.js.org/providers/github)
+- [Google API Console](https://console.cloud.google.com/)
+- [GitHub Developer Settings](https://github.com/settings/apps)
+
+---
+
+<CardGroup cols={2}>
+<Card title="Integrations" href="/latest/integrations/introduction" icon='circle-nodes'>
+Integrate your LLM Stack with OpenLIT
+</Card>
+<Card title="Connections" href="/latest/connections/intro" icon='link'>
+Connect to your existing Observablity Stack
+</Card>
+</CardGroup>
\ No newline at end of file
diff --git a/docs/latest/ui-configuration.mdx b/docs/latest/ui-configuration.mdx
index 62269de0..fb9f47d6 100644
--- a/docs/latest/ui-configuration.mdx
+++ b/docs/latest/ui-configuration.mdx
@@ -6,7 +6,7 @@ icon: 'sliders'
This guide covers all the available environment variables to fine-tune OpenLIT according to your needs.
-## Environment Varibales
+## Environment Variables
<ResponseField name="INIT_DB_HOST" required>
Sets the host address of the ClickHouse server for OpenLIT to connect
@@ -62,24 +62,134 @@ This guide covers all the available environment variables to fine-tune OpenLIT a
```
</ResponseField>
+## OAuth Authentication Variables
+
+<Note>
+For detailed OAuth setup instructions, see the [OAuth Authentication Setup](/latest/oauth-authentication) guide.
+</Note>
+
+<ResponseField name="NEXTAUTH_URL">
+ Sets the canonical URL of your site for NextAuth.js authentication
+
+ **Example**:
+ ```yaml
+ export NEXTAUTH_URL=http://localhost:3000
+ ```
+</ResponseField>
+
+<ResponseField name="NEXTAUTH_SECRET">
+ Used to encrypt the NextAuth.js JWT tokens and email verification hashes
+
+ **Example**:
+ ```yaml
+ export NEXTAUTH_SECRET=your-secret-here
+ ```
+
+ **Generate with**: `openssl rand -base64 32`
+</ResponseField>
+
+<ResponseField name="GOOGLE_CLIENT_ID">
+ Google OAuth client ID for Google sign-in integration
+
+ **Example**:
+ ```yaml
+ export GOOGLE_CLIENT_ID=your-google-client-id
+ ```
+</ResponseField>
+
+<ResponseField name="GOOGLE_CLIENT_SECRET">
+ Google OAuth client secret for Google sign-in integration
+
+ **Example**:
+ ```yaml
+ export GOOGLE_CLIENT_SECRET=your-google-client-secret
+ ```
+</ResponseField>
+
+<ResponseField name="GITHUB_CLIENT_ID">
+ GitHub OAuth client ID for GitHub sign-in integration
+
+ **Example**:
+ ```yaml
+ export GITHUB_CLIENT_ID=your-github-client-id
+ ```
+</ResponseField>
+
+<ResponseField name="GITHUB_CLIENT_SECRET">
+ GitHub OAuth client secret for GitHub sign-in integration
+
+ **Example**:
+ ```yaml
+ export GITHUB_CLIENT_SECRET=your-github-client-secret
+ ```
+</ResponseField>
+
+## Environment File Placement
+
+Environment variables can be configured in multiple ways depending on your deployment method:
+
+### Development Setup
+
+<Steps>
+ <Step title="Client-side .env">
+ Create a `.env` file in the `src/client/` directory for development:
+ ```bash
+ src/client/.env
+ ```
+ This file is automatically loaded by Next.js during development.
+ </Step>
+
+ <Step title="Docker Compose .env">
+ Create a `.env` file in the same directory as your `docker-compose.yml` file:
+ ```bash
+ # In the root directory with docker-compose.yml
+ .env
+ ```
+ This file is automatically loaded by Docker Compose.
+ </Step>
+
+ <Step title="Development Docker Compose .env">
+ For development Docker setup, create a `.env` file alongside `src/dev-docker-compose.yml`:
+ ```bash
+ # In the src/ directory with dev-docker-compose.yml
+ src/.env
+ ```
+ </Step>
+</Steps>
+
+### Production Setup
+
+For production deployments, set environment variables directly in your hosting platform or container orchestration system (Kubernetes, Docker Swarm, etc.).
+
## Sample Environment File (.env)
```.env.example .env
+# Database Configuration
INIT_DB_HOST="127.0.0.1"
INIT_DB_PORT="8123"
INIT_DB_DATABASE="default"
INIT_DB_USERNAME="default"
INIT_DB_PASSWORD="OPENLIT"
SQLITE_DATABASE_URL="file:/app/client/data/data.db"
+
+# NextAuth Configuration (Optional)
+NEXTAUTH_URL="http://localhost:3000"
+NEXTAUTH_SECRET="your-secret-here"
+
+# OAuth Providers (Optional)
+GOOGLE_CLIENT_ID="your-google-client-id"
+GOOGLE_CLIENT_SECRET="your-google-client-secret"
+GITHUB_CLIENT_ID="your-github-client-id"
+GITHUB_CLIENT_SECRET="your-github-client-secret"
```
---
<CardGroup cols={2}>
+<Card title="OAuth Authentication" href="/latest/oauth-authentication" icon='shield-check'>
+Setup Google and GitHub sign-in
+</Card>
<Card title="Integrations" href="/latest/integrations/introduction" icon='circle-nodes'>
Integrate your LLM Stack with OpenLIT
</Card>
-<Card title="Connections" href="/latest/connections/intro" icon='link'>
-Connect to your existing Observablity Stack
-</Card>
</CardGroup>
\ No newline at end of file
diff --git a/docs/mint.json b/docs/mint.json
index 914ee7fb..91d6bf5d 100644
--- a/docs/mint.json
+++ b/docs/mint.json
@@ -54,7 +54,8 @@
"latest/quickstart-guard",
"latest/installation",
"latest/sdk-configuration",
- "latest/ui-configuration"
+ "latest/ui-configuration",
+ "latest/oauth-authentication"
],
"version": "latest"
},
diff --git a/src/client/.env.example b/src/client/.env.example
index 3a94747e..69aa0028 100644
--- a/src/client/.env.example
+++ b/src/client/.env.example
@@ -1,5 +1,8 @@
-# GOOGLE_CLIENT_ID=
-# GOOGLE_CLIENT_SECRET=
+GOOGLE_CLIENT_ID=
+GOOGLE_CLIENT_SECRET=
+
+GITHUB_CLIENT_ID=
+GITHUB_CLIENT_SECRET=
# Generate NEXTAUTH_SECRET by running command : `openssl rand -base64 32` on your terminal
diff --git a/src/client/package-lock.json b/src/client/package-lock.json
index e7c70fd7..27b3d909 100644
--- a/src/client/package-lock.json
+++ b/src/client/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "openlit",
- "version": "1.14.3",
+ "version": "1.14.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openlit",
- "version": "1.14.3",
+ "version": "1.14.4",
"dependencies": {
"@anthropic-ai/sdk": "^0.21.1",
"@clickhouse/client": "^1.1.0",
diff --git a/src/client/package.json b/src/client/package.json
index d50f4d69..2e94fa3b 100644
--- a/src/client/package.json
+++ b/src/client/package.json
@@ -1,6 +1,6 @@
{
"name": "openlit",
- "version": "1.14.3",
+ "version": "1.14.4",
"private": true,
"scripts": {
"dev": "next dev",
diff --git a/src/client/src/app/auth.ts b/src/client/src/app/auth.ts
index e9bdef6d..2eb5e13e 100644
--- a/src/client/src/app/auth.ts
+++ b/src/client/src/app/auth.ts
@@ -1,5 +1,6 @@
import NextAuth, { AuthOptions } from "next-auth";
-// import GoogleProvider from "next-auth/providers/google";
+import GoogleProvider from "next-auth/providers/google";
+import GithubProvider from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
@@ -17,7 +18,7 @@ const prisma = new PrismaClient();
export const authOptions = {
adapter: PrismaAdapter(prisma),
callbacks: {
- async jwt({ token, account, user, ...rest }) {
+ async jwt({ token, account, user }) {
// Persist the OAuth access_token and or the user id to the token right after signin
if (account) {
token.accessToken = account.access_token;
@@ -34,7 +35,7 @@ export const authOptions = {
const [, existingUser] = await asaw(
getUserById({ id: token.id as string })
);
-
+
// If user doesn't exist in database, invalidate the token
if (!existingUser) {
return null;
@@ -53,24 +54,76 @@ export const authOptions = {
if (!user.email) {
return false;
}
- if (account?.provider === "google") {
+
+ // For Google provider, handle account linking
+ if (account?.provider === "google" || account?.provider === "github") {
const [, existingUser] = await asaw(
getUserByEmail({ email: user.email })
);
- // if the user already exists via email,
- // update the user with their name and image from Google
- if (existingUser && !existingUser.name) {
- await asaw(
- updateUser({
- where: { email: user.email },
- data: {
- name: profile?.name,
+
+ // If user exists but doesn't have Google account linked
+ if (existingUser) {
+ try {
+ // Check if Provider's account is already linked
+ const existingAccount = await prisma.account.findFirst({
+ where: {
+ userId: existingUser.id,
+ provider: account?.provider
+ }
+ });
+
+ // If Provider's account not linked, link it manually
+ if (!existingAccount) {
+ await prisma.account.create({
+ data: {
+ userId: existingUser.id,
+ type: account.type,
+ provider: account.provider,
+ providerAccountId: account.providerAccountId,
+ access_token: account.access_token,
+ expires_at: account.expires_at,
+ id_token: account.id_token,
+ refresh_token: account.refresh_token,
+ scope: account.scope,
+ token_type: account.token_type,
+ }
+ });
+ }
+
+ // Update user info if name/image is missing
+ if (!existingUser.name || !existingUser.image) {
+ const updateData: { name?: string; image?: string } = {};
+
+ // Handle different profile structures for different providers
+ if (account.provider === "google") {
+ updateData.name = profile?.name || existingUser.name;
// @ts-ignore - this is a bug in the types, `picture` is a valid on the `Profile` type
- image: profile?.picture,
- },
- })
- );
+ updateData.image = profile?.picture || existingUser.image;
+ } else if (account.provider === "github") {
+ // @ts-ignore - this is a bug in the types, `login` is a valid on the `Profile` type
+ updateData.name = profile?.name || profile?.login || existingUser.name;
+ // @ts-ignore - this is a bug in the types, `avatar_url` is a valid on the `Profile` type
+ updateData.image = profile?.avatar_url || existingUser.image;
+ }
+
+ if (Object.keys(updateData).length > 0) {
+ await asaw(
+ updateUser({
+ where: { email: user.email },
+ data: updateData
+ })
+ );
+ }
+ }
+
+ // Set the user ID to the existing user
+ user.id = existingUser.id;
+ } catch (error) {
+ console.error(`Error linking ${account.provider} account:`, error);
+ return false;
+ }
}
+ return true;
}
return true;
@@ -84,11 +137,36 @@ export const authOptions = {
return session;
},
},
+ events: {
+ async createUser({ user }) {
+ // Run custom setup for new users
+ if (user.email && user.id) {
+ try {
+ const { moveSharedDBConfigToDBUser } = await import("@/lib/db-config");
+ await moveSharedDBConfigToDBUser(user.email, user.id);
+ } catch (error) {
+ console.error("Error moving shared db configs to new user:", error);
+ }
+ }
+ }
+ },
providers: [
- // GoogleProvider({
- // clientId: process.env.GOOGLE_CLIENT_ID || "",
- // clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
- // }),
+ ...(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET
+ ? [
+ GoogleProvider({
+ clientId: process.env.GOOGLE_CLIENT_ID,
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET,
+ }),
+ ]
+ : []),
+ ...(process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET
+ ? [
+ GithubProvider({
+ clientId: process.env.GITHUB_CLIENT_ID,
+ clientSecret: process.env.GITHUB_CLIENT_SECRET,
+ }),
+ ]
+ : []),
CredentialsProvider({
id: "login",
name: "Credentials Login",
@@ -143,10 +221,11 @@ export const authOptions = {
pages: {
signIn: "/login",
newUser: "/register",
+ error: "/login", // Redirect errors back to login page
},
session: { strategy: "jwt" },
} as AuthOptions;
const handler = NextAuth(authOptions);
-export { handler as GET, handler as POST };
+export { handler as GET, handler as POST };
\ No newline at end of file
diff --git a/src/client/src/components/(auth)/auth-form.tsx b/src/client/src/components/(auth)/auth-form.tsx
index 0176d11f..13e33990 100644
--- a/src/client/src/components/(auth)/auth-form.tsx
+++ b/src/client/src/components/(auth)/auth-form.tsx
@@ -1,10 +1,10 @@
"use client";
import { DEFAULT_LOGGED_IN_ROUTE } from "@/constants/route";
import asaw from "@/utils/asaw";
-import { signIn } from "next-auth/react";
+import { getProviders, signIn } from "next-auth/react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -25,12 +25,15 @@ const errors = {
EmailSignin: "Check your email address.",
CredentialsSignin:
"Sign in failed. Check the details you provided are correct.",
+ Configuration: "There is a problem with the server configuration.",
default: "Unable to sign in.",
};
-const SignInError = ({ error }: { error: keyof typeof errors }) => {
- const errorMessage = error && (errors[error] ?? errors.default);
- return <div className="text-xs text-red-600 text-center">{errorMessage}</div>;
+const SignInError = ({ error }: { error: string }) => {
+ if (!error || error === "undefined") return null;
+
+ const errorMessage = errors[error as keyof typeof errors] ?? error ?? errors.default;
+ return <div className="text-xs text-red-600 text-center bg-red-50 p-3 rounded-md">{errorMessage}</div>;
};
export function AuthForm({ type }: { type: "login" | "register" }) {
@@ -38,7 +41,22 @@ export function AuthForm({ type }: { type: "login" | "register" }) {
const searchParams = useSearchParams();
const callbackUrl: string =
(searchParams.get("callbackUrl") as string) || DEFAULT_LOGGED_IN_ROUTE;
- const [error, setError] = useState<string>("");
+ const errorType: string = (searchParams.get("error") as string);
+ const [error, setError] = useState<string>(errorType || "");
+ const [isGoogleLoading, setIsGoogleLoading] = useState(false);
+ const [isGithubLoading, setIsGithubLoading] = useState(false);
+ const [providers, setProviders] = useState<string[]>([]);
+
+ useEffect(() => {
+ const fetchProviders = async () => {
+ const res = await getProviders();
+ if (typeof res === "object" && res !== null) {
+ setProviders(Object.keys(res).filter(e => !["login", "register"].includes(e)));
+ }
+ };
+ fetchProviders();
+ }, []);
+
async function authWrapper(fn: any) {
const [err, response] = await asaw(fn());
@@ -57,6 +75,55 @@ export function AuthForm({ type }: { type: "login" | "register" }) {
);
window.location.replace(callbackUrl);
}
+
+ async function handleGoogleSignIn() {
+ setIsGoogleLoading(true);
+ setError("");
+
+ try {
+ // For Google OAuth, we need to allow natural redirects
+ const result = await signIn("google", {
+ callbackUrl,
+ redirect: false,
+ // Don't set redirect: false for OAuth providers
+ });
+
+ // If we reach here, there might be an error
+ if (result?.error) {
+ console.error("Google sign-in error:", result.error);
+ setError(result.error);
+ }
+ } catch (err) {
+ console.error("Google sign-in exception:", err);
+ setError("Failed to sign in with Google");
+ } finally {
+ setIsGoogleLoading(false);
+ }
+ }
+
+ async function handleGithubSignIn() {
+ setIsGithubLoading(true);
+ setError("");
+
+ try {
+ const result = await signIn("github", {
+ callbackUrl,
+ redirect: false,
+ });
+
+ // If we reach here, there might be an error
+ if (result?.error) {
+ console.error("Github sign-in error:", result.error);
+ setError(result.error);
+ }
+ } catch (err) {
+ console.error("Github sign-in exception:", err);
+ setError("Failed to sign in with Github");
+ } finally {
+ setIsGithubLoading(false);
+ }
+ }
+
async function login(formData: FormData) {
authWrapper(() =>
signIn("login", {
@@ -83,7 +150,91 @@ export function AuthForm({ type }: { type: "login" | "register" }) {
<div className="mx-auto grid gap-6 w-[350px] text-stone-900">
<div className="grid gap-2 text-center">
</div>
- {error && <SignInError error={error as keyof typeof errors} />}
+ {error && <SignInError error={error} />}
+
+ {/* Google Sign-in Button */}
+ {providers.includes("google") && (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={handleGoogleSignIn}
+ disabled={isGoogleLoading}
+ className="w-full bg-white dark:bg-white text-stone-900 dark:text-stone-900 border-stone-200 dark:border-stone-200 hover:bg-stone-50 dark:hover:bg-stone-50 rounded-full hover:bg-stone-50 dark:hover:bg-stone-50 dark:hover:text-stone-900 hover:text-stone-900"
+ >
+ {isGoogleLoading ? (
+ "Signing in..."
+ ) : (
+ <div className="flex items-center justify-center gap-2">
+ <svg
+ className="w-4 h-4"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ fill="#4285F4"
+ d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
+ />
+ <path
+ fill="#34A853"
+ d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
+ />
+ <path
+ fill="#FBBC05"
+ d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
+ />
+ <path
+ fill="#EA4335"
+ d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
+ />
+ </svg>
+ Continue with Google
+ </div>
+ )}
+ </Button>
+ )}
+
+ {providers.includes("github") && (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={handleGithubSignIn}
+ disabled={isGithubLoading}
+ className="w-full bg-white dark:bg-white text-stone-900 dark:text-stone-900 dark:hover:text-stone-900 border-stone-200 dark:border-stone-200 hover:bg-stone-50 dark:hover:bg-stone-50 rounded-full hover:bg-stone-50 dark:hover:bg-stone-50 hover:dark:bg-stone-50 hover:dark:text-stone-900 hover:text-stone-900"
+ >
+ {isGithubLoading ? (
+ "Signing in..."
+ ) : (
+ <div className="flex items-center justify-center gap-2">
+ <svg
+ className="w-4 h-4"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ fill="#181717"
+ d="M12 0C5.374 0 0 5.373 0 12c0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23A11.509 11.509 0 0112 5.803c1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576C20.566 21.797 24 17.3 24 12c0-6.627-5.373-12-12-12z"
+ />
+ </svg>
+ Continue with Github
+ </div>
+ )}
+ </Button>
+ )}
+
+ {/* Divider */}
+ {
+ providers.length > 0 && (
+ <div className="relative">
+ <div className="absolute inset-0 flex items-center">
+ <span className="w-full border-t border-stone-300" />
+ </div>
+ <div className="relative flex justify-center text-xs uppercase">
+ <span className="bg-white px-2 text-stone-500">Or</span>
+ </div>
+ </div>
+ )
+ }
+
<form
action={type === "login" ? login : register}
className="flex flex-col"
diff --git a/src/dev-docker-compose.yml b/src/dev-docker-compose.yml
index c76d40b2..90856b54 100644
--- a/src/dev-docker-compose.yml
+++ b/src/dev-docker-compose.yml
@@ -29,6 +29,15 @@ services:
SQLITE_DATABASE_URL: file:/app/client/data/data.db
PORT: ${PORT:-3000}
DOCKER_PORT: ${DOCKER_PORT:-3000}
+ # OAuth Environment Variables
+ GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}
+ GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}
+ GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}
+ GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}
+
+ env_file:
+ - path: .env
+ required: false
ports:
- "${PORT:-3000}:${DOCKER_PORT:-3000}"
depends_on: