-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
68 lines (64 loc) · 2.17 KB
/
Copy pathauth.ts
File metadata and controls
68 lines (64 loc) · 2.17 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import NextAuth from "next-auth";
import Google from "next-auth/providers/google";
import { Pool } from "@neondatabase/serverless";
import { routing } from "./i18n/routing";
import { userSchema } from "./lib/squemas";
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [Google],
pages: {
signIn: "/login",
},
callbacks: {
async signIn({ user, account, profile }) {
const { rows } = await pool.query(
`SELECT * FROM users WHERE email = $1`,
[user.email]
);
if (rows.length != 0) return true;
const { username, email, image_url, preference_currency } =
userSchema.parse({
username: user.name,
email: user.email,
image_url: user.image,
preference_currency: "usd",
});
await pool.query(
`INSERT INTO users (username, email, image_url, created_at, preference_currency) VALUES ($1, $2, $3, NOW(), $4) ON CONFLICT (email) DO UPDATE SET username = $1, email = $2, image_url = $3, preference_currency = $4;`,
[username, email, image_url, preference_currency]
);
return true;
},
async jwt({ token, trigger, session }) {
if (trigger === "update") return { ...token, ...session };
if (token.email) {
const { rows } = await pool.query(
`SELECT user_id::text, preference_currency::text FROM users WHERE email = $1`,
[token.email]
);
if (rows.length > 0) {
token.userId = rows[0].user_id as string;
token.preferenceCurrency = rows[0].preference_currency as string;
}
}
return token;
},
session({ session, token }) {
if (token.userId) {
session.user = {
...session.user,
id: token.userId as string,
preferenceCurrency: token.preferenceCurrency as string,
};
}
return session;
},
async redirect({ url, baseUrl }) {
const locale = url.split("/")[3];
const isValidLocale = routing.locales.includes(locale);
return isValidLocale ? url : `${baseUrl}/${routing.defaultLocale}`;
},
},
});