feat: add 2FA, secure cookies and publishing tools
All checks were successful
CI / Validate frontend and API (push) Successful in 3m5s
CI / Build and publish Docker images (push) Successful in 1m42s

This commit is contained in:
Cauê Faleiros
2026-11-06 10:29:37 -03:00
parent fff63f5efa
commit 50905eefd7
40 changed files with 3493 additions and 215 deletions

4
.prettierignore Normal file
View File

@@ -0,0 +1,4 @@
dist
node_modules
package-lock.json
server/migrations

6
.prettierrc.json Normal file
View File

@@ -0,0 +1,6 @@
{
"singleQuote": true,
"semi": true,
"printWidth": 140,
"trailingComma": "all"
}

View File

@@ -2,8 +2,6 @@ import React from 'react';
import {
PlayCircleIcon as PlayCircle,
DownloadSimpleIcon as Download,
FileTextIcon as FileText,
CheckCircleIcon as CheckCircle2
} from '@phosphor-icons/react';
import { Course, SectionVariant } from '../types';
import { CourseCoverImage } from './CourseCoverImage';
@@ -20,7 +18,6 @@ export const CourseCard: React.FC<CourseCardProps> = ({
course,
variant,
onClick,
onOpenMaterials
}) => {
const navigate = useNavigate();
const widthClass = variant === 'landscape'

View File

@@ -3,7 +3,6 @@ import {
FileTextIcon as FileText,
FileXlsIcon as FileSpreadsheet,
FileArchiveIcon as FileArchive,
FileCodeIcon as FileCode,
ImageIcon as ImageIcon,
LinkIcon as LinkIcon,
DownloadSimpleIcon as Download,

View File

@@ -0,0 +1,282 @@
import React, { useEffect, useState } from 'react';
import { CircleNotchIcon, ShieldCheckIcon } from '@phosphor-icons/react';
import { authApi, TwoFactorStatus } from '../../services/api';
import { useToast } from '../../context/ToastContext';
type SetupData = { secret: string; otpauthUrl: string; qrCode: string };
export const TwoFactorSettings: React.FC = () => {
const { showToast } = useToast();
const [status, setStatus] = useState<TwoFactorStatus | null>(null);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [setup, setSetup] = useState<SetupData | null>(null);
const [code, setCode] = useState('');
const [password, setPassword] = useState('');
const [mode, setMode] = useState<'idle' | 'regenerate' | 'disable'>('idle');
const [backupCodes, setBackupCodes] = useState<string[]>([]);
const load = async () => {
setLoading(true);
try {
const response = await authApi.twoFactorStatus();
setStatus(response.data);
} catch {
setStatus(null);
} finally {
setLoading(false);
}
};
useEffect(() => {
void load();
}, []);
const startSetup = async () => {
setBusy(true);
try {
const response = await authApi.setupTwoFactor();
setSetup(response.data);
setCode('');
setBackupCodes([]);
} catch {
showToast('Não foi possível iniciar a configuração do 2FA.', 'error');
} finally {
setBusy(false);
}
};
const enable = async (event: React.FormEvent) => {
event.preventDefault();
setBusy(true);
try {
const response = await authApi.enableTwoFactor(code.trim());
setBackupCodes(response.data.backupCodes);
setSetup(null);
setCode('');
await load();
showToast('Verificação em duas etapas ativada.', 'success');
} catch {
showToast('Código inválido. Confira o aplicativo autenticador.', 'error');
} finally {
setBusy(false);
}
};
const regenerate = async (event: React.FormEvent) => {
event.preventDefault();
setBusy(true);
try {
const response = await authApi.regenerateBackupCodes(code.trim());
setBackupCodes(response.data.backupCodes);
setCode('');
setMode('idle');
await load();
showToast('Novos códigos de recuperação gerados.', 'success');
} catch {
showToast('Código inválido. Tente novamente.', 'error');
} finally {
setBusy(false);
}
};
const disable = async (event: React.FormEvent) => {
event.preventDefault();
setBusy(true);
try {
await authApi.disableTwoFactor(code.trim(), password);
setCode('');
setPassword('');
setMode('idle');
setBackupCodes([]);
await load();
showToast('Verificação em duas etapas desativada.', 'success');
} catch {
showToast('Não foi possível desativar o 2FA. Verifique senha e código.', 'error');
} finally {
setBusy(false);
}
};
return (
<section className="form twofa-section">
<h2>Segurança</h2>
<div className="box twofa-card">
<div className="twofa-head">
<span className="twofa-icon">
<ShieldCheckIcon className="ph" />
</span>
<div>
<h3>Verificação em duas etapas</h3>
<p className="small">Proteja sua conta de administrador com um código do autenticador.</p>
</div>
</div>
{loading ? (
<div className="loading">
<CircleNotchIcon className="ph spin" />
</div>
) : !status ? (
<p className="small bad-text">Não foi possível consultar o status do 2FA.</p>
) : status.enabled ? (
<>
<p className="formmsg ok">
2FA ativo · {status.backupCodesRemaining}{' '}
{status.backupCodesRemaining === 1 ? 'código de recuperação restante' : 'códigos de recuperação restantes'}
</p>
{mode === 'regenerate' ? (
<form className="twofa-form" onSubmit={regenerate}>
<div className="field">
<label htmlFor="twofa-regenerate-code">Código atual do autenticador</label>
<input
id="twofa-regenerate-code"
value={code}
onChange={(event) => setCode(event.target.value)}
autoComplete="one-time-code"
required
/>
</div>
<div className="review-actions">
<button className="btn" type="submit" disabled={busy}>
{busy ? 'Gerando…' : 'Gerar novos códigos'}
</button>
<button
className="link"
type="button"
onClick={() => {
setMode('idle');
setCode('');
}}
>
Cancelar
</button>
</div>
</form>
) : mode === 'disable' ? (
<form className="twofa-form" onSubmit={disable}>
<p className="small">Confirme sua senha e um código atual para desativar.</p>
<div className="field">
<label htmlFor="twofa-disable-code">Código do autenticador ou recuperação</label>
<input
id="twofa-disable-code"
value={code}
onChange={(event) => setCode(event.target.value)}
autoComplete="one-time-code"
required
/>
</div>
<div className="field">
<label htmlFor="twofa-disable-password">Senha atual</label>
<input
id="twofa-disable-password"
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
autoComplete="current-password"
required
/>
</div>
<div className="review-actions">
<button className="btn sec bad-text" type="submit" disabled={busy}>
{busy ? 'Desativando…' : 'Desativar 2FA'}
</button>
<button
className="link"
type="button"
onClick={() => {
setMode('idle');
setCode('');
setPassword('');
}}
>
Cancelar
</button>
</div>
</form>
) : (
<div className="review-actions">
<button
className="btn sec"
type="button"
onClick={() => {
setMode('regenerate');
setCode('');
}}
>
Gerar novos códigos
</button>
<button
className="link bad-text"
type="button"
onClick={() => {
setMode('disable');
setCode('');
setPassword('');
}}
>
Desativar 2FA
</button>
</div>
)}
</>
) : setup ? (
<>
<p className="small">Escaneie o QR code com Google Authenticator, 1Password ou outro aplicativo TOTP.</p>
<div className="twofa-setup">
<img src={setup.qrCode} alt="QR code para configurar a verificação em duas etapas" width={220} height={220} />
<div>
<p className="small">Se preferir, digite esta chave manualmente:</p>
<code className="twofa-secret">{setup.secret}</code>
<form className="twofa-form" onSubmit={enable}>
<div className="field">
<label htmlFor="twofa-enable-code">Código de 6 dígitos</label>
<input
id="twofa-enable-code"
value={code}
onChange={(event) => setCode(event.target.value)}
autoComplete="one-time-code"
autoFocus
required
/>
</div>
<div className="review-actions">
<button className="btn" type="submit" disabled={busy}>
{busy ? 'Ativando…' : 'Ativar 2FA'}
</button>
<button
className="link"
type="button"
onClick={() => {
setSetup(null);
setCode('');
}}
>
Cancelar
</button>
</div>
</form>
</div>
</div>
</>
) : (
<button className="btn" type="button" onClick={() => void startSetup()} disabled={busy}>
{busy ? 'Preparando…' : 'Configurar 2FA'}
</button>
)}
</div>
{backupCodes.length > 0 && (
<div className="box twofa-codes">
<h3>Guarde seus códigos de recuperação</h3>
<p className="small">Cada código funciona uma vez. Eles não serão exibidos novamente.</p>
<div className="twofa-code-grid">
{backupCodes.map((backupCode) => (
<code key={backupCode}>{backupCode}</code>
))}
</div>
<button className="btn sec" type="button" onClick={() => setBackupCodes([])}>
Já salvei os códigos
</button>
</div>
)}
</section>
);
};

View File

@@ -1,6 +1,5 @@
import React, { useEffect, useRef, useState } from 'react';
import { adminApi, HomeBanner } from '../../services/api';
import { instructorApi } from '../../services/api';
import { adminApi, HomeBanner, instructorApi } from '../../services/api';
import { useToast } from '../../context/ToastContext';
import { CourseCoverImage } from '../CourseCoverImage';
import { Select } from '../ui/Select';

View File

@@ -2,11 +2,15 @@ import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { Sidebar } from './Sidebar';
import { MobileBack, MobileTabBar } from './MobileNavigation';
import { useAuth } from '../../context/AuthContext';
import { useIsMobile } from '../../hooks/useMediaQuery';
import { paths } from '../../lib/routes';
export const AppShell: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const location = useLocation();
const isMobile = useIsMobile();
const { user, stopImpersonation } = useAuth();
const impersonating = Boolean(user?.impersonatedBy);
useEffect(() => {
window.scrollTo(0, 0);
@@ -16,6 +20,10 @@ export const AppShell: React.FC<{ children: React.ReactNode }> = ({ children })
return (
<>
{impersonating && <div className="impersonation-banner" role="status">
<span>Você está vendo a plataforma como <b>{user?.name}</b>.</span>
<button type="button" onClick={async () => { if (await stopImpersonation()) window.location.assign(paths.admin); }}>Sair da impersonação</button>
</div>}
{!isMobile && <Sidebar />}
{isMobile && <MobileBack />}
{/* Keyed by path: the arrival animation only plays when navigating to a new page. */}

View File

@@ -115,9 +115,9 @@ export const Sidebar: React.FC = () => {
return !value;
});
const signOut = () => {
const signOut = async () => {
setMenuOpen(false);
logout();
await logout();
navigate(paths.explore);
};

View File

@@ -1,4 +1,4 @@
import { Course, Section, SectionVariant, Lesson, Attachment } from './types';
import { Course, Section } from './types';
export const CATEGORIES = [
'Tráfego Pago & Meta Ads',

View File

@@ -1,12 +1,18 @@
import React, { createContext, useContext, useState, useEffect } from 'react';
import { User, UserRole } from '../types';
import { ApiUser, authApi, clearSession, getSession, saveSession } from '../services/api';
import { User } from '../types';
import { ApiUser, authApi, clearSession, saveSession } from '../services/api';
export type LoginResult =
| { user: User }
| { twoFactorRequired: true; challengeToken: string };
interface AuthContextType {
user: User | null;
login: (email: string, password: string) => Promise<User | null>;
login: (email: string, password: string) => Promise<LoginResult | null>;
verifyTwoFactor: (challengeToken: string, code: string) => Promise<User | null>;
stopImpersonation: () => Promise<User | null>;
register: (name: string, email: string, password: string) => Promise<User | null>;
logout: () => void;
logout: () => Promise<void>;
updateCurrentUser: (user: ApiUser) => void;
isLoading: boolean;
}
@@ -19,17 +25,10 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
useEffect(() => {
const restoreSession = async () => {
const session = getSession();
if (!session) {
setIsLoading(false);
return;
}
try {
const { user: apiUser } = await authApi.me();
const restoredUser = toFrontendUser(apiUser);
saveSession({ ...session, user: apiUser });
setUser(restoredUser);
setUser(toFrontendUser(apiUser));
saveSession({ user: apiUser });
} catch {
clearSession();
} finally {
@@ -39,11 +38,24 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
void restoreSession();
}, []);
const login = async (email: string, password: string): Promise<User | null> => {
const login = async (email: string, password: string): Promise<LoginResult | null> => {
try {
const session = await authApi.login(email, password);
const response = await authApi.login(email, password);
if ('twoFactorRequired' in response) return response;
const signedInUser = toFrontendUser(response.user);
saveSession({ user: response.user });
setUser(signedInUser);
return { user: signedInUser };
} catch {
return null;
}
};
const verifyTwoFactor = async (challengeToken: string, code: string): Promise<User | null> => {
try {
const session = await authApi.verifyTwoFactor(challengeToken, code);
const signedInUser = toFrontendUser(session.user);
saveSession(session);
saveSession({ user: session.user });
setUser(signedInUser);
return signedInUser;
} catch {
@@ -51,11 +63,23 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
}
};
const stopImpersonation = async (): Promise<User | null> => {
try {
const response = await authApi.stopImpersonation();
const restored = toFrontendUser(response.user);
saveSession({ user: response.user });
setUser(restored);
return restored;
} catch {
return null;
}
};
const register = async (name: string, email: string, password: string): Promise<User | null> => {
try {
const session = await authApi.register(name, email, password);
const signedInUser = toFrontendUser(session.user);
saveSession(session);
saveSession({ user: session.user });
setUser(signedInUser);
return signedInUser;
} catch {
@@ -63,29 +87,30 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
}
};
const logout = () => {
const logout = async () => {
await authApi.logout().catch(() => undefined);
setUser(null);
clearSession();
};
const updateCurrentUser = (apiUser: ApiUser) => {
const session = getSession();
if (session) saveSession({ ...session, user: apiUser });
saveSession({ user: apiUser });
setUser(toFrontendUser(apiUser));
};
return (
<AuthContext.Provider value={{ user, login, register, logout, updateCurrentUser, isLoading }}>
<AuthContext.Provider value={{ user, login, verifyTwoFactor, stopImpersonation, register, logout, updateCurrentUser, isLoading }}>
{children}
</AuthContext.Provider>
);
};
const toFrontendUser = (user: { id: string; email: string; name: string; role: string }): User => ({
const toFrontendUser = (user: { id: string; email: string; name: string; role: string; impersonatedBy?: string }): User => ({
id: user.id,
email: user.email,
name: user.name,
role: user.role === 'admin' ? 'superadmin' : user.role === 'instructor' ? 'professor' : 'student',
impersonatedBy: user.impersonatedBy,
});
export const useAuth = () => {

28
eslint.config.js Normal file
View File

@@ -0,0 +1,28 @@
import tseslint from 'typescript-eslint';
export default [
{
ignores: ['dist/**', 'node_modules/**', 'design/**', 'server/migrations/**', 'package-lock.json'],
},
{
files: ['**/*.{ts,tsx}'],
languageOptions: {
parser: tseslint.parser,
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
ecmaFeatures: { jsx: true },
},
},
plugins: { '@typescript-eslint': tseslint.plugin },
rules: {
'no-debugger': 'error',
'no-duplicate-imports': 'error',
'no-unreachable': 'error',
'no-constant-condition': 'error',
'no-var': 'error',
'prefer-const': 'warn',
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
},
},
];

2160
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -14,11 +14,17 @@
"db:seed-demo-content": "tsx server/src/db/seed-demo-content.ts",
"typecheck:client": "tsc --project tsconfig.json",
"typecheck:api": "tsc --project server/tsconfig.json",
"typecheck": "npm run typecheck:client && npm run typecheck:api"
"typecheck": "npm run typecheck:client && npm run typecheck:api",
"test": "vitest run",
"test:watch": "vitest",
"lint": "eslint .",
"format": "prettier --write .",
"check": "npm run typecheck && npm test && npm run lint"
},
"dependencies": {
"@fastify/cookie": "^11.1.5",
"@fastify/cors": "^11.0.0",
"@fastify/jwt": "^9.1.0",
"@fastify/jwt": "^10.2.7",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource/mrs-saint-delafield": "^5.3.0",
"@phosphor-icons/react": "^2.1.10",
@@ -26,22 +32,29 @@
"fastify": "^5.3.2",
"fastify-plugin": "^5.0.1",
"nodemailer": "^10.0.1",
"otpauth": "^9.6.0",
"pg": "^8.16.3",
"qrcode": "^1.5.4",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-router-dom": "6.22.3",
"zod": "^3.24.4"
"react-router-dom": "^7.18.5",
"zod": "^4.6.7"
},
"devDependencies": {
"@types/node": "^22.14.0",
"@types/nodemailer": "^8.0.1",
"@types/pg": "^8.15.4",
"@types/qrcode": "^1.5.6",
"@vitejs/plugin-react": "^5.0.0",
"autoprefixer": "^10.6.2",
"eslint": "^9.39.5",
"postcss": "^8.5.32",
"prettier": "^3.9.10",
"tailwindcss": "^3.4.17",
"tsx": "^4.19.4",
"typescript": "~5.8.2",
"vite": "^6.2.0"
"typescript-eslint": "^8.36.0",
"vite": "^6.2.0",
"vitest": "^5.1.0"
}
}

View File

@@ -12,7 +12,7 @@ interface AuthPageProps {
export const AuthPage: React.FC<AuthPageProps> = ({ mode }) => {
const isRegistering = mode === 'signup';
const { user, login, register } = useAuth();
const { user, login, verifyTwoFactor, register } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const lead = (location.state as { message?: string } | null)?.message;
@@ -21,6 +21,9 @@ export const AuthPage: React.FC<AuthPageProps> = ({ mode }) => {
const [name, setName] = useState('');
const [error, setError] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [challengeToken, setChallengeToken] = useState('');
const [twoFactorCode, setTwoFactorCode] = useState('');
const isTwoFactor = Boolean(challengeToken);
if (user && !isSubmitting) return <Navigate to={homeFor(user.role)} replace />;
@@ -40,9 +43,9 @@ export const AuthPage: React.FC<AuthPageProps> = ({ mode }) => {
return;
}
setIsSubmitting(true);
const signedInUser = isRegistering ? await register(name, email, password) : await login(email, password);
const response = isRegistering ? await register(name, email, password) : await login(email, password);
if (!signedInUser) {
if (!response) {
setIsSubmitting(false);
setError(isRegistering
? 'Não foi possível criar sua conta. Use um e-mail válido e uma senha com pelo menos 8 caracteres.'
@@ -50,33 +53,76 @@ export const AuthPage: React.FC<AuthPageProps> = ({ mode }) => {
return;
}
if ('twoFactorRequired' in response) {
setChallengeToken(response.challengeToken);
setTwoFactorCode('');
setError('');
setIsSubmitting(false);
return;
}
const signedInUser = 'user' in response ? response.user : response;
navigate(homeFor(signedInUser.role), { replace: true });
};
const handleTwoFactor = async (event: React.FormEvent) => {
event.preventDefault();
setError('');
if (twoFactorCode.trim().length < 6) { setError('Informe o código de verificação.'); return; }
setIsSubmitting(true);
const verified = await verifyTwoFactor(challengeToken, twoFactorCode.trim());
setIsSubmitting(false);
if (!verified) {
setError('Código inválido ou expirado. Tente novamente.');
return;
}
navigate(homeFor(verified.role), { replace: true });
};
const backToCredentials = () => {
setChallengeToken('');
setTwoFactorCode('');
setError('');
};
return (
<main className="wrap page auth-page enter">
<div className="auth">
<h1>{isRegistering ? 'Criar conta' : 'Entrar'}</h1>
<p>{lead || (isRegistering ? 'Gratuita. Dá acesso a todos os cursos e materiais.' : 'Use o e-mail da sua conta Compor.')}</p>
<form noValidate onSubmit={handleSubmit}>
{isRegistering && (
<div className="field"><label htmlFor="auth-name">Nome</label><input id="auth-name" value={name} onChange={(event) => setName(event.target.value)} autoComplete="name" required /></div>
)}
<div className="field"><label htmlFor="auth-email">E-mail</label><input id="auth-email" type="email" value={email} onChange={(event) => setEmail(event.target.value)} autoComplete="email" autoCapitalize="none" required /></div>
<div className="field">
<label htmlFor="auth-password">Senha</label>
<input id="auth-password" type="password" value={password} onChange={(event) => setPassword(event.target.value)} autoComplete={isRegistering ? 'new-password' : 'current-password'} required />
{isRegistering && <small>Pelo menos 8 caracteres.</small>}
</div>
{error && <p className="formmsg bad" role="alert">{error}</p>}
<button className="btn" type="submit" disabled={isSubmitting}>{isSubmitting ? 'Aguarde…' : isRegistering ? 'Criar conta' : 'Entrar'}</button>
</form>
<p className="alt">
{isRegistering
? <>Já tem conta? <Link className="link" to={paths.signIn}>Entrar</Link></>
: <>Não tem conta? <Link className="link" to={paths.signUp}>Criar conta</Link></>}
</p>
{!isRegistering && <p className="alt"><Link className="link" to={paths.forgotPassword}>Esqueci minha senha</Link></p>}
{isTwoFactor ? <>
<h1>Verificação em duas etapas</h1>
<p>Digite o código do seu autenticador ou um código de recuperação.</p>
<form noValidate onSubmit={handleTwoFactor}>
<div className="field">
<label htmlFor="auth-2fa">Código de verificação</label>
<input id="auth-2fa" value={twoFactorCode} onChange={(event) => setTwoFactorCode(event.target.value)} autoComplete="one-time-code" autoFocus required />
</div>
{error && <p className="formmsg bad" role="alert">{error}</p>}
<button className="btn" type="submit" disabled={isSubmitting}>{isSubmitting ? 'Verificando…' : 'Verificar'}</button>
</form>
<p className="alt"><button className="link" type="button" onClick={backToCredentials}>Voltar</button></p>
</> : <>
<h1>{isRegistering ? 'Criar conta' : 'Entrar'}</h1>
<p>{lead || (isRegistering ? 'Gratuita. Dá acesso a todos os cursos e materiais.' : 'Use o e-mail da sua conta Compor.')}</p>
<form noValidate onSubmit={handleSubmit}>
{isRegistering && (
<div className="field"><label htmlFor="auth-name">Nome</label><input id="auth-name" value={name} onChange={(event) => setName(event.target.value)} autoComplete="name" required /></div>
)}
<div className="field"><label htmlFor="auth-email">E-mail</label><input id="auth-email" type="email" value={email} onChange={(event) => setEmail(event.target.value)} autoComplete="email" autoCapitalize="none" required /></div>
<div className="field">
<label htmlFor="auth-password">Senha</label>
<input id="auth-password" type="password" value={password} onChange={(event) => setPassword(event.target.value)} autoComplete={isRegistering ? 'new-password' : 'current-password'} required />
{isRegistering && <small>Pelo menos 8 caracteres.</small>}
</div>
{error && <p className="formmsg bad" role="alert">{error}</p>}
<button className="btn" type="submit" disabled={isSubmitting}>{isSubmitting ? 'Aguarde…' : isRegistering ? 'Criar conta' : 'Entrar'}</button>
</form>
<p className="alt">
{isRegistering
? <>Já tem conta? <Link className="link" to={paths.signIn}>Entrar</Link></>
: <>Não tem conta? <Link className="link" to={paths.signUp}>Criar conta</Link></>}
</p>
{!isRegistering && <p className="alt"><Link className="link" to={paths.forgotPassword}>Esqueci minha senha</Link></p>}
</>}
</div>
</main>
);

View File

@@ -1,4 +1,4 @@
import React from 'react';
import React, { useState } from 'react';
import { Link, Navigate, useParams } from 'react-router-dom';
import { BookmarkSimpleIcon, CaretRightIcon, CheckIcon, CircleNotchIcon, PlayIcon } from '@phosphor-icons/react';
import { Attachment, Course } from '../types';
@@ -6,15 +6,13 @@ import { useCourse, useLessonProgress } from '../hooks/useCourse';
import { useAuth } from '../context/AuthContext';
import { useCatalog } from '../context/CatalogContext';
import { ArtImage, CourseCard, Cover, courseFraming, useCoverImage } from '../components/catalog/Artwork';
import { MaterialRow, useMaterialAction } from '../components/course/Materials';
import { MaterialButton, MaterialRow, attachmentIcon, useMaterialAction } from '../components/course/Materials';
import { CourseReviews } from '../components/course/CourseReviews';
import { Avatar } from '../components/ui/Avatar';
import { courseMeta, lessonDuration, plural } from '../lib/format';
import { paths } from '../lib/routes';
import { useSavedCourses } from '../hooks/useSavedCourses';
import { useIsMobile } from '../hooks/useMediaQuery';
import { MaterialButton, attachmentIcon } from '../components/course/Materials';
import { useState } from 'react';
export type CourseMaterial = { attachment: Attachment; detail: string; lessonIndex?: number };

View File

@@ -7,13 +7,12 @@ import { useCourse, useLessonProgress } from '../hooks/useCourse';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
import { LessonVideo } from '../components/course/LessonVideo';
import { MaterialRow, useMaterialAction } from '../components/course/Materials';
import { MaterialButton, MaterialRow, attachmentIcon, useMaterialAction } from '../components/course/Materials';
import { Avatar } from '../components/ui/Avatar';
import { lessonDuration } from '../lib/format';
import { paths } from '../lib/routes';
import { signUpState } from './CoursePage';
import { useIsMobile } from '../hooks/useMediaQuery';
import { attachmentIcon, MaterialButton } from '../components/course/Materials';
export type LessonTab = 'aulas' | 'materiais' | 'discussao';

View File

@@ -1,6 +1,6 @@
import React, { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { ChatCircleIcon, CircleNotchIcon, CopyIcon, TrashIcon } from '@phosphor-icons/react';
import { CircleNotchIcon, CopyIcon, TrashIcon } from '@phosphor-icons/react';
import { Attachment, AttachmentType, Comment, Course, Lesson, LessonMedia } from '../types';
import { deleteCourse, duplicateCourse, getComments, getManagedCourses, moderateComment, replyToComment, saveCourse } from '../services/db';
import { courseApi, instructorApi, InstructorAnalytics } from '../services/api';
@@ -12,7 +12,7 @@ import { ConfirmDialog } from '../components/ui/ConfirmDialog';
import { useToast } from '../context/ToastContext';
import { useAuth } from '../context/AuthContext';
import { attachmentIcon, attachmentLabel } from '../components/course/Materials';
import { ArrowRightMockIcon, CheckCircleMockIcon, DragMockIcon, EditMockIcon, MoreMockIcon, PlusMockIcon, SpinnerMockIcon, UploadMockIcon, WarningCircleMockIcon } from '../components/ui/MockupIcons';
import { ArrowRightMockIcon, CheckCircleMockIcon, DragMockIcon, EditMockIcon, PlusMockIcon, SpinnerMockIcon, UploadMockIcon, WarningCircleMockIcon } from '../components/ui/MockupIcons';
import { formatMinutes, lessonDuration, shortDate } from '../lib/format';
import { useIsMobile } from '../hooks/useMediaQuery';
import { paths } from '../lib/routes';
@@ -25,6 +25,23 @@ const formatSize = (bytes?: number | null) => {
return `${new Intl.NumberFormat('pt-BR', { maximumFractionDigits: 1 }).format(bytes / 1024 ** (index + 1))} ${units[index]}`;
};
const toDatetimeLocal = (value?: string | null) => {
if (!value) return '';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '';
return new Date(date.getTime() - date.getTimezoneOffset() * 60_000).toISOString().slice(0, 16);
};
const formatScheduled = (value?: string | null) => value
? new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }).format(new Date(value))
: '';
const courseStatusText = (course: Course) => course.status === 'published'
? 'Publicado'
: course.scheduledPublishAt
? `Agendado para ${formatScheduled(course.scheduledPublishAt)}`
: 'Rascunho';
const newLessonId = () => `lesson-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
const statusLabel = (lesson: Lesson) => {
const status = lesson.media?.[0]?.status;
@@ -46,6 +63,7 @@ const CourseEditor: React.FC<{
const [description, setDescription] = useState(initialData?.description || '');
const [category, setCategory] = useState(initialData?.category || categories[0] || '');
const [status, setStatus] = useState<Course['status']>(initialData?.status || 'draft');
const [scheduledPublishAt, setScheduledPublishAt] = useState(toDatetimeLocal(initialData?.scheduledPublishAt));
const [cover, setCover] = useState(initialData?.thumbnail && initialData.thumbnail !== '/course-placeholder.svg' ? initialData.thumbnail : '');
const [lessons, setLessons] = useState<Lesson[]>(initialData?.lessons || []);
const [editingLessonId, setEditingLessonId] = useState<string | null>(null);
@@ -190,6 +208,15 @@ const CourseEditor: React.FC<{
if (!title.trim()) { showToast('Informe o título do curso.', 'error'); return; }
if (!category) { showToast('Selecione uma área para o curso.', 'error'); return; }
if (!lessons.length) { showToast('Adicione pelo menos uma aula.', 'error'); return; }
const scheduleDate = nextStatus === 'draft' && scheduledPublishAt ? new Date(scheduledPublishAt) : null;
if (scheduledPublishAt && Number.isNaN(new Date(scheduledPublishAt).getTime())) {
showToast('Informe uma data de publicação válida.', 'error');
return;
}
if (scheduleDate && scheduleDate.getTime() <= Date.now()) {
showToast('Escolha uma data futura para agendar a publicação.', 'error');
return;
}
setSaving(true);
try {
const seconds = lessons.reduce((total, lesson) => total + (lesson.media?.[0]?.durationSeconds || 0), 0);
@@ -199,6 +226,7 @@ const CourseEditor: React.FC<{
description,
category,
status: nextStatus,
scheduledPublishAt: scheduleDate ? scheduleDate.toISOString() : null,
thumbnail: cover || '/course-placeholder.svg',
coverImageZoom: initialData?.coverImageZoom || 1,
coverImagePositionX: initialData?.coverImagePositionX ?? 50,
@@ -211,7 +239,8 @@ const CourseEditor: React.FC<{
attachments,
});
setStatus(nextStatus);
showToast('Curso salvo.', 'success');
if (nextStatus === 'published') setScheduledPublishAt('');
showToast(nextStatus === 'draft' && scheduleDate ? 'Curso salvo e agendado.' : 'Curso salvo.', 'success');
onSaved();
} catch (error) {
showToast(error instanceof Error ? error.message : 'Não foi possível salvar o curso.', 'error');
@@ -232,7 +261,7 @@ const CourseEditor: React.FC<{
<div className="m-cover sm" style={cover ? { backgroundImage: `url("${cover}")`, backgroundSize: 'cover', backgroundPosition: 'center' } : { background: 'var(--bg-2)' }}>{!cover && <span className="t">{title || 'Novo curso'}</span>}</div>
<div className="m-under"><button className="link" type="button" disabled={!coverConfigured || coverUploading} onClick={() => coverInput.current?.click()}>{coverUploading ? 'Enviando…' : 'Trocar capa'}</button>{initialData?.id && status === 'published' && <Link className="link" to={paths.course(initialData.id)}>Ver como aluno</Link>}</div>
<input ref={coverInput} type="file" accept="image/jpeg,image/png,image/webp" hidden onChange={(event) => { const file = event.target.files?.[0]; event.currentTarget.value = ''; void uploadCover(file); }} />
<header className="m-title"><h1>{title || 'Novo curso'}</h1><p>{status === 'published' ? 'Publicado' : 'Rascunho'}{initialData?.updatedAt ? ` · atualizado em ${shortDate(initialData.updatedAt)}` : ''}</p></header>
<header className="m-title"><h1>{title || 'Novo curso'}</h1><p>{status === 'published' ? 'Publicado' : scheduledPublishAt ? `Agendado para ${formatScheduled(scheduledPublishAt)}` : 'Rascunho'}{initialData?.updatedAt ? ` · atualizado em ${shortDate(initialData.updatedAt)}` : ''}</p></header>
<section className="m-group"><h2>Aulas</h2><div className="m-list">
{lessons.map((lesson, index) => <button className="m-row" type="button" key={lesson.id} onClick={() => setEditingLessonId(lesson.id)}><span className="m-n num">{index + 1}</span><span className="m-rt"><b>{lesson.title}</b><small>{lessonDuration(lesson) || 'Sem duração'}</small></span>{statusLabel(lesson)}</button>)}
<label className="m-row m-add" style={{ opacity: bunnyConfigured ? 1 : 0.6 }}>
@@ -245,6 +274,7 @@ const CourseEditor: React.FC<{
<div className="m-field"><span>Área</span><Select variant="mobile" value={category} options={categories.map((item) => ({ value: item, label: item }))} onChange={setCategory} ariaLabel="Área do curso" /></div>
<label className="m-field"><span>Título</span><input value={title} onChange={(event) => setTitle(event.target.value)} /></label>
<label className="m-field col"><span>Descrição</span><textarea rows={4} value={description} onChange={(event) => setDescription(event.target.value)} /></label>
{status === 'draft' && <label className="m-field col"><span>Agendar publicação</span><input type="datetime-local" value={scheduledPublishAt} onChange={(event) => setScheduledPublishAt(event.target.value)} /><small>Opcional. O curso publica sozinho quando os vídeos estiverem prontos.</small></label>}
</div>{status === 'draft' && <button className="link" type="button" style={{ marginTop: 12 }} onClick={() => void save('draft')} disabled={saving}>Salvar rascunho</button>}</section>
<section className="m-group"><h2>Materiais</h2><div className="m-list">
{attachments.map((attachment) => <div className="m-row" key={attachment.id}><span className="m-ic">{attachmentIcon(attachment.type)}</span><span className="m-rt"><b>{attachment.name}</b><small>{[attachmentLabel(attachment.type), attachment.size].filter(Boolean).join(' · ')}</small></span><button className="m-icb" type="button" onClick={() => removeAttachment(attachment.id)} aria-label={`Remover ${attachment.name}`}><TrashIcon className="ph" /></button></div>)}
@@ -272,7 +302,7 @@ const CourseEditor: React.FC<{
return <main className="wrap page enter">
<div className="crumb"><Link to={paths.manage} onClick={onClose}>Gerenciar cursos</Link><ArrowRightMockIcon className="ph" /><span>{title || 'Novo curso'}</span></div>
<div className="ptitle">
<div><h1>{title || 'Novo curso'}</h1><p>{status === 'published' ? 'Publicado' : 'Rascunho'}{initialData?.updatedAt ? ` · atualizado em ${shortDate(initialData.updatedAt)}` : ''}</p></div>
<div><h1>{title || 'Novo curso'}</h1><p>{status === 'published' ? 'Publicado' : scheduledPublishAt ? `Agendado para ${formatScheduled(scheduledPublishAt)}` : 'Rascunho'}{initialData?.updatedAt ? ` · atualizado em ${shortDate(initialData.updatedAt)}` : ''}</p></div>
<div className="acts">
{initialData?.id && status === 'published' && <Link className="btn sec" to={paths.course(initialData.id)}>Ver como aluno</Link>}
{status === 'draft' && <button className="btn ghost" type="button" onClick={() => void save()} disabled={saving}>Salvar rascunho</button>}
@@ -326,6 +356,7 @@ const CourseEditor: React.FC<{
<div className="field"><label htmlFor="manage-title">Título</label><input id="manage-title" value={title} onChange={(event) => setTitle(event.target.value)} /></div>
<div className="field"><label>Área</label><Select variant="field" value={category} options={categories.map((item) => ({ value: item, label: item }))} onChange={setCategory} ariaLabel="Área do curso" /></div>
<div className="field"><label htmlFor="manage-description">Descrição</label><textarea id="manage-description" rows={4} value={description} onChange={(event) => setDescription(event.target.value)} /></div>
{status === 'draft' && <div className="field"><label htmlFor="manage-schedule">Agendar publicação <span className="faint">(opcional)</span></label><input id="manage-schedule" type="datetime-local" value={scheduledPublishAt} onChange={(event) => setScheduledPublishAt(event.target.value)} /><small>O curso publica sozinho quando os vídeos estiverem prontos.</small></div>}
</div>
</div>
<div className="box">
@@ -459,7 +490,7 @@ export const ManageCourses: React.FC = () => {
<header className="m-large"><h1>Gerenciar cursos</h1><button className="m-icb" type="button" onClick={openNew} aria-label="Novo curso"><PlusMockIcon className="ph" /></button></header>
<div className="m-stats num"><div><b>{published}</b><small>Publicados</small></div><div><b>{courses.length - published}</b><small>Rascunhos</small></div><div><b>{analytics?.learners ?? 0}</b><small>Alunos</small></div><div><b>{analytics?.unansweredComments ?? 0}</b><small>Sem resposta</small></div></div>
<div className="m-seg" role="tablist"><button type="button" role="tab" aria-selected={activeTab === 'courses'} onClick={() => setActiveTab('courses')}>Cursos</button><button type="button" role="tab" aria-selected={activeTab === 'comments'} onClick={() => setActiveTab('comments')}>Discussões</button></div>
{activeTab === 'courses' ? <section className="m-group"><div className="m-list">{courses.map((course) => <div className="m-row" key={course.id}><Thumb course={course} className="m-th" /><button className="m-rt" type="button" onClick={() => openCourse(course)}><b>{course.title}</b><small>{course.status === 'published' ? 'Publicado' : 'Rascunho'} · {course.lessons.length} aulas{course.learners ? ` · ${course.learners} alunos` : ''}</small></button><button className="m-icb" type="button" onClick={() => void duplicate(course)} aria-label={`Duplicar ${course.title}`}><CopyIcon className="ph" /></button><button className="m-icb" type="button" onClick={() => setCourseDeleteTarget(course)} aria-label={`Excluir ${course.title}`}><TrashIcon className="ph" /></button></div>)}</div>{!loading && !courses.length && <p className="m-empty">Nenhum curso ainda.</p>}</section>
{activeTab === 'courses' ? <section className="m-group"><div className="m-list">{courses.map((course) => <div className="m-row" key={course.id}><Thumb course={course} className="m-th" /><button className="m-rt" type="button" onClick={() => openCourse(course)}><b>{course.title}</b><small>{courseStatusText(course)} · {course.lessons.length} aulas{course.learners ? ` · ${course.learners} alunos` : ''}</small></button><button className="m-icb" type="button" onClick={() => void duplicate(course)} aria-label={`Duplicar ${course.title}`}><CopyIcon className="ph" /></button><button className="m-icb" type="button" onClick={() => setCourseDeleteTarget(course)} aria-label={`Excluir ${course.title}`}><TrashIcon className="ph" /></button></div>)}</div>{!loading && !courses.length && <p className="m-empty">Nenhum curso ainda.</p>}</section>
: <><div className="m-chips" role="group" aria-label="Filtrar discussões">{([['all', 'Todas'], ['unanswered', 'Sem resposta'], ['answered', 'Respondidas']] as const).map(([key, label]) => <button key={key} type="button" aria-pressed={commentFilter === key} onClick={() => setCommentFilter(key)}>{label}</button>)}</div><section className="m-group"><div className="m-list multi">{visibleComments.map(({ comment, courseTitle }) => <div className="m-row" key={comment.id}><span className="m-rt"><b>{comment.text}</b><small>{comment.user} · {courseTitle} · {comment.date}</small>{comment.reply ? <small>Professor respondeu: {comment.reply}</small> : replyingTo === comment.id ? <span className="m-reply"><input value={replyText} onChange={(event) => setReplyText(event.target.value)} placeholder="Escrever resposta" /><button className="link" type="button" disabled={sendingReply} onClick={() => void sendReply(comment.id)}>Enviar</button></span> : <button className="link" type="button" onClick={() => { setReplyingTo(comment.id); setReplyText(''); }}>Responder</button>}<button className="link bad-text" type="button" onClick={() => setCommentDeleteTarget(comment)}>Remover</button></span></div>)}</div>{!loading && !visibleComments.length && <p className="m-empty">Nenhuma discussão encontrada.</p>}</section></>}
{listDialogs}
</main>;
@@ -478,7 +509,7 @@ export const ManageCourses: React.FC = () => {
</div>
{activeTab === 'comments' && <div className="chips2" role="group" aria-label="Filtrar discussões">{([['all', 'Todas'], ['unanswered', 'Sem resposta'], ['answered', 'Respondidas']] as const).map(([key, label]) => <button key={key} type="button" aria-pressed={commentFilter === key} onClick={() => setCommentFilter(key)}>{label}</button>)}</div>}
{activeTab === 'courses' ? (loading ? <div className="loading"><CircleNotchIcon className="ph spin" /></div> : courses.length ? <div className="tablewrap"><table className="t-ger"><thead><tr><th>Curso</th><th>Status</th><th>Aulas</th><th>Alunos</th><th>Atualizado</th><th></th></tr></thead><tbody>
{courses.map((course) => <tr className="click" key={course.id} onClick={() => openCourse(course)}><td><span className="person"><Thumb course={course} /><span><b style={{ fontWeight: 500 }}>{course.title}</b><small>{course.category}</small></span></span></td><td><span className={`st ${course.status === 'published' ? 'ok' : 'mut'}`}>{course.status === 'published' ? 'Publicado' : 'Rascunho'}</span></td><td className="num">{course.lessons.length}</td><td className="num">{course.learners ?? 0}</td><td className="num">{shortDate(course.updatedAt) || '—'}</td><td className="right"><div className="acts"><button className="iconbtn" type="button" aria-label={`Editar ${course.title}`} onClick={(event) => { event.stopPropagation(); openCourse(course); }}><EditMockIcon className="ph" /></button><button className="iconbtn" type="button" aria-label={`Duplicar ${course.title}`} onClick={(event) => { event.stopPropagation(); void duplicate(course); }}><CopyIcon className="ph" /></button><button className="iconbtn" type="button" aria-label={`Excluir ${course.title}`} onClick={(event) => { event.stopPropagation(); setCourseDeleteTarget(course); }}><TrashIcon className="ph" /></button></div></td></tr>)}
{courses.map((course) => <tr className="click" key={course.id} onClick={() => openCourse(course)}><td><span className="person"><Thumb course={course} /><span><b style={{ fontWeight: 500 }}>{course.title}</b><small>{course.category}</small></span></span></td><td><span className={`st ${course.status === 'published' ? 'ok' : 'mut'}`}>{courseStatusText(course)}</span></td><td className="num">{course.lessons.length}</td><td className="num">{course.learners ?? 0}</td><td className="num">{shortDate(course.updatedAt) || '—'}</td><td className="right"><div className="acts"><button className="iconbtn" type="button" aria-label={`Editar ${course.title}`} onClick={(event) => { event.stopPropagation(); openCourse(course); }}><EditMockIcon className="ph" /></button><button className="iconbtn" type="button" aria-label={`Duplicar ${course.title}`} onClick={(event) => { event.stopPropagation(); void duplicate(course); }}><CopyIcon className="ph" /></button><button className="iconbtn" type="button" aria-label={`Excluir ${course.title}`} onClick={(event) => { event.stopPropagation(); setCourseDeleteTarget(course); }}><TrashIcon className="ph" /></button></div></td></tr>)}
</tbody></table></div> : <p className="empty">Nenhum curso criado ainda.</p>) : visibleComments.length ? <div className="list">{visibleComments.map(({ comment, courseTitle }) => <article className="manage-comment" key={comment.id}><div><b>{comment.user}</b><small>{courseTitle} · {comment.date}</small></div><p>{comment.text}</p>{comment.reply ? <div className="reply"><small>Resposta do professor</small><p>{comment.reply}</p></div> : replyingTo === comment.id ? <div className="composer"><textarea value={replyText} onChange={(event) => setReplyText(event.target.value)} placeholder="Escreva sua resposta" /><button className="btn" type="button" disabled={sendingReply} onClick={() => void sendReply(comment.id)}>Enviar</button></div> : <button className="link" type="button" onClick={() => { setReplyingTo(comment.id); setReplyText(''); }}>Responder</button>}<button className="link bad-text" type="button" onClick={() => setCommentDeleteTarget(comment)}>Remover comentário</button></article>)}</div> : <p className="empty">{allComments.length ? 'Nenhuma discussão com esse filtro.' : 'Nenhuma discussão ainda.'}</p>}
{listDialogs}
</main>;

View File

@@ -2,10 +2,17 @@ import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { BellIcon, CircleNotchIcon } from '@phosphor-icons/react';
import { useToast } from '../context/ToastContext';
import { NotificationFeed, NotificationItem, getNotifications, markAllNotificationsRead, markNotificationRead } from '../services/notifications';
import {
NotificationFeed,
NotificationItem,
getNotifications,
markAllNotificationsRead,
markNotificationRead,
} from '../services/notifications';
import { useIsMobile } from '../hooks/useMediaQuery';
const formatWhen = (value: string) => new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }).format(new Date(value));
const formatWhen = (value: string) =>
new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }).format(new Date(value));
export const NotificationsPage: React.FC = () => {
const { showToast } = useToast();
@@ -25,12 +32,18 @@ export const NotificationsPage: React.FC = () => {
}
};
useEffect(() => { void load(); }, []);
useEffect(() => {
void load();
}, []);
const markAll = async () => {
try {
await markAllNotificationsRead();
setFeed((current) => current ? { ...current, unread: 0, items: current.items.map((item) => ({ ...item, readAt: item.readAt || new Date().toISOString() })) } : current);
setFeed((current) =>
current
? { ...current, unread: 0, items: current.items.map((item) => ({ ...item, readAt: item.readAt || new Date().toISOString() })) }
: current,
);
window.dispatchEvent(new Event('compor:notifications-updated'));
} catch {
showToast('Não foi possível marcar as notificações como lidas.', 'error');
@@ -39,34 +52,78 @@ export const NotificationsPage: React.FC = () => {
const open = (item: NotificationItem) => {
if (item.readAt) return;
void markNotificationRead(item.id).then(() => {
setFeed((current) => current ? {
...current,
unread: Math.max(0, current.unread - 1),
items: current.items.map((entry) => entry.id === item.id ? { ...entry, readAt: new Date().toISOString() } : entry),
} : current);
window.dispatchEvent(new Event('compor:notifications-updated'));
}).catch(() => undefined);
void markNotificationRead(item.id)
.then(() => {
setFeed((current) =>
current
? {
...current,
unread: Math.max(0, current.unread - 1),
items: current.items.map((entry) => (entry.id === item.id ? { ...entry, readAt: new Date().toISOString() } : entry)),
}
: current,
);
window.dispatchEvent(new Event('compor:notifications-updated'));
})
.catch(() => undefined);
};
const list = loading ? <div className="loading"><CircleNotchIcon className="ph spin" /></div> : feed?.items.length ? <div className="notification-list">
{feed.items.map((item) => <Link className={`notification${item.readAt ? '' : ' unread'}`} to={item.href} key={item.id} onClick={() => open(item)}>
<span className="n-ic"><BellIcon className="ph" /></span>
<span className="n-copy"><b>{item.title}</b>{item.body && <p>{item.body}</p>}</span>
<small>{formatWhen(item.createdAt)}</small>
</Link>)}
</div> : <div className="empty notification-empty"><BellIcon className="ph" /><h2>Nenhuma notificação</h2><p>Quando alguém responder seus comentários ou fizer uma pergunta nos seus cursos, você verá aqui.</p></div>;
if (isMobile) return <main className="m-page m-gut enter">
<header className="m-large"><h1>Notificações</h1>{Boolean(feed?.unread) && <button className="link" type="button" onClick={() => void markAll()}>Marcar lidas</button>}</header>
{list}
</main>;
return <main className="wrap page enter">
<div className="ptitle">
<div><h1>Notificações</h1><p>{feed?.unread ? `${feed.unread} não ${feed.unread === 1 ? 'lida' : 'lidas'}` : 'Tudo em dia.'}</p></div>
{Boolean(feed?.unread) && <button className="btn sec" type="button" onClick={() => void markAll()}>Marcar todas como lidas</button>}
const list = loading ? (
<div className="loading">
<CircleNotchIcon className="ph spin" />
</div>
{list}
</main>;
) : feed?.items.length ? (
<div className="notification-list">
{feed.items.map((item) => (
<Link className={`notification${item.readAt ? '' : ' unread'}`} to={item.href} key={item.id} onClick={() => open(item)}>
<span className="n-ic">
<BellIcon className="ph" />
</span>
<span className="n-copy">
<b>{item.title}</b>
{item.body && <p>{item.body}</p>}
</span>
<small>{formatWhen(item.createdAt)}</small>
</Link>
))}
</div>
) : (
<div className="empty notification-empty">
<BellIcon className="ph" />
<h2>Nenhuma notificação</h2>
<p>Quando alguém responder seus comentários ou fizer uma pergunta nos seus cursos, você verá aqui.</p>
</div>
);
if (isMobile)
return (
<main className="m-page m-gut enter">
<header className="m-large">
<h1>Notificações</h1>
{Boolean(feed?.unread) && (
<button className="link" type="button" onClick={() => void markAll()}>
Marcar lidas
</button>
)}
</header>
{list}
</main>
);
return (
<main className="wrap page enter">
<div className="ptitle">
<div>
<h1>Notificações</h1>
<p>{feed?.unread ? `${feed.unread} não ${feed.unread === 1 ? 'lida' : 'lidas'}` : 'Tudo em dia.'}</p>
</div>
{Boolean(feed?.unread) && (
<button className="btn sec" type="button" onClick={() => void markAll()}>
Marcar todas como lidas
</button>
)}
</div>
{list}
</main>
);
};

View File

@@ -4,9 +4,9 @@ import { ArrowSquareOutIcon, CameraIcon, CircleNotchIcon, GlobeIcon, InstagramLo
import { useAuth } from '../context/AuthContext';
import { Profile, ProfileInput, instructorApi, profileApi } from '../services/api';
import { CourseCoverImage } from '../components/CourseCoverImage';
import { TwoFactorSettings } from '../components/account/TwoFactorSettings';
import { Switch } from '../components/ui/Switch';
import { useToast } from '../context/ToastContext';
import { paths } from '../lib/routes';
const emptyProfile = (user: { id: string; email: string; name: string; role: string }): Profile => ({
id: user.id, email: user.email, name: user.name,
@@ -52,6 +52,7 @@ export const ProfilePage: React.FC = () => {
<section className="form"><h2>Links e visibilidade</h2><p className="muted">Use links completos, começando com https://.</p><UrlField icon={<GlobeIcon />} label="Site" value={profile.websiteUrl} onChange={(value) => update('websiteUrl', value || null)} /><UrlField icon={<LinkedinLogoIcon />} label="LinkedIn" value={profile.linkedinUrl} onChange={(value) => update('linkedinUrl', value || null)} /><UrlField icon={<InstagramLogoIcon />} label="Instagram" value={profile.instagramUrl} onChange={(value) => update('instagramUrl', value || null)} /><UrlField icon={<YoutubeLogoIcon />} label="YouTube" value={profile.youtubeUrl} onChange={(value) => update('youtubeUrl', value || null)} /><div className="toggle"><span>Perfil público<small>Permite que outras pessoas vejam sua apresentação e seus cursos.</small></span><Switch checked={profile.isPublic} onChange={(checked) => update('isPublic', checked)} label="Perfil público" /></div></section></div>
<button className="btn lg profile-save" type="submit" disabled={isSaving}>{isSaving ? 'Salvando…' : 'Salvar'}</button>
</form>
{user.role === 'superadmin' && <TwoFactorSettings />}
</main>;
};

View File

@@ -1,6 +1,6 @@
import React, { useEffect, useMemo, useState } from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { CircleNotchIcon } from '@phosphor-icons/react';
import { CheckIcon, CircleNotchIcon } from '@phosphor-icons/react';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
import { useCatalog } from '../context/CatalogContext';
@@ -13,6 +13,7 @@ import { CategoryManager } from '../components/admin/CategoryManager';
import { TrailManager } from '../components/admin/TrailManager';
import { DragMockIcon, MoreMockIcon, PlusMockIcon, SearchMockIcon } from '../components/ui/MockupIcons';
import { useIsMobile } from '../hooks/useMediaQuery';
import { paths } from '../lib/routes';
type HomeConfiguration = {
featuredCourseId: string | null;
@@ -78,6 +79,13 @@ export const SuperAdmin: React.FC = () => {
const [draggedCourseId, setDraggedCourseId] = useState<string | null>(null);
const [mobileUser, setMobileUser] = useState<ManagedUser | null>(null);
const [deleteTarget, setDeleteTarget] = useState<ManagedUser | null>(null);
const [selectedUsers, setSelectedUsers] = useState<Set<string>>(new Set());
const [bulkTarget, setBulkTarget] = useState<boolean | null>(null);
const [bulkBusy, setBulkBusy] = useState(false);
const [bulkInvites, setBulkInvites] = useState<Array<{ email: string; inviteUrl?: string; error?: string }>>([]);
const [bulkInviteOpen, setBulkInviteOpen] = useState(false);
const [bulkInviteBusy, setBulkInviteBusy] = useState(false);
const bulkInviteInput = useRef<HTMLInputElement>(null);
const loadData = async () => {
setLoading(true);
@@ -112,6 +120,38 @@ export const SuperAdmin: React.FC = () => {
return audit.filter((entry) => [entry.actorName, describeAction(entry), dateTime(entry.createdAt)].some((value) => value.toLowerCase().includes(normalized)));
}, [audit, auditQuery]);
const selectableUsers = useMemo(() => filteredUsers.filter((account) => account.id !== user?.id), [filteredUsers, user?.id]);
const allSelected = selectableUsers.length > 0 && selectableUsers.every((account) => selectedUsers.has(account.id));
const toggleSelected = (accountId: string) => {
setSelectedUsers((current) => {
const next = new Set(current);
if (next.has(accountId)) next.delete(accountId);
else next.add(accountId);
return next;
});
};
const toggleAllSelected = () => {
setSelectedUsers(allSelected ? new Set() : new Set(selectableUsers.map((account) => account.id)));
};
const performBulkStatus = async () => {
if (bulkTarget === null || !selectedUsers.size) return;
setBulkBusy(true);
try {
const response = await adminApi.bulkUpdateUsers([...selectedUsers], bulkTarget);
setUsers((current) => current.map((account) => response.data.find((updated) => updated.id === account.id) || account));
setSelectedUsers(new Set());
setBulkTarget(null);
showToast(bulkTarget ? 'Contas ativadas.' : 'Contas desativadas.', 'success');
} catch {
showToast('Não foi possível atualizar as contas selecionadas.', 'error');
} finally {
setBulkBusy(false);
}
};
const exportUsersCsv = () => {
const rows = [
['Nome', 'E-mail', 'Papel', 'Status', 'Cadastro', 'Último acesso'],
@@ -168,6 +208,52 @@ export const SuperAdmin: React.FC = () => {
}
};
const importBulkInvitations = async (file?: File) => {
if (!file) return;
setBulkInviteBusy(true);
try {
const text = await file.text();
const emails = [...new Set(text.split(/\r?\n/)
.map((line) => line.split(/[;,]/)[0].trim().replace(/^"|"$/g, ''))
.filter((value) => value && value.toLowerCase() !== 'email' && value.toLowerCase() !== 'e-mail' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)))].slice(0, 100);
if (!emails.length) {
showToast('Nenhum e-mail válido encontrado no CSV.', 'error');
return;
}
const response = await adminApi.bulkInvite(emails);
setBulkInvites(response.data);
setBulkInviteOpen(true);
const created = response.data.filter((item) => item.inviteUrl).length;
showToast(`${created} ${created === 1 ? 'convite gerado' : 'convites gerados'}.`, 'success');
} catch {
showToast('Não foi possível importar os convites.', 'error');
} finally {
setBulkInviteBusy(false);
if (bulkInviteInput.current) bulkInviteInput.current.value = '';
}
};
const copyBulkLinks = () => {
const links = bulkInvites
.filter((item) => item.inviteUrl)
.map((item) => `${item.email}: ${item.inviteUrl}`)
.join('\n');
if (links) void navigator.clipboard.writeText(links);
};
const impersonate = async (account: ManagedUser) => {
setBusyUserId(account.id);
setOpenMenu(null);
setMobileUser(null);
try {
await adminApi.impersonate(account.id);
window.location.assign(paths.explore);
} catch {
setBusyUserId(null);
showToast('Não foi possível entrar como este usuário.', 'error');
}
};
const resetPassword = async (account: ManagedUser) => {
setBusyUserId(account.id);
setOpenMenu(null);
@@ -252,6 +338,32 @@ export const SuperAdmin: React.FC = () => {
onConfirm={() => void performDelete()}
/>;
const bulkInviteDialog = <>{bulkInviteOpen && <div className="scrim" role="dialog" aria-modal="true" aria-label="Convites importados" onMouseDown={(event) => { if (event.target === event.currentTarget) setBulkInviteOpen(false); }}>
<div className="dialog" style={{ maxWidth: 620 }}>
<header><div><h2>Convites importados</h2><p>{bulkInvites.filter((item) => item.inviteUrl).length} links gerados. Você também pode copiar todos e enviar pelo canal que preferir.</p></div><button type="button" className="iconbtn" onClick={() => setBulkInviteOpen(false)} aria-label="Fechar">×</button></header>
<div className="list" style={{ maxHeight: 360, overflow: 'auto' }}>
{bulkInvites.map((item) => <div className="row" key={item.email} style={{ gridTemplateColumns: 'minmax(0, 1fr) auto', padding: '10px 0' }}>
<span className="t">{item.email}<small>{item.inviteUrl ? 'Convite criado' : item.error || 'Não foi possível criar o convite.'}</small></span>
{item.inviteUrl && <button className="btn sec" type="button" onClick={() => void navigator.clipboard.writeText(item.inviteUrl!)}>Copiar</button>}
</div>)}
</div>
<div className="review-actions" style={{ marginTop: 16 }}>
<button className="btn" type="button" onClick={copyBulkLinks} disabled={!bulkInvites.some((item) => item.inviteUrl)}>Copiar todos os links</button>
<button className="btn sec" type="button" onClick={() => setBulkInviteOpen(false)}>Fechar</button>
</div>
</div>
</div>}</>;
const bulkDialog = <ConfirmDialog
open={bulkTarget !== null}
title={bulkTarget ? 'Ativar contas' : 'Desativar contas'}
message={bulkTarget === null ? '' : `${selectedUsers.size} ${selectedUsers.size === 1 ? 'conta será' : 'contas serão'} ${bulkTarget ? 'ativadas' : 'desativadas'}.`}
confirmLabel={bulkTarget ? 'Ativar' : 'Desativar'}
busy={bulkBusy}
onCancel={() => { if (!bulkBusy) setBulkTarget(null); }}
onConfirm={() => void performBulkStatus()}
/>;
if (isMobile) return <main className="m-page m-gut enter">
<header className="m-large"><h1>Administração</h1><button className="m-icb" type="button" aria-label="Convidar usuário" onClick={() => { setAccessLink(''); setInviteOpen(true); }}><PlusMockIcon className="ph" /></button></header>
<div className="m-stats num"><div><b>{analytics?.totalUsers ?? users.length}</b><small>Usuários</small></div><div><b>{instructorCount}</b><small>Professores</small></div><div><b>{analytics?.publishedCourses ?? 0}</b><small>Cursos</small></div><div><b>{analytics?.pendingInvitations ?? 0}</b><small>Convites</small></div></div>
@@ -301,11 +413,14 @@ export const SuperAdmin: React.FC = () => {
<div className="field"><label>Papel</label><Select variant="field" value={mobileUser.role} options={roleOptions} disabled={mobileUser.id === user?.id} onChange={(role) => { setMobileUser(null); void updateUser(mobileUser, { role: role as ManagedUser['role'] }); }} ariaLabel={`Papel de ${mobileUser.name}`} /></div>
<button className="btn sec" type="button" onClick={() => { setMobileUser(null); void updateUser(mobileUser, { isActive: !mobileUser.isActive }); }}>{mobileUser.isActive ? 'Desativar conta' : 'Ativar conta'}</button>
<button className="btn sec" type="button" onClick={() => { setMobileUser(null); void resetPassword(mobileUser); }}>Redefinir senha</button>
{mobileUser.role !== 'admin' && mobileUser.isActive && <button className="btn sec" type="button" onClick={() => void impersonate(mobileUser)}>Entrar como usuário</button>}
{mobileUser.id !== user?.id && <button className="btn sec bad-text" type="button" onClick={() => { setMobileUser(null); void deleteUser(mobileUser); }}>Excluir conta</button>}
</div>
</div>
</div>}
{deleteDialog}
{bulkDialog}
{bulkInviteDialog}
</main>;
return <main className="wrap page enter">
@@ -326,18 +441,22 @@ export const SuperAdmin: React.FC = () => {
<div className="toolbar">
<label className="search"><SearchMockIcon className="ph" /><input type="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Buscar por nome ou e-mail" aria-label="Buscar usuários" /></label>
<span className="sp" />
<input ref={bulkInviteInput} type="file" accept=".csv,text/csv" hidden onChange={(event) => void importBulkInvitations(event.target.files?.[0])} />
<button className="btn sec" type="button" onClick={() => bulkInviteInput.current?.click()} disabled={bulkInviteBusy}>{bulkInviteBusy ? 'Importando…' : 'Importar CSV'}</button>
<button className="btn sec" type="button" onClick={exportUsersCsv} disabled={!filteredUsers.length}>Exportar CSV</button>
<button className="btn" type="button" onClick={() => { setAccessLink(''); setInviteOpen(true); }}><PlusMockIcon className="ph" /> Convidar</button>
</div>
{loading ? <div className="loading"><CircleNotchIcon className="ph spin" /></div> : <div className="tablewrap"><table><thead><tr><th>Nome</th><th>Papel</th><th>Status</th><th>Último acesso</th><th></th></tr></thead><tbody>
{selectedUsers.size > 0 && <div className="bulkbar"><span className="num">{selectedUsers.size} {selectedUsers.size === 1 ? 'conta selecionada' : 'contas selecionadas'}</span><span className="sp" /><button className="btn sec" type="button" onClick={() => setBulkTarget(true)}>Ativar</button><button className="btn sec bad-text" type="button" onClick={() => setBulkTarget(false)}>Desativar</button><button className="link" type="button" onClick={() => setSelectedUsers(new Set())}>Limpar seleção</button></div>}
{loading ? <div className="loading"><CircleNotchIcon className="ph spin" /></div> : <div className="tablewrap"><table><thead><tr><th style={{ width: 36 }}><button className="check" type="button" role="checkbox" aria-checked={allSelected} aria-label="Selecionar todos" disabled={!selectableUsers.length} onClick={toggleAllSelected}>{allSelected && <CheckIcon className="ph" />}</button></th><th>Nome</th><th>Papel</th><th>Status</th><th>Último acesso</th><th></th></tr></thead><tbody>
{filteredUsers.map((account) => <tr key={account.id}>
<td><button className="check" type="button" role="checkbox" aria-checked={selectedUsers.has(account.id)} aria-label={`Selecionar ${account.name}`} disabled={account.id === user?.id} onClick={() => toggleSelected(account.id)}>{selectedUsers.has(account.id) && <CheckIcon className="ph" />}</button></td>
<td><span className="person"><Avatar name={account.name} size="sm" /><span>{account.name}<small>{account.email}</small></span></span></td>
<td><Select value={account.role} options={roleOptions} disabled={busyUserId === account.id || account.id === user?.id} onChange={(role) => void updateUser(account, { role: role as ManagedUser['role'] })} ariaLabel={`Papel de ${account.name}`} /></td>
<td><span className={`st ${account.isActive ? 'ok' : 'mut'}`}>{account.isActive ? 'Ativo' : 'Desativado'}</span></td>
<td className="num" style={{ color: 'var(--fg-2)' }}>{lastAccess(account.lastAccessAt)}</td>
<td className="right"><div className="rowmenu"><button className="iconbtn" type="button" aria-label={`Mais ações para ${account.name}`} aria-haspopup="menu" aria-expanded={openMenu?.account.id === account.id} disabled={busyUserId === account.id} onClick={(event) => { const rect = event.currentTarget.getBoundingClientRect(); setOpenMenu({ account, top: Math.min(rect.bottom + 6, window.innerHeight - 160), right: Math.max(12, window.innerWidth - rect.right) }); }}><MoreMockIcon className="ph" /></button></div></td>
</tr>)}
{!filteredUsers.length && <tr><td colSpan={5}><p className="empty">Nenhum usuário encontrado.</p></td></tr>}
{!filteredUsers.length && <tr><td colSpan={6}><p className="empty">Nenhum usuário encontrado.</p></td></tr>}
</tbody></table></div>}
</>}
@@ -396,10 +515,13 @@ export const SuperAdmin: React.FC = () => {
<button type="button" className="menu-scrim" aria-label="Fechar menu" onClick={() => setOpenMenu(null)} />
<div className="menu" role="menu" style={{ top: openMenu.top, right: openMenu.right, transformOrigin: 'top right' }}>
<button role="menuitem" type="button" onClick={() => void resetPassword(openMenu.account)}>Redefinir senha</button>
{openMenu.account.role !== 'admin' && openMenu.account.isActive && <button role="menuitem" type="button" onClick={() => void impersonate(openMenu.account)}>Entrar como usuário</button>}
<button role="menuitem" type="button" onClick={() => void updateUser(openMenu.account, { isActive: !openMenu.account.isActive })}>{openMenu.account.isActive ? 'Desativar conta' : 'Ativar conta'}</button>
{openMenu.account.id !== user?.id && <button role="menuitem" type="button" className="bad-text" onClick={() => deleteUser(openMenu.account)}>Excluir conta</button>}
</div>
</>, document.body)}
{deleteDialog}
{bulkDialog}
{bulkInviteDialog}
</main>;
};

View File

@@ -7,7 +7,6 @@ import {
ArrowSquareOutIcon as ExternalLink,
CircleNotchIcon as Loader2,
PencilIcon as Pencil,
PlusIcon as Plus,
FloppyDiskIcon as Save,
TrashIcon as Trash2,
UploadSimpleIcon as Upload,

View File

@@ -24,6 +24,6 @@ export const YouPage: React.FC = () => {
<Group title="Conta" entries={[{ label: 'Notificações', to: paths.notifications, icon: BellIcon }, { label: 'Dados pessoais', to: paths.account, icon: UserIcon }]} />
</> : <><div className="m-signin"><UserIcon className="m-ic xl" /><h2>Entre para continuar</h2><p>Com uma conta gratuita você assiste aos cursos, salva o progresso e participa da comunidade.</p><Link className="btn m-big" to={paths.signUp}>Criar conta</Link><Link className="btn sec m-big" to={paths.signIn}>Entrar</Link></div><Group title="Materiais" entries={[{ label: 'Biblioteca', to: paths.library, icon: FolderIcon }]} /></>}
<section className="m-group"><h2>Aparência</h2><div className="m-list"><div className="m-row"><span className="m-ic"><MoonIcon className="ph" /></span><span className="m-rt"><b>Modo escuro</b></span><button className="sw" type="button" role="switch" aria-checked={theme === 'dark'} aria-label="Modo escuro" onClick={toggleTheme} /></div></div></section>
{user && <section className="m-group"><div className="m-list"><button className="m-row m-danger" type="button" onClick={() => { logout(); navigate(paths.explore); }}><span className="m-ic"><SignOutIcon className="ph" /></span><span className="m-rt"><b>Sair</b></span></button></div></section>}
{user && <section className="m-group"><div className="m-list"><button className="m-row m-danger" type="button" onClick={() => { void logout().then(() => navigate(paths.explore)); }}><span className="m-ic"><SignOutIcon className="ph" /></span><span className="m-rt"><b>Sair</b></span></button></div></section>}
</main>;
};

View File

@@ -0,0 +1,5 @@
-- Optional TOTP two-factor authentication for administrators.
alter table users
add column if not exists two_factor_secret text,
add column if not exists two_factor_enabled boolean not null default false,
add column if not exists two_factor_backup_codes jsonb not null default '[]'::jsonb;

View File

@@ -0,0 +1,7 @@
-- Optional future publication time for draft courses.
alter table courses
add column if not exists scheduled_publish_at timestamptz;
create index if not exists courses_scheduled_publish_index
on courses (scheduled_publish_at)
where status = 'draft' and scheduled_publish_at is not null;

View File

@@ -1,3 +1,4 @@
import cookie from '@fastify/cookie';
import cors from '@fastify/cors';
import Fastify from 'fastify';
import { ZodError } from 'zod';
@@ -53,8 +54,10 @@ export function buildApp() {
app.addContentTypeParser(contentType, { parseAs: 'buffer', bodyLimit: config.BUNNY_ASSET_MAX_UPLOAD_MB * 1024 * 1024 }, (_request, body, done) => done(null, body));
}
app.register(cookie);
app.register(cors, {
origin: config.FRONTEND_ORIGIN,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
});

View File

@@ -12,6 +12,7 @@ export interface AuthUser {
role: UserRole;
name: string;
tokenVersion: number;
impersonatedBy?: string;
}
declare module '@fastify/jwt' {
@@ -29,7 +30,11 @@ declare module 'fastify' {
}
const registerAuth: FastifyPluginAsync = async (app) => {
await app.register(fastifyJwt, { secret: config.JWT_SECRET });
await app.register(fastifyJwt, {
secret: config.JWT_SECRET,
cookie: { cookieName: 'compor_session', signed: false },
sign: { expiresIn: '7d' },
});
const verifyActiveUser = async (request: { jwtVerify: () => Promise<void>; user: AuthUser }, reply: { code: (status: number) => { send: (payload: object) => unknown } }) => {
try {
@@ -54,6 +59,11 @@ const registerAuth: FastifyPluginAsync = async (app) => {
return false;
}
if (request.user.impersonatedBy && account.role === 'admin') {
reply.code(403).send({ error: 'Encerre a impersonação para acessar esta área.' });
return false;
}
request.user.role = account.role;
request.user.name = account.display_name;
request.user.tokenVersion = account.token_version;

View File

@@ -0,0 +1,37 @@
import type { FastifyReply } from 'fastify';
import { config } from '../config.js';
export const SESSION_COOKIE = 'compor_session';
export const ADMIN_SESSION_COOKIE = 'compor_admin_session';
const SESSION_MAX_AGE_SECONDS = (() => {
const match = /^(\d+)([smhd])$/.exec(config.JWT_SESSION_TTL);
if (!match) return 60 * 60 * 24 * 7;
const value = Number(match[1]);
const unit = match[2];
return unit === 's' ? value : unit === 'm' ? value * 60 : unit === 'h' ? value * 3600 : value * 86400;
})();
const cookieOptions = {
httpOnly: true,
secure: config.APP_ENV === 'production',
sameSite: 'lax' as const,
path: '/',
maxAge: SESSION_MAX_AGE_SECONDS,
};
export const setSessionCookie = (reply: FastifyReply, token: string) => {
reply.setCookie(SESSION_COOKIE, token, cookieOptions);
};
export const clearSessionCookie = (reply: FastifyReply) => {
reply.clearCookie(SESSION_COOKIE, { path: '/' });
};
export const setAdminSessionCookie = (reply: FastifyReply, token: string) => {
reply.setCookie(ADMIN_SESSION_COOKIE, token, cookieOptions);
};
export const clearAdminSessionCookie = (reply: FastifyReply) => {
reply.clearCookie(ADMIN_SESSION_COOKIE, { path: '/' });
};

View File

@@ -1,12 +1,14 @@
import { buildApp } from './app.js';
import { config } from './config.js';
import { closePool } from './db/pool.js';
import { startScheduledPublisher } from './services/scheduler.js';
const app = buildApp();
async function start() {
try {
await app.listen({ host: '0.0.0.0', port: config.API_PORT });
startScheduledPublisher(app.log);
} catch (error) {
app.log.error(error);
await closePool();

View File

@@ -3,6 +3,8 @@ import type { PoolClient } from 'pg';
import { z } from 'zod';
import { pool } from '../db/pool.js';
import { createRawToken, hashToken } from '../auth/account-tokens.js';
import type { AuthUser } from '../auth/plugin.js';
import { setAdminSessionCookie, setSessionCookie } from '../auth/session-cookie.js';
import { config } from '../config.js';
import { recordAudit } from '../audit.js';
import { sendInvitationEmail, sendPasswordResetEmail } from '../services/email.js';
@@ -20,6 +22,13 @@ const updateUserSchema = z.object({
message: 'Informe pelo menos um campo para atualizar.',
});
const invitationSchema = z.object({ email: z.string().email().transform((email) => email.toLowerCase()), role: z.literal('instructor').default('instructor') });
const bulkInvitationSchema = z.object({
emails: z.array(z.string().email().transform((email) => email.toLowerCase())).min(1).max(100),
});
const bulkUserStatusSchema = z.object({
userIds: z.array(z.string().uuid()).min(1).max(200),
isActive: z.boolean(),
});
const categorySchema = z.object({ name: z.string().trim().min(1).max(120), isActive: z.boolean().optional(), position: z.number().int().min(0).max(10_000).optional() });
const categoryParamsSchema = z.object({ categoryId: z.string().uuid() });
const homeConfigurationSchema = z.object({
@@ -131,6 +140,29 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
return { data: result.rows };
});
app.patch('/users/bulk', adminAccess, async (request, reply) => {
const input = bulkUserStatusSchema.parse(request.body);
if (!input.isActive && input.userIds.includes(request.user.id)) {
return reply.code(400).send({ error: 'Você não pode desativar sua própria conta.' });
}
const result = await pool.query(
`update users
set is_active = $2
where id = any($1::uuid[])
returning id, email, display_name as name, role, is_active as "isActive", created_at as "createdAt",
(select max(lp.updated_at) from lesson_progress lp where lp.user_id = users.id) as "lastAccessAt"`,
[input.userIds, input.isActive],
);
await recordAudit({
actorId: request.user.id,
action: input.isActive ? 'user.bulk_activated' : 'user.bulk_deactivated',
subjectType: 'user',
metadata: { userIds: input.userIds },
ipAddress: request.ip,
});
return { data: result.rows };
});
app.get('/dashboard', adminAccess, async () => {
const result = await pool.query(
`select
@@ -351,6 +383,81 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
return { data: result.rows };
});
app.post('/invitations/bulk', adminAccess, async (request) => {
const input = bulkInvitationSchema.parse(request.body);
const emails = [...new Set(input.emails)];
const results: Array<{ email: string; inviteUrl?: string; error?: string }> = [];
for (const email of emails) {
const existing = await pool.query('select 1 from users where email = $1', [email]);
if (existing.rowCount) {
results.push({ email, error: 'Este e-mail já possui uma conta.' });
continue;
}
try {
const rawToken = createRawToken();
await pool.query(
`insert into account_access_tokens (email, role, purpose, token_hash, expires_at, created_by)
values ($1, 'instructor'::user_role, 'invitation', $2, now() + ($3::int * interval '1 hour'), $4)`,
[email, hashToken(rawToken), config.INVITATION_TTL_HOURS, request.user.id],
);
const inviteUrl = `${config.FRONTEND_ORIGIN}/invite?token=${rawToken}`;
try {
const sent = await sendInvitationEmail({ email, inviteUrl });
if (!sent && config.SMTP_HOST) request.log.warn({ email }, 'Bulk invitation email was rejected by the SMTP server');
} catch (error) {
request.log.error(error, 'Bulk invitation email could not be sent');
}
results.push({ email, inviteUrl });
} catch (error) {
request.log.error(error, 'Could not create bulk invitation');
results.push({ email, error: 'Não foi possível gerar o convite.' });
}
}
await recordAudit({
actorId: request.user.id,
action: 'invitation.bulk_created',
subjectType: 'invitation',
metadata: { emails, created: results.filter((result) => result.inviteUrl).length },
ipAddress: request.ip,
});
return { data: results };
});
app.post('/users/:userId/impersonate', adminAccess, async (request, reply) => {
const { userId } = userParamsSchema.parse(request.params);
if (userId === request.user.id) return reply.code(400).send({ error: 'Você já está usando sua própria conta.' });
const result = await pool.query<{ id: string; email: string; display_name: string; role: AuthUser['role']; token_version: number; is_active: boolean }>(
'select id, email, display_name, role, token_version, is_active from users where id = $1',
[userId],
);
const target = result.rows[0];
if (!target || !target.is_active) return reply.code(404).send({ error: 'Usuário não encontrado ou desativado.' });
if (target.role === 'admin') return reply.code(400).send({ error: 'Não é possível impersonar outra conta de administrador.' });
const targetUser: AuthUser = {
id: target.id,
email: target.email,
name: target.display_name,
role: target.role,
tokenVersion: target.token_version,
impersonatedBy: request.user.id,
};
setAdminSessionCookie(reply, await reply.jwtSign(request.user));
setSessionCookie(reply, await reply.jwtSign(targetUser));
await recordAudit({
actorId: request.user.id,
action: 'user.impersonated',
subjectType: 'user',
subjectId: target.id,
metadata: { email: target.email },
ipAddress: request.ip,
});
return { data: targetUser };
});
app.get('/users/:userId', adminAccess, async (request, reply) => {
const { userId } = userParamsSchema.parse(request.params);
const result = await pool.query(

View File

@@ -1,8 +1,18 @@
import type { FastifyPluginAsync } from 'fastify';
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
import * as OTPAuth from 'otpauth';
import QRCode from 'qrcode';
import { z } from 'zod';
import { hashPassword, verifyPassword } from '../auth/passwords.js';
import { createRawToken, hashToken } from '../auth/account-tokens.js';
import type { AuthUser } from '../auth/plugin.js';
import {
ADMIN_SESSION_COOKIE,
clearAdminSessionCookie,
clearSessionCookie,
setSessionCookie,
} from '../auth/session-cookie.js';
import { recordAudit } from '../audit.js';
import { pool } from '../db/pool.js';
import { config } from '../config.js';
import { sendPasswordResetEmail, sendWelcomeEmail } from '../services/email.js';
@@ -19,6 +29,14 @@ const tokenPasswordSchema = z.object({ token: z.string().min(20), password: z.st
const forgotPasswordSchema = z.object({
email: z.string().email().transform((email) => email.toLowerCase()),
});
const twoFactorCodeSchema = z.object({ code: z.string().trim().min(6).max(32) });
const twoFactorDisableSchema = twoFactorCodeSchema.extend({ password: z.string().min(8).max(200) });
const twoFactorVerifySchema = z.object({
challengeToken: z.string().min(20),
code: z.string().trim().min(6).max(32),
});
type UserRow = {
id: string;
@@ -28,6 +46,12 @@ type UserRow = {
password_hash: string;
is_active: boolean;
token_version: number;
two_factor_enabled: boolean;
};
type TwoFactorRow = UserRow & {
two_factor_secret: string | null;
two_factor_backup_codes: string[];
};
const serializeUser = (user: UserRow): AuthUser => ({
@@ -38,6 +62,40 @@ const serializeUser = (user: UserRow): AuthUser => ({
tokenVersion: user.token_version,
});
const createTotp = (secret: string, email: string) => new OTPAuth.TOTP({
issuer: 'Compor HUB',
label: email,
algorithm: 'SHA1',
digits: 6,
period: 30,
secret: OTPAuth.Secret.fromBase32(secret),
});
const verifyTotp = (secret: string | null, email: string, code: string) => {
if (!secret) return false;
const token = code.replace(/\s+/g, '');
return createTotp(secret, email).validate({ token, window: 1 }) !== null;
};
const generateBackupCodes = () => Array.from({ length: 10 }, () => {
const raw = randomBytes(5).toString('hex').toUpperCase();
return `${raw.slice(0, 5)}-${raw.slice(5)}`;
});
const normalizeBackupCode = (code: string) => code.replace(/[\s-]/g, '').toUpperCase();
const backupCodeHash = (code: string) => createHmac('sha256', config.JWT_SECRET).update(normalizeBackupCode(code)).digest('hex');
const verifyBackupCode = (hashes: string[], code: string) => {
const hash = Buffer.from(backupCodeHash(code), 'hex');
return hashes.some((candidate) => {
const stored = Buffer.from(candidate, 'hex');
return stored.length === hash.length && timingSafeEqual(stored, hash);
});
};
const removeBackupCode = (hashes: string[], code: string) => hashes.filter((hash) => hash !== backupCodeHash(code));
export const authRoutes: FastifyPluginAsync = async (app) => {
// This is stored in PostgreSQL rather than process memory so the limit keeps
// working if the API is restarted or later scaled to more than one replica.
@@ -83,12 +141,13 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
}
const result = await client.query<UserRow>(
`insert into users (email, password_hash, display_name, role) values ($1, $2, $3, $4)
returning id, email, display_name, role, password_hash, is_active, token_version`,
returning id, email, display_name, role, password_hash, is_active, token_version, two_factor_enabled`,
[token.rows[0].email, await hashPassword(input.password), input.name, token.rows[0].role],
);
await client.query('commit');
const user = serializeUser(result.rows[0]);
return reply.code(201).send({ token: await reply.jwtSign(user, { expiresIn: config.JWT_SESSION_TTL }), user });
setSessionCookie(reply, await reply.jwtSign(user));
return reply.code(201).send({ user });
} catch {
await client.query('rollback');
return reply.code(409).send({ error: 'Este e-mail de convite já possui uma conta.' });
@@ -159,18 +218,18 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
const result = await pool.query<UserRow>(
`insert into users (email, password_hash, display_name)
values ($1, $2, $3)
returning id, email, display_name, role, password_hash, is_active, token_version`,
returning id, email, display_name, role, password_hash, is_active, token_version, two_factor_enabled`,
[input.email, passwordHash, input.name],
);
const user = serializeUser(result.rows[0]);
const token = await reply.jwtSign(user, { expiresIn: config.JWT_SESSION_TTL });
setSessionCookie(reply, await reply.jwtSign(user));
try {
const sent = await sendWelcomeEmail({ name: user.name, email: user.email });
if (!sent && config.SMTP_HOST) request.log.warn({ email: user.email }, 'Welcome email was rejected by the SMTP server');
} catch (error) {
request.log.error(error, 'Welcome email could not be sent');
}
return reply.code(201).send({ token, user });
return reply.code(201).send({ user });
} catch (error: unknown) {
if (typeof error === 'object' && error && 'code' in error && error.code === '23505') {
return reply.code(409).send({ error: 'Já existe uma conta com este e-mail.' });
@@ -183,7 +242,7 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
if (await rejectIfRateLimited(request.ip, reply)) return;
const input = credentialsSchema.parse(request.body);
const result = await pool.query<UserRow>(
`select id, email, display_name, role, password_hash, is_active, token_version from users where email = $1`,
`select id, email, display_name, role, password_hash, is_active, token_version, two_factor_enabled from users where email = $1`,
[input.email],
);
const account = result.rows[0];
@@ -192,9 +251,197 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
return reply.code(401).send({ error: 'E-mail ou senha inválidos.' });
}
if (account.two_factor_enabled) {
const challengeToken = app.jwt.sign(
{ sub: account.id, purpose: '2fa', tokenVersion: account.token_version } as unknown as AuthUser,
{ expiresIn: '5m' },
);
return { twoFactorRequired: true, challengeToken };
}
const user = serializeUser(account);
const token = await reply.jwtSign(user, { expiresIn: config.JWT_SESSION_TTL });
return { token, user };
setSessionCookie(reply, await reply.jwtSign(user));
return { user };
});
app.post('/2fa/verify', async (request, reply) => {
if (await rejectIfRateLimited(request.ip, reply)) return;
const input = twoFactorVerifySchema.parse(request.body);
let challenge: { sub?: string; purpose?: string; tokenVersion?: number };
try {
challenge = app.jwt.verify<{ sub?: string; purpose?: string; tokenVersion?: number }>(input.challengeToken);
} catch {
return reply.code(401).send({ error: 'Verificação expirada. Entre novamente.' });
}
if (challenge.purpose !== '2fa' || !challenge.sub) {
return reply.code(401).send({ error: 'Verificação inválida. Entre novamente.' });
}
const result = await pool.query<TwoFactorRow>(
`select id, email, display_name, role, password_hash, is_active, token_version, two_factor_enabled,
two_factor_secret, two_factor_backup_codes
from users where id = $1`,
[challenge.sub],
);
const account = result.rows[0];
if (!account || !account.is_active || !account.two_factor_enabled || account.token_version !== challenge.tokenVersion) {
return reply.code(401).send({ error: 'Verificação expirada. Entre novamente.' });
}
if (verifyTotp(account.two_factor_secret, account.email, input.code)) {
// Valid authenticator code.
} else if (verifyBackupCode(account.two_factor_backup_codes, input.code)) {
await pool.query('update users set two_factor_backup_codes = $2::jsonb where id = $1', [
account.id,
JSON.stringify(removeBackupCode(account.two_factor_backup_codes, input.code)),
]);
} else {
return reply.code(401).send({ error: 'Código de verificação inválido.' });
}
const user = serializeUser(account);
setSessionCookie(reply, await reply.jwtSign(user));
return { user };
});
app.post('/logout', async (_request, reply) => {
clearSessionCookie(reply);
clearAdminSessionCookie(reply);
return reply.code(204).send();
});
app.post('/stop-impersonation', async (request, reply) => {
const adminToken = request.cookies[ADMIN_SESSION_COOKIE];
if (!adminToken) return reply.code(400).send({ error: 'Não há impersonação ativa.' });
let payload: AuthUser;
try {
payload = app.jwt.verify<AuthUser>(adminToken);
} catch {
clearAdminSessionCookie(reply);
return reply.code(401).send({ error: 'Sessão de administrador expirada.' });
}
const result = await pool.query<{ id: string; email: string; display_name: string; role: AuthUser['role']; token_version: number; is_active: boolean }>(
'select id, email, display_name, role, token_version, is_active from users where id = $1',
[payload.id],
);
const account = result.rows[0];
if (!account || !account.is_active || account.role !== 'admin' || account.token_version !== payload.tokenVersion) {
clearSessionCookie(reply);
clearAdminSessionCookie(reply);
return reply.code(401).send({ error: 'Sessão de administrador expirada.' });
}
const admin: AuthUser = {
id: account.id,
email: account.email,
name: account.display_name,
role: account.role,
tokenVersion: account.token_version,
};
setSessionCookie(reply, await reply.jwtSign(admin));
clearAdminSessionCookie(reply);
await recordAudit({
actorId: admin.id,
action: 'user.impersonation_stopped',
subjectType: 'session',
ipAddress: request.ip,
});
return { user: admin };
});
app.get('/2fa', { preHandler: app.requireRoles(['admin']) }, async (request) => {
const result = await pool.query<{ enabled: boolean; backupCodes: string[] }>(
`select two_factor_enabled as enabled, two_factor_backup_codes as "backupCodes"
from users where id = $1`,
[request.user.id],
);
return { data: { enabled: result.rows[0]?.enabled ?? false, backupCodesRemaining: result.rows[0]?.backupCodes?.length ?? 0 } };
});
app.post('/2fa/setup', { preHandler: app.requireRoles(['admin']) }, async (request, reply) => {
const result = await pool.query<{ email: string; enabled: boolean }>(
'select email, two_factor_enabled as enabled from users where id = $1',
[request.user.id],
);
const account = result.rows[0];
if (!account) return reply.code(404).send({ error: 'Conta não encontrada.' });
if (account.enabled) return reply.code(400).send({ error: 'A verificação em duas etapas já está ativa.' });
const secret = new OTPAuth.Secret({ size: 20 }).base32;
await pool.query(
'update users set two_factor_secret = $2, two_factor_enabled = false, two_factor_backup_codes = $3::jsonb where id = $1',
[request.user.id, secret, JSON.stringify([])],
);
const otpauthUrl = createTotp(secret, account.email).toString();
const qrCode = await QRCode.toDataURL(otpauthUrl, { margin: 1, width: 240 });
return { data: { secret, otpauthUrl, qrCode } };
});
app.post('/2fa/enable', { preHandler: app.requireRoles(['admin']) }, async (request, reply) => {
const input = twoFactorCodeSchema.parse(request.body);
const result = await pool.query<{ email: string; enabled: boolean; secret: string | null }>(
'select email, two_factor_enabled as enabled, two_factor_secret as secret from users where id = $1',
[request.user.id],
);
const account = result.rows[0];
if (!account?.secret) return reply.code(400).send({ error: 'Configure a verificação em duas etapas primeiro.' });
if (account.enabled) return reply.code(400).send({ error: 'A verificação em duas etapas já está ativa.' });
if (!verifyTotp(account.secret, account.email, input.code)) {
return reply.code(400).send({ error: 'Código de verificação inválido.' });
}
const backupCodes = generateBackupCodes();
await pool.query(
'update users set two_factor_enabled = true, two_factor_backup_codes = $2::jsonb where id = $1',
[request.user.id, JSON.stringify(backupCodes.map(backupCodeHash))],
);
return { data: { backupCodes } };
});
app.post('/2fa/backup-codes', { preHandler: app.requireRoles(['admin']) }, async (request, reply) => {
const input = twoFactorCodeSchema.parse(request.body);
const result = await pool.query<{ email: string; enabled: boolean; secret: string | null }>(
'select email, two_factor_enabled as enabled, two_factor_secret as secret from users where id = $1',
[request.user.id],
);
const account = result.rows[0];
if (!account?.enabled || !account.secret) return reply.code(400).send({ error: 'A verificação em duas etapas não está ativa.' });
if (!verifyTotp(account.secret, account.email, input.code)) {
return reply.code(400).send({ error: 'Código de verificação inválido.' });
}
const backupCodes = generateBackupCodes();
await pool.query(
'update users set two_factor_backup_codes = $2::jsonb where id = $1',
[request.user.id, JSON.stringify(backupCodes.map(backupCodeHash))],
);
return { data: { backupCodes } };
});
app.post('/2fa/disable', { preHandler: app.requireRoles(['admin']) }, async (request, reply) => {
const input = twoFactorDisableSchema.parse(request.body);
const result = await pool.query<{ email: string; password_hash: string; enabled: boolean; secret: string | null; backupCodes: string[] }>(
`select email, password_hash, two_factor_enabled as enabled, two_factor_secret as secret,
two_factor_backup_codes as "backupCodes"
from users where id = $1`,
[request.user.id],
);
const account = result.rows[0];
if (!account?.enabled) return reply.code(400).send({ error: 'A verificação em duas etapas não está ativa.' });
if (!(await verifyPassword(input.password, account.password_hash))) {
return reply.code(401).send({ error: 'Senha incorreta.' });
}
if (!verifyTotp(account.secret, account.email, input.code) && !verifyBackupCode(account.backupCodes, input.code)) {
return reply.code(401).send({ error: 'Código de verificação inválido.' });
}
await pool.query(
'update users set two_factor_enabled = false, two_factor_secret = null, two_factor_backup_codes = $2::jsonb where id = $1',
[request.user.id, JSON.stringify([])],
);
return reply.code(204).send();
});
app.get('/me', { preHandler: app.authenticate }, async (request) => ({ user: request.user }));

View File

@@ -34,6 +34,7 @@ export const courseSelect = (publicOnly = false, includeUnreadyMedia = false) =>
c.cover_image_position_x as "coverImagePositionX",
c.cover_image_position_y as "coverImagePositionY",
c.status,
c.scheduled_publish_at as "scheduledPublishAt",
c.published_at as "publishedAt",
c.updated_at as "updatedAt",
c.created_at as "createdAt",

View File

@@ -50,6 +50,7 @@ const courseSchema = z.object({
coverImagePositionX: z.number().min(0).max(100).default(50),
coverImagePositionY: z.number().min(0).max(100).default(50),
status: z.enum(['draft', 'published']).default('draft'),
scheduledPublishAt: z.string().datetime().nullable().optional(),
lessons: z.array(lessonSchema).min(1),
assets: z.array(assetSchema).default([]),
});
@@ -230,10 +231,10 @@ export const manageCourseRoutes: FastifyPluginAsync = async (app) => {
await client.query('begin');
const slug = await uniqueSlug(client, input.slug, input.title);
const course = await client.query<{ id: string }>(
`insert into courses (slug, title, description, category, cover_image_url, cover_image_zoom, cover_image_position_x, cover_image_position_y, status, instructor_id, published_at)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9::course_status, $10, case when $9::course_status = 'published'::course_status then now() else null end)
`insert into courses (slug, title, description, category, cover_image_url, cover_image_zoom, cover_image_position_x, cover_image_position_y, status, instructor_id, published_at, scheduled_publish_at)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9::course_status, $10, case when $9::course_status = 'published'::course_status then now() else null end, case when $9::course_status = 'published'::course_status then null else $11::timestamptz end)
returning id`,
[slug, input.title, input.description, input.category, input.coverImageUrl ?? null, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status, request.user.id],
[slug, input.title, input.description, input.category, input.coverImageUrl ?? null, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status, request.user.id, input.scheduledPublishAt ?? null],
);
await replaceCourseContents(client, course.rows[0].id, input);
await client.query('commit');
@@ -263,9 +264,10 @@ export const manageCourseRoutes: FastifyPluginAsync = async (app) => {
await client.query(
`update courses
set slug = $2, title = $3, description = $4, category = $5, cover_image_url = $6, cover_image_zoom = $7, cover_image_position_x = $8, cover_image_position_y = $9,
status = $10::course_status, published_at = case when $10::course_status = 'published'::course_status then coalesce(published_at, now()) else null end
status = $10::course_status, published_at = case when $10::course_status = 'published'::course_status then coalesce(published_at, now()) else null end,
scheduled_publish_at = case when $10::course_status = 'published'::course_status then null else $11::timestamptz end
where id = $1`,
[courseId, slug, input.title, input.description, input.category, input.coverImageUrl ?? null, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status],
[courseId, slug, input.title, input.description, input.category, input.coverImageUrl ?? null, input.coverImageZoom, input.coverImagePositionX, input.coverImagePositionY, input.status, input.scheduledPublishAt ?? null],
);
await replaceCourseContents(client, courseId, input);
await client.query('commit');
@@ -287,7 +289,7 @@ export const manageCourseRoutes: FastifyPluginAsync = async (app) => {
const client = await pool.connect();
try {
await client.query('begin');
await client.query(`update courses set status = 'archived', published_at = null where id = $1`, [courseId]);
await client.query(`update courses set status = 'archived', published_at = null, scheduled_publish_at = null where id = $1`, [courseId]);
await client.query('delete from learning_path_courses where course_id = $1', [courseId]);
await client.query('commit');
} catch (error) {

View File

@@ -15,10 +15,9 @@ export const notificationRoutes: FastifyPluginAsync = async (app) => {
limit 50`,
[request.user.id],
),
pool.query<{ count: number }>(
'select count(*)::int as count from notifications where user_id = $1 and read_at is null',
[request.user.id],
),
pool.query<{ count: number }>('select count(*)::int as count from notifications where user_id = $1 and read_at is null', [
request.user.id,
]),
]);
return { data: { items: items.rows, unread: unread.rows[0].count } };
});
@@ -30,7 +29,10 @@ export const notificationRoutes: FastifyPluginAsync = async (app) => {
app.post('/:notificationId/read', { preHandler: app.authenticate }, async (request, reply) => {
const { notificationId } = notificationParamsSchema.parse(request.params);
await pool.query('update notifications set read_at = coalesce(read_at, now()) where id = $1 and user_id = $2', [notificationId, request.user.id]);
await pool.query('update notifications set read_at = coalesce(read_at, now()) where id = $1 and user_id = $2', [
notificationId,
request.user.id,
]);
return reply.code(204).send();
});
};

View File

@@ -0,0 +1,71 @@
import type { FastifyBaseLogger } from 'fastify';
import { recordAudit } from '../audit.js';
import { pool } from '../db/pool.js';
/**
* Publishes drafts whose scheduled time has arrived, but only when every lesson
* has a ready video. If media is still processing, the course stays scheduled
* and is retried on the next tick.
*/
export const publishScheduledCourses = async (log?: FastifyBaseLogger) => {
const client = await pool.connect();
try {
await client.query('begin');
const result = await client.query<{ id: string; title: string; instructor_id: string }>(
`update courses c
set status = 'published'::course_status,
published_at = now(),
scheduled_publish_at = null
where c.status = 'draft'
and c.scheduled_publish_at is not null
and c.scheduled_publish_at <= now()
and exists (select 1 from lessons l where l.course_id = c.id)
and not exists (
select 1
from lessons l
where l.course_id = c.id
and not exists (
select 1 from lesson_media lm
where lm.lesson_id = l.id and lm.status = 'ready'
)
)
returning c.id, c.title, c.instructor_id`,
);
for (const course of result.rows) {
await client.query(
`insert into notifications (user_id, kind, title, body, href)
values ($1, 'course_published', $2, $3, $4)`,
[course.instructor_id, `Curso publicado: ${course.title}`, 'A publicação agendada foi concluída automaticamente.', '/gerenciar'],
);
}
await client.query('commit');
for (const course of result.rows) {
await recordAudit({
action: 'course.published.scheduled',
subjectType: 'course',
subjectId: course.id,
metadata: { title: course.title },
});
}
if (result.rowCount) log?.info({ count: result.rowCount }, 'Scheduled courses published');
} catch (error) {
await client.query('rollback');
throw error;
} finally {
client.release();
}
};
export const startScheduledPublisher = (log?: FastifyBaseLogger) => {
const run = () => {
void publishScheduledCourses(log).catch((error) => log?.error(error, 'Scheduled publisher failed'));
};
run();
const timer = setInterval(run, 60_000);
timer.unref?.();
return timer;
};

View File

@@ -8,6 +8,7 @@ export interface ApiUser {
email: string;
name: string;
role: ApiRole;
impersonatedBy?: string;
}
export interface Profile {
@@ -118,11 +119,17 @@ export interface HomeBanner extends HomeBannerInput {
courseImageUrl: string | null;
}
interface Session {
token: string;
export interface Session {
user: ApiUser;
}
export type LoginResponse = Session | { twoFactorRequired: true; challengeToken: string };
export interface TwoFactorStatus {
enabled: boolean;
backupCodesRemaining: number;
}
export class ApiError extends Error {
constructor(message: string, public status: number) {
super(message);
@@ -149,10 +156,7 @@ export function clearSession() {
}
export async function downloadCourseAsset(assetId: string, filename: string) {
const session = getSession();
const headers = new Headers();
if (session) headers.set('Authorization', `Bearer ${session.token}`);
const response = await fetch(`${API_URL}/courses/assets/${assetId}/download`, { headers });
const response = await fetch(`${API_URL}/courses/assets/${assetId}/download`, { credentials: 'include' });
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new ApiError(body.error || 'Não foi possível baixar este material.', response.status);
@@ -169,12 +173,10 @@ export async function downloadCourseAsset(assetId: string, filename: string) {
}
export async function apiRequest<T>(path: string, options: RequestInit = {}): Promise<T> {
const session = getSession();
const headers = new Headers(options.headers);
if (options.body) headers.set('Content-Type', 'application/json');
if (session) headers.set('Authorization', `Bearer ${session.token}`);
const response = await fetch(`${API_URL}${path}`, { ...options, headers });
const response = await fetch(`${API_URL}${path}`, { ...options, headers, credentials: 'include' });
if (response.status === 204) return undefined as T;
const body = await response.json().catch(() => ({}));
@@ -185,20 +187,16 @@ export async function apiRequest<T>(path: string, options: RequestInit = {}): Pr
}
async function uploadRequest<T>(path: string, file: File): Promise<T> {
const session = getSession();
const headers = new Headers({ 'Content-Type': file.type || 'application/octet-stream' });
if (session) headers.set('Authorization', `Bearer ${session.token}`);
const response = await fetch(`${API_URL}${path}`, { method: 'PUT', headers, body: file });
const response = await fetch(`${API_URL}${path}`, { method: 'PUT', headers, body: file, credentials: 'include' });
const body = await response.json().catch(() => ({}));
if (!response.ok) throw new ApiError(body.error || 'Não foi possível concluir o envio do vídeo.', response.status);
return body as T;
}
async function uploadImageRequest<T>(path: string, file: File): Promise<T> {
const session = getSession();
const headers = new Headers({ 'Content-Type': file.type || 'application/octet-stream' });
if (session) headers.set('Authorization', `Bearer ${session.token}`);
const response = await fetch(`${API_URL}${path}`, { method: 'POST', headers, body: file });
const response = await fetch(`${API_URL}${path}`, { method: 'POST', headers, body: file, credentials: 'include' });
const body = await response.json().catch(() => ({}));
if (!response.ok) throw new ApiError(body.error || 'Não foi possível enviar a imagem de capa.', response.status);
return body as T;
@@ -206,7 +204,10 @@ async function uploadImageRequest<T>(path: string, file: File): Promise<T> {
export const authApi = {
async login(email: string, password: string) {
return apiRequest<Session>('/auth/login', { method: 'POST', body: JSON.stringify({ email, password }) });
return apiRequest<LoginResponse>('/auth/login', { method: 'POST', body: JSON.stringify({ email, password }) });
},
async verifyTwoFactor(challengeToken: string, code: string) {
return apiRequest<Session>('/auth/2fa/verify', { method: 'POST', body: JSON.stringify({ challengeToken, code }) });
},
async register(name: string, email: string, password: string) {
return apiRequest<Session>('/auth/register', { method: 'POST', body: JSON.stringify({ name, email, password }) });
@@ -214,6 +215,12 @@ export const authApi = {
async me() {
return apiRequest<{ user: ApiUser }>('/auth/me');
},
async logout() {
return apiRequest<void>('/auth/logout', { method: 'POST' });
},
async stopImpersonation() {
return apiRequest<{ user: ApiUser }>('/auth/stop-impersonation', { method: 'POST' });
},
async acceptInvitation(token: string, name: string, password: string) {
return apiRequest<Session>('/auth/accept-invitation', { method: 'POST', body: JSON.stringify({ token, name, password }) });
},
@@ -223,6 +230,21 @@ export const authApi = {
async forgotPassword(email: string) {
return apiRequest<void>('/auth/forgot-password', { method: 'POST', body: JSON.stringify({ email }) });
},
async twoFactorStatus() {
return apiRequest<{ data: TwoFactorStatus }>('/auth/2fa');
},
async setupTwoFactor() {
return apiRequest<{ data: { secret: string; otpauthUrl: string; qrCode: string } }>('/auth/2fa/setup', { method: 'POST' });
},
async enableTwoFactor(code: string) {
return apiRequest<{ data: { backupCodes: string[] } }>('/auth/2fa/enable', { method: 'POST', body: JSON.stringify({ code }) });
},
async regenerateBackupCodes(code: string) {
return apiRequest<{ data: { backupCodes: string[] } }>('/auth/2fa/backup-codes', { method: 'POST', body: JSON.stringify({ code }) });
},
async disableTwoFactor(code: string, password: string) {
return apiRequest<void>('/auth/2fa/disable', { method: 'POST', body: JSON.stringify({ code, password }) });
},
};
export const adminApi = {
@@ -230,6 +252,15 @@ export const adminApi = {
async listUsers() {
return apiRequest<{ data: ManagedUser[] }>('/admin/users');
},
async impersonate(userId: string) {
return apiRequest<{ data: ApiUser }>(`/admin/users/${userId}/impersonate`, { method: 'POST' });
},
async bulkUpdateUsers(userIds: string[], isActive: boolean) {
return apiRequest<{ data: ManagedUser[] }>('/admin/users/bulk', {
method: 'PATCH',
body: JSON.stringify({ userIds, isActive }),
});
},
async updateUser(userId: string, update: Partial<Pick<ManagedUser, 'name' | 'email' | 'role' | 'isActive'>>) {
return apiRequest<{ data: ManagedUser }>(`/admin/users/${userId}`, {
method: 'PATCH',
@@ -239,6 +270,12 @@ export const adminApi = {
async invite(email: string, role: 'instructor' = 'instructor') {
return apiRequest<{ data: { inviteUrl: string } }>('/admin/invitations', { method: 'POST', body: JSON.stringify({ email, role }) });
},
async bulkInvite(emails: string[]) {
return apiRequest<{ data: Array<{ email: string; inviteUrl?: string; error?: string }> }>('/admin/invitations/bulk', {
method: 'POST',
body: JSON.stringify({ emails }),
});
},
async passwordReset(userId: string) {
return apiRequest<{ data: { resetUrl: string } }>(`/admin/users/${userId}/password-reset`, { method: 'POST' });
},

View File

@@ -23,6 +23,7 @@ export type ApiCourse = {
coverImagePositionX: number;
coverImagePositionY: number;
status: 'draft' | 'published' | 'archived';
scheduledPublishAt?: string | null;
progress?: number;
views?: number;
learners?: number;
@@ -135,6 +136,7 @@ export const toCourse = (course: ApiCourse): Course => ({
instructor: course.instructor.name,
instructorId: course.instructor.id,
status: course.status === 'draft' ? 'draft' : 'published',
scheduledPublishAt: course.scheduledPublishAt || null,
progress: course.progress,
views: course.views,
learners: course.learners,
@@ -206,6 +208,7 @@ const toCoursePayload = (course: Course) => ({
coverImagePositionX: course.coverImagePositionX ?? 50,
coverImagePositionY: course.coverImagePositionY ?? 50,
status: course.status || 'published',
scheduledPublishAt: course.status === 'draft' ? course.scheduledPublishAt || null : null,
assets: (course.attachments || []).filter((attachment) => attachment.url && attachment.url !== '#').map(toAssetPayload),
lessons: course.lessons.map((lesson) => ({
id: /^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(lesson.id) ? lesson.id : undefined,

View File

@@ -943,6 +943,33 @@ a.m-row:active, button.m-row:active { background: var(--bg-3) }
.notification small { flex: none; color: var(--fg-3); font-size: 12px; white-space: nowrap }
.notification-empty .ph { width: 36px; height: 36px; color: var(--fg-3); margin-bottom: 8px }
.notification-empty h2 { font-size: 20px; margin-bottom: 6px }
/* ---------- two-factor authentication ---------- */
.twofa-section { margin-top: 28px; max-width: 760px }
.twofa-card { display: grid; gap: 14px }
.twofa-head { display: flex; gap: 12px; align-items: flex-start }
.twofa-icon { width: 38px; height: 38px; flex: none; border-radius: 50%; display: grid; place-items: center; background: var(--blue-soft); color: var(--blue) }
.twofa-setup { display: grid; grid-template-columns: 220px minmax(0, 1fr); gap: 20px; align-items: start }
.twofa-secret { display: block; padding: 8px 10px; border-radius: 8px; background: var(--bg-2); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; word-break: break-all; font-size: 13px; margin: 6px 0 14px }
.twofa-form { display: grid; gap: 10px; margin-top: 8px }
.twofa-code-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; margin: 12px 0 }
.twofa-code-grid code { padding: 8px 10px; border-radius: 8px; background: var(--bg-2); text-align: center; letter-spacing: .08em; font-size: 13px }
@media (max-width: 760px) {
.twofa-setup { grid-template-columns: 1fr }
.twofa-code-grid { grid-template-columns: 1fr }
}
/* ---------- bulk selection ---------- */
.check { width: 18px; height: 18px; border: 1.5px solid var(--fg-3); border-radius: 5px; display: inline-grid; place-items: center; color: var(--white); background: transparent; transition: background-color .15s, border-color .15s, opacity .15s }
.check[aria-checked="true"] { background: var(--blue); border-color: var(--blue) }
.check:disabled { opacity: .35 }
.check .ph { width: 12px; height: 12px }
.bulkbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; padding: 10px 14px; margin: -8px 0 16px; border-radius: 10px; background: var(--bg-2); font-size: 13px }
.bulkbar .sp { flex: 1 }
.impersonation-banner { position: fixed; z-index: 300; top: 12px; left: 50%; transform: translateX(-50%); display: flex; align-items: center; justify-content: center; gap: 14px; flex-wrap: wrap; width: max-content; max-width: calc(100vw - 24px); padding: 7px 8px 7px 16px; border-radius: 980px; background: var(--fg); color: var(--bg); box-shadow: var(--menu-shadow); font-size: 13px }
.impersonation-banner b { font-weight: 600 }
.impersonation-banner button { min-height: 28px; padding: 4px 12px; border-radius: 980px; background: var(--bg); color: var(--fg); font-size: 13px; font-weight: 600; white-space: nowrap }
@media (max-width: 760px) {
.reviews-layout { grid-template-columns: 1fr }
.review-average { font-size: 36px }

33
tests/auth.test.ts Normal file
View File

@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest';
import { createRawToken, hashToken } from '../server/src/auth/account-tokens';
import { hashPassword, verifyPassword } from '../server/src/auth/passwords';
describe('account tokens', () => {
it('produces unique URL-safe tokens', () => {
const first = createRawToken();
const second = createRawToken();
expect(first).not.toBe(second);
expect(first).toMatch(/^[A-Za-z0-9_-]+$/);
expect(first.length).toBeGreaterThan(30);
});
it('hashes deterministically without exposing the token', () => {
const token = 'example-token';
expect(hashToken(token)).toBe(hashToken(token));
expect(hashToken(token)).not.toBe(token);
expect(hashToken(token)).toMatch(/^[a-f0-9]{64}$/);
});
});
describe('password hashing', () => {
it('accepts the correct password and rejects others', async () => {
const hash = await hashPassword('Compor@123');
expect(hash).not.toContain('Compor@123');
await expect(verifyPassword('Compor@123', hash)).resolves.toBe(true);
await expect(verifyPassword('wrong-password', hash)).resolves.toBe(false);
});
it('rejects malformed hashes', async () => {
await expect(verifyPassword('Compor@123', 'not-a-hash')).resolves.toBe(false);
});
});

44
tests/format.test.ts Normal file
View File

@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest';
import { formatMinutes, initials, lessonDuration, plural, shortDate, totalDuration } from '../lib/format';
import { Course } from '../types';
const course = (duration: string): Course => ({
id: duration,
title: 'Curso',
category: 'Área',
thumbnail: '',
duration,
description: '',
lessons: [],
});
describe('formatting helpers', () => {
it('pluralizes counts', () => {
expect(plural(1, 'aula', 'aulas')).toBe('1 aula');
expect(plural(3, 'aula', 'aulas')).toBe('3 aulas');
});
it('formats minutes with and without hours', () => {
expect(formatMinutes(0)).toBe('0min');
expect(formatMinutes(45)).toBe('45min');
expect(formatMinutes(60)).toBe('1h');
expect(formatMinutes(125)).toBe('2h 05min');
});
it('builds initials and lesson durations', () => {
expect(initials('Ana Maria Silva')).toBe('AM');
expect(lessonDuration({ id: '1', title: 'Aula', duration: '—' } as never)).toBe('');
expect(lessonDuration({ id: '1', title: 'Aula', duration: '12min' } as never)).toBe('12min');
});
it('sums course durations', () => {
expect(totalDuration([course('1h 30min'), course('45min')])).toBe('2h 15min');
expect(totalDuration([])).toBe('');
});
it('formats short dates and rejects invalid values', () => {
expect(shortDate('2026-11-05T12:00:00Z')).toContain('5');
expect(shortDate('invalid')).toBe('');
expect(shortDate(null)).toBe('');
});
});

View File

@@ -60,6 +60,7 @@ export interface Course {
tips?: string[]; // Key takeaways / instructor tips
attachments?: Attachment[]; // Downloadable materials across entire course
status?: 'draft' | 'published';
scheduledPublishAt?: string | null;
lastActivity?: string;
}
@@ -77,6 +78,7 @@ export interface User {
name: string;
role: UserRole;
avatar?: string;
impersonatedBy?: string;
}
export interface Comment {