feat: add headless email auth, account settings, and push notification cleanup
This commit is contained in:
parent
371c1e4618
commit
730ed1a76a
1
bun.lock
1
bun.lock
@ -31,6 +31,7 @@
|
||||
"styled-jsx": "^5.1.6",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"web-push": "^3.6.7",
|
||||
"yaml": "^2.8.2",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^4.20250121.0",
|
||||
|
||||
@ -40,9 +40,10 @@
|
||||
"react-day-picker": "^9.13.0",
|
||||
"react-dom": "19.2.3",
|
||||
"recharts": "^3.7.0",
|
||||
"styled-jsx": "^5.1.6",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"web-push": "^3.6.7",
|
||||
"styled-jsx": "^5.1.6"
|
||||
"yaml": "^2.8.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^4.20250121.0",
|
||||
|
||||
86
src/app/api/auth/email/route.ts
Normal file
86
src/app/api/auth/email/route.ts
Normal file
@ -0,0 +1,86 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { workos, clientId } from '@/lib/workos';
|
||||
import { setSession } from '@/lib/session';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json() as {
|
||||
email?: string;
|
||||
password?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
type?: 'signup' | 'login';
|
||||
stayLoggedIn?: boolean;
|
||||
};
|
||||
const { email, password, firstName, lastName, type, stayLoggedIn } = body;
|
||||
|
||||
if (!email || !password) {
|
||||
return NextResponse.json({ error: 'Email and password are required' }, { status: 400 });
|
||||
}
|
||||
|
||||
let user;
|
||||
|
||||
// Handle Signup
|
||||
if (type === 'signup') {
|
||||
try {
|
||||
await workos.userManagement.createUser({
|
||||
email,
|
||||
password,
|
||||
firstName,
|
||||
lastName,
|
||||
emailVerified: false, // WorkOS sends verification email automatically if configured
|
||||
});
|
||||
} catch (error: any) {
|
||||
// Handle user already exists
|
||||
if (error.code === 'user_already_exists') {
|
||||
return NextResponse.json({ error: 'A user with this email already exists.' }, { status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Authenticate (for both login and after signup)
|
||||
try {
|
||||
const response = await workos.userManagement.authenticateWithPassword({
|
||||
email,
|
||||
password,
|
||||
clientId,
|
||||
});
|
||||
|
||||
user = response.user;
|
||||
|
||||
// extensive logging to debug structure if needed
|
||||
// console.log('Auth response:', JSON.stringify(response, null, 2));
|
||||
|
||||
// Create session
|
||||
await setSession({
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
profilePictureUrl: user.profilePictureUrl,
|
||||
},
|
||||
accessToken: response.accessToken, // Note: SDK returns camelCase
|
||||
refreshToken: response.refreshToken,
|
||||
stayLoggedIn: !!stayLoggedIn,
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true, user });
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Authentication error:', error);
|
||||
|
||||
// Map WorkOS errors to user-friendly messages
|
||||
if (error.code === 'invalid_credentials' || error.message?.includes('Invalid credentials')) {
|
||||
return NextResponse.json({ error: 'Invalid email or password.' }, { status: 401 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: error.message || 'Authentication failed' }, { status: 400 });
|
||||
}
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Login API error:', error);
|
||||
return NextResponse.json({ error: 'An internal error occurred.' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@ -5,31 +5,48 @@ import { cookies } from 'next/headers';
|
||||
const VALID_PROVIDERS = ['GoogleOAuth', 'AppleOAuth', 'GitHubOAuth'];
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const provider = searchParams.get('provider') as OAuthProvider | 'authkit' | null;
|
||||
const stayLoggedIn = searchParams.get('stayLoggedIn') === 'true';
|
||||
try {
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const provider = searchParams.get('provider') as OAuthProvider | 'authkit' | null;
|
||||
const stayLoggedIn = searchParams.get('stayLoggedIn') === 'true';
|
||||
|
||||
// Store the stay logged in preference in a cookie
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set('stay_logged_in', stayLoggedIn.toString(), {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 60 * 10, // 10 minutes for the auth flow
|
||||
path: '/',
|
||||
});
|
||||
// Store the stay logged in preference in a cookie
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set('stay_logged_in', stayLoggedIn.toString(), {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 60 * 10, // 10 minutes for the auth flow
|
||||
path: '/',
|
||||
});
|
||||
|
||||
// If no provider or 'authkit', redirect to hosted AuthKit (email/password, phone)
|
||||
if (!provider || provider === 'authkit') {
|
||||
const authUrl = getAuthKitUrl();
|
||||
// If no provider or 'authkit', redirect to hosted AuthKit (email/password, phone)
|
||||
if (!provider || provider === 'authkit') {
|
||||
const authUrl = getAuthKitUrl();
|
||||
console.log('AuthKit URL generated:', authUrl);
|
||||
|
||||
if (!authUrl || typeof authUrl !== 'string') {
|
||||
return NextResponse.json({
|
||||
error: 'Failed to generate AuthKit URL',
|
||||
debug: { authUrl, hasClientId: !!process.env.WORKOS_CLIENT_ID, hasRedirectUri: !!process.env.WORKOS_REDIRECT_URI }
|
||||
}, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.redirect(authUrl);
|
||||
}
|
||||
|
||||
// Validate OAuth provider
|
||||
if (!VALID_PROVIDERS.includes(provider)) {
|
||||
return NextResponse.json({ error: 'Invalid provider' }, { status: 400 });
|
||||
}
|
||||
|
||||
const authUrl = getAuthorizationUrl(provider);
|
||||
return NextResponse.redirect(authUrl);
|
||||
} catch (error) {
|
||||
console.error('Login route error:', error);
|
||||
return NextResponse.json({
|
||||
error: 'Authentication error',
|
||||
message: String(error)
|
||||
}, { status: 500 });
|
||||
}
|
||||
|
||||
// Validate OAuth provider
|
||||
if (!VALID_PROVIDERS.includes(provider)) {
|
||||
return NextResponse.json({ error: 'Invalid provider' }, { status: 400 });
|
||||
}
|
||||
|
||||
const authUrl = getAuthorizationUrl(provider);
|
||||
return NextResponse.redirect(authUrl);
|
||||
}
|
||||
|
||||
30
src/app/api/auth/reset-password/route.ts
Normal file
30
src/app/api/auth/reset-password/route.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getSession } from '@/lib/session';
|
||||
|
||||
// Send password reset email to current user
|
||||
// NOTE: WorkOS AuthKit handles password reset through the hosted UI flow
|
||||
// Users can reset their password by clicking "Forgot password" on the login page
|
||||
export async function POST() {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
// For WorkOS AuthKit, password reset is handled through the hosted UI
|
||||
// The user should be directed to re-authenticate via the login page
|
||||
// where they can click "Forgot password"
|
||||
|
||||
// Return a message directing the user to the login page
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'To reset your password, please log out and use the "Forgot Password" option on the login page.',
|
||||
redirectTo: '/login'
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Password reset error:', error);
|
||||
return NextResponse.json({
|
||||
error: 'An error occurred. Please try again.'
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import webPush from 'web-push';
|
||||
import { getUsersForRemindersD1, updateLastNotifiedD1 } from '@/lib/d1';
|
||||
import { getUsersForRemindersD1, updateLastNotifiedD1, deletePushSubscriptionD1 } from '@/lib/d1';
|
||||
|
||||
// Configure web-push - Helper called inside handler to ensure env is ready
|
||||
function ensureVapidConfig() {
|
||||
@ -207,8 +207,21 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
} catch (err) {
|
||||
console.error(`Failed to process user ${user.userId}:`, err);
|
||||
processed.push({ userId: user.userId, status: 'error', error: String(err) });
|
||||
// If 410 Gone, we should delete subscription, but for now just log
|
||||
|
||||
// Check for 410 Gone - subscription expired, delete from DB
|
||||
const errorStr = String(err);
|
||||
if (errorStr.includes('410') || errorStr.includes('Gone') || errorStr.includes('expired')) {
|
||||
console.log(`Subscription expired for user ${user.userId}, cleaning up...`);
|
||||
try {
|
||||
await deletePushSubscriptionD1(user.userId);
|
||||
processed.push({ userId: user.userId, status: 'expired_cleaned', error: 'Subscription expired and removed' });
|
||||
} catch (deleteErr) {
|
||||
console.error(`Failed to delete expired subscription for ${user.userId}:`, deleteErr);
|
||||
processed.push({ userId: user.userId, status: 'error', error: String(err) });
|
||||
}
|
||||
} else {
|
||||
processed.push({ userId: user.userId, status: 'error', error: String(err) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,21 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Mail, Phone } from 'lucide-react';
|
||||
|
||||
type AuthProvider = 'GoogleOAuth' | 'AppleOAuth' | 'GitHubOAuth' | 'authkit';
|
||||
import { UnifiedLogin } from '@/components/UnifiedLogin';
|
||||
|
||||
export default function LoginPage() {
|
||||
const [stayLoggedIn, setStayLoggedIn] = useState(false);
|
||||
|
||||
const handleLogin = (provider: AuthProvider) => {
|
||||
window.location.href = `/api/auth/login?provider=${provider}&stayLoggedIn=${stayLoggedIn}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-4 bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-950 dark:to-slate-900 overflow-hidden relative">
|
||||
{/* Background Orbs */}
|
||||
@ -36,106 +24,8 @@ export default function LoginPage() {
|
||||
Your companion to a smoke-free life
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6 pb-8">
|
||||
{/* OAuth Providers */}
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-14 text-base font-bold rounded-xl border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50 hover:scale-[1.02] transition-all shadow-sm"
|
||||
onClick={() => handleLogin('GoogleOAuth')}
|
||||
>
|
||||
<svg className="mr-3 h-5 w-5" viewBox="0 0 24 24">
|
||||
<path
|
||||
fill="currentColor"
|
||||
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="currentColor"
|
||||
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="currentColor"
|
||||
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="currentColor"
|
||||
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
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-14 text-base font-bold rounded-xl border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50 hover:scale-[1.02] transition-all shadow-sm"
|
||||
onClick={() => handleLogin('AppleOAuth')}
|
||||
>
|
||||
<svg className="mr-3 h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z" />
|
||||
</svg>
|
||||
Continue with Apple
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-14 text-base font-bold rounded-xl border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50 hover:scale-[1.02] transition-all shadow-sm"
|
||||
onClick={() => handleLogin('GitHubOAuth')}
|
||||
>
|
||||
<svg className="mr-3 h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 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.23.957-.266 1.983-.399 3.003-.404 1.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.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
||||
</svg>
|
||||
Continue with GitHub
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-slate-200 dark:border-slate-700" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-white dark:bg-slate-900 px-3 text-slate-400 font-bold tracking-widest">or</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Email & Phone Options */}
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-14 text-base font-bold rounded-xl border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50 hover:scale-[1.02] transition-all shadow-sm"
|
||||
onClick={() => handleLogin('authkit')}
|
||||
>
|
||||
<Mail className="mr-3 h-5 w-5" />
|
||||
Continue with Email
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-14 text-base font-bold rounded-xl border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50 hover:scale-[1.02] transition-all shadow-sm"
|
||||
onClick={() => handleLogin('authkit')}
|
||||
>
|
||||
<Phone className="mr-3 h-5 w-5" />
|
||||
Continue with Phone
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-3 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-xl border border-slate-100 dark:border-slate-700/50">
|
||||
<Checkbox
|
||||
id="stayLoggedIn"
|
||||
checked={stayLoggedIn}
|
||||
onCheckedChange={(checked) => setStayLoggedIn(checked === true)}
|
||||
className="w-5 h-5 rounded-md border-slate-300 dark:border-slate-700"
|
||||
/>
|
||||
<Label htmlFor="stayLoggedIn" className="text-sm font-medium cursor-pointer select-none opacity-80">
|
||||
Keep me logged in on this device
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<div className="pt-2">
|
||||
<p className="text-center text-[10px] uppercase font-bold tracking-widest text-slate-400 dark:text-slate-500 leading-relaxed max-w-[200px] mx-auto">
|
||||
By continuing, you agree to our Terms & Privacy Policy
|
||||
</p>
|
||||
</div>
|
||||
<CardContent className="pb-8">
|
||||
<UnifiedLogin />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
112
src/app/settings/page.tsx
Normal file
112
src/app/settings/page.tsx
Normal file
@ -0,0 +1,112 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ArrowLeft, Mail, Lock, LogOut, ExternalLink } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useTheme } from '@/lib/theme-context';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export default function SettingsPage() {
|
||||
const router = useRouter();
|
||||
const { theme } = useTheme();
|
||||
|
||||
const handlePasswordReset = () => {
|
||||
// Log out and redirect to login page where they can use "Forgot Password"
|
||||
window.location.href = '/api/auth/logout?redirect=/login';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen pb-24">
|
||||
{/* Header */}
|
||||
<div className={cn(
|
||||
"sticky top-0 z-40 backdrop-blur-xl border-b",
|
||||
theme === 'light'
|
||||
? "bg-white/80 border-slate-200"
|
||||
: "bg-slate-950/80 border-white/10"
|
||||
)}>
|
||||
<div className="container mx-auto px-4 h-16 flex items-center gap-4">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => router.back()}
|
||||
className="rounded-full"
|
||||
>
|
||||
<ArrowLeft className="h-5 w-5" />
|
||||
</Button>
|
||||
<h1 className="text-xl font-bold">Account Settings</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<main className="container mx-auto px-4 py-8 max-w-2xl space-y-6">
|
||||
{/* Password Reset Card */}
|
||||
<Card className={cn(
|
||||
"overflow-hidden",
|
||||
theme === 'light'
|
||||
? "bg-white border-slate-200"
|
||||
: "bg-slate-900/50 border-white/10"
|
||||
)}>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Lock className="h-5 w-5 text-amber-500" />
|
||||
Change Password
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Reset your password through our secure authentication provider.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className={cn(
|
||||
"p-4 rounded-xl border",
|
||||
theme === 'light'
|
||||
? "bg-slate-50 border-slate-200"
|
||||
: "bg-white/5 border-white/10"
|
||||
)}>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
To change your password, you'll be logged out and redirected to the login page.
|
||||
Use the <strong>"Forgot Password"</strong> option to receive a reset link via email.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handlePasswordReset}
|
||||
variant="outline"
|
||||
className="w-full h-12 text-base font-semibold rounded-xl"
|
||||
>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Log Out to Reset Password
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Email Info Card */}
|
||||
<Card className={cn(
|
||||
"overflow-hidden",
|
||||
theme === 'light'
|
||||
? "bg-white border-slate-200"
|
||||
: "bg-slate-900/50 border-white/10"
|
||||
)}>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Mail className="h-5 w-5 text-blue-500" />
|
||||
Email & Account
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Your authentication is managed securely through WorkOS.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className={cn(
|
||||
"text-sm",
|
||||
theme === 'light' ? "text-slate-500" : "text-white/50"
|
||||
)}>
|
||||
To change your email address or manage connected accounts (Google, Apple, GitHub),
|
||||
contact support or create a new account with your preferred email.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -140,6 +140,12 @@ export function SideMenu({ isOpen, onClose, user, userName }: SideMenuProps) {
|
||||
"p-4 border-t",
|
||||
theme === 'light' ? "border-slate-100" : "border-white/5"
|
||||
)}>
|
||||
<MenuLink
|
||||
icon={Settings}
|
||||
label="Account Settings"
|
||||
onClick={() => handleNavigate('/settings')}
|
||||
color="blue"
|
||||
/>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="w-full flex items-center gap-3 px-3 py-3 rounded-xl text-red-500 hover:bg-red-500/10 transition-colors font-medium mt-1"
|
||||
|
||||
298
src/components/UnifiedLogin.tsx
Normal file
298
src/components/UnifiedLogin.tsx
Normal file
@ -0,0 +1,298 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Mail, Lock, Loader2, AlertCircle, ArrowRight } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
|
||||
interface UnifiedLoginProps {
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
export function UnifiedLogin({ onSuccess }: UnifiedLoginProps) {
|
||||
const router = useRouter();
|
||||
const [isSignup, setIsSignup] = useState(false);
|
||||
const [showEmailForm, setShowEmailForm] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [stayLoggedIn, setStayLoggedIn] = useState(false);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
email: '',
|
||||
password: '',
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/auth/email', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...formData,
|
||||
type: isSignup ? 'signup' : 'login',
|
||||
stayLoggedIn,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await res.json() as { error?: string };
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || 'Authentication failed');
|
||||
}
|
||||
|
||||
// Success
|
||||
if (onSuccess) onSuccess();
|
||||
router.push('/home');
|
||||
router.refresh();
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOAuthLogin = (provider: string) => {
|
||||
window.location.href = `/api/auth/login?provider=${provider}&stayLoggedIn=${stayLoggedIn}`;
|
||||
};
|
||||
|
||||
const toggleMode = () => {
|
||||
setIsSignup(!isSignup);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
// Checkbox Component to reuse
|
||||
const StayLoggedInCheckbox = () => (
|
||||
<div className="flex items-center space-x-3 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-xl border border-slate-100 dark:border-slate-700/50">
|
||||
<Checkbox
|
||||
id="stayLoggedIn"
|
||||
checked={stayLoggedIn}
|
||||
onCheckedChange={(checked) => setStayLoggedIn(checked === true)}
|
||||
className="w-5 h-5 rounded-md border-slate-300 dark:border-slate-700"
|
||||
/>
|
||||
<Label htmlFor="stayLoggedIn" className="text-sm font-medium cursor-pointer select-none opacity-80">
|
||||
Keep me logged in on this device
|
||||
</Label>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!showEmailForm) {
|
||||
return (
|
||||
<div className="space-y-3 animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-14 text-base font-bold rounded-xl border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50 hover:scale-[1.02] transition-all shadow-sm"
|
||||
onClick={() => handleOAuthLogin('GoogleOAuth')}
|
||||
>
|
||||
<svg className="mr-3 h-5 w-5" viewBox="0 0 24 24">
|
||||
<path
|
||||
fill="currentColor"
|
||||
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="currentColor"
|
||||
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="currentColor"
|
||||
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="currentColor"
|
||||
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
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-14 text-base font-bold rounded-xl border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50 hover:scale-[1.02] transition-all shadow-sm"
|
||||
onClick={() => handleOAuthLogin('AppleOAuth')}
|
||||
>
|
||||
<svg className="mr-3 h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z" />
|
||||
</svg>
|
||||
Continue with Apple
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-14 text-base font-bold rounded-xl border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50 hover:scale-[1.02] transition-all shadow-sm"
|
||||
onClick={() => handleOAuthLogin('GitHubOAuth')}
|
||||
>
|
||||
<svg className="mr-3 h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 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.23.957-.266 1.983-.399 3.003-.404 1.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.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
||||
</svg>
|
||||
Continue with GitHub
|
||||
</Button>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="relative py-2">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-slate-200 dark:border-slate-700" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-white/80 dark:bg-slate-900 px-3 text-slate-400 font-bold tracking-widest backdrop-blur-sm">or</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-14 text-base font-bold rounded-xl border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/50 hover:scale-[1.02] transition-all shadow-sm"
|
||||
onClick={() => setShowEmailForm(true)}
|
||||
>
|
||||
<Mail className="mr-3 h-5 w-5" />
|
||||
Continue with Email
|
||||
</Button>
|
||||
|
||||
<StayLoggedInCheckbox />
|
||||
|
||||
<div className="pt-2">
|
||||
<p className="text-center text-[10px] uppercase font-bold tracking-widest text-slate-400 dark:text-slate-500 leading-relaxed max-w-[200px] mx-auto">
|
||||
By continuing, you agree to our Terms & Privacy Policy
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4 animate-in fade-in slide-in-from-right-4 duration-300">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-xl font-bold text-slate-900 dark:text-white">
|
||||
{isSignup ? 'Create Account' : 'Welcome Back'}
|
||||
</h2>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowEmailForm(false)}
|
||||
className="text-slate-500 hover:text-slate-900 dark:text-slate-400 dark:hover:text-white"
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-500/30 rounded-lg flex items-center gap-3 text-red-600 dark:text-red-400 text-sm">
|
||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isSignup && (
|
||||
<div className="grid grid-cols-2 gap-3 animate-in fade-in slide-in-from-top-2 duration-300">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="firstName">First Name</Label>
|
||||
<Input
|
||||
id="firstName"
|
||||
placeholder="John"
|
||||
value={formData.firstName}
|
||||
onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
|
||||
required={isSignup}
|
||||
className="bg-slate-50 dark:bg-slate-800/50"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="lastName">Last Name</Label>
|
||||
<Input
|
||||
id="lastName"
|
||||
placeholder="Doe"
|
||||
value={formData.lastName}
|
||||
onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
|
||||
required={isSignup}
|
||||
className="bg-slate-50 dark:bg-slate-800/50"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email Address</Label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="name@example.com"
|
||||
value={formData.email}
|
||||
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
|
||||
required
|
||||
className="pl-10 bg-slate-50 dark:bg-slate-800/50"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
{!isSignup && (
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
alert('Please use the Contact Support option or wait for upcoming full password reset features.');
|
||||
}}
|
||||
className="text-xs text-primary hover:underline"
|
||||
>
|
||||
Forgot password?
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
value={formData.password}
|
||||
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
|
||||
required
|
||||
minLength={8}
|
||||
className="pl-10 bg-slate-50 dark:bg-slate-800/50"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<StayLoggedInCheckbox />
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full h-12 text-base font-bold rounded-xl shadow-lg shadow-primary/20"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{isSignup ? 'Creating Account...' : 'Signing In...'}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{isSignup ? 'Create Account' : 'Sign In'}
|
||||
<ArrowRight className="ml-2 h-4 w-4 group-hover:translate-x-1 transition-transform" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="text-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleMode}
|
||||
className="text-sm text-slate-500 dark:text-slate-400 hover:text-primary dark:hover:text-primary transition-colors font-medium"
|
||||
>
|
||||
{isSignup ? 'Already have an account? Sign in' : "Don't have an account? Sign up"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -439,6 +439,15 @@ export async function upsertPushSubscriptionD1(
|
||||
return getPushSubscriptionD1(userId);
|
||||
}
|
||||
|
||||
export async function deletePushSubscriptionD1(userId: string): Promise<void> {
|
||||
const db = getD1();
|
||||
if (!db) return;
|
||||
|
||||
await db.prepare(
|
||||
'DELETE FROM PushSubscriptions WHERE userId = ?'
|
||||
).bind(userId).run();
|
||||
}
|
||||
|
||||
// ============ MOOD TRACKER ============
|
||||
|
||||
export interface MoodEntryRow {
|
||||
|
||||
@ -15,9 +15,14 @@ export function getAuthorizationUrl(provider: OAuthProvider) {
|
||||
}
|
||||
|
||||
// Get AuthKit hosted login URL (for email/password and phone)
|
||||
// Note: We manually construct this URL with provider=authkit
|
||||
export function getAuthKitUrl() {
|
||||
return workos.userManagement.getAuthorizationUrl({
|
||||
clientId,
|
||||
redirectUri: process.env.WORKOS_REDIRECT_URI!,
|
||||
const params = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
redirect_uri: process.env.WORKOS_REDIRECT_URI!,
|
||||
response_type: 'code',
|
||||
provider: 'authkit',
|
||||
});
|
||||
|
||||
return `https://api.workos.com/user_management/authorize?${params.toString()}`;
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user