Lade till admin-behörighet

X-Lovable-Edit-ID: edt-d1b6275c-b3bc-4caf-a945-39ffc8111688
Co-authored-by: wolfoftyreso-debug <250630591+wolfoftyreso-debug@users.noreply.github.com>
This commit is contained in:
gpt-engineer-app[bot]
2026-07-11 13:54:24 +00:00
6 changed files with 192 additions and 27 deletions
+32 -3
View File
@@ -186,15 +186,42 @@ export type Database = {
} }
Relationships: [] Relationships: []
} }
user_roles: {
Row: {
created_at: string
id: string
role: Database["public"]["Enums"]["app_role"]
user_id: string
}
Insert: {
created_at?: string
id?: string
role: Database["public"]["Enums"]["app_role"]
user_id: string
}
Update: {
created_at?: string
id?: string
role?: Database["public"]["Enums"]["app_role"]
user_id?: string
}
Relationships: []
}
} }
Views: { Views: {
[_ in never]: never [_ in never]: never
} }
Functions: { Functions: {
[_ in never]: never has_role: {
Args: {
_role: Database["public"]["Enums"]["app_role"]
_user_id: string
}
Returns: boolean
}
} }
Enums: { Enums: {
[_ in never]: never app_role: "admin" | "user"
} }
CompositeTypes: { CompositeTypes: {
[_ in never]: never [_ in never]: never
@@ -321,6 +348,8 @@ export type CompositeTypes<
export const Constants = { export const Constants = {
public: { public: {
Enums: {}, Enums: {
app_role: ["admin", "user"],
},
}, },
} as const } as const
+61 -24
View File
@@ -8,50 +8,52 @@ import { OrdersTable } from "@/components/admin/OrdersTable";
import { CustomersTable } from "@/components/admin/CustomersTable"; import { CustomersTable } from "@/components/admin/CustomersTable";
import { PaymentsTable } from "@/components/admin/PaymentsTable"; import { PaymentsTable } from "@/components/admin/PaymentsTable";
import { LeadsGenerator } from "@/components/admin/LeadsGenerator"; import { LeadsGenerator } from "@/components/admin/LeadsGenerator";
import { Package, Users, CreditCard, LogOut, ArrowLeft, Sparkles } from "lucide-react"; import AuthDialog from "@/components/AuthDialog";
import { Package, Users, CreditCard, LogOut, ArrowLeft, Sparkles, Lock } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
type AuthState = "loading" | "signed_out" | "not_admin" | "admin";
export default function Admin() { export default function Admin() {
const navigate = useNavigate(); const navigate = useNavigate();
const [loading, setLoading] = useState(true); const [state, setState] = useState<AuthState>("loading");
const [isAuthenticated, setIsAuthenticated] = useState(false); const [authOpen, setAuthOpen] = useState(false);
const [authMode, setAuthMode] = useState<"login" | "signup">("login");
useEffect(() => { useEffect(() => {
const checkAuth = async () => { const check = async (session: any) => {
const { data: { session } } = await supabase.auth.getSession(); if (!session?.user) {
if (!session) { setState("signed_out");
navigate("/");
return; return;
} }
setIsAuthenticated(true); const { data, error } = await supabase
setLoading(false); .from("user_roles")
.select("role")
.eq("user_id", session.user.id)
.eq("role", "admin")
.maybeSingle();
if (error) console.error("Role check failed:", error);
setState(data ? "admin" : "not_admin");
}; };
const { data: { subscription } } = supabase.auth.onAuthStateChange((event, session) => { const { data: { subscription } } = supabase.auth.onAuthStateChange((_e, session) => {
if (!session) { check(session);
navigate("/");
}
}); });
supabase.auth.getSession().then(({ data }) => check(data.session));
checkAuth();
return () => subscription.unsubscribe(); return () => subscription.unsubscribe();
}, [navigate]); }, []);
const handleLogout = async () => { const handleLogout = async () => {
await supabase.auth.signOut(); await supabase.auth.signOut();
navigate("/");
}; };
if (loading) { if (state === "loading") {
return ( return (
<div className="min-h-screen bg-background p-8"> <div className="min-h-screen bg-background p-8">
<div className="max-w-7xl mx-auto space-y-8"> <div className="max-w-7xl mx-auto space-y-8">
<Skeleton className="h-10 w-48" /> <Skeleton className="h-10 w-48" />
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4"> <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
{[...Array(4)].map((_, i) => ( {[...Array(4)].map((_, i) => <Skeleton key={i} className="h-32" />)}
<Skeleton key={i} className="h-32" />
))}
</div> </div>
<Skeleton className="h-96" /> <Skeleton className="h-96" />
</div> </div>
@@ -59,8 +61,43 @@ export default function Admin() {
); );
} }
if (!isAuthenticated) { if (state === "signed_out") {
return null; return (
<>
<div className="min-h-screen flex items-center justify-center bg-background px-6">
<div className="max-w-md text-center space-y-6">
<Lock className="h-12 w-12 mx-auto text-primary" />
<h1 className="text-3xl font-serif">Admin-inloggning krävs</h1>
<p className="text-muted-foreground">
Denna sida är privat. Logga in med ditt admin-konto för att se ordrar och annan intern information.
</p>
<div className="flex gap-3 justify-center">
<Button onClick={() => setAuthOpen(true)}>Logga in</Button>
<Button variant="outline" onClick={() => navigate("/")}>Till startsidan</Button>
</div>
</div>
</div>
<AuthDialog open={authOpen} onOpenChange={setAuthOpen} mode={authMode} onModeChange={setAuthMode} />
</>
);
}
if (state === "not_admin") {
return (
<div className="min-h-screen flex items-center justify-center bg-background px-6">
<div className="max-w-md text-center space-y-6">
<Lock className="h-12 w-12 mx-auto text-destructive" />
<h1 className="text-3xl font-serif">Ingen behörighet</h1>
<p className="text-muted-foreground">
Ditt konto har inte tillgång till admin-sidan. Endast ägaren kan se den här sidan.
</p>
<div className="flex gap-3 justify-center">
<Button variant="outline" onClick={handleLogout}>Logga ut</Button>
<Button onClick={() => navigate("/")}>Till startsidan</Button>
</div>
</div>
</div>
);
} }
return ( return (
@@ -0,0 +1,62 @@
-- Role enum
DO $$ BEGIN
CREATE TYPE public.app_role AS ENUM ('admin', 'user');
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
-- user_roles table
CREATE TABLE IF NOT EXISTS public.user_roles (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
role public.app_role NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (user_id, role)
);
GRANT SELECT ON public.user_roles TO authenticated;
GRANT ALL ON public.user_roles TO service_role;
ALTER TABLE public.user_roles ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "Users can view own roles" ON public.user_roles;
CREATE POLICY "Users can view own roles"
ON public.user_roles FOR SELECT
TO authenticated
USING (auth.uid() = user_id);
-- Security definer role check
CREATE OR REPLACE FUNCTION public.has_role(_user_id uuid, _role public.app_role)
RETURNS boolean
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public
AS $$
SELECT EXISTS (
SELECT 1 FROM public.user_roles
WHERE user_id = _user_id AND role = _role
)
$$;
-- Backfill admin for existing owner
INSERT INTO public.user_roles (user_id, role)
SELECT id, 'admin'::public.app_role
FROM auth.users
WHERE lower(email) = 'tiffanysvson@gmail.com'
ON CONFLICT (user_id, role) DO NOTHING;
-- Auto-grant admin on future signup with owner email
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER SET search_path = public
AS $$
BEGIN
INSERT INTO public.profiles (user_id) VALUES (NEW.id)
ON CONFLICT DO NOTHING;
IF lower(NEW.email) = 'tiffanysvson@gmail.com' THEN
INSERT INTO public.user_roles (user_id, role)
VALUES (NEW.id, 'admin')
ON CONFLICT (user_id, role) DO NOTHING;
END IF;
RETURN NEW;
END;
$$;
@@ -0,0 +1,7 @@
REVOKE ALL ON FUNCTION public.has_role(uuid, public.app_role) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.has_role(uuid, public.app_role) TO authenticated, service_role;
REVOKE ALL ON FUNCTION public.handle_new_user() FROM PUBLIC, anon, authenticated;
REVOKE ALL ON FUNCTION public.update_updated_at_column() FROM PUBLIC, anon, authenticated;
@@ -0,0 +1,27 @@
-- Orders: admin-only reads
DROP POLICY IF EXISTS "Authenticated users can view all orders" ON public.orders;
CREATE POLICY "Admins can view orders"
ON public.orders FOR SELECT
TO authenticated
USING (public.has_role(auth.uid(), 'admin'));
-- Customers: admin-only
DROP POLICY IF EXISTS "Authenticated users can manage customers" ON public.customers;
DROP POLICY IF EXISTS "Authenticated users can view customers" ON public.customers;
CREATE POLICY "Admins can view customers"
ON public.customers FOR SELECT
TO authenticated
USING (public.has_role(auth.uid(), 'admin'));
CREATE POLICY "Admins can manage customers"
ON public.customers FOR ALL
TO authenticated
USING (public.has_role(auth.uid(), 'admin'))
WITH CHECK (public.has_role(auth.uid(), 'admin'));
-- Payments: admin-only reads
DROP POLICY IF EXISTS "Authenticated users can view payments" ON public.payments;
CREATE POLICY "Admins can view payments"
ON public.payments FOR SELECT
TO authenticated
USING (public.has_role(auth.uid(), 'admin'));
@@ -0,0 +1,3 @@
DROP POLICY IF EXISTS "Service role can insert orders" ON public.orders;
DROP POLICY IF EXISTS "Service can insert payments" ON public.payments;