-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
53 lines (48 loc) · 1.69 KB
/
auth.js
File metadata and controls
53 lines (48 loc) · 1.69 KB
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
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
import { MongoDBAdapter } from "@auth/mongodb-adapter";
import { clientPromise } from "./lib/mongodb";
import User from "./models/User";
import bcrypt from "bcryptjs";
import dbConnect from "./lib/mongodb";
import { authConfig } from "./auth.config";
import { sendWelcomeEmail } from "./lib/mailer";
export const { handlers, auth, signIn, signOut } = NextAuth({
...authConfig,
adapter: MongoDBAdapter(clientPromise),
providers: [
GoogleProvider({
clientId: process.env.AUTH_GOOGLE_ID,
clientSecret: process.env.AUTH_GOOGLE_SECRET,
}),
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" }
},
async authorize(credentials) {
await dbConnect();
if (!credentials?.email || !credentials?.password) return null;
const user = await User.findOne({ email: credentials.email });
if (!user || !user.password) return null;
const passwordsMatch = await bcrypt.compare(credentials.password, user.password);
if (passwordsMatch) return user;
return null;
}
})
],
events: {
// Fires once when a brand-new user is created (Google OAuth first sign-in)
async createUser({ user }) {
try {
if (user.email) {
await sendWelcomeEmail({ to: user.email, name: user.name ?? 'Traveller' });
}
} catch (err) {
console.error('Welcome email failed:', err.message);
}
},
},
});