Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 0 additions & 67 deletions apps/mail/app/api/v1/mail/auth/[providerId]/callback/route.ts

This file was deleted.

20 changes: 0 additions & 20 deletions apps/mail/app/api/v1/mail/auth/[providerId]/init/route.ts

This file was deleted.

11 changes: 8 additions & 3 deletions apps/mail/components/connection/add.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
DialogTrigger,
} from '../ui/dialog';
import { emailProviders } from '@/lib/constants';
import { authClient } from '@/lib/auth-client';
import { Plus, UserPlus } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { Button } from '../ui/button';
Expand Down Expand Up @@ -52,9 +53,8 @@ export const AddConnectionDialog = ({
transition={{ duration: 0.3 }}
>
{emailProviders.map((provider, index) => (
<motion.a
<motion.div
key={provider.name}
href={`/api/v1/mail/auth/${provider.providerId}/init`}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1, duration: 0.3 }}
Expand All @@ -64,13 +64,18 @@ export const AddConnectionDialog = ({
<Button
variant="outline"
className="h-24 w-full flex-col items-center justify-center gap-2"
onClick={async () =>
await authClient.linkSocial({
provider: provider.providerId,
})
}
>
<svg viewBox="0 0 24 24" className="h-12 w-12">
<path fill="currentColor" d={provider.icon} />
</svg>
<span className="text-xs">{provider.name}</span>
</Button>
</motion.a>
</motion.div>
))}
<motion.div
initial={{ opacity: 0, y: 20 }}
Expand Down
76 changes: 72 additions & 4 deletions apps/mail/lib/auth.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { connection, user as _user, account, userSettings, earlyAccess } from '@zero/db/schema';
import { createAuthMiddleware, customSession } from 'better-auth/plugins';
import { Account, betterAuth, type BetterAuthOptions } from 'better-auth';
import { getBrowserTimezone, isValidTimezone } from '@/lib/timezones';
import { defaultUserSettings } from '@zero/db/user_settings_default';
import { betterAuth, type BetterAuthOptions } from 'better-auth';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { getSocialProviders } from './auth-providers';
import { createDriver } from '@/app/api/driver';
import { redirect } from 'next/navigation';
import { APIError } from 'better-auth/api';
import { eq } from 'drizzle-orm';
import { Resend } from 'resend';
import { db } from '@zero/db';
Expand All @@ -17,10 +19,59 @@ const resend = process.env.RESEND_API_KEY
? new Resend(process.env.RESEND_API_KEY)
: { emails: { send: async (...args: any[]) => console.log(args) } };

const connectionHandlerHook = async (account: Account) => {
if (!account.accessToken || !account.refreshToken) {
console.error('Missing Access/Refresh Tokens', { account });
throw new APIError('EXPECTATION_FAILED', { message: 'Missing Access/Refresh Tokens' });
}

const driver = await createDriver(account.providerId, {});
const userInfo = await driver
.getUserInfo({
access_token: account.accessToken,
refresh_token: account.refreshToken,
email: '',
})
.catch(() => {
throw new APIError('UNAUTHORIZED', { message: 'Failed to get user info' });
});

if (!userInfo.data?.emailAddresses?.[0]?.value) {
console.error('Missing email in user info:', { userInfo });
throw new APIError('BAD_REQUEST', { message: 'Missing "email" in user info' });
}

const updatingInfo = {
name: userInfo.data.names?.[0]?.displayName || 'Unknown',
picture: userInfo.data.photos?.[0]?.url || '',
accessToken: account.accessToken,
refreshToken: account.refreshToken,
scope: driver.getScope(),
expiresAt: new Date(Date.now() + (account.accessTokenExpiresAt?.getTime() || 3600000)),
};

await db
.insert(connection)
.values({
providerId: account.providerId,
id: crypto.randomUUID(),
email: userInfo.data.emailAddresses[0].value,
userId: account.userId,
createdAt: new Date(),
updatedAt: new Date(),
...updatingInfo,
})
.onConflictDoUpdate({
target: [connection.email, connection.userId],
set: {
...updatingInfo,
updatedAt: new Date(),
},
});
};

const options = {
database: drizzleAdapter(db, {
provider: 'pg',
}),
database: drizzleAdapter(db, { provider: 'pg' }),
advanced: {
ipAddress: {
disableIpTracking: true,
Expand All @@ -31,6 +82,23 @@ const options = {
updateAge: 60 * 60 * 24, // 1 day (every 1 day the session expiration is updated)
},
socialProviders: getSocialProviders(),
account: {
accountLinking: {
enabled: true,
allowDifferentEmails: true,
trustedProviders: ['google'],
},
},
databaseHooks: {
account: {
create: {
after: connectionHandlerHook,
},
update: {
after: connectionHandlerHook,
},
},
},
emailAndPassword: {
enabled: false,
requireEmailVerification: true,
Expand Down
2 changes: 1 addition & 1 deletion apps/mail/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,4 @@ export const emailProviders = [
icon: "M11.99 13.9v-3.72h9.36c.14.63.25 1.22.25 2.05c0 5.71-3.83 9.77-9.6 9.77c-5.52 0-10-4.48-10-10S6.48 2 12 2c2.7 0 4.96.99 6.69 2.61l-2.84 2.76c-.72-.68-1.98-1.48-3.85-1.48c-3.31 0-6.01 2.75-6.01 6.12s2.7 6.12 6.01 6.12c3.83 0 5.24-2.65 5.5-4.22h-5.51z",
providerId: "google",
},
];
] as const;
2 changes: 1 addition & 1 deletion apps/mail/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
"@zero/db": "workspace:*",
"@zero/eslint-config": "workspace:*",
"axios": "1.8.1",
"better-auth": "1.2.1",
"better-auth": "1.2.7",
"canvas-confetti": "1.9.3",
"cheerio": "1.0.0",
"class-variance-authority": "0.7.1",
Expand Down
10 changes: 4 additions & 6 deletions bun.lock

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