feat: implement Supabase database schema and core authentication flow with registration and login pages

This commit is contained in:
Poyraz Avsever
2026-05-07 11:11:15 +03:00
parent 4126b41064
commit 904375ea5c
21 changed files with 8832 additions and 127 deletions
+20
View File
@@ -0,0 +1,20 @@
import { Sidebar } from "@/components/layout/sidebar";
import { Header } from "@/components/layout/header";
export default function DashboardLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<div className="flex min-h-screen bg-background text-foreground">
<Sidebar />
<div className="flex flex-col flex-1 h-screen overflow-hidden">
<Header />
<main className="flex-1 overflow-y-auto p-6 md:p-8">
{children}
</main>
</div>
</div>
);
}
+81
View File
@@ -0,0 +1,81 @@
'use server'
import { createClient } from '@/lib/supabase/server'
import { revalidatePath } from 'next/cache'
export async function updateProfile(formData: FormData) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return { error: 'Kullanıcı bulunamadı.' }
}
const firstName = formData.get('firstName') as string
const lastName = formData.get('lastName') as string
const avatarFile = formData.get('avatar') as File | null
let avatarUrl = undefined
// Upload avatar if a new file is provided
if (avatarFile && avatarFile.size > 0) {
const fileExt = avatarFile.name.split('.').pop()
const fileName = `${user.id}/${Math.random()}.${fileExt}`
const { error: uploadError, data: uploadData } = await supabase.storage
.from('avatars')
.upload(fileName, avatarFile, { upsert: true })
if (uploadError) {
return { error: 'Profil fotoğrafı yüklenirken hata oluştu: ' + uploadError.message }
}
// Get public URL
const { data: { publicUrl } } = supabase.storage
.from('avatars')
.getPublicUrl(fileName)
avatarUrl = publicUrl
}
// Update profile
const updateData: any = {
first_name: firstName,
last_name: lastName,
}
if (avatarUrl) {
updateData.avatar_url = avatarUrl
}
// Upsert profile in case it doesn't exist yet
const { error } = await supabase
.from('profiles')
.upsert({ id: user.id, ...updateData })
if (error) {
return { error: 'Profil güncellenirken hata oluştu: ' + error.message }
}
revalidatePath('/settings')
return { success: true }
}
export async function updatePassword(formData: FormData) {
const supabase = await createClient()
const password = formData.get('password') as string
if (!password || password.length < 6) {
return { error: 'Şifre en az 6 karakter olmalıdır.' }
}
const { error } = await supabase.auth.updateUser({
password: password
})
if (error) {
return { error: 'Şifre güncellenirken hata oluştu: ' + error.message }
}
return { success: true }
}
+228
View File
@@ -0,0 +1,228 @@
"use client";
import { useState, useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectTrigger,
SelectValue,
SelectContent,
SelectItem,
} from "@/components/ui/select";
import { Bot, Save, User, KeyRound } from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { updateProfile, updatePassword } from "./actions";
export default function SettingsPage() {
const [aiProvider, setAiProvider] = useState("groq");
const [apiKey, setApiKey] = useState("");
const [saveStatus, setSaveStatus] = useState("");
// Profile state
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [avatarUrl, setAvatarUrl] = useState("");
const [profileSaveStatus, setProfileSaveStatus] = useState("");
const [passwordSaveStatus, setPasswordSaveStatus] = useState("");
const formRef = useRef<HTMLFormElement>(null);
const supabase = createClient();
useEffect(() => {
const savedProvider = localStorage.getItem("mindspace_ai_provider");
const savedApiKey = localStorage.getItem("mindspace_api_key");
if (savedProvider) setAiProvider(savedProvider);
if (savedApiKey) setApiKey(savedApiKey);
// Fetch user profile
async function fetchProfile() {
const { data: { user } } = await supabase.auth.getUser();
if (user) {
const { data } = await supabase.from("profiles").select("*").eq("id", user.id).single();
if (data) {
setFirstName(data.first_name || "");
setLastName(data.last_name || "");
setAvatarUrl(data.avatar_url || "");
}
}
}
fetchProfile();
}, []);
const handleSaveAI = () => {
localStorage.setItem("mindspace_ai_provider", aiProvider);
localStorage.setItem("mindspace_api_key", apiKey);
setSaveStatus("Ayarlar başarıyla kaydedildi!");
setTimeout(() => setSaveStatus(""), 3000);
};
const handleProfileAction = async (formData: FormData) => {
const res = await updateProfile(formData);
if (res?.error) {
setProfileSaveStatus("Hata: " + res.error);
} else {
setProfileSaveStatus("Profil başarıyla güncellendi!");
if (formData.get("avatar") && (formData.get("avatar") as File).size > 0) {
window.location.reload();
}
}
setTimeout(() => setProfileSaveStatus(""), 3000);
};
const handlePasswordAction = async (formData: FormData) => {
const res = await updatePassword(formData);
if (res?.error) {
setPasswordSaveStatus("Hata: " + res.error);
} else {
setPasswordSaveStatus("Şifre başarıyla güncellendi!");
formRef.current?.reset();
}
setTimeout(() => setPasswordSaveStatus(""), 3000);
};
return (
<div className="flex flex-col gap-6 p-4 max-w-2xl mx-auto w-full">
<div>
<h1 className="text-3xl font-bold text-foreground">Ayarlar</h1>
<p className="text-muted-foreground mt-1">
Kullanıcı profili ve yapay zeka asistanı yapılandırmanızı yönetin.
</p>
</div>
{/* Profile Settings */}
<div className="bg-card border border-border rounded-xl p-6 shadow-sm space-y-6 flex flex-col">
<div className="flex items-center gap-3 border-b border-border/50 pb-4">
<User className="w-6 h-6 text-primary" />
<h2 className="text-xl font-semibold">Kullanıcı Profili</h2>
</div>
<form action={handleProfileAction} className="space-y-4">
<div className="flex items-center gap-4 mb-6">
{avatarUrl ? (
<img src={avatarUrl} alt="Avatar" className="w-16 h-16 rounded-full object-cover border border-border" />
) : (
<div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center border border-border">
<User className="w-8 h-8 text-muted-foreground" />
</div>
)}
<div className="space-y-1 flex-1">
<Label htmlFor="avatar">Profil Fotoğrafı Yükle</Label>
<Input id="avatar" name="avatar" type="file" accept="image/*" />
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="firstName">Ad</Label>
<Input id="firstName" name="firstName" value={firstName} onChange={(e) => setFirstName(e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="lastName">Soyad</Label>
<Input id="lastName" name="lastName" value={lastName} onChange={(e) => setLastName(e.target.value)} />
</div>
</div>
<div className="flex items-center gap-4 mt-4">
<Button type="submit" className="w-max">
<Save className="w-4 h-4 mr-2" />
Profili Kaydet
</Button>
{profileSaveStatus && (
<span className={`text-sm ${profileSaveStatus.startsWith("Hata") ? "text-red-500" : "text-green-600 dark:text-green-400"}`}>
{profileSaveStatus}
</span>
)}
</div>
</form>
</div>
{/* Password Settings */}
<div className="bg-card border border-border rounded-xl p-6 shadow-sm space-y-6 flex flex-col">
<div className="flex items-center gap-3 border-b border-border/50 pb-4">
<KeyRound className="w-6 h-6 text-primary" />
<h2 className="text-xl font-semibold">Şifre Değiştir</h2>
</div>
<form ref={formRef} action={handlePasswordAction} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="password">Yeni Şifre</Label>
<Input id="password" name="password" type="password" minLength={6} placeholder="En az 6 karakter" required />
</div>
<div className="flex items-center gap-4 mt-4">
<Button type="submit" className="w-max">
<Save className="w-4 h-4 mr-2" />
Şifreyi Güncelle
</Button>
{passwordSaveStatus && (
<span className={`text-sm ${passwordSaveStatus.startsWith("Hata") ? "text-red-500" : "text-green-600 dark:text-green-400"}`}>
{passwordSaveStatus}
</span>
)}
</div>
</form>
</div>
{/* AI Settings */}
<div className="bg-card border border-border rounded-xl p-6 shadow-sm space-y-6 flex flex-col">
<div className="flex items-center gap-3 border-b border-border/50 pb-4">
<Bot className="w-6 h-6 text-primary" />
<h2 className="text-xl font-semibold">Terapist (AI) Ayarları</h2>
</div>
<div className="space-y-4">
<div className="space-y-2">
<Label>AI Sağlayıcısı</Label>
<Select value={aiProvider} onValueChange={setAiProvider}>
<SelectTrigger className="w-full">
<SelectValue placeholder="Sağlayıcı seçin" />
</SelectTrigger>
<SelectContent>
<SelectItem value="ollama">
Ollama (Yerel & Gizlilik Odaklı)
</SelectItem>
<SelectItem value="openai">OpenAI (GPT-4o vb.)</SelectItem>
<SelectItem value="groq">Groq (Llama-3 Bulut)</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Gizliliğiniz için yerel Ollama önerilir. Sunucunuzda çalışmayan
durumlarda OpenAI veya Groq gibi bulut çözümlerine geçebilirsiniz.
</p>
</div>
{aiProvider !== "ollama" && (
<div className="space-y-2">
<Label>API Anahtarı ({aiProvider.toUpperCase()})</Label>
<Input
type="password"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder="sk-..."
/>
<p className="text-xs text-muted-foreground">
Anahtarınız sadece tarayıcınızın kendi local hafızasında güvenle
saklanır, hiçbir sunucuya kaydedilmez.
</p>
</div>
)}
<div className="flex items-center gap-4 mt-4">
<Button onClick={handleSaveAI} className="w-max">
<Save className="w-4 h-4 mr-2" />
Kaydet
</Button>
{saveStatus && (
<span className="text-sm text-green-600 dark:text-green-400">
{saveStatus}
</span>
)}
</div>
</div>
</div>
</div>
);
}
+3 -11
View File
@@ -3,8 +3,7 @@ import "./globals.css";
import { Geist } from "next/font/google"; import { Geist } from "next/font/google";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { ThemeProvider } from "@/components/theme-provider"; import { ThemeProvider } from "@/components/theme-provider";
import { Sidebar } from "@/components/layout/sidebar"; import { Toaster } from "react-hot-toast";
import { Header } from "@/components/layout/header";
const geist = Geist({ subsets: ["latin"], variable: "--font-sans" }); const geist = Geist({ subsets: ["latin"], variable: "--font-sans" });
@@ -31,15 +30,8 @@ export default function RootLayout({
enableSystem enableSystem
disableTransitionOnChange disableTransitionOnChange
> >
<div className="flex min-h-screen bg-background text-foreground"> {children}
<Sidebar /> <Toaster position="top-right" />
<div className="flex flex-col flex-1 h-screen overflow-hidden">
<Header />
<main className="flex-1 overflow-y-auto p-6 md:p-8">
{children}
</main>
</div>
</div>
</ThemeProvider> </ThemeProvider>
</body> </body>
</html> </html>
+2 -3
View File
@@ -15,8 +15,7 @@ export async function login(formData: FormData) {
const { error } = await supabase.auth.signInWithPassword(data) const { error } = await supabase.auth.signInWithPassword(data)
if (error) { if (error) {
// Ideally, pass this error to the UI via URL params or state redirect(`/login?error=true&message=${encodeURIComponent(error.message)}`)
redirect('/login?error=true')
} }
revalidatePath('/', 'layout') revalidatePath('/', 'layout')
@@ -34,7 +33,7 @@ export async function signup(formData: FormData) {
const { error } = await supabase.auth.signUp(data) const { error } = await supabase.auth.signUp(data)
if (error) { if (error) {
redirect('/login?error=true') redirect(`/login?error=true&message=${encodeURIComponent(error.message)}`)
} }
revalidatePath('/', 'layout') revalidatePath('/', 'layout')
+22 -8
View File
@@ -1,17 +1,28 @@
import { login, signup } from './actions' import { login } from './actions'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label' import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card' import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import Link from 'next/link'
import { ErrorToaster } from '@/components/error-toaster'
export default async function LoginPage({
searchParams,
}: {
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
const resolvedParams = await searchParams;
const error = resolvedParams?.error;
const message = resolvedParams?.message;
export default function LoginPage() {
return ( return (
<div className="flex items-center justify-center min-h-screen bg-background"> <div className="flex items-center justify-center min-h-screen bg-background p-4">
{error && message && <ErrorToaster message={String(message)} />}
<Card className="w-full max-w-md"> <Card className="w-full max-w-md">
<CardHeader className="space-y-1"> <CardHeader className="space-y-1">
<CardTitle className="text-2xl font-bold text-center">MindSpace</CardTitle> <CardTitle className="text-2xl font-bold text-center">MindSpace</CardTitle>
<CardDescription className="text-center"> <CardDescription className="text-center">
Hesabınıza giriş yapın veya yeni hesap oluşturun Hesabınıza giriş yapın
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
@@ -26,13 +37,16 @@ export default function LoginPage() {
<Input id="password" name="password" type="password" required /> <Input id="password" name="password" type="password" required />
</div> </div>
</div> </div>
<div className="flex flex-col space-y-2 mt-6"> <div className="flex flex-col space-y-4 mt-6">
<Button formAction={login} className="w-full"> <Button formAction={login} className="w-full">
Giriş Yap Giriş Yap
</Button> </Button>
<Button formAction={signup} variant="outline" className="w-full"> <div className="text-center text-sm">
Kayıt Ol Hesabınız yok mu?{' '}
</Button> <Link href="/register" className="text-primary hover:underline">
Kayıt Ol
</Link>
</div>
</div> </div>
</form> </form>
</CardContent> </CardContent>
+56
View File
@@ -0,0 +1,56 @@
import { signup } from '@/app/login/actions'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import Link from 'next/link'
import { ErrorToaster } from '@/components/error-toaster'
export default async function RegisterPage({
searchParams,
}: {
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
const resolvedParams = await searchParams;
const error = resolvedParams?.error;
const message = resolvedParams?.message;
return (
<div className="flex items-center justify-center min-h-screen bg-background p-4">
{error && message && <ErrorToaster message={String(message)} />}
<Card className="w-full max-w-md">
<CardHeader className="space-y-1">
<CardTitle className="text-2xl font-bold text-center">MindSpace</CardTitle>
<CardDescription className="text-center">
Yeni bir hesap oluşturun
</CardDescription>
</CardHeader>
<CardContent>
<form>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">E-posta</Label>
<Input id="email" name="email" type="email" placeholder="ornek@mail.com" required />
</div>
<div className="space-y-2">
<Label htmlFor="password">Şifre</Label>
<Input id="password" name="password" type="password" required />
</div>
</div>
<div className="flex flex-col space-y-4 mt-6">
<Button formAction={signup} className="w-full">
Kayıt Ol
</Button>
<div className="text-center text-sm">
Zaten hesabınız var mı?{' '}
<Link href="/login" className="text-primary hover:underline">
Giriş Yap
</Link>
</div>
</div>
</form>
</CardContent>
</Card>
</div>
)
}
-104
View File
@@ -1,104 +0,0 @@
"use client";
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectTrigger,
SelectValue,
SelectContent,
SelectItem,
} from "@/components/ui/select";
import { Bot, Save } from "lucide-react";
export default function SettingsPage() {
const [aiProvider, setAiProvider] = useState("groq"); // Varsayılan olarak Groq yapalım
const [apiKey, setApiKey] = useState("");
const [saveStatus, setSaveStatus] = useState("");
// Sayfa yüklendiğinde LocalStorage'dan ayarları çek
useEffect(() => {
const savedProvider = localStorage.getItem("mindspace_ai_provider");
const savedApiKey = localStorage.getItem("mindspace_api_key");
if (savedProvider) setAiProvider(savedProvider);
if (savedApiKey) setApiKey(savedApiKey);
}, []);
const handleSave = () => {
localStorage.setItem("mindspace_ai_provider", aiProvider);
localStorage.setItem("mindspace_api_key", apiKey);
setSaveStatus("Ayarlar başarıyla kaydedildi!");
setTimeout(() => setSaveStatus(""), 3000);
};
return (
<div className="flex flex-col gap-6 p-4 max-w-2xl mx-auto w-full">
<div>
<h1 className="text-3xl font-bold text-foreground">Ayarlar</h1>
<p className="text-muted-foreground mt-1">
Yapay zeka asistanı ve uygulama yapılandırmanızı yönetin.
</p>
</div>
<div className="bg-card border border-border rounded-xl p-6 shadow-sm space-y-6 flex flex-col">
<div className="flex items-center gap-3 border-b border-border/50 pb-4">
<Bot className="w-6 h-6 text-primary" />
<h2 className="text-xl font-semibold">Terapist (AI) Ayarları</h2>
</div>
<div className="space-y-4">
<div className="space-y-2">
<Label>AI Sağlayıcısı</Label>
<Select value={aiProvider} onValueChange={setAiProvider}>
<SelectTrigger className="w-full">
<SelectValue placeholder="Sağlayıcı seçin" />
</SelectTrigger>
<SelectContent>
<SelectItem value="ollama">
Ollama (Yerel & Gizlilik Odaklı)
</SelectItem>
<SelectItem value="openai">OpenAI (GPT-4o vb.)</SelectItem>
<SelectItem value="groq">Groq (Llama-3 Bulut)</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Gizliliğiniz için yerel Ollama önerilir. Sunucunuzda çalışmayan
durumlarda OpenAI veya Groq gibi bulut çözümlerine geçebilirsiniz.
</p>
</div>
{aiProvider !== "ollama" && (
<div className="space-y-2">
<Label>API Anahtarı ({aiProvider.toUpperCase()})</Label>
<Input
type="password"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder="sk-..."
/>
<p className="text-xs text-muted-foreground">
Anahtarınız sadece tarayıcınızın kendi local hafızasında güvenle
saklanır, hiçbir sunucuya kaydedilmez.
</p>
</div>
)}
<div className="flex items-center gap-4 mt-4">
<Button onClick={handleSave} className="w-max">
<Save className="w-4 h-4 mr-2" />
Kaydet
</Button>
{saveStatus && (
<span className="text-sm text-green-600 dark:text-green-400">
{saveStatus}
</span>
)}
</div>
</div>
</div>
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
'use client'
import { useEffect } from 'react'
import { toast } from 'react-hot-toast'
export function ErrorToaster({ message }: { message: string }) {
useEffect(() => {
if (message) {
toast.error(message)
}
}, [message])
return null
}
+1
View File
@@ -38,6 +38,7 @@ export async function updateSession(request: NextRequest) {
if ( if (
!user && !user &&
!request.nextUrl.pathname.startsWith('/login') && !request.nextUrl.pathname.startsWith('/login') &&
!request.nextUrl.pathname.startsWith('/register') &&
!request.nextUrl.pathname.startsWith('/auth') !request.nextUrl.pathname.startsWith('/auth')
) { ) {
// no user, potentially respond by redirecting the user to the login page // no user, potentially respond by redirecting the user to the login page
View File
+1
View File
@@ -33,6 +33,7 @@
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"react-hook-form": "^7.75.0", "react-hook-form": "^7.75.0",
"react-hot-toast": "^2.6.0",
"recharts": "^2.15.4", "recharts": "^2.15.4",
"shadcn": "^4.7.0", "shadcn": "^4.7.0",
"tailwind-merge": "^3.5.0", "tailwind-merge": "^3.5.0",
+8343
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

+59
View File
@@ -121,3 +121,62 @@ create policy "Users can delete their own chat messages." on public.chat_message
and chat_sessions.user_id = auth.uid() and chat_sessions.user_id = auth.uid()
) )
); );
-- 5. Create profiles table
create table public.profiles (
id uuid references auth.users(id) on delete cascade primary key,
first_name text,
last_name text,
avatar_url text,
updated_at timestamp with time zone default timezone('utc'::text, now()) not null
);
alter table public.profiles enable row level security;
create policy "Users can view their own profile." on public.profiles
for select using (auth.uid() = id);
create policy "Users can insert their own profile." on public.profiles
for insert with check (auth.uid() = id);
create policy "Users can update their own profile." on public.profiles
for update using (auth.uid() = id);
-- Function to handle new user signup
create or replace function public.handle_new_user()
returns trigger as $$$
begin
insert into public.profiles (id, first_name, last_name, avatar_url)
values (new.id, '', '', '');
return new;
end;
$$$ language plpgsql security definer;
-- Drop trigger if exists to avoid errors on multiple runs
drop trigger if exists on_auth_user_created on auth.users;
-- Trigger to automatically create profile on signup
create trigger on_auth_user_created
after insert on auth.users
for each row execute procedure public.handle_new_user();
-- Setup storage bucket for avatars
insert into storage.buckets (id, name, public)
values ('avatars', 'avatars', true)
on conflict (id) do nothing;
create policy "Avatar images are publicly accessible."
on storage.objects for select
using ( bucket_id = 'avatars' );
create policy "Users can upload an avatar."
on storage.objects for insert
with check ( bucket_id = 'avatars' AND auth.uid()::text = (storage.foldername(name))[1] );
create policy "Users can update their own avatar."
on storage.objects for update
using ( bucket_id = 'avatars' AND auth.uid()::text = (storage.foldername(name))[1] );
create policy "Users can delete their own avatar."
on storage.objects for delete
using ( bucket_id = 'avatars' AND auth.uid()::text = (storage.foldername(name))[1] );
+2 -1
View File
@@ -1,4 +1,5 @@
import type { Config } from "tailwindcss"; import type { Config } from "tailwindcss";
import tailwindcssAnimate from "tailwindcss-animate";
const config: Config = { const config: Config = {
darkMode: ["class"], darkMode: ["class"],
@@ -59,7 +60,7 @@ const config: Config = {
}, },
}, },
}, },
plugins: [require("tailwindcss-animate")], plugins: [tailwindcssAnimate],
}; };
export default config; export default config;