mirror of
https://github.com/lucasrcsantana/story-generator.git
synced 2025-12-17 05:47:52 +00:00
fix: corrige redirecionamento após login do aluno
- Atualiza lógica de redirecionamento no LoginForm - Ajusta verificação de roles no useAuth hook - Melhora proteção de rotas no ProtectedRoute - Atualiza rotas para suportar diferentes perfis de usuário
This commit is contained in:
parent
beef3da647
commit
fca293c4fc
@ -2,6 +2,7 @@ import React, { useState } from 'react';
|
|||||||
import { LogIn, Eye, EyeOff, School, GraduationCap, User } from 'lucide-react';
|
import { LogIn, Eye, EyeOff, School, GraduationCap, User } from 'lucide-react';
|
||||||
import { useAuth } from '../../hooks/useAuth';
|
import { useAuth } from '../../hooks/useAuth';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { supabase } from '../../lib/supabase';
|
||||||
|
|
||||||
interface LoginFormProps {
|
interface LoginFormProps {
|
||||||
userType: 'school' | 'teacher' | 'student';
|
userType: 'school' | 'teacher' | 'student';
|
||||||
@ -36,16 +37,32 @@ export function LoginForm({ userType, onLogin, onRegisterClick }: LoginFormProps
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { user } = await signIn(email, password);
|
const { data, error } = await supabase.auth.signInWithPassword({
|
||||||
if (user) {
|
email: email,
|
||||||
if (userType === 'school') {
|
password: password
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
const userRole = data.user?.user_metadata?.role;
|
||||||
|
|
||||||
|
switch (userRole) {
|
||||||
|
case 'student':
|
||||||
|
navigate('/aluno');
|
||||||
|
break;
|
||||||
|
case 'teacher':
|
||||||
|
navigate('/professor');
|
||||||
|
break;
|
||||||
|
case 'school':
|
||||||
navigate('/dashboard');
|
navigate('/dashboard');
|
||||||
} else if (onLogin) {
|
break;
|
||||||
await onLogin({ email, password });
|
default:
|
||||||
}
|
throw new Error('Tipo de usuário inválido');
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError('Erro ao fazer login. Verifique suas credenciais.');
|
console.error('Erro no login:', err);
|
||||||
|
setError('Email ou senha incorretos');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
|
|||||||
36
src/components/auth/ProtectedRoute.tsx
Normal file
36
src/components/auth/ProtectedRoute.tsx
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Navigate } from 'react-router-dom';
|
||||||
|
import { useAuth } from '../../hooks/useAuth';
|
||||||
|
|
||||||
|
interface ProtectedRouteProps {
|
||||||
|
children: React.ReactNode;
|
||||||
|
allowedRoles?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProtectedRoute({ children, allowedRoles = [] }: ProtectedRouteProps) {
|
||||||
|
const { user, loading, userRole } = useAuth();
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <div>Carregando...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return <Navigate to="/login/student" />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allowedRoles.length > 0 && !allowedRoles.includes(userRole || '')) {
|
||||||
|
// Redirecionar para a página inicial apropriada baseado no papel do usuário
|
||||||
|
switch (userRole) {
|
||||||
|
case 'student':
|
||||||
|
return <Navigate to="/aluno" />;
|
||||||
|
case 'teacher':
|
||||||
|
return <Navigate to="/professor" />;
|
||||||
|
case 'school':
|
||||||
|
return <Navigate to="/dashboard" />;
|
||||||
|
default:
|
||||||
|
return <Navigate to="/" />;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
84
src/hooks/useAuth.tsx
Normal file
84
src/hooks/useAuth.tsx
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { supabase } from '../lib/supabase';
|
||||||
|
|
||||||
|
interface AuthContextType {
|
||||||
|
user: any;
|
||||||
|
loading: boolean;
|
||||||
|
signOut: () => Promise<void>;
|
||||||
|
userRole: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AuthContext = React.createContext<AuthContextType | undefined>(undefined);
|
||||||
|
|
||||||
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [user, setUser] = React.useState<any>(null);
|
||||||
|
const [userRole, setUserRole] = React.useState<string | null>(null);
|
||||||
|
const [loading, setLoading] = React.useState(true);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const fetchSession = async () => {
|
||||||
|
const { data: { session } } = await supabase.auth.getSession();
|
||||||
|
setUser(session?.user ?? null);
|
||||||
|
setUserRole(session?.user?.user_metadata?.role ?? null);
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchSession();
|
||||||
|
|
||||||
|
const { data: { subscription } } = supabase.auth.onAuthStateChange(async (event, session) => {
|
||||||
|
setUser(session?.user ?? null);
|
||||||
|
setUserRole(session?.user?.user_metadata?.role ?? null);
|
||||||
|
setLoading(false);
|
||||||
|
|
||||||
|
// Redirecionar baseado no evento de autenticação
|
||||||
|
if (event === 'SIGNED_IN') {
|
||||||
|
const role = session?.user?.user_metadata?.role;
|
||||||
|
switch (role) {
|
||||||
|
case 'student':
|
||||||
|
navigate('/aluno');
|
||||||
|
break;
|
||||||
|
case 'teacher':
|
||||||
|
navigate('/professor');
|
||||||
|
break;
|
||||||
|
case 'school':
|
||||||
|
navigate('/dashboard');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else if (event === 'SIGNED_OUT') {
|
||||||
|
navigate('/');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
subscription.unsubscribe();
|
||||||
|
};
|
||||||
|
}, [navigate]);
|
||||||
|
|
||||||
|
const signOut = async () => {
|
||||||
|
await supabase.auth.signOut();
|
||||||
|
navigate('/');
|
||||||
|
};
|
||||||
|
|
||||||
|
const value = {
|
||||||
|
user,
|
||||||
|
loading,
|
||||||
|
signOut,
|
||||||
|
userRole
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthContext.Provider value={value}>
|
||||||
|
{children}
|
||||||
|
</AuthContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAuth() {
|
||||||
|
const context = React.useContext(AuthContext);
|
||||||
|
if (context === undefined) {
|
||||||
|
throw new Error('useAuth must be used within an AuthProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
@ -19,6 +19,7 @@ import { StudentDashboardLayout } from './pages/student-dashboard/StudentDashboa
|
|||||||
import { StudentStoriesPage } from './pages/student-dashboard/StudentStoriesPage';
|
import { StudentStoriesPage } from './pages/student-dashboard/StudentStoriesPage';
|
||||||
import { CreateStoryPage } from './pages/student-dashboard/CreateStoryPage';
|
import { CreateStoryPage } from './pages/student-dashboard/CreateStoryPage';
|
||||||
import { StoryPage } from './pages/student-dashboard/StoryPage';
|
import { StoryPage } from './pages/student-dashboard/StoryPage';
|
||||||
|
import { ProtectedRoute } from './components/auth/ProtectedRoute';
|
||||||
|
|
||||||
export const router = createBrowserRouter([
|
export const router = createBrowserRouter([
|
||||||
{
|
{
|
||||||
@ -62,7 +63,11 @@ export const router = createBrowserRouter([
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '/dashboard',
|
path: '/dashboard',
|
||||||
element: <DashboardLayout />,
|
element: (
|
||||||
|
<ProtectedRoute allowedRoles={['school']}>
|
||||||
|
<DashboardLayout />
|
||||||
|
</ProtectedRoute>
|
||||||
|
),
|
||||||
children: [
|
children: [
|
||||||
{
|
{
|
||||||
index: true,
|
index: true,
|
||||||
@ -123,7 +128,11 @@ export const router = createBrowserRouter([
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '/aluno',
|
path: '/aluno',
|
||||||
element: <StudentDashboardLayout />,
|
element: (
|
||||||
|
<ProtectedRoute allowedRoles={['student']}>
|
||||||
|
<StudentDashboardLayout />
|
||||||
|
</ProtectedRoute>
|
||||||
|
),
|
||||||
children: [
|
children: [
|
||||||
{
|
{
|
||||||
index: true,
|
index: true,
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user