-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
53 lines (47 loc) · 1.45 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import PostgresAdapter from '@auth/pg-adapter';
import { Pool } from '@neondatabase/serverless';
import NextAuth from 'next-auth';
import Resend from 'next-auth/providers/resend';
import { neon } from '@neondatabase/serverless';
if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL is not defined in environment variables.');
const sql = neon(process.env.DATABASE_URL);
export const { handlers, auth, signIn, signOut } = NextAuth(() => {
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
return {
adapter: PostgresAdapter(pool),
providers: [Resend({ from: 'Student Evals Sign In <[email protected]>' })],
}
})
export async function sessionUser () {
const session = await auth();
if (session && typeof session.user?.email === 'string') {
const user = await sql`
SELECT * FROM users
WHERE email = ${session.user.email}
`;
if (user.length === 0) {
return null;
}
return user[0] as User;
}
return null;
}
export interface User {
id: string;
email: string;
name: string;
}
export async function authUser (): Promise<User> {
const session = await auth();
if (session && typeof session.user?.email === 'string') {
const user = await sql`
SELECT * FROM users
WHERE email = ${session.user.email}
`;
if (user.length === 0) {
throw new Error('User not found');
}
return user[0] as User;
}
throw new Error('Not authenticated or email is missing');
}