Skip to content

Commit

Permalink
mudanças ai
Browse files Browse the repository at this point in the history
  • Loading branch information
AnthonyHeimlich committed Sep 10, 2024
1 parent cdb2dfd commit 3176ba9
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 94 deletions.
4 changes: 2 additions & 2 deletions backend/middlewares/authMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ const authMiddleware = async (req, res, next) => {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded.userId);

if (!user || !user.pagante) {
return res.status(403).json({ message: 'Access denied' });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}

req.user = user;
Expand Down
14 changes: 13 additions & 1 deletion backend/routes/authRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ const router = express.Router();
const User = require('../models/User');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const authMiddleware = require('../middlewares/authMiddleware'); // Use require para importar middleware

const secret = process.env.JWT_SECRET;

router.post('/register', async (req, res) => {
try {
const { username, email, password, pagante } = req.body;

const newUser = new User({ username, email, password, pagante });
const hashedPassword = await bcrypt.hash(password, 10); // Hash da senha
const newUser = new User({ username, email, password: hashedPassword, pagante });
await newUser.save();

res.status(201).json({ message: 'User registered successfully' });
Expand Down Expand Up @@ -42,4 +45,13 @@ router.post('/login', async (req, res) => {
}
});

router.get('/profile', authMiddleware, async (req, res) => {
try {
const user = req.user;
res.status(200).json({ username: user.username, pagante: user.pagante });
} catch (error) {
res.status(500).json({ message: 'Erro no servidor', error: error.message });
}
});

module.exports = router;
3 changes: 2 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ function App() {
<div className="container">
<Routes>
<Route path='/' element={[<Navbar/>,<Home/>,<UR/>,<Contato/>,<Footer/>]}/>
<Route path='/perfil' element={[<Navbar/>,<NU/>]}/>
<Route path='/perfil' element={[<Navbar/>,<Perfil/>]}/>
<Route path='/compras' element={[<Navbar/>,<NU/>]}/>
<Route path='/login' element={[<Navbar/>,<Login/>]}/>
<Route path='/cadastro' element={[<Navbar/>,<Cadastro/>]}/>
<Route path="/recipes/:id" element={[<Navbar/>,<ReceitaDetalhe/>]} />
Expand Down
140 changes: 69 additions & 71 deletions src/components/Navbar.js
Original file line number Diff line number Diff line change
@@ -1,125 +1,123 @@
import styles from './Navbar.module.css'
import { FaBars, FaTimes } from 'react-icons/fa'
import {useEffect, useRef, useState} from "react"
import {useTranslation} from "react-i18next"
import {Link} from 'react-scroll'
import {Link as LinkRouter} from 'react-router-dom'
import {BiMenuAltRight} from "react-icons/bi";
import {AiOutlineClose} from "react-icons/ai";
import brasil from "../assets/img/brasil2.png"
import uk from "../assets/img/uk2.png"
import logo from "../assets/img/solislogo.png"
import styles from './Navbar.module.css';
import { FaBars, FaTimes } from 'react-icons/fa';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-scroll';
import { Link as LinkRouter, useNavigate } from 'react-router-dom';
import { BiMenuAltRight } from 'react-icons/bi';
import { AiOutlineClose } from 'react-icons/ai';
import brasil from '../assets/img/brasil2.png';
import uk from '../assets/img/uk2.png';
import logo from '../assets/img/solislogo.png';
import { checkUserLoggedIn } from '../utils/auth';


function Navbar(){
function Navbar() {
const [t, i18n] = useTranslation("global");

const currentUrl = window.location.pathname;
const isHome = currentUrl === '/';

const handleChangeLanguage = (lang: string) =>{
const navigate = useNavigate();

const handleProfileClick = async () => {
const loggedIn = await checkUserLoggedIn();
if (loggedIn) {
navigate('/perfil');
} else {
navigate('/login');
}
};

const handleChangeLanguage = (lang) => {
i18n.changeLanguage(lang);
setOpenLanguages(false);
};

const [click, setClick] = useState(false)
const [click, setClick] = useState(false);
const handleClick = () => {
if (click){
body.style.overflowY = 'auto';
} else{
body.style.overflowY = 'hidden';
}
setClick(!click)
}
setClick(!click);
document.body.style.overflowY = click ? 'auto' : 'hidden';
};

const closeMenu = () => {
if (click){
body.style.overflowY = 'auto';
} else{
body.style.overflowY = 'hidden';
}
setClick(false)
}
setClick(false);
document.body.style.overflowY = 'auto';
};

const [openLanguages, setOpenLanguages] = useState(false)
let languagesRef = useRef();
useEffect(() =>{
let handler = (e)=>{
if(!languagesRef.current.contains(e.target)){
const [openLanguages, setOpenLanguages] = useState(false);
const languagesRef = useRef(null);

useEffect(() => {
const handler = (e) => {
if (languagesRef.current && !languagesRef.current.contains(e.target)) {
setOpenLanguages(false);
}
};

document.addEventListener("mousedown", handler)
});

var body = document.getElementsByTagName('body')[0];
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
}, []);

return (
<div className={styles.header}>
<nav className={styles.navbar}>
<div className={styles.hamburger} onClick={handleClick}>
{click ? (<FaTimes size={40} style={{display:"none" }} />) : (<BiMenuAltRight size={40} style={{ color: '#E4C576'}}/>)}
{click ? (<FaTimes size={40} style={{ color: '#E4C576' }} />) : (<BiMenuAltRight size={40} style={{ color: '#E4C576' }} />)}
</div>
<div className={styles.container}>
<a href="/" className={styles.logo}>
<img src={logo} alt='logo'/>
<img src={logo} alt='logo' />
</a>
</div>
<ul className={styles.navMenu}>
<li className={styles.navItem}>
<LinkRouter to ="/">{t("navBar.home")}</LinkRouter>
<LinkRouter to="/">{t("navBar.home")}</LinkRouter>
</li>
{isHome && <li className={styles.navItem}>
<Link to ="UR" spy={true} smooth={true} offset={0} duration={1000}>{t("navBar.UR")}</Link>
{isHome && <li className={styles.navItem}>
<Link to="UR" spy={true} smooth={true} offset={0} duration={1000}>{t("navBar.UR")}</Link>
</li>}
{isHome && <li className={styles.navItem}>
<Link to ="Contato" spy={true} smooth={true} offset={0} duration={1000}>{t("navBar.Contato")}</Link>
{isHome && <li className={styles.navItem}>
<Link to="Contato" spy={true} smooth={true} offset={0} duration={1000}>{t("navBar.Contato")}</Link>
</li>}
{isHome && <li className={styles.navItem}>
<LinkRouter to ="/perfil">{t("navBar.perfil")}</LinkRouter>
{isHome && <li className={styles.navItem} onClick={handleProfileClick}>
<Link onClick={handleProfileClick} to="" spy={true} smooth={true} offset={0} duration={1000}>{t("navBar.perfil")}</Link>
</li>}

<div className={styles.dropdown} ref={languagesRef} >
<div className={styles.select} onClick={() => setOpenLanguages((prev) => !prev) }>
<div className={styles.dropdown} ref={languagesRef}>
<div className={styles.select} onClick={() => setOpenLanguages((prev) => !prev)}>
<span className={styles.selected}>{t("navBar.language")}</span>
<div className={styles.caret}/>
<div className={styles.caret} />
</div>
{
openLanguages && <ul className={styles.menu}>
<li onClick={() => handleChangeLanguage("pt")}>Português</li>
<li onClick={() => handleChangeLanguage("en")}>English</li>
</ul>
}
{openLanguages && <ul className={styles.menu}>
<li onClick={() => handleChangeLanguage("pt")}>Português</li>
<li onClick={() => handleChangeLanguage("en")}>English</li>
</ul>}
</div>
</ul>



<ul className={click ? "sideNavMenu active" : "sideNavMenu"}>
<div className='hamburger' onClick={handleClick}>
{click ? (<AiOutlineClose size={25} style={{ color: '#E4C576', right:"15", top:"33", position:"absolute"}} />) : (<FaBars size={20} style={{ display:"none"}} />)}
{click ? (<AiOutlineClose size={25} style={{ color: '#E4C576', right: "15", top: "33", position: "absolute" }} />) : (<FaBars size={20} style={{ display: "none" }} />)}
</div>
<div className={styles.languageButtonContainer}>
<img src={brasil} className={styles.languageButton} onClick={() => handleChangeLanguage("pt")}/>
<img src={uk} className={styles.languageButton} onClick={() => handleChangeLanguage("en")}/>
<img src={brasil} className={styles.languageButton} onClick={() => handleChangeLanguage("pt")} />
<img src={uk} className={styles.languageButton} onClick={() => handleChangeLanguage("en")} />
</div>
<li className={styles.navItem}>
<LinkRouter to ="/" spy={true} smooth={true} offset={0} duration={1000} onClick={closeMenu}>{t("navBar.home")}</LinkRouter>
<LinkRouter to="/" onClick={closeMenu}>{t("navBar.home")}</LinkRouter>
</li>
{isHome && <li className={styles.navItem}>
<Link to ="UR" spy={true} smooth={true} offset={0} duration={1000} onClick={closeMenu}>{t("navBar.UR")}</Link>
{isHome && <li className={styles.navItem}>
<Link to="UR" spy={true} smooth={true} offset={0} duration={1000} onClick={closeMenu}>{t("navBar.UR")}</Link>
</li>}
{isHome && <li className={styles.navItem}>
<Link to ="Contato" spy={true} smooth={true} offset={0} duration={1000} onClick={closeMenu}>{t("navBar.Contato")}</Link>
{isHome && <li className={styles.navItem}>
<Link to="Contato" spy={true} smooth={true} offset={0} duration={1000} onClick={closeMenu}>{t("navBar.Contato")}</Link>
</li>}
{isHome && <li className={styles.navItem}>
<LinkRouter to ="/perfil" spy={true} smooth={true} offset={0} duration={1000} onClick={closeMenu}>{t("navBar.perfil")}</LinkRouter>
{isHome && <li className={styles.navItem} onClick={handleProfileClick}>
<span className={styles.navLink}>{t("navBar.perfil")}</span>
</li>}
</ul>
</nav>
</div>
)
);
}

export default Navbar
export default Navbar;
44 changes: 25 additions & 19 deletions src/components/Perfil.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
import styles from './Perfil.module.css'
import {useTranslation} from "react-i18next"
import {Link} from 'react-scroll'
import other from '../assets/img/other.png'
import gray from "../assets/img/gray.png"
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faAngleDown} from "@fortawesome/free-solid-svg-icons";
import {Link as LinkRouter} from "react-router-dom";
import React, { useEffect, useState } from 'react';
import { fetchUserProfile } from '../utils/auth';

function Perfil(){
const [t, i18n] = useTranslation("global");
const UserProfile = () => {
const [user, setUser] = useState(null);

useEffect(() => {
const getUserProfile = async () => {
const profile = await fetchUserProfile();
if (profile) {
setUser(profile);
}
};

getUserProfile();
}, []);

if (!user) return <p>Loading...</p>;

return (
<section id='Perfil' className={styles.perfil}>
<img className={styles.icon} src={other} alt="other"/>
<h1 className={styles.pageTitle} style={{cursor:"auto"}}>{t("Perfil.title")}</h1>
<div className={styles.container}>
</div>
</section>
)
}
<div>
<h1>Profile</h1>
<p>Welcome, {user.username}!</p>
<p>{user.pagante ? 'Plano Pagante' : 'Plano Gratuito'}</p>
</div>
);
};

export default Perfil
export default UserProfile;
48 changes: 48 additions & 0 deletions src/utils/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
export const checkUserLoggedIn = async () => {
try {
const response = await fetch('/api/auth/profile', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`, // Adicione o token ao cabeçalho
},
});

if (!response.ok) {
if (response.status === 401) {
// Token não fornecido ou inválido
return false;
} else {
throw new Error(`HTTP error! status: ${response.status}`);
}
}

const data = await response.json();
return data ? true : false; // Verifique se o perfil foi retornado
} catch (error) {
console.error('Error checking login status:', error);
return false;
}
};

export const fetchUserProfile = async () => {
try {
const response = await fetch('/api/auth/profile', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`, // Adicione o token ao cabeçalho
},
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching user profile:', error);
return null;
}
};

0 comments on commit 3176ba9

Please sign in to comment.