feat: all of auth, start of settings

This commit is contained in:
joshuafhiggins committed 2026-06-04 11:37:01 -04:00 Verified
1 parent 43c5dcefbb
commit dad88f88e3
33 files changed
+1876 -48

No files matched your search

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+17
View File
@@ -0,0 +1,17 @@
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { AppSidebar } from "@/components/app-sidebar"
import { PlayerBar } from "@/components/player-bar"
export default function AppLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<SidebarProvider>
<AppSidebar />
<SidebarInset>{children}</SidebarInset>
<PlayerBar />
</SidebarProvider>
)
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+11
View File
@@ -0,0 +1,11 @@
export default function AuthLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<div className="flex min-h-svh flex-col items-center justify-center bg-muted/30 p-6">
{children}
</div>
)
}
+7
View File
@@ -0,0 +1,7 @@
"use client"
import { AuthForm } from "@/components/auth-form"
export default function SignInPage() {
return <AuthForm flow="signIn" />
}
+7
View File
@@ -0,0 +1,7 @@
"use client"
import { AuthForm } from "@/components/auth-form"
export default function SignUpPage() {
return <AuthForm flow="signUp" />
}
+9 -15
View File
@@ -1,12 +1,10 @@
import { Geist, Geist_Mono, Inter } from "next/font/google"
import "./globals.css"
import { ConvexAuthNextjsServerProvider } from "@convex-dev/auth/nextjs/server"
import { ConvexClientProvider } from "@/components/convex-client-provider"
import { ThemeProvider } from "@/components/theme-provider"
import { cn } from "@/lib/utils"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { AppSidebar } from "@/components/app-sidebar"
import { PlayerBar } from "@/components/player-bar"
import { Toaster } from "@/components/ui/sonner"
import type { Metadata } from "next"
@@ -39,18 +37,14 @@ export default function RootLayout({
)}
>
<body className={"overflow-x-hidden"}>
<ConvexClientProvider>
<ThemeProvider>
<SidebarProvider>
<AppSidebar />
<SidebarInset>
{children}
<PlayerBar />
</SidebarInset>
</SidebarProvider>
<Toaster />
</ThemeProvider>
</ConvexClientProvider>
<ConvexAuthNextjsServerProvider>
<ConvexClientProvider>
<ThemeProvider>
{children}
<Toaster />
</ThemeProvider>
</ConvexClientProvider>
</ConvexAuthNextjsServerProvider>
</body>
</html>
)
+65 -21
View File
@@ -5,15 +5,25 @@ import {
House,
LayoutGrid,
ListMusic,
LogOut,
Mic,
Music2,
Search,
Settings,
Star,
} from "lucide-react"
import { usePathname } from "next/navigation"
import { usePathname, useRouter } from "next/navigation"
import { useAuthActions } from "@convex-dev/auth/react"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { OptionsModal } from "@/components/options-modal"
import {
Sidebar,
SidebarContent,
@@ -32,6 +42,8 @@ import Link from "next/link"
import { useTheme } from "next-themes"
import * as React from "react"
import { placeholderPlaylists } from "@/lib/playlists"
import { useQuery } from "convex/react"
import { api } from "@/convex/_generated/api"
const browse = [
{ title: "Home", path: "/", icon: House },
@@ -56,9 +68,19 @@ const playlists = [
export function AppSidebar() {
const pathname = usePathname()
const router = useRouter()
const { signOut } = useAuthActions()
const user = useQuery(api.auth.currentUser)
const fallbackLetters = user?.name?.match(/\b(\w)/g)!.join('') || "NA"
const { resolvedTheme } = useTheme()
const [mounted, setMounted] = React.useState(false)
const [optionsOpen, setOptionsOpen] = React.useState(false)
async function handleSignOut() {
await signOut()
router.push("/signin")
}
React.useEffect(() => {
setMounted(true)
@@ -70,7 +92,13 @@ export function AppSidebar() {
<Sidebar>
<SidebarHeader>
<div className="flex items-center gap-1 px-2 py-1">
<Image src={isDark ? "/logo-dark.png" : "/logo.png"} alt={"oTunes"} width={20} height={20} className="size-5" />
<Image
src={isDark ? "/logo-dark.png" : "/logo.png"}
alt={"oTunes"}
width={20}
height={20}
className="size-5"
/>
<span className="text-lg font-semibold tracking-tight">oTunes</span>
</div>
</SidebarHeader>
@@ -81,10 +109,7 @@ export function AppSidebar() {
<SidebarMenu>
{browse.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton
isActive={pathname === item.path}
asChild
>
<SidebarMenuButton isActive={pathname === item.path} asChild>
<Link href={item.path}>
<item.icon />
<span>{item.title}</span>
@@ -102,10 +127,7 @@ export function AppSidebar() {
<SidebarMenu>
{library.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton
isActive={pathname === item.path}
asChild
>
<SidebarMenuButton isActive={pathname === item.path} asChild>
<Link href={item.path}>
<item.icon />
<span>{item.title}</span>
@@ -123,10 +145,7 @@ export function AppSidebar() {
<SidebarMenu>
{playlists.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton
isActive={pathname === item.path}
asChild
>
<SidebarMenuButton isActive={pathname === item.path} asChild>
<Link href={item.path}>
<item.icon />
<span>{item.title}</span>
@@ -142,12 +161,37 @@ export function AppSidebar() {
<SidebarFooter>
<SidebarMenu>
<SidebarMenuItem className="flex items-center justify-around gap-1">
<SidebarMenuButton size="lg" className="min-w-0 flex-1">
<Avatar size="sm">
<AvatarFallback>JH</AvatarFallback>
</Avatar>
<span className="truncate">Joshua Higgins</span>
</SidebarMenuButton>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuButton size="lg" className="min-w-0 flex-1">
<Avatar size="sm" key={user?.image ?? "fallback"}>
{user?.image ? (
<AvatarImage src={user.image} alt={user.name} />
) : null}
<AvatarFallback>{fallbackLetters}</AvatarFallback>
</Avatar>
<span className="truncate">{user?.name || "N/A"}</span>
</SidebarMenuButton>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start" className="w-40">
<DropdownMenuItem
variant="destructive"
className="justify-between"
onClick={handleSignOut}
>
Sign Out
<LogOut />
</DropdownMenuItem>
<DropdownMenuItem
className="justify-between"
onClick={() => setOptionsOpen(true)}
>
Options
<Settings />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<OptionsModal open={optionsOpen} onOpenChange={setOptionsOpen} />
<ThemeToggle />
</SidebarMenuItem>
</SidebarMenu>
+164
View File
@@ -0,0 +1,164 @@
"use client"
import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { useAuthActions } from "@convex-dev/auth/react"
import { useQuery } from "convex/react"
import { Button } from "@/components/ui/button"
import { api } from "@/convex/_generated/api"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Spinner } from "@/components/ui/spinner"
type AuthFlow = "signIn" | "signUp"
const copy: Record<
AuthFlow,
{
title: string
description: string
submit: string
switchPrompt: string
switchLabel: string
switchHref: string
}
> = {
signIn: {
title: "Welcome back",
description: "Sign in to your oTunes account to keep listening.",
submit: "Sign in",
switchPrompt: "Don't have an account?",
switchLabel: "Sign up",
switchHref: "/signup",
},
signUp: {
title: "Create your account",
description: "Sign up to start building your oTunes library.",
submit: "Sign up",
switchPrompt: "Already have an account?",
switchLabel: "Sign in",
switchHref: "/signin",
},
}
export function AuthForm({ flow }: { flow: AuthFlow }) {
const { signIn } = useAuthActions()
const router = useRouter()
const appSettings = useQuery(api.users.getAppSettings)
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
const text = copy[flow]
const accountCreationDisabled = appSettings?.disableAccountCreation ?? false
const signupsDisabled = flow === "signUp" && accountCreationDisabled
const hideSignUpLink = flow === "signIn" && accountCreationDisabled
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault()
if (signupsDisabled) {
return
}
setError(null)
setSubmitting(true)
const formData = new FormData(event.currentTarget)
formData.set("flow", flow)
try {
await signIn("password", formData)
router.push("/")
} catch {
setError(
flow === "signIn"
? "Invalid email or password."
: "Could not create account. Try a different email."
)
setSubmitting(false)
}
}
return (
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle className="text-lg">{text.title}</CardTitle>
<CardDescription>{text.description}</CardDescription>
</CardHeader>
<CardContent>
{signupsDisabled ? (
<p className="text-sm text-muted-foreground">
New account registration is currently disabled. Contact an
administrator if you need access.
</p>
) : (
<form onSubmit={handleSubmit}>
<FieldGroup>
{flow === "signUp" && (
<Field>
<FieldLabel htmlFor="name">Name</FieldLabel>
<Input
id="name"
name="name"
type="text"
autoComplete="name"
placeholder="Ada Lovelace"
required
/>
</Field>
)}
<Field>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input
id="email"
name="email"
type="email"
autoComplete="email"
placeholder="you@example.com"
required
/>
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input
id="password"
name="password"
type="password"
autoComplete={
flow === "signIn" ? "current-password" : "new-password"
}
required
/>
</Field>
{error && <FieldError>{error}</FieldError>}
<Field>
<Button type="submit" disabled={submitting}>
{submitting && <Spinner />}
{text.submit}
</Button>
</Field>
{!hideSignUpLink ? (
<p className="text-center text-sm text-muted-foreground">
{text.switchPrompt}{" "}
<Link
href={text.switchHref}
className="text-primary underline-offset-4 hover:underline"
>
{text.switchLabel}
</Link>
</p>
) : null}
</FieldGroup>
</form>
)}
</CardContent>
</Card>
)
}
+9 -7
View File
@@ -1,13 +1,15 @@
"use client"
import { ConvexProvider, ConvexReactClient } from "convex/react"
import { ConvexAuthNextjsProvider } from "@convex-dev/auth/nextjs"
import { ConvexReactClient } from "convex/react"
import { ReactNode } from "react"
const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!)
export function ConvexClientProvider({
children,
}: {
children: React.ReactNode
}) {
return <ConvexProvider client={convex}>{children}</ConvexProvider>
export function ConvexClientProvider({ children }: { children: ReactNode }) {
return (
<ConvexAuthNextjsProvider client={convex}>
{children}
</ConvexAuthNextjsProvider>
)
}
+855
View File
@@ -0,0 +1,855 @@
"use client"
import { useAction, useMutation, useQuery } from "convex/react"
import {
MoreHorizontal,
Trash2,
Upload,
UserPlus,
} from "lucide-react"
import { useCallback, useEffect, useRef, useState } from "react"
import { toast } from "sonner"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
import { Spinner } from "@/components/ui/spinner"
import { Switch } from "@/components/ui/switch"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { api } from "@/convex/_generated/api"
import type { Doc, Id } from "@/convex/_generated/dataModel"
import { resizeProfileImageToDataUrl } from "@/lib/resize-profile-image"
import { cn } from "@/lib/utils"
type Section = "profile" | "quality" | "users"
type PlaybackQuality = "low" | "medium" | "high" | "lossless"
const QUALITY_OPTIONS: {
value: PlaybackQuality
label: string
description: string
}[] = [
{ value: "low", label: "Low", description: "AAC HE 128kb/s" },
{ value: "medium", label: "Medium", description: "AAC 256kb/s" },
{ value: "high", label: "High", description: "AAC 320kb/s" },
{ value: "lossless", label: "Lossless", description: "ALAC" },
]
function useDebouncedCallback<T extends (...args: never[]) => void>(
callback: T,
delay: number
) {
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const callbackRef = useRef(callback)
callbackRef.current = callback
useEffect(() => {
return () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
}
}, [])
return useCallback(
(...args: Parameters<T>) => {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
timeoutRef.current = setTimeout(() => {
callbackRef.current(...args)
}, delay)
},
[delay]
)
}
function NavButton({
active,
onClick,
children,
}: {
active: boolean
onClick: () => void
children: React.ReactNode
}) {
return (
<button
type="button"
onClick={onClick}
className={cn(
"w-full rounded-lg px-2.5 py-1.5 text-left text-sm transition-colors",
active
? "bg-muted font-medium text-foreground"
: "text-muted-foreground hover:bg-muted/60 hover:text-foreground"
)}
>
{children}
</button>
)
}
function UserAvatar({
user,
size = "default",
}: {
user: Pick<Doc<"users">, "name" | "image">
size?: "default" | "sm"
}) {
const initials = user.name
.split(" ")
.map((part) => part[0])
.join("")
.slice(0, 2)
.toUpperCase()
return (
<Avatar
key={user.image ?? "fallback"}
size={size === "sm" ? "sm" : "default"}
>
{user.image ? (
<AvatarImage src={user.image} alt={user.name} />
) : null}
<AvatarFallback>{initials}</AvatarFallback>
</Avatar>
)
}
function ProfileSection({ user }: { user: Doc<"users"> }) {
const updateName = useMutation(api.users.updateProfileName)
const updateEmail = useMutation(api.users.updateProfileEmail)
const updateImage = useMutation(api.users.updateProfileImage)
const updatePassword = useAction(api.users.updateOwnPassword)
const [name, setName] = useState(user.name)
const [email, setEmail] = useState(user.email)
const [newPassword, setNewPassword] = useState("")
const [confirmPassword, setConfirmPassword] = useState("")
const [changingPassword, setChangingPassword] = useState(false)
const fileInputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
setName(user.name)
setEmail(user.email)
}, [user.name, user.email])
const debouncedUpdateName = useDebouncedCallback((value: string) => {
if (value.trim() === user.name) return
updateName({ name: value }).catch((error: Error) =>
toast.error(error.message)
)
}, 500)
const debouncedUpdateEmail = useDebouncedCallback((value: string) => {
if (value.trim().toLowerCase() === user.email) return
updateEmail({ email: value }).catch((error: Error) =>
toast.error(error.message)
)
}, 500)
async function handleImageUpload(file: File) {
if (!file.type.startsWith("image/")) {
toast.error("Please upload an image file")
return
}
if (file.size > 2 * 1024 * 1024) {
toast.error("Image must be smaller than 2 MB")
return
}
try {
const dataUrl = await resizeProfileImageToDataUrl(file)
await updateImage({ image: dataUrl })
toast.success("Profile photo updated")
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to update photo"
)
}
}
async function handleClearImage() {
try {
await updateImage({})
toast.success("Profile photo removed")
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to remove photo"
)
}
}
async function handlePasswordChange() {
if (newPassword !== confirmPassword) {
toast.error("Passwords do not match")
return
}
if (newPassword.length < 8) {
toast.error("Password must be at least 8 characters")
return
}
setChangingPassword(true)
try {
await updatePassword({ newPassword })
setNewPassword("")
setConfirmPassword("")
toast.success("Password updated")
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to update password"
)
} finally {
setChangingPassword(false)
}
}
return (
<div className="space-y-8">
<div>
<h3 className="text-base font-medium">Profile</h3>
<p className="text-sm text-muted-foreground">
Manage your profile photo and account details.
</p>
</div>
<FieldGroup>
<Field>
<FieldLabel>Profile photo</FieldLabel>
<div className="flex items-center gap-4">
<UserAvatar user={user} size="default" />
<div className="flex flex-wrap gap-2">
<input
ref={fileInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={(event) => {
const file = event.target.files?.[0]
if (file) void handleImageUpload(file)
event.target.value = ""
}}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
<Upload />
Upload image
</Button>
{user.image ? (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => void handleClearImage()}
>
Remove photo
</Button>
) : null}
</div>
</div>
</Field>
<Field>
<FieldLabel htmlFor="profile-name">Name</FieldLabel>
<Input
id="profile-name"
value={name}
onChange={(event) => {
setName(event.target.value)
debouncedUpdateName(event.target.value)
}}
/>
</Field>
<Field>
<FieldLabel htmlFor="profile-email">Email</FieldLabel>
<Input
id="profile-email"
type="email"
value={email}
onChange={(event) => {
setEmail(event.target.value)
debouncedUpdateEmail(event.target.value)
}}
/>
</Field>
</FieldGroup>
<Separator />
<div className="space-y-4">
<div>
<h4 className="text-sm font-medium">Password</h4>
<p className="text-sm text-muted-foreground">
Confirm your new password to update it.
</p>
</div>
<FieldGroup>
<Field>
<FieldLabel htmlFor="new-password">New password</FieldLabel>
<Input
id="new-password"
type="password"
autoComplete="new-password"
value={newPassword}
onChange={(event) => setNewPassword(event.target.value)}
/>
</Field>
<Field>
<FieldLabel htmlFor="confirm-password">Confirm password</FieldLabel>
<Input
id="confirm-password"
type="password"
autoComplete="new-password"
value={confirmPassword}
onChange={(event) => setConfirmPassword(event.target.value)}
/>
</Field>
<Field>
<Button
type="button"
disabled={
changingPassword ||
!newPassword ||
!confirmPassword ||
newPassword !== confirmPassword
}
onClick={() => void handlePasswordChange()}
>
{changingPassword && <Spinner />}
Update password
</Button>
</Field>
</FieldGroup>
</div>
</div>
)
}
function QualitySection({ user }: { user: Doc<"users"> }) {
const updateQuality = useMutation(api.users.updatePlaybackQuality)
const updateAtmos = useMutation(api.users.updatePreferAtmos)
const quality = user.playbackQuality ?? "medium"
return (
<div className="space-y-8">
<div>
<h3 className="text-base font-medium">Quality</h3>
<p className="text-sm text-muted-foreground">
Choose your preferred playback quality and spatial audio options.
</p>
</div>
<RadioGroup
value={quality}
onValueChange={(value) => {
updateQuality({ playbackQuality: value as PlaybackQuality }).catch(
(error: Error) => toast.error(error.message)
)
}}
className="gap-3"
>
{QUALITY_OPTIONS.map((option) => (
<div
key={option.value}
className="flex items-start gap-3 rounded-lg border p-3"
>
<RadioGroupItem
value={option.value}
id={`quality-${option.value}`}
className="mt-0.5"
/>
<Label
htmlFor={`quality-${option.value}`}
className="flex cursor-pointer flex-col gap-0.5 font-normal"
>
<span className="font-medium">
{option.label} · {option.description}
</span>
</Label>
</div>
))}
</RadioGroup>
<div className="flex items-center gap-3 rounded-lg border p-4">
<Checkbox
id="prefer-atmos"
checked={user.preferAtmos ?? false}
onCheckedChange={(checked) => {
updateAtmos({ preferAtmos: checked === true }).catch(
(error: Error) => toast.error(error.message)
)
}}
/>
<Label htmlFor="prefer-atmos" className="cursor-pointer font-normal">
Prefer Dolby Atmos when available
</Label>
</div>
</div>
)
}
function CreateUserDialog({
open,
onOpenChange,
}: {
open: boolean
onOpenChange: (open: boolean) => void
}) {
const createUser = useAction(api.users.adminCreateUser)
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [isAdmin, setIsAdmin] = useState(false)
const [submitting, setSubmitting] = useState(false)
function reset() {
setName("")
setEmail("")
setPassword("")
setIsAdmin(false)
}
async function handleSubmit(event: React.FormEvent) {
event.preventDefault()
setSubmitting(true)
try {
await createUser({ name, email, password, isAdmin })
toast.success("User created")
reset()
onOpenChange(false)
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to create user"
)
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Create user</DialogTitle>
<DialogDescription>
Add a new account with email and password.
</DialogDescription>
</DialogHeader>
<form onSubmit={(event) => void handleSubmit(event)}>
<FieldGroup>
<Field>
<FieldLabel htmlFor="create-name">Name</FieldLabel>
<Input
id="create-name"
value={name}
onChange={(event) => setName(event.target.value)}
required
/>
</Field>
<Field>
<FieldLabel htmlFor="create-email">Email</FieldLabel>
<Input
id="create-email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
required
/>
</Field>
<Field>
<FieldLabel htmlFor="create-password">Password</FieldLabel>
<Input
id="create-password"
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
required
minLength={8}
/>
</Field>
<div className="flex items-center gap-2">
<Checkbox
id="create-admin"
checked={isAdmin}
onCheckedChange={(checked) => setIsAdmin(checked === true)}
/>
<Label htmlFor="create-admin" className="font-normal">
Grant admin access
</Label>
</div>
</FieldGroup>
<DialogFooter className="mt-4">
<Button type="submit" disabled={submitting}>
{submitting && <Spinner />}
Create user
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
function ChangePasswordDialog({
user,
open,
onOpenChange,
}: {
user: Doc<"users">
open: boolean
onOpenChange: (open: boolean) => void
}) {
const changePassword = useAction(api.users.adminChangeUserPassword)
const [password, setPassword] = useState("")
const [confirm, setConfirm] = useState("")
const [submitting, setSubmitting] = useState(false)
async function handleSubmit(event: React.FormEvent) {
event.preventDefault()
if (password !== confirm) {
toast.error("Passwords do not match")
return
}
setSubmitting(true)
try {
await changePassword({ userId: user._id, newPassword: password })
toast.success(`Password updated for ${user.name}`)
setPassword("")
setConfirm("")
onOpenChange(false)
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to update password"
)
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Change password</DialogTitle>
<DialogDescription>
Set a new password for {user.name} ({user.email}).
</DialogDescription>
</DialogHeader>
<form onSubmit={(event) => void handleSubmit(event)}>
<FieldGroup>
<Field>
<FieldLabel htmlFor="admin-new-password">New password</FieldLabel>
<Input
id="admin-new-password"
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
required
minLength={8}
/>
</Field>
<Field>
<FieldLabel htmlFor="admin-confirm-password">
Confirm password
</FieldLabel>
<Input
id="admin-confirm-password"
type="password"
value={confirm}
onChange={(event) => setConfirm(event.target.value)}
required
minLength={8}
/>
</Field>
</FieldGroup>
<DialogFooter className="mt-4">
<Button
type="submit"
disabled={
submitting || !password || !confirm || password !== confirm
}
>
{submitting && <Spinner />}
Update password
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
function UserRowActions({
user,
currentUserId,
}: {
user: Doc<"users">
currentUserId: Id<"users">
}) {
const setAdmin = useMutation(api.users.setUserAdmin)
const deleteUserMutation = useMutation(api.users.deleteUser)
const [passwordDialogOpen, setPasswordDialogOpen] = useState(false)
const [deleting, setDeleting] = useState(false)
const isSelf = user._id === currentUserId
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-sm">
<MoreHorizontal />
<span className="sr-only">Actions</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{!isSelf && (
<DropdownMenuItem
onClick={() => {
setAdmin({ userId: user._id, isAdmin: !user.isAdmin })
.then(() =>
toast.success(
user.isAdmin ? "Admin access removed" : "User is now admin"
)
)
.catch((error: Error) => toast.error(error.message))
}}
>
{user.isAdmin ? "Remove admin" : "Make admin"}
</DropdownMenuItem>
)}
<DropdownMenuItem onClick={() => setPasswordDialogOpen(true)}>
Change password
</DropdownMenuItem>
{!isSelf && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
disabled={deleting}
onClick={() => {
setDeleting(true)
deleteUserMutation({ userId: user._id })
.then(() => toast.success("User deleted"))
.catch((error: Error) => toast.error(error.message))
.finally(() => setDeleting(false))
}}
>
<Trash2 />
Delete account
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
<ChangePasswordDialog
user={user}
open={passwordDialogOpen}
onOpenChange={setPasswordDialogOpen}
/>
</>
)
}
function UsersSection({
users,
currentUserId,
}: {
users: Doc<"users">[]
currentUserId: Id<"users">
}) {
const appSettings = useQuery(api.users.getAppSettings)
const setDisableCreation = useMutation(api.users.setDisableAccountCreation)
const [createOpen, setCreateOpen] = useState(false)
return (
<div className="space-y-6">
<div>
<h3 className="text-base font-medium">Users</h3>
<p className="text-sm text-muted-foreground">
Manage accounts, permissions, and sign-up settings.
</p>
</div>
<div className="flex flex-col gap-4 rounded-lg border p-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-center gap-3">
<Switch
id="disable-signups"
checked={appSettings?.disableAccountCreation ?? false}
onCheckedChange={(checked) => {
setDisableCreation({ disabled: checked })
.then(() =>
toast.success(
checked
? "Account creation disabled"
: "Account creation enabled"
)
)
.catch((error: Error) => toast.error(error.message))
}}
/>
<Label htmlFor="disable-signups" className="font-normal">
Disable account creation
</Label>
</div>
<Button type="button" size="sm" onClick={() => setCreateOpen(true)}>
<UserPlus />
Create user
</Button>
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>User</TableHead>
<TableHead>Name</TableHead>
<TableHead>Email</TableHead>
<TableHead className="w-10" />
</TableRow>
</TableHeader>
<TableBody>
{users.map((user) => (
<TableRow key={user._id}>
<TableCell>
<div className="flex items-center gap-2">
<UserAvatar user={user} size="sm" />
{user.isAdmin ? (
<span className="text-xs text-muted-foreground">Admin</span>
) : null}
</div>
</TableCell>
<TableCell>{user.name}</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>
<UserRowActions user={user} currentUserId={currentUserId} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<CreateUserDialog open={createOpen} onOpenChange={setCreateOpen} />
</div>
)
}
export function OptionsModal({
open,
onOpenChange,
}: {
open: boolean
onOpenChange: (open: boolean) => void
}) {
const user = useQuery(api.auth.currentUser)
const allUsers = useQuery(api.users.listUsers)
const [section, setSection] = useState<Section>("profile")
const isAdmin = user?.isAdmin === true
useEffect(() => {
if (!open) {
setSection("profile")
}
}, [open])
useEffect(() => {
if (!isAdmin && section === "users") {
setSection("profile")
}
}, [isAdmin, section])
if (!user) {
return null
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
showCloseButton
className="flex h-[min(32rem,85vh)] max-h-[85vh] flex-col gap-0 overflow-hidden p-0 sm:max-w-4xl"
>
<DialogTitle className="sr-only">Settings</DialogTitle>
<div className="flex min-h-0 flex-1">
<aside className="flex w-52 shrink-0 flex-col border-r bg-muted/20 p-4">
<p className="mb-2 px-2.5 text-xs font-medium tracking-wide text-muted-foreground uppercase">
User Settings
</p>
<nav className="flex flex-col gap-0.5">
<NavButton
active={section === "profile"}
onClick={() => setSection("profile")}
>
Profile
</NavButton>
<NavButton
active={section === "quality"}
onClick={() => setSection("quality")}
>
Quality
</NavButton>
</nav>
{isAdmin ? (
<>
<Separator className="my-4" />
<p className="mb-2 px-2.5 text-xs font-medium tracking-wide text-muted-foreground uppercase">
Admin Settings
</p>
<nav className="flex flex-col gap-0.5">
<NavButton
active={section === "users"}
onClick={() => setSection("users")}
>
Users
</NavButton>
</nav>
</>
) : null}
</aside>
<ScrollArea className="min-h-0 flex-1">
<div className="p-6">
{section === "profile" && <ProfileSection user={user} />}
{section === "quality" && <QualitySection user={user} />}
{section === "users" && isAdmin && allUsers ? (
<UsersSection users={allUsers} currentUserId={user._id} />
) : null}
</div>
</ScrollArea>
</div>
</DialogContent>
</Dialog>
)
}
+1 -1
View File
@@ -15,7 +15,7 @@ import { Button } from "@/components/ui/button"
export function PlayerBar() {
return (
<div className="pointer-events-none absolute inset-x-0 bottom-0 z-10 flex justify-center px-4 pb-4">
<div className="pointer-events-none fixed bottom-0 left-0 right-0 z-10 flex justify-center px-4 pb-4 md:left-[var(--sidebar-width)] md:peer-data-[state=collapsed]:left-0">
<div className="pointer-events-auto flex w-full max-w-3xl items-center gap-3 rounded-xl border bg-card/80 px-3 py-2 shadow-lg backdrop-blur">
<div className="flex items-center gap-1">
<Button variant="ghost" size="icon" aria-label="Shuffle">
+3 -3
View File
@@ -43,7 +43,7 @@ function DropdownMenuContent({
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
align={align}
className={cn("z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 animate-none! relative bg-popover/70 before:pointer-events-none before:absolute before:inset-0 before:-z-1 before:rounded-[inherit] before:backdrop-blur-2xl before:backdrop-saturate-150 **:data-[slot$=-item]:focus:bg-foreground/10 **:data-[slot$=-item]:data-highlighted:bg-foreground/10 **:data-[slot$=-separator]:bg-foreground/5 **:data-[slot$=-trigger]:focus:bg-foreground/10 **:data-[slot$=-trigger]:aria-expanded:bg-foreground/10! **:data-[variant=destructive]:focus:bg-foreground/10! **:data-[variant=destructive]:text-accent-foreground! **:data-[variant=destructive]:**:text-accent-foreground!", className )}
className={cn("z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 animate-none! relative bg-popover/70 before:pointer-events-none before:absolute before:inset-0 before:-z-1 before:rounded-[inherit] before:backdrop-blur-2xl before:backdrop-saturate-150 **:data-[slot$=-item]:not-data-[variant=destructive]:focus:bg-foreground/10 **:data-[slot$=-item]:not-data-[variant=destructive]:data-highlighted:bg-foreground/10 **:data-[slot$=-item]:not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground **:data-[slot$=-separator]:bg-foreground/5 **:data-[slot$=-trigger]:focus:bg-foreground/10 **:data-[slot$=-trigger]:aria-expanded:bg-foreground/10!", className )}
{...props}
/>
</DropdownMenuPrimitive.Portal>
@@ -73,7 +73,7 @@ function DropdownMenuItem({
data-inset={inset}
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:data-highlighted:bg-destructive/10 data-[variant=destructive]:data-highlighted:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 dark:data-[variant=destructive]:data-highlighted:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
className
)}
{...props}
@@ -244,7 +244,7 @@ function DropdownMenuSubContent({
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn("z-50 min-w-[96px] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-lg p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 animate-none! relative bg-popover/70 before:pointer-events-none before:absolute before:inset-0 before:-z-1 before:rounded-[inherit] before:backdrop-blur-2xl before:backdrop-saturate-150 **:data-[slot$=-item]:focus:bg-foreground/10 **:data-[slot$=-item]:data-highlighted:bg-foreground/10 **:data-[slot$=-separator]:bg-foreground/5 **:data-[slot$=-trigger]:focus:bg-foreground/10 **:data-[slot$=-trigger]:aria-expanded:bg-foreground/10! **:data-[variant=destructive]:focus:bg-foreground/10! **:data-[variant=destructive]:text-accent-foreground! **:data-[variant=destructive]:**:text-accent-foreground!", className )}
className={cn("z-50 min-w-[96px] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-lg p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 animate-none! relative bg-popover/70 before:pointer-events-none before:absolute before:inset-0 before:-z-1 before:rounded-[inherit] before:backdrop-blur-2xl before:backdrop-saturate-150 **:data-[slot$=-item]:not-data-[variant=destructive]:focus:bg-foreground/10 **:data-[slot$=-item]:not-data-[variant=destructive]:data-highlighted:bg-foreground/10 **:data-[slot$=-item]:not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground **:data-[slot$=-separator]:bg-foreground/5 **:data-[slot$=-trigger]:focus:bg-foreground/10 **:data-[slot$=-trigger]:aria-expanded:bg-foreground/10!", className )}
{...props}
/>
)
+6
View File
@@ -9,8 +9,11 @@
*/
import type * as actions from "../actions.js";
import type * as auth from "../auth.js";
import type * as crons from "../crons.js";
import type * as http from "../http.js";
import type * as library from "../library.js";
import type * as users from "../users.js";
import type {
ApiFromModules,
@@ -20,8 +23,11 @@ import type {
declare const fullApi: ApiFromModules<{
actions: typeof actions;
auth: typeof auth;
crons: typeof crons;
http: typeof http;
library: typeof library;
users: typeof users;
}>;
/**
+8
View File
@@ -0,0 +1,8 @@
export default {
providers: [
{
domain: process.env.CONVEX_SITE_URL,
applicationID: "convex",
},
],
};
+61
View File
@@ -0,0 +1,61 @@
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)
},
})
+8
View File
@@ -0,0 +1,8 @@
import { httpRouter } from "convex/server";
import { auth } from "./auth";
const http = httpRouter();
auth.addHttpRoutes(http);
export default http;
+20
View File
@@ -1,7 +1,27 @@
import { defineSchema, defineTable } from "convex/server"
import { v } from "convex/values"
import { authTables } from "@convex-dev/auth/server"
export default defineSchema({
...authTables,
users: defineTable({
name: v.string(),
image: v.optional(v.string()),
email: v.string(),
isAdmin: v.optional(v.boolean()),
playbackQuality: v.optional(
v.union(
v.literal("low"),
v.literal("medium"),
v.literal("high"),
v.literal("lossless")
)
),
preferAtmos: v.optional(v.boolean()),
}).index("email", ["email"]),
appSettings: defineTable({
disableAccountCreation: v.boolean(),
}),
artists: defineTable({
name: v.string(),
cover: v.nullable(v.string()),
+325
View File
@@ -0,0 +1,325 @@
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,
},
})
},
})
+49
View File
@@ -0,0 +1,49 @@
const PROFILE_IMAGE_SIZE = 256
/**
* Downscales an image to 256×256 (center-cropped cover) and returns a base64 data URL.
*/
export function resizeProfileImageToDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(file)
const image = new Image()
image.onload = () => {
URL.revokeObjectURL(url)
const canvas = document.createElement("canvas")
canvas.width = PROFILE_IMAGE_SIZE
canvas.height = PROFILE_IMAGE_SIZE
const ctx = canvas.getContext("2d")
if (!ctx) {
reject(new Error("Could not process image"))
return
}
const scale = Math.max(
PROFILE_IMAGE_SIZE / image.width,
PROFILE_IMAGE_SIZE / image.height
)
const width = image.width * scale
const height = image.height * scale
const x = (PROFILE_IMAGE_SIZE - width) / 2
const y = (PROFILE_IMAGE_SIZE - height) / 2
ctx.drawImage(image, x, y, width, height)
const outputType =
file.type === "image/png" || file.type === "image/webp"
? "image/png"
: "image/jpeg"
resolve(canvas.toDataURL(outputType, outputType === "image/jpeg" ? 0.9 : undefined))
}
image.onerror = () => {
URL.revokeObjectURL(url)
reject(new Error("Could not load image"))
}
image.src = url
})
}
+226 -1
View File
@@ -8,7 +8,9 @@
"name": "otunes",
"version": "0.0.1",
"dependencies": {
"@auth/core": "^0.37.0",
"@base-ui/react": "^1.5.0",
"@convex-dev/auth": "^0.0.93",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
@@ -17,7 +19,7 @@
"embla-carousel-react": "^8.6.0",
"input-otp": "^1.4.2",
"lucide-react": "^1.17.0",
"music-metadata": "^11.12.3",
"music-metadata": "11.12.3",
"next": "16.2.6",
"next-themes": "^0.4.6",
"radix-ui": "^1.4.3",
@@ -59,6 +61,55 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@auth/core": {
"version": "0.37.0",
"resolved": "https://registry.npmjs.org/@auth/core/-/core-0.37.0.tgz",
"integrity": "sha512-LybAgfFC5dta3Mu3al0UbnzMGVBpZRqLMvvXupQOfETtPNlL7rXgTO13EVRTCdvPqMQrVYjODUDvgVfQM1M3Qg==",
"license": "ISC",
"dependencies": {
"@panva/hkdf": "^1.2.1",
"@types/cookie": "0.6.0",
"cookie": "0.7.1",
"jose": "^5.9.3",
"oauth4webapi": "^3.0.0",
"preact": "10.11.3",
"preact-render-to-string": "5.2.3"
},
"peerDependencies": {
"@simplewebauthn/browser": "^9.0.1",
"@simplewebauthn/server": "^9.0.2",
"nodemailer": "^6.8.0"
},
"peerDependenciesMeta": {
"@simplewebauthn/browser": {
"optional": true
},
"@simplewebauthn/server": {
"optional": true
},
"nodemailer": {
"optional": true
}
}
},
"node_modules/@auth/core/node_modules/cookie": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz",
"integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/@auth/core/node_modules/jose": {
"version": "5.10.0",
"resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz",
"integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/@babel/code-frame": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
@@ -543,6 +594,59 @@
"url": "https://github.com/sponsors/Borewit"
}
},
"node_modules/@convex-dev/auth": {
"version": "0.0.93",
"resolved": "https://registry.npmjs.org/@convex-dev/auth/-/auth-0.0.93.tgz",
"integrity": "sha512-z7g1lxcNz1Yck238i79rCIubT+rCM1V9sDUdUkZfthPmOarDx0uchut/Gy78xvjQTTSy1oW1XHECKxdclmdJQA==",
"license": "Apache-2.0",
"dependencies": {
"@oslojs/crypto": "^1.0.1",
"@oslojs/encoding": "^1.1.0",
"cookie": "^1.0.1",
"is-network-error": "^1.1.0",
"jose": "^5.2.2",
"jwt-decode": "^4.0.0",
"lucia": "^3.2.0",
"oauth4webapi": "^3.1.2",
"path-to-regexp": "^6.3.0",
"server-only": "^0.0.1"
},
"bin": {
"auth": "dist/bin.cjs"
},
"peerDependencies": {
"@auth/core": "^0.37.0",
"convex": "^1.17.0",
"react": "^18.2.0 || ^19.0.0-0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
}
}
},
"node_modules/@convex-dev/auth/node_modules/cookie": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/@convex-dev/auth/node_modules/jose": {
"version": "5.10.0",
"resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz",
"integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/@convex-dev/eslint-plugin": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@convex-dev/eslint-plugin/-/eslint-plugin-2.0.0.tgz",
@@ -2624,6 +2728,46 @@
"integrity": "sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==",
"license": "MIT"
},
"node_modules/@oslojs/asn1": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@oslojs/asn1/-/asn1-1.0.0.tgz",
"integrity": "sha512-zw/wn0sj0j0QKbIXfIlnEcTviaCzYOY3V5rAyjR6YtOByFtJiT574+8p9Wlach0lZH9fddD4yb9laEAIl4vXQA==",
"license": "MIT",
"dependencies": {
"@oslojs/binary": "1.0.0"
}
},
"node_modules/@oslojs/binary": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@oslojs/binary/-/binary-1.0.0.tgz",
"integrity": "sha512-9RCU6OwXU6p67H4NODbuxv2S3eenuQ4/WFLrsq+K/k682xrznH5EVWA7N4VFk9VYVcbFtKqur5YQQZc0ySGhsQ==",
"license": "MIT"
},
"node_modules/@oslojs/crypto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@oslojs/crypto/-/crypto-1.0.1.tgz",
"integrity": "sha512-7n08G8nWjAr/Yu3vu9zzrd0L9XnrJfpMioQcvCMxBIiF5orECHe5/3J0jmXRVvgfqMm/+4oxlQ+Sq39COYLcNQ==",
"license": "MIT",
"dependencies": {
"@oslojs/asn1": "1.0.0",
"@oslojs/binary": "1.0.0"
}
},
"node_modules/@oslojs/encoding": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@oslojs/encoding/-/encoding-1.1.0.tgz",
"integrity": "sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ==",
"license": "MIT"
},
"node_modules/@panva/hkdf": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@panva/hkdf/-/hkdf-1.2.1.tgz",
"integrity": "sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/@radix-ui/number": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
@@ -4584,6 +4728,12 @@
"tslib": "^2.4.0"
}
},
"node_modules/@types/cookie": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",
"integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==",
"license": "MIT"
},
"node_modules/@types/d3-array": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
@@ -8747,6 +8897,18 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-network-error": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/is-network-error/-/is-network-error-1.3.2.tgz",
"integrity": "sha512-PhBY86zaxNZUuWP6h13Vu5oFe0XY6/UlKzQnYFELzGVHygP3MxmvTfYSG7GN3aIab/iWudSMgjSnG9Dq+nHrgA==",
"license": "MIT",
"engines": {
"node": ">=16"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-node-process": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/is-node-process/-/is-node-process-1.2.0.tgz",
@@ -9158,6 +9320,15 @@
"node": ">=4.0"
}
},
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -9563,6 +9734,17 @@
"yallist": "^3.0.2"
}
},
"node_modules/lucia": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/lucia/-/lucia-3.2.2.tgz",
"integrity": "sha512-P1FlFBGCMPMXu+EGdVD9W4Mjm0DqsusmKgO7Xc33mI5X1bklmsQb0hfzPhXomQr9waWIBDsiOjvr1e6BTaUqpA==",
"deprecated": "This package has been deprecated. Please see https://lucia-auth.com/lucia-v3/migrate.",
"license": "MIT",
"dependencies": {
"@oslojs/crypto": "^1.0.1",
"@oslojs/encoding": "^1.1.0"
}
},
"node_modules/lucide-react": {
"version": "1.17.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.17.0.tgz",
@@ -10046,6 +10228,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/oauth4webapi": {
"version": "3.8.6",
"resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.6.tgz",
"integrity": "sha512-iwemM91xz8nryHti2yTmg5fhyEMVOkOXwHNqbvcATjyajb5oQxCQzrNOA6uElRHuMhQQTKUyFKV9y/CNyg25BQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@@ -10547,6 +10738,28 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/preact": {
"version": "10.11.3",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.11.3.tgz",
"integrity": "sha512-eY93IVpod/zG3uMF22Unl8h9KkrcKIRs2EGar8hwLZZDU1lkjph303V9HZBwufh2s736U6VXuhD109LYqPoffg==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
}
},
"node_modules/preact-render-to-string": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-5.2.3.tgz",
"integrity": "sha512-aPDxUn5o3GhWdtJtW0svRC2SS/l8D9MAgo2+AWml+BhDImb27ALf04Q2d+AHqUUOc6RdSXFIBVa2gxzgMKgtZA==",
"license": "MIT",
"dependencies": {
"pretty-format": "^3.8.0"
},
"peerDependencies": {
"preact": ">=10"
}
},
"node_modules/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
@@ -10651,6 +10864,12 @@
}
}
},
"node_modules/pretty-format": {
"version": "3.8.0",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-3.8.0.tgz",
"integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==",
"license": "MIT"
},
"node_modules/pretty-ms": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.3.0.tgz",
@@ -11406,6 +11625,12 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/server-only": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/server-only/-/server-only-0.0.1.tgz",
"integrity": "sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==",
"license": "MIT"
},
"node_modules/set-cookie-parser": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.1.0.tgz",
+2
View File
@@ -12,7 +12,9 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@auth/core": "^0.37.0",
"@base-ui/react": "^1.5.0",
"@convex-dev/auth": "^0.0.93",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
+23
View File
@@ -0,0 +1,23 @@
import {
convexAuthNextjsMiddleware,
createRouteMatcher,
nextjsMiddlewareRedirect,
} from "@convex-dev/auth/nextjs/server"
const isAuthPage = createRouteMatcher(["/signin", "/signup"])
export default convexAuthNextjsMiddleware(async (request, { convexAuth }) => {
const authenticated = await convexAuth.isAuthenticated()
if (isAuthPage(request) && authenticated) {
return nextjsMiddlewareRedirect(request, "/")
}
if (!isAuthPage(request) && !authenticated) {
return nextjsMiddlewareRedirect(request, "/signin")
}
})
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
}