62 lines
1.8 KiB
TypeScript
62 lines
1.8 KiB
TypeScript
import { convexAuth, getAuthUserId } from "@convex-dev/auth/server"
|
|
import { ConvexError } from "convex/values"
|
|
import { Password } from "@convex-dev/auth/providers/Password"
|
|
import { query } from "./_generated/server"
|
|
|
|
export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
|
|
providers: [
|
|
Password({
|
|
profile(params) {
|
|
return {
|
|
email: params.email as string,
|
|
name: params.name as string,
|
|
}
|
|
},
|
|
}),
|
|
],
|
|
callbacks: {
|
|
async afterUserCreatedOrUpdated(ctx, { userId, existingUserId }) {
|
|
if (existingUserId === null) {
|
|
const settings = await ctx.db.query("appSettings").first()
|
|
if (settings?.disableAccountCreation) {
|
|
const sessions = await ctx.db
|
|
.query("authSessions")
|
|
.filter((q) => q.eq(q.field("userId"), userId))
|
|
.collect()
|
|
for (const session of sessions) {
|
|
await ctx.db.delete(session._id)
|
|
}
|
|
const accounts = await ctx.db
|
|
.query("authAccounts")
|
|
.filter((q) => q.eq(q.field("userId"), userId))
|
|
.collect()
|
|
for (const account of accounts) {
|
|
await ctx.db.delete(account._id)
|
|
}
|
|
await ctx.db.delete(userId)
|
|
throw new ConvexError("Account creation is currently disabled")
|
|
}
|
|
|
|
const users = await ctx.db.query("users").collect()
|
|
if (users.length === 1) {
|
|
await ctx.db.patch(userId, { isAdmin: true })
|
|
} else {
|
|
await ctx.db.patch(userId, { isAdmin: false })
|
|
}
|
|
return
|
|
}
|
|
},
|
|
},
|
|
})
|
|
|
|
export const currentUser = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
return null
|
|
}
|
|
return await ctx.db.get(userId)
|
|
},
|
|
})
|