Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[US18]: Fazer login na Central Administrativa #96

Merged
merged 21 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat: adicinado página avisos no login
  • Loading branch information
DanielRogs committed Dec 8, 2024
commit 55be6d4f339965addc6278e32c53902451b38aff
3 changes: 1 addition & 2 deletions apps/backend/src/controllers/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ const loginUser = async (req, res) => {
return res.status(400).send({ message: 'Preencha todos os campos para logar!'})

const user = await userService.findService({ email });
console.log(user);
if ( user.length == 0)
return res.status(404).send({ message: 'Usuário não encontrado!'});

Expand All @@ -53,7 +52,7 @@ const loginUser = async (req, res) => {
}

if (user[0].password != bcrypt.hashSync(password, salt))
return res.status(400).send({ message: 'Senha ou email inválido!'});
return res.status(403).send({ message: 'Senha ou email inválido!'});

const token = userService.generateToken(user);
return res.status(200).send({ message: 'Usuário encontrado!', case: 1, token });
Expand Down
44 changes: 8 additions & 36 deletions apps/backend/src/controllers/visita.controller.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,23 @@
import DisponibilidadeVisita from "../models/Visita.js";
import VisitaService from"../services/visita.service.js";


const criarDisponibilidade = async (req, res) => {
const createVisita = async (req, res) => {
try {
const { data, hora } = req.body;
const { date, startTime, endTime } = req.body;

if(!data || !hora){
return res.status(400).json({ message: "Os campos 'data' e 'hora' são obrigatórios."});
}
if(!date || !startTime || !endTime)
return res.status(400).json({ message: "Preencha todos os campos para criar a disponibilidade!"});

await VisitaService.criarAgendamento(data, hora);
const visita = await VisitaService.createService(req.body);

res.status(201).json({ message: "Disponibilidade criada com sucesso!" })
return res.status(201).send({ message: "Disponibilidade criada com sucesso!", visita })
} catch (err) {
res.status(500).json({ message: "Erro ao criar disponibilidade.", error: err.message });
}
};

const listarDisponibilidades = async (req, res) => {
try {
const disponibilidades = await DisponibilidadeVisita.find();
res.status(200).json(disponibilidades);
}catch (err) {
res.status(500).json({ message: "Erro ao listar disponibilidades.", error: err.message });
}
};

const deletarDisponibilidade = async (req, res) => {
try{
const { id } = req.params;

const disponibilidade = await DisponibilidadeVisita.findByIdAndDelete(id);
if (!disponibilidade){
return res.status(404).json({ message: "Disponibilidade não encontrada." });
}

res.status(200).json({ message: "Disponibilidade deletada com sucesso!"});
} catch (err){
res.status(500).json({ message: "Erro ao deletar disponibilidade.", error: err.message });
return res.status(500).send({ message: "Erro ao criar disponibilidade.", error: err.message });
}
};

export default {
criarDisponibilidade,
listarDisponibilidades,
deletarDisponibilidade
createVisita,
};


4 changes: 4 additions & 0 deletions apps/backend/src/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ const UserSchema = new mongoose.Schema({
password: {
type: String,
require: false,
},
sector: {
type: String,
require: true,
}
});

Expand Down
32 changes: 28 additions & 4 deletions apps/backend/src/models/Visita.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
import mongoose from "mongoose";

const DisponibilidadeVisitaSchema = new mongoose.Schema({
dataHora: {
const VisitaSchema = new mongoose.Schema({
date: {
type: Date,
require: true,
},
startTime: {
type: Date,
require: true,
},
endTime: {
type: Date,
require: true,
},
nameVisitor: {
type: String,
require: false,
},
emailVisitor: {
type: String,
require: false,
},
phoneVisitor: {
type: String,
require: false,
},
Institution: {
type: String,
require: false,
}
});

const DisponibilidadeVisita = mongoose.model("DisponibilidadeVisita", DisponibilidadeVisitaSchema);
const Visita = mongoose.model("Visita", VisitaSchema);

export default DisponibilidadeVisita;
export default Visita;
10 changes: 3 additions & 7 deletions apps/backend/src/routes/visita.route.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import express from 'express';
import VisitaController from '../controllers/visita.controller.js';
const visitaRouter = express.Router();

const router = express.Router();
visitaRouter.post('/createVisita', VisitaController.createVisita);

router.post('/disponibilidades', VisitaController.criarDisponibilidade);
router.get('/disponibilidades', VisitaController.listarDisponibilidades);
router.delete('/disponibilidades/:id', VisitaController.deletarDisponibilidade);


export default router;
export default visitaRouter;
1 change: 1 addition & 0 deletions apps/backend/src/scripts/seeds.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const UserSeed = async() => {
name: 'Sitio Admin',
email: 'sitioAdmin@familiadositio.com.br',
password: bcrypt.hashSync('@admin&Sitio+UnB', salt),
sector: 'System-Administrator',
});

await newUser.save();
Expand Down
19 changes: 1 addition & 18 deletions apps/backend/src/services/visita.service.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,8 @@
import Visita from '../models/Visita.js';

const createService = () => Schema.create();
const createService = (body) => Visita.create(body);

const criarAgendamento = async (data, hora) => {
const horaMinuto = hora.split(':');

const dataHora = new Date(data);
dataHora.setHours(horaMinuto[0], horaMinuto[1]);

const visitas = await Visita.find({dataHora: dataHora});
if(visitas.length != 0){
throw new Error('A data e horário marcados já estão ocupados.');
}

const novaDisponibilidade = new Visita({ dataHora: dataHora });
await novaDisponibilidade.save();
};
//validar campos vaziosd
//validar se data e horário estão ocupados
export default {
createService,
criarAgendamento,
};

1 change: 0 additions & 1 deletion apps/frontendAdmin/src/components/Header/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ const Header = () => {
if (token) {
try {
const decodedToken = jwtDecode(token);
console.log("DECODIFICAÇÃO:", decodedToken);
username = decodedToken.name || "Usuário";
} catch (err) {
console.error("Erro ao decodificar o token:", err);
Expand Down
42 changes: 38 additions & 4 deletions apps/frontendAdmin/src/pages/(public)/LoginPage/index.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { ConteudoGeral, LoginCard, Input, Button, ParteSuperior } from "./styled";
import { ConteudoGeral, LoginCard, Input, Button, ParteSuperior, Warning, Espaco } from "./styled";
import { loginUser } from "@familiadositio/core";
import { ROUTES } from "../../../routes/RoutesConstants";

Expand All @@ -11,6 +11,7 @@ const LoginPage = () => {

const [email, setEmail] = useState('');
const [password, setPassord] = useState('');
const [warning, setWarning] = useState(0);

// FUNÇÕES PARA FAZER REQUISIÇÃO À API DE LOGIN:
const handleChangeEmail = (e) => {
Expand All @@ -23,10 +24,34 @@ const LoginPage = () => {
try {
const response = await loginUser(email, password);
localStorage.setItem("authToken", response.data.token);
navigate(ROUTES.HOME);
if(response.data.case === 1) {
setEmail('');
setPassord('');
navigate(ROUTES.HOME);
}
else
console.log("EM PRODUÇÃO!");
} catch (err) {
console.log(err);
alert("Falha ao fazer login! Verifique suas credenciais.");
if(err.response){
if(err.response.status === 404){
setWarning(1);
setTimeout(() => {
setWarning(0);
}, 2000);
}
else if(err.response.status === 403){
setWarning(2);
setTimeout(() => {
setWarning(0);
}, 2000);
}
}
else {
setWarning(3);
setTimeout(() => {
setWarning(0);
}, 2000);
}
}
}

Expand All @@ -40,6 +65,15 @@ const LoginPage = () => {
</ParteSuperior>
<Input type="email" placeholder="Email" onChange={handleChangeEmail}/>
<Input type="password" placeholder="Senha" onChange={handleChangePassword}/>
{warning === 1? (
<Warning><span>Usuário não encontrado!</span></Warning>
) : warning === 2? (
<Warning><span>Email ou senha incorreto!</span></Warning>
) : warning === 3? (
<Warning><span>Erro inesperado!</span></Warning>
) : (
<Espaco />
)}
<Button onClick={login}>Entrar</Button>
</LoginCard>
</ConteudoGeral>
Expand Down
17 changes: 17 additions & 0 deletions apps/frontendAdmin/src/pages/(public)/LoginPage/styled.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,21 @@ export const Button = styled.button`
&:hover {
background-color: darkgreen;
}
`;

export const Warning = styled.div`
height: 20px;
width: auto;
font-size: 12px;
text-align: center;
color: red;
font-family: 'Myriad Pro', sans-serif;

span{
margin: 0px;
}
`;

export const Espaco = styled.div`
height: 20px;
`;
3 changes: 2 additions & 1 deletion packages/core/src/services/index.js
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { loginUser, createUser } from "./userService.js";
export { loginUser, createUser } from "./userService.js";
export { createVisita } from "./visitaService.js";
11 changes: 5 additions & 6 deletions packages/core/src/services/userService.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import axios from 'axios';
// import Cookies from 'js-cookie';

const baseURL = 'http://localhost:3002';

Expand All @@ -13,11 +12,11 @@ export function createUser(name, email, password){
const response = axios.post(
`${baseURL}/user/createUser`,
body,
// {
// headers: {
// Authorization: `Bearer ${Cookies.get("token")}`,
// }
// }
{
headers: {
Authorization: `Bearer ${localStorage.get("authToken")}`,
}
}
);

return response;
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/services/visitaService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import axios from "axios";

export function createVisita() {
return 0;
};