-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
156 lines (146 loc) · 5.22 KB
/
Copy pathauth.ts
File metadata and controls
156 lines (146 loc) · 5.22 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { createClient, type AuthFunctions } from "@convex-dev/better-auth";
import { betterAuth, type BetterAuthOptions } from "better-auth";
import { convex, crossDomain } from "@convex-dev/better-auth/plugins";
import { magicLink, admin } from "better-auth/plugins";
import { createAuthMiddleware, APIError } from "better-auth/api";
import { components, internal } from "./_generated/api";
import { query } from "./_generated/server";
import { v } from "convex/values";
import { type GenericCtx } from "convex/server";
import type { DataModel } from "./_generated/dataModel.d.ts";
import authConfig from "./auth.config";
const authFunctions: AuthFunctions = internal.auth;
export const authComponent = createClient<DataModel>(components.betterAuth, {
authFunctions,
triggers: {
user: {
onCreate: async (ctx, authUser) => {
// Sync user to your custom 'users' table
await ctx.db.insert("users", {
name: authUser.name || undefined,
email: authUser.email,
image: authUser.image || undefined,
// safeGetAuthUser returns the raw Convex doc, whose id is `_id`
// (there is no `.id` field) — using `.id` here wrote undefined.
tokenIdentifier: authUser._id,
});
},
},
},
});
export const { onCreate, onUpdate, onDelete } = authComponent.triggersApi();
export const createAuthOptions = (ctx: GenericCtx<DataModel>): BetterAuthOptions => {
return {
database: authComponent.adapter(ctx),
baseURL: process.env.BETTER_AUTH_URL ||
process.env.SITE_URL ||
(process.env.CONVEX_SITE_URL ? `${process.env.CONVEX_SITE_URL}/api/auth` : undefined),
secret: process.env.BETTER_AUTH_SECRET || "dev-secret-key-at-least-32-chars-long-exemplai",
trustedOrigins: [
"http://localhost:3000",
"http://localhost:5173",
"http://127.0.0.1:3000",
"http://127.0.0.1:5173",
...(process.env.VITE_TRUSTED_ORIGINS?.split(",") || []),
],
user: {
deleteUser: {
enabled: true
},
additionalFields: {
isAnonymous: { type: "boolean", required: false },
phone: { type: "string", required: false },
phoneVerificationTime: { type: "number", required: false },
emailVerificationTime: { type: "number", required: false },
tokenIdentifier: { type: "string", required: false },
role: { type: "string", required: false },
banned: { type: "boolean", required: false },
},
},
emailAndPassword: {
enabled: true,
},
hooks: {
before: createAuthMiddleware(async (apiCtx) => {
if (apiCtx.path === "/sign-up/email") {
const body = apiCtx.body as any;
const code = body?.code;
if (!code) {
throw new APIError("BAD_REQUEST", {
message: "Invitation code is required.",
});
}
const invitation = await ctx.db
.query("invitationCodes")
.withIndex("by_code", (q) => q.eq("code", code))
.unique();
if (!invitation || !invitation.isValid || invitation.usesCount >= invitation.quantity) {
throw new APIError("BAD_REQUEST", {
message: "Invalid or expired invitation code.",
});
}
if (invitation.expiryDate) {
const expiry = new Date(invitation.expiryDate);
if (!isNaN(expiry.getTime()) && expiry.getTime() < Date.now()) {
throw new APIError("BAD_REQUEST", {
message: "Invitation code has expired.",
});
}
}
}
}),
},
plugins: [
convex({ authConfig, jwtExpirationSeconds: 60 * 60 * 24 }),
crossDomain({
siteUrl: process.env.SITE_URL || "http://localhost:5173",
}),
/* magicLink({
sendMagicLink: async ({ email, url }) => {
console.log(`\n==================================================`);
console.log(`[Dev Mailer] Magic Link for: ${email}`);
console.log(`URL: ${url}`);
console.log(`==================================================\n`);
},
}), */
admin(),
],
};
};
export const createAuth = (ctx: GenericCtx<DataModel>) => {
return betterAuth(createAuthOptions(ctx));
};
// Query to get currently authenticated user session
export const getSessionUser = query({
args: {},
handler: async (ctx) => {
const authUser = await authComponent.safeGetAuthUser(ctx);
if (!authUser) return null;
return {
user: {
// safeGetAuthUser returns the raw Convex doc; its id is `_id`.
id: authUser._id,
email: authUser.email,
name: authUser.name || undefined,
image: authUser.image || undefined,
emailVerified: authUser.emailVerified,
createdAt: authUser.createdAt,
updatedAt: authUser.updatedAt,
},
session: {
userId: authUser._id,
},
};
},
});
// Public query to check if user exists in Convex by email
export const checkUserExistsQuery = query({
args: { email: v.string() },
handler: async (ctx, args) => {
const user = await ctx.db
.query("users")
.withIndex("by_email", (q) => q.eq("email", args.email))
.unique();
return !!user;
},
});