# Session: Monkchat II
>[color=#055b5c]**Autor:** Letícia Rodrigues da Silva
**Número:** 25
**Turma:** IndoD
[toc]
## Códigos Api
```javascript=
import db from './db.js';
import express from 'express'
import cors from 'cors'
import crypto from 'crypto-js'
const app = express();
app.use(cors());
app.use(express.json());
app.post('/login', async (req,resp) => {
const login = req.body;
const cryptoSenha = crypto.SHA256(login.senha).toString(crypto.enc.Base64);
let r = await db.tb_usuario.findOne({
where: {
ds_login: login.usuario,
ds_senha: cryptoSenha
}
});
if(r == null)
return resp.send({erro: 'Credenciais inválidas'})
resp.sendStatus(200);
});
app.post('/sala', async (req, resp) => {
try {
let salaParam = req.body;
let s = await db.tb_sala.findOne({ where: { nm_sala: salaParam.nome } });
if (s != null)
return resp.send({ erro: 'Sala já existe!' });
let r = await db.tb_sala.create({
nm_sala: salaParam.nome,
bt_ativo: salaParam.ativo
})
resp.send(r);
} catch (e) {
resp.send({ erro: 'Ocorreu um erro!'})
}
})
app.get('/sala', async (req, resp) => {
try {
let salas = await db.tb_sala.findAll();
resp.send(salas);
} catch (e) {
resp.send({ erro: 'Ocorreu um erro!'})
}
})
app.post('/usuario', async (req, resp) => {
try {
let usuParam = req.body;
let u = await db.tb_usuario.findOne({ where: { nm_usuario: usuParam.nome } });
if (u != null)
return resp.send({ erro: 'Usuário já existe!' });
let r = await db.tb_usuario.create({
nm_usuario: usuParam.nome,
ds_login: usuParam.login,
ds_senha: crypto.SHA256(usuParam.senha).toString(crypto.enc.Base64)
})
resp.send(r);
} catch (e) {
resp.send({ erro: 'Ocorreu um erro!'})
}
})
app.get('/usuario', async (req, resp) => {
try {
let usuarios = await db.tb_usuario.findAll();
resp.send(usuarios);
} catch (e) {
resp.send({ erro: 'Ocorreu um erro!'})
}
})
app.post('/chat', async (req, resp) => {
try {
let chat = req.body;
let sala = await db.tb_sala.findOne({ where: { nm_sala: chat.sala.nome } });
let usu = await db.tb_usuario.findOne({ where: { nm_usuario: chat.usuario.nome } })
if (usu == null)
return resp.send({ erro: 'Usuário não existe!' });
if (sala == null)
return resp.send({ erro: 'Sala não existe!' });
if (!chat.mensagem || chat.mensagem.replace(/\n/g, '') == '')
return resp.send({ erro: 'Mensagem é obrigatória!' });
let mensagem = {
id_sala: sala.id_sala,
id_usuario: usu.id_usuario,
ds_mensagem: chat.mensagem,
dt_mensagem: new Date()
}
let r = await db.tb_chat.create(mensagem);
resp.send(r);
} catch (e) {
resp.send('Deu erro');
console.log(e.toString());
}
});
app.get('/chat/:sala', async (req, resp) => {
try {
let sala = await db.tb_sala.findOne({ where: { nm_sala: req.params.sala } });
if (sala == null)
return resp.send({ erro: 'Sala não existe!' });
let mensagens = await
db.tb_chat.findAll({
where: {
id_sala: sala.id_sala
},
order: [['id_chat', 'desc']],
include: ['tb_usuario', 'tb_sala'],
});
resp.send(mensagens);
} catch (e) {
resp.send(e.toString())
}
})
app.listen(process.env.PORT,
x => console.log(`>> Server up at port ${process.env.PORT}`))
```
## Códigos cabecalho
```javascript=
import { Barra, ContainerCabecalho } from './styled'
import Cookies from 'js-cookie'
import { useHistory } from 'react-router'
export default function Cabecalho() {
const navigation = useHistory();
const logoff = () => {
Cookies.remove('usuario-logado');
navigation.push('/')
}
return (
<ContainerCabecalho>
<img src="/assets/images/logo-monkchat.png" alt="" />
<Barra />
<div className="titulo"> MonkChat </div>
<div onClick={logoff}> Sair</div>
</ContainerCabecalho>
)
}
```
## Códigos login
```javascript=
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import LoadingBar from 'react-top-loading-bar'
import { Container } from './styled'
import { ChatButton, ChatInput } from '../../components/outros/inputs'
import { useState, useRef } from 'react'
import {useHistory} from 'react-router-dom'
import cookie from 'js-cookie'
import Api from '../../service/api'
import Cookies from 'js-cookie'
const api = new Api();
export default function Login() {
const [usuario, setUsuario] = useState('');
const [senha, setSenha] = useState('');
const navigation = useHistory();
const loading = useRef(null);
const logar = async()=> {
loading.current.continuousStart();
let r = await api.login(usuario, senha);
if(r.erro) {
toast.error(`${r.erro}`)
} else {
Cookies.set('usuario-logado', true)
navigation.push('/chat')
}
}
return (
<Container>
<ToastContainer />
<LoadingBar color="red" ref={loading} />
<div className="box">
<div className="titulo">
<img src="/assets/images/logo-monkchat.png" alt="" />
<br />
MonkChat
</div>
</div>
<div className="login">
<div className="container-form">
<div className="form-row">
<div className="title">Faça seu Login</div>
</div>
<div className="form-row">
<div>
<div className="label">Login </div>
<ChatInput
value={usuario}
onChange={e => setUsuario(e.target.value)}
style={{ border: '1px solid gray', fontSize: '1.5em' }}
/>
</div>
<div>
<div className="label">Senha </div>
<ChatInput
value={senha}
onChange={e => setSenha(e.target.value)}
type="password"
style={{ border: '1px solid gray', fontSize: '1.5em' }}
/>
</div>
<div>
<ChatButton
onClick={logar}
style={{ fontSize: '1.2em'}}> Login </ChatButton>
</div>
</div>
</div>
</div>
</Container>
)
}
```
## Códigos service
```javascript=
import axios from 'axios'
const api = axios.create({
baseURL: 'http://localhost:3030'
})
export default class Api {
async listarMensagens(idSala) {
let r = await api.get(`/chat/${idSala}`);
return r.data;
}
async inserirMensagem(nomeSala, nomeUsuario, mensagem) {
let chat = {
sala: {
nome: nomeSala
},
usuario: {
nome: nomeUsuario
},
mensagem: mensagem
}
let r = await api.post(`/chat`, chat);
return r.data;
}
async inserirSala(sala) {
let r = await api.post(`/sala/`, { nome: sala });
return r.data;
}
async inserirUsuario(usuario) {
let r = await api.post(`/usuario/`, { nome: usuario });
return r.data;
}
async login(usuario, senha){
let r = await api.post('/login', {usuario, senha})
return r.data;
}
}
{"metaMigratedAt":"2023-06-16T09:13:41.425Z","metaMigratedFrom":"Content","title":"Session: Monkchat II","breaks":true,"contributors":"[{\"id\":\"f2f98191-1ff5-4afd-8e66-66ff77c4c5b1\",\"add\":8370,\"del\":0}]"}