338338 text-shadow : 0 0 8px # d4af37 ;
339339 z-index : 2000 ;
340340 }
341+
342+ /* Info do usuário */
343+ .user-info {
344+ position : absolute;
345+ top : 20px ;
346+ right : 20px ;
347+ background : rgba (212 , 175 , 55 , 0.1 );
348+ border : 1px solid rgba (212 , 175 , 55 , 0.3 );
349+ border-radius : 10px ;
350+ padding : 10px 15px ;
351+ font-size : 0.9rem ;
352+ color : # d4af37 ;
353+ }
341354 </ style >
342355</ head >
343356
344357< body >
345358
359+ <!-- Informação do usuário logado -->
360+ < div class ="user-info " id ="userInfo ">
361+ < i class ="fas fa-user "> </ i > Carregando...
362+ </ div >
363+
346364< div class ="container ">
347365 < header >
348366 < h1 > 🌍 Painel de Autoridade — Terra Dourada</ h1 >
@@ -445,11 +463,48 @@ <h3 id="confirmationElectionName" style="color: #d4af37; margin: 10px 0 20px;"><
445463< script >
446464// Banco de dados
447465const dbEleicoes = new PouchDB ( 'terra_dourada_eleicoes' ) ;
466+ const dbConfig = new PouchDB ( 'terra_dourada_config' ) ;
448467
449468// Variáveis
450469let photoBase64 = null ;
451470let electionData = null ;
452471let tipoEleicao = 'online' ; // Padrão: online
472+ let usuarioLogado = null ; // ⭐⭐ NOVA VARIÁVEL: usuário atual
473+
474+ // ⭐⭐ FUNÇÃO NOVA: Identificar usuário logado
475+ async function identificarUsuarioLogado ( ) {
476+ try {
477+ console . log ( '🔍 Identificando usuário logado...' ) ;
478+
479+ // Primeiro tenta do localStorage (mais rápido)
480+ const usuarioData = JSON . parse ( localStorage . getItem ( "usuario_data" ) || '{}' ) ;
481+ if ( usuarioData . email ) {
482+ console . log ( '✅ Usuário do localStorage:' , usuarioData . email ) ;
483+ return usuarioData ;
484+ }
485+
486+ // Se não tiver no localStorage, tenta do PouchDB
487+ const conta = await dbConfig . get ( 'dono_da_sala' ) ;
488+ console . log ( '✅ Usuário do PouchDB:' , conta . email ) ;
489+ return conta ;
490+
491+ } catch ( error ) {
492+ console . error ( '❌ Erro ao identificar usuário:' , error ) ;
493+
494+ // Se não conseguir identificar, redireciona para login
495+ alert ( 'Sessão expirada. Faça login novamente.' ) ;
496+ window . location . href = 'login.html' ;
497+ return null ;
498+ }
499+ }
500+
501+ // ⭐⭐ FUNÇÃO NOVA: Atualizar info do usuário na tela
502+ function atualizarInfoUsuario ( usuario ) {
503+ const userInfo = document . getElementById ( 'userInfo' ) ;
504+ if ( usuario && userInfo ) {
505+ userInfo . innerHTML = `<i class="fas fa-user"></i> ${ usuario . name || usuario . email } (${ usuario . provider } )` ;
506+ }
507+ }
453508
454509// --- CONTROLE DE ABAS ---
455510function showTab ( tab ) {
@@ -478,23 +533,38 @@ <h3 id="confirmationElectionName" style="color: #d4af37; margin: 10px 0 20px;"><
478533 element . classList . add ( 'selecionado' ) ;
479534}
480535
481- // --- CARREGAR ELEIÇÕES ---
536+ // ⭐⭐ MODIFICADA: Carregar apenas eleições do usuário logado
482537async function carregarEleicoes ( ) {
483538 try {
539+ if ( ! usuarioLogado ) {
540+ console . error ( '❌ Usuário não identificado' ) ;
541+ return ;
542+ }
543+
484544 const res = await dbEleicoes . allDocs ( { include_docs : true } ) ;
485545 const cont = document . getElementById ( 'eleicoes-list' ) ;
486546
487- if ( res . rows . length === 0 ) {
547+ // ⭐⭐ FILTRAR apenas eleições do usuário logado
548+ const eleicoesDoUsuario = res . rows . filter ( row =>
549+ row . doc . ownerId === usuarioLogado . email || row . doc . ownerEmail === usuarioLogado . email
550+ ) ;
551+
552+ console . log ( `📊 Eleições encontradas: ${ res . rows . length } , Do usuário: ${ eleicoesDoUsuario . length } ` ) ;
553+
554+ if ( eleicoesDoUsuario . length === 0 ) {
488555 cont . innerHTML = `
489556 <div class="empty-state">
490557 <h3>Nenhuma eleição cadastrada</h3>
491558 <p>Clique em "Nova Eleição" para criar sua primeira eleição</p>
559+ <p style="margin-top: 10px; font-size: 0.8rem; color: #666;">
560+ Usuário: ${ usuarioLogado . email }
561+ </p>
492562 </div>
493563 ` ;
494564 return ;
495565 }
496566
497- cont . innerHTML = res . rows . map ( r => {
567+ cont . innerHTML = eleicoesDoUsuario . map ( r => {
498568 const eleicao = r . doc ;
499569 const status = eleicao . status === 'ativa' ? 'status-ativa' : 'status-inativa' ;
500570 const statusText = eleicao . status === 'ativa' ? 'Ativa' : 'Inativa' ;
@@ -589,8 +659,14 @@ <h3>${eleicao.name}</h3>
589659 electionData = null ;
590660}
591661
592- // --- CONFIRMAR ELEIÇÃO ---
662+ // ⭐⭐ MODIFICADA: Vincular eleição ao usuário logado
593663async function confirmarEleicao ( ) {
664+ if ( ! usuarioLogado ) {
665+ alert ( 'Erro: Usuário não identificado. Faça login novamente.' ) ;
666+ window . location . href = 'login.html' ;
667+ return ;
668+ }
669+
594670 document . getElementById ( "processando" ) . style . display = "flex" ;
595671
596672 try {
@@ -601,7 +677,7 @@ <h3>${eleicao.name}</h3>
601677 // Criar ID único
602678 const electionId = `election_${ Date . now ( ) } ` ;
603679
604- // Criar documento da eleição
680+ // ⭐⭐ CRIAR documento da eleição VINCULADO ao usuário
605681 const election = {
606682 _id : electionId ,
607683 name : electionData . name ,
@@ -612,13 +688,18 @@ <h3>${eleicao.name}</h3>
612688 screenshot_hash : hashPrint ,
613689 status : 'ativa' ,
614690 createdAt : new Date ( ) . toISOString ( ) ,
615- candidateCount : 0
691+ candidateCount : 0 ,
692+ // ⭐⭐ CAMPOS NOVOS: Vincular ao usuário
693+ ownerId : usuarioLogado . email , // ID único do usuário
694+ ownerEmail : usuarioLogado . email ,
695+ ownerName : usuarioLogado . name ,
696+ ownerProvider : usuarioLogado . provider
616697 } ;
617698
618699 // Salvar no banco de dados
619700 await dbEleicoes . put ( election ) ;
620701
621- console . log ( "💾 Eleição criada:" , election ) ;
702+ console . log ( "💾 Eleição criada para usuário:" , usuarioLogado . email , election ) ;
622703
623704 document . getElementById ( "processando" ) . style . display = "none" ;
624705
@@ -666,9 +747,20 @@ <h3>${eleicao.name}</h3>
666747 return canvas . toDataURL ( "image/png" ) ;
667748}
668749
669- // --- INICIALIZAÇÃO ---
670- document . addEventListener ( "DOMContentLoaded" , ( ) => {
671- carregarEleicoes ( ) ;
750+ // ⭐⭐ MODIFICADA: Inicialização com identificação do usuário
751+ document . addEventListener ( "DOMContentLoaded" , async ( ) => {
752+ console . log ( '🚀 Iniciando Painel de Autoridade...' ) ;
753+
754+ // Identificar usuário logado
755+ usuarioLogado = await identificarUsuarioLogado ( ) ;
756+
757+ if ( usuarioLogado ) {
758+ console . log ( '✅ Usuário identificado:' , usuarioLogado . email ) ;
759+ atualizarInfoUsuario ( usuarioLogado ) ;
760+ carregarEleicoes ( ) ;
761+ } else {
762+ console . error ( '❌ Não foi possível identificar o usuário' ) ;
763+ }
672764} ) ;
673765</ script >
674766</ body >
0 commit comments