Files
otunes/convex/users.ts
T

326 lines
8.4 KiB
TypeScript

import {
createAccount,
getAuthUserId,
modifyAccountCredentials,
} from "@convex-dev/auth/server"
import { ConvexError, v } from "convex/values"
import { api } from "./_generated/api"
import { action, mutation, query } from "./_generated/server"
import type { Id } from "./_generated/dataModel"
import type { MutationCtx } from "./_generated/server"
const playbackQualityValidator = v.union(
v.literal("low"),
v.literal("medium"),
v.literal("high"),
v.literal("lossless")
)
async function requireAuth(ctx: MutationCtx) {
const userId = await getAuthUserId(ctx)
if (userId === null) {
throw new ConvexError("Not authenticated")
}
return userId
}
async function requireAdmin(ctx: MutationCtx) {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user?.isAdmin) {
throw new ConvexError("Not authorized")
}
return { userId, user }
}
async function deleteUserAuthData(ctx: MutationCtx, userId: Id<"users">) {
const sessions = await ctx.db
.query("authSessions")
.withIndex("userId", (q) => q.eq("userId", userId))
.collect()
for (const session of sessions) {
const refreshTokens = await ctx.db
.query("authRefreshTokens")
.withIndex("sessionId", (q) => q.eq("sessionId", session._id))
.collect()
for (const token of refreshTokens) {
await ctx.db.delete(token._id)
}
const verifiers = await ctx.db
.query("authVerifiers")
.filter((q) => q.eq(q.field("sessionId"), session._id))
.collect()
for (const verifier of verifiers) {
await ctx.db.delete(verifier._id)
}
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) {
const codes = await ctx.db
.query("authVerificationCodes")
.withIndex("accountId", (q) => q.eq("accountId", account._id))
.collect()
for (const code of codes) {
await ctx.db.delete(code._id)
}
await ctx.db.delete(account._id)
}
await ctx.db.delete(userId)
}
export const getAppSettings = query({
args: {},
handler: async (ctx) => {
const settings = await ctx.db.query("appSettings").first()
return {
disableAccountCreation: settings?.disableAccountCreation ?? false,
}
},
})
export const getUserByEmail = query({
args: { email: v.string() },
handler: async (ctx, { email }) => {
return await ctx.db
.query("users")
.withIndex("email", (q) => q.eq("email", email))
.unique()
},
})
export const listUsers = query({
args: {},
handler: async (ctx) => {
const userId = await getAuthUserId(ctx)
if (userId === null) {
return null
}
const currentUser = await ctx.db.get(userId)
if (!currentUser?.isAdmin) {
return null
}
return await ctx.db.query("users").collect()
},
})
export const updateProfileImage = mutation({
args: {
image: v.union(v.string(), v.null()),
},
handler: async (ctx, { image }) => {
const userId = await requireAuth(ctx)
await ctx.db.patch(userId, {
image: image === null ? undefined : image,
})
},
})
export const updateProfileName = mutation({
args: { name: v.string() },
handler: async (ctx, { name }) => {
const userId = await requireAuth(ctx)
const trimmed = name.trim()
if (!trimmed) {
throw new ConvexError("Name cannot be empty")
}
await ctx.db.patch(userId, { name: trimmed })
},
})
export const updateProfileEmail = mutation({
args: { email: v.string() },
handler: async (ctx, { email }) => {
const userId = await requireAuth(ctx)
const trimmed = email.trim().toLowerCase()
if (!trimmed || !trimmed.includes("@")) {
throw new ConvexError("Invalid email")
}
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
if (user.email === trimmed) {
return
}
const existing = await ctx.db
.query("users")
.withIndex("email", (q) => q.eq("email", trimmed))
.unique()
if (existing && existing._id !== userId) {
throw new ConvexError("Email is already in use")
}
const account = await ctx.db
.query("authAccounts")
.withIndex("userIdAndProvider", (q) =>
q.eq("userId", userId).eq("provider", "password")
)
.unique()
if (account) {
await ctx.db.patch(account._id, { providerAccountId: trimmed })
}
await ctx.db.patch(userId, { email: trimmed })
},
})
export const updatePlaybackQuality = mutation({
args: { playbackQuality: playbackQualityValidator },
handler: async (ctx, { playbackQuality }) => {
const userId = await requireAuth(ctx)
await ctx.db.patch(userId, { playbackQuality })
},
})
export const updatePreferAtmos = mutation({
args: { preferAtmos: v.boolean() },
handler: async (ctx, { preferAtmos }) => {
const userId = await requireAuth(ctx)
await ctx.db.patch(userId, { preferAtmos })
},
})
export const setDisableAccountCreation = mutation({
args: { disabled: v.boolean() },
handler: async (ctx, { disabled }) => {
await requireAdmin(ctx)
const existing = await ctx.db.query("appSettings").first()
if (existing) {
await ctx.db.patch(existing._id, { disableAccountCreation: disabled })
} else {
await ctx.db.insert("appSettings", { disableAccountCreation: disabled })
}
},
})
export const setUserAdmin = mutation({
args: {
userId: v.id("users"),
isAdmin: v.boolean(),
},
handler: async (ctx, { userId, isAdmin }) => {
const { userId: adminId } = await requireAdmin(ctx)
if (userId === adminId && !isAdmin) {
throw new ConvexError("You cannot remove your own admin access")
}
await ctx.db.patch(userId, { isAdmin })
},
})
export const deleteUser = mutation({
args: { userId: v.id("users") },
handler: async (ctx, { userId }) => {
const { userId: adminId } = await requireAdmin(ctx)
if (userId === adminId) {
throw new ConvexError("You cannot delete your own account")
}
await deleteUserAuthData(ctx, userId)
},
})
export const updateOwnPassword = action({
args: { newPassword: v.string() },
handler: async (ctx, { newPassword }) => {
const user = await ctx.runQuery(api.auth.currentUser)
if (!user) {
throw new ConvexError("Not authenticated")
}
if (newPassword.length < 8) {
throw new ConvexError("Password must be at least 8 characters")
}
await modifyAccountCredentials(ctx, {
provider: "password",
account: { id: user.email, secret: newPassword },
})
},
})
export const adminChangeUserPassword = action({
args: {
userId: v.id("users"),
newPassword: v.string(),
},
handler: async (ctx, { userId, newPassword }) => {
const users = await ctx.runQuery(api.users.listUsers)
if (!users) {
throw new ConvexError("Not authorized")
}
const target = users.find((u) => u._id === userId)
if (!target) {
throw new ConvexError("User not found")
}
if (newPassword.length < 8) {
throw new ConvexError("Password must be at least 8 characters")
}
await modifyAccountCredentials(ctx, {
provider: "password",
account: { id: target.email, secret: newPassword },
})
},
})
export const adminCreateUser = action({
args: {
name: v.string(),
email: v.string(),
password: v.string(),
isAdmin: v.optional(v.boolean()),
},
handler: async (ctx, { name, email, password, isAdmin }) => {
const users = await ctx.runQuery(api.users.listUsers)
if (!users) {
throw new ConvexError("Not authorized")
}
const trimmedName = name.trim()
const trimmedEmail = email.trim().toLowerCase()
if (!trimmedName) {
throw new ConvexError("Name is required")
}
if (!trimmedEmail.includes("@")) {
throw new ConvexError("Invalid email")
}
if (password.length < 8) {
throw new ConvexError("Password must be at least 8 characters")
}
const existing = await ctx.runQuery(api.users.getUserByEmail, {
email: trimmedEmail,
})
if (existing) {
throw new ConvexError("Email is already in use")
}
const { user } = await createAccount(ctx, {
provider: "password",
account: { id: trimmedEmail, secret: password },
profile: {
name: trimmedName,
email: trimmedEmail,
isAdmin: isAdmin ?? false,
},
})
},
})