Skip to content

OpenStock is an open-source alternative to expensive market platforms. Track real-time prices, set personalized alerts, and explore detailed company insights — built openly, for everyone, forever free.

feat(auth): Google/GitHub sign-in, working password reset, saved onboarding fields

ravixalgorithm2f9385d4c6e8
diff --git a/__tests__/reset-password-email.test.ts b/__tests__/reset-password-email.test.ts
index e629e76..6066bc4 100644
--- a/__tests__/reset-password-email.test.ts
+++ b/__tests__/reset-password-email.test.ts
@@ -43,6 +43,16 @@ describe('sendPasswordResetEmail', () => {
expect(mailOptions.text).toContain('https://example.com/reset-password?token=a%20b&next=%3Cscript%3E');
});
+ it('keeps the already-encoded callbackURL from Better Auth intact', async () => {
+ const resetUrl = 'http://localhost:3000/api/auth/reset-password/abc123?callbackURL=http%3A%2F%2Flocalhost%3A3000%2Freset-password';
+ await sendPasswordResetEmail({ email: '[email protected]', name: 'User', resetUrl });
+
+ const [mailOptions] = sendMailMock.mock.calls[0];
+ expect(mailOptions.html).toContain(`href="${resetUrl}"`);
+ expect(mailOptions.text).toContain(resetUrl);
+ expect(mailOptions.html).not.toContain('%253A');
+ });
+
it('throws when reset email credentials are missing', async () => {
delete process.env.NODEMAILER_EMAIL;
delete process.env.NODEMAILER_PASSWORD;
diff --git a/app/(auth)/forgot-password/page.tsx b/app/(auth)/forgot-password/page.tsx
index 1c0f747..3a741f6 100644
--- a/app/(auth)/forgot-password/page.tsx
+++ b/app/(auth)/forgot-password/page.tsx
@@ -61,7 +61,7 @@ const ForgotPasswordPage = () => {
validation={{
required: 'Email is required',
pattern: {
- value: /^[\w-.]+@([\w-]+\.)+[\w-]{2,}$/,
+ value: /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/,
message: 'Please enter a valid email address',
},
}}
diff --git a/app/api/auth/[...all]/route.ts b/app/api/auth/[...all]/route.ts
new file mode 100644
index 0000000..08aacfd
--- /dev/null
+++ b/app/api/auth/[...all]/route.ts
@@ -0,0 +1,5 @@
+import { auth } from "@/lib/better-auth/auth";
+import { toNextJsHandler } from "better-auth/next-js";
+
+// Needed for OAuth callbacks (/api/auth/callback/google, /api/auth/callback/github)
+export const { GET, POST } = toNextJsHandler(auth);
diff --git a/components/forms/SocialAuthButtons.tsx b/components/forms/SocialAuthButtons.tsx
new file mode 100644
index 0000000..cfdae06
--- /dev/null
+++ b/components/forms/SocialAuthButtons.tsx
@@ -0,0 +1,62 @@
+'use client';
+
+import React, { useState } from "react";
+import { Github } from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { signInWithSocial } from "@/lib/actions/auth.actions";
+
+const GoogleIcon = () => (
+ <svg viewBox="0 0 24 24" aria-hidden="true" className="size-5">
+ <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.27-4.74 3.27-8.1z" />
+ <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.84A11 11 0 0 0 12 23z" />
+ <path fill="#FBBC05" d="M5.84 14.1a6.6 6.6 0 0 1 0-4.2V7.06H2.18a11 11 0 0 0 0 9.88l3.66-2.84z" />
+ <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15A10.96 10.96 0 0 0 12 1 11 11 0 0 0 2.18 7.06l3.66 2.84C6.71 7.31 9.14 5.38 12 5.38z" />
+ </svg>
+);
+
+const PROVIDERS = [
+ { id: 'google', label: 'Google', icon: <GoogleIcon /> },
+ { id: 'github', label: 'GitHub', icon: <Github className="size-5" /> },
+] as const;
+
+const SocialAuthButtons = () => {
+ const [pending, setPending] = useState<string | null>(null);
+
+ const onClick = async (provider: 'google' | 'github') => {
+ setPending(provider);
+ const result = await signInWithSocial(provider);
+ if (result.success && result.url) {
+ window.location.href = result.url;
+ return;
+ }
+ setPending(null);
+ toast.error('Sign in failed', { description: result.error });
+ }
+
+ return (
+ <div className="space-y-5 mb-5">
+ <div className="grid grid-cols-2 gap-3">
+ {PROVIDERS.map(({ id, label, icon }) => (
+ <Button
+ key={id}
+ type="button"
+ variant="outline"
+ disabled={pending !== null}
+ onClick={() => onClick(id)}
+ className="h-12 border-gray-600 text-gray-400 text-base rounded-lg cursor-pointer"
+ >
+ {icon}
+ {pending === id ? 'Redirecting' : label}
+ </Button>
+ ))}
+ </div>
+ <div className="flex items-center gap-3 text-sm text-gray-500">
+ <span className="h-px flex-1 bg-gray-600" />
+ or
+ <span className="h-px flex-1 bg-gray-600" />
+ </div>
+ </div>
+ );
+};
+export default SocialAuthButtons;
diff --git a/lib/actions/auth.actions.ts b/lib/actions/auth.actions.ts
index 220c831..edb79aa 100644
--- a/lib/actions/auth.actions.ts
+++ b/lib/actions/auth.actions.ts
@@ -6,7 +6,7 @@ import { headers } from "next/headers";
export const signUpWithEmail = async ({ email, password, fullName, country, investmentGoals, riskTolerance, preferredIndustry }: SignUpFormData) => {
try {
- const response = await auth.api.signUpEmail({ body: { email, password, name: fullName } })
+ const response = await auth.api.signUpEmail({ body: { email, password, name: fullName, country, investmentGoals, riskTolerance, preferredIndustry } })
if (response) {
try {
@@ -58,7 +58,19 @@ export const signInWithEmail = async ({ email, password }: SignInFormData) => {
}
}
-export const requestPasswordResetEmail = async ({ email }: { email: string }) => {
+export const signInWithSocial = async (provider: 'google' | 'github') => {
+ try {
+ const { url } = await auth.api.signInSocial({
+ body: { provider, callbackURL: '/dashboard', errorCallbackURL: '/sign-in' },
+ });
+ return { success: true, url }
+ } catch (e) {
+ console.log('Social sign in failed', e)
+ return { success: false, error: `${provider === 'google' ? 'Google' : 'GitHub'} sign in is not available right now.` }
+ }
+}
+
+export const requestPasswordResetEmail =async ({ email }: { email: string }) => {
if (!process.env.NODEMAILER_EMAIL || !process.env.NODEMAILER_PASSWORD) {
return { success: false, error: 'Password reset email is not configured.' }
}
diff --git a/lib/better-auth/auth.ts b/lib/better-auth/auth.ts
index ff7f1d2..713e74e 100644
--- a/lib/better-auth/auth.ts
+++ b/lib/better-auth/auth.ts
@@ -2,29 +2,27 @@ import { betterAuth } from "better-auth";
import {mongodbAdapter} from "better-auth/adapters/mongodb";
import {connectToDatabase} from "@/database/mongoose";
import {nextCookies} from "better-auth/next-js";
+import { headers } from "next/headers";
+import { cache } from "react";
import { sendPasswordResetEmail } from "@/lib/nodemailer/reset-password";
-let authInstance: ReturnType<typeof betterAuth> | null = null;
+type MongoDb = Parameters<typeof mongodbAdapter>[0];
-
-export const getAuth = async () => {
- if(authInstance) {
- return authInstance;
- }
-
- const mongoose = await connectToDatabase();
- const db = mongoose.connection;
- const database = db.db;
-
- if (!db || !database) {
- throw new Error("MongoDB connection not found!");
- }
-
- authInstance = betterAuth({
+// Typed from the real config, so additional user fields (country, ...) show up in session types
+const createAuth = (database: MongoDb) => betterAuth({
database: mongodbAdapter(database),
secret: process.env.BETTER_AUTH_SECRET,
baseURL: process.env.BETTER_AUTH_URL,
+ // Onboarding answers live on the user so the profile page can show and edit them
+ user: {
+ additionalFields: {
+ country: { type: "string", required: false },
+ investmentGoals: { type: "string", required: false },
+ riskTolerance: { type: "string", required: false },
+ preferredIndustry: { type: "string", required: false },
+ },
+ },
emailAndPassword: {
enabled: true,
disableSignUp: false,
@@ -42,11 +40,50 @@ export const getAuth = async () => {
});
},
},
+ // Signed session cookie for 5 min: pages stop paying a MongoDB round trip per request.
+ // Trade-off: a revoked session can stay valid for up to 5 minutes.
+ session: {
+ cookieCache: { enabled: true, maxAge: 5 * 60 },
+ },
+ // Providers stay disabled until their env vars are set
+ socialProviders: {
+ google: {
+ enabled: !!process.env.GOOGLE_CLIENT_ID,
+ clientId: process.env.GOOGLE_CLIENT_ID as string,
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
+ },
+ github: {
+ enabled: !!process.env.GITHUB_CLIENT_ID,
+ clientId: process.env.GITHUB_CLIENT_ID as string,
+ clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
+ },
+ },
plugins: [nextCookies()],
+});
+
+let authInstance: ReturnType<typeof createAuth> | null = null;
+
+export const getAuth = async () => {
+ if (authInstance) return authInstance;
- });
+ const mongoose = await connectToDatabase();
+ const database = mongoose.connection.db;
+ if (!database) {
+ throw new Error("MongoDB connection not found!");
+ }
+ authInstance = createAuth(database);
return authInstance;
}
export const auth = await getAuth();
+
+// One session lookup per request, shared by layouts, pages and actions
+export const getSession = cache(async () => auth.api.getSession({ headers: await headers() }));
+
+// Server actions are public endpoints: never trust a userId sent from the client.
+export const requireUserId = async () => {
+ const session = await getSession();
+ if (!session?.user) throw new Error("Unauthorized");
+ return session.user.id;
+}
diff --git a/lib/nodemailer/reset-password.ts b/lib/nodemailer/reset-password.ts
index 309cdb1..786eaa5 100644
--- a/lib/nodemailer/reset-password.ts
+++ b/lib/nodemailer/reset-password.ts
@@ -8,6 +8,12 @@ const escapeHtml = (value: string) =>
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
+// Better Auth hands us an already-encoded URL (callbackURL=http%3A%2F%2F...).
+// encodeURI would turn those % into %25 and the link fails with INVALID_CALLBACKURL,
+// so only encode characters that are unsafe and leave existing escapes alone.
+const encodeUnsafeUrlChars = (url: string) =>
+ url.replace(/[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]/g, encodeURIComponent);
+
export const sendPasswordResetEmail = async (
{ email, name, resetUrl }: { email: string; name?: string | null; resetUrl: string }
) => {
@@ -18,7 +24,7 @@ export const sendPasswordResetEmail = async (
const firstName = name?.trim().split(' ')[0] || 'there';
const escapedFirstName = escapeHtml(firstName);
- const escapedResetUrl = escapeHtml(encodeURI(resetUrl));
+ const escapedResetUrl = escapeHtml(encodeUnsafeUrlChars(resetUrl));
const html = `
<div style="background:#000;padding:32px;font-family:Arial,sans-serif;color:#fff;">
<div style="max-width:560px;margin:0 auto;border:1px solid #333;border-radius:12px;padding:32px;background:#111;">
@@ -44,7 +50,7 @@ export const sendPasswordResetEmail = async (
from: `"Openstock" <${process.env.NODEMAILER_EMAIL}>`,
to: email,
subject: 'Reset your Openstock password',
- text: `Reset your password: ${encodeURI(resetUrl)}`,
+ text: `Reset your password: ${encodeUnsafeUrlChars(resetUrl)}`,
html,
});
diff --git a/scripts/check-env.mjs b/scripts/check-env.mjs
index 6282e30..f029ffe 100644
--- a/scripts/check-env.mjs
+++ b/scripts/check-env.mjs
@@ -59,6 +59,16 @@ const optionalVars = {
'KIT_API_KEY': 'ConvertKit API key (for news summary broadcasts)',
'KIT_API_SECRET': 'ConvertKit API secret (for news summary broadcasts)',
+ // Market data freshness + key pool
+ 'FINNHUB_API_KEYS': 'Comma-separated Finnhub keys, rotated per request (each adds 60 req/min). Falls back to NEXT_PUBLIC_FINNHUB_API_KEY',
+ 'NEXT_PUBLIC_OPENSTOCK_DATA_MODE': '"cached" (default: quotes refresh hourly, shared by everyone) or "realtime" (every 15s; OpenStock Cloud / self-hosted)',
+
+ // Social sign-in (Better Auth)
+ 'GOOGLE_CLIENT_ID': 'Google OAuth client ID (callback: <BETTER_AUTH_URL>/api/auth/callback/google)',
+ 'GOOGLE_CLIENT_SECRET': 'Google OAuth client secret',
+ 'GITHUB_CLIENT_ID': 'GitHub OAuth app client ID (callback: <BETTER_AUTH_URL>/api/auth/callback/github)',
+ 'GITHUB_CLIENT_SECRET': 'GitHub OAuth app client secret',
+
// AI Provider selection (defaults to "gemini")
'AI_PROVIDER': 'AI provider: "gemini" | "minimax" | "siray" (default: "gemini")',
};