Skip to content

Commit

Permalink
Merge pull request #141 from ES2-UFPI/gisele#118
Browse files Browse the repository at this point in the history
Desenvolvendo issue #118
  • Loading branch information
basilioarth authored Jul 12, 2021
2 parents 58edaa5 + a6dcb15 commit f91e10c
Show file tree
Hide file tree
Showing 13 changed files with 91 additions and 37 deletions.
14 changes: 9 additions & 5 deletions backend/src/controllers/ClientController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@ interface ClientInterface{
password?:string;
phone?:string;
professional_id?:string;
id:string;
avatar?: number;
}

class ClientController {

async create(request: Request, response: Response): Promise<Response> {
try {
const {name,phone,email,password} = request.body;
const {name,phone,email,password, avatar} = request.body;

const clientService = new UserService();

await clientService.createUser({name,phone,type:0,email,password})
await clientService.createUser({name,phone,type:0,email,password, avatar})

return response.status(200).json({ message:"Cliente criado com sucesso!"});
} catch (error) {
Expand All @@ -30,11 +30,15 @@ class ClientController {

async update(request: Request, response: Response){
try{
const {name,phone,email,password,professional_id,id} = request.body as ClientInterface;
const user = request.app.get('user');

if(!user?.id) return response.status(400).json({ erro: 'Usuário não autenticado' });

const {name,phone,email,password,professional_id} = request.body as ClientInterface;

const clientService = new ClientService();

await clientService.update({name,phone,email,password,professional_id,id})
await clientService.update({name,phone,email,password,professional_id,id: user.id})

return response.status(200).json({ message:"Cliente atualizado com sucesso!"});

Expand Down
27 changes: 23 additions & 4 deletions backend/src/controllers/EmotionalRecordController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ class EmotionalReactionController {

async index(request: Request, response: Response): Promise<Response> {
try {
const { id } = request.params;
const user = request.app.get('user');

if(!user?.id) return response.status(400).json({ erro: 'Usuário não autenticado' });

const emotionalReactionService = new EmotionalReactionService();

const emotionalReactions = await emotionalReactionService.listByUser(id);
const emotionalReactions = await emotionalReactionService.listByUser(user?.id);

return response.json(emotionalReactions)

Expand All @@ -22,6 +24,11 @@ class EmotionalReactionController {

async getById(request: Request, response: Response): Promise<Response> {
try {

const user = request.app.get('user');

if(!user?.id) return response.status(400).json({ erro: 'Usuário não autenticado' });

const { id } = request.params;

const emotionalReactionService = new EmotionalReactionService();
Expand All @@ -37,6 +44,11 @@ class EmotionalReactionController {

async destroy(request: Request, response: Response): Promise<Response> {
try {

const user = request.app.get('user');

if(!user?.id) return response.status(400).json({ erro: 'Usuário não autenticado' });

const { id } = request.params;

const emotionalReactionService = new EmotionalReactionService();
Expand All @@ -53,11 +65,14 @@ class EmotionalReactionController {

async create(request: Request, response: Response): Promise<Response> {
try {
const client_id = request.params['id'];

const user = request.app.get('user');

if(!user?.id) return response.status(400).json({ erro: 'Usuário não autenticado' });

const emotionalReactionService = new EmotionalReactionService();

const id = await emotionalReactionService.create(client_id);
const id = await emotionalReactionService.create(user?.id);

return response.status(200).json({ id })
} catch (error) {
Expand All @@ -67,6 +82,10 @@ class EmotionalReactionController {

async update(request: Request, response: Response): Promise<Response> {
try {
const user = request.app.get('user');

if(!user?.id) return response.status(400).json({ erro: 'Usuário não autenticado' });

const reaction_id = request.params['id'];

const body: EmotionalReaction = request.body;
Expand Down
19 changes: 13 additions & 6 deletions backend/src/controllers/ProfessionalController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ class ProfessionalController {

async getClients(request: Request, response: Response) {
try {
const { id } = request.params;

const user = request.app.get('user');

if(!user?.id) return response.status(400).json({ erro: 'Usuário não autenticado' });

const professionalService = new ProfessionalService();

const clients = await professionalService.getClients(id);
const clients = await professionalService.getClients(user?.id);

return response.status(200).json({clients});
} catch(error) {
Expand All @@ -20,11 +23,11 @@ class ProfessionalController {

async create(request: Request, response: Response): Promise<Response> {
try {
const {name,crm_crp,speciality,email,password} = request.body;
const {name,crm_crp,speciality,email,password, avatar} = request.body;

const professionalService = new UserService();

await professionalService.createUser({name,crm_crp,speciality,type:1,email,password})
await professionalService.createUser({name,crm_crp,speciality,type:1,email,password, avatar})

return response.status(200).json({ message:"Profissional criado com sucesso!"});
} catch (error) {
Expand All @@ -34,11 +37,15 @@ class ProfessionalController {

async update(request: Request, response: Response){
try{
const {name,email,password,crm_crp,speciality,id,association_code} = request.body;
const user = request.app.get('user');

if(!user?.id) return response.status(400).json({ erro: 'Usuário não autenticado' });

const {name,email,password,crm_crp,speciality,association_code} = request.body;

const professionalService = new ProfessionalService();

await professionalService.update({name,crm_crp,speciality,email,password,association_code,id})
await professionalService.update({name,crm_crp,speciality,email,password,association_code,id: user?.id})

return response.status(200).json({ message:"Profissional atualizado com sucesso!"});

Expand Down
7 changes: 5 additions & 2 deletions backend/src/controllers/UserController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ class UserController {

async getUserById(request: Request, response: Response) {
try {
const { id } = request.params;
const userCtx = request.app.get('user');

if(!userCtx?.id) return response.status(400).json({ erro: 'Usuário não autenticado' });

const userService = new UserService();

const user = await userService.getUser(id);
const user = await userService.getUser(userCtx?.id);

return response.status(200).json({ user });
} catch (error) {
Expand Down
8 changes: 4 additions & 4 deletions backend/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,19 @@ const userController = new UserController();

routes.post("/professionals",professionalController.create);
routes.put("/professionals",professionalController.update);
routes.get("/professionals/:id/clients", professionalController.getClients);
routes.get("/professionals/clients", professionalController.getClients);

routes.post("/clients", clientController.create);
routes.put("/clients", clientController.update);
routes.get("/clients/:id/reactions", emotionalReactionController.index);
routes.post("/clients/:id/reactions", emotionalReactionController.create);
routes.get("/clients/reactions", emotionalReactionController.index);
routes.post("/clients/reactions", emotionalReactionController.create);

routes.get("/reactions/:id", emotionalReactionController.getById);
routes.put("/reactions/:id", emotionalReactionController.update);
routes.delete("/reactions/:id", emotionalReactionController.destroy);

routes.post("/users/authentication", userController.login);
routes.get("/users/:id", userController.getUserById);
routes.get("/users", userController.getUserById);



Expand Down
29 changes: 26 additions & 3 deletions backend/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,39 @@
import express from 'express';
import cors from 'cors';
import {routes} from "./routes";
import { routes } from "./routes";
import * as jsonwebtoken from 'jsonwebtoken';
require('dotenv/config');
import './database';

const app = express();
const app = express();

app.use(cors({
origin: '*',
credentials: false
}))
app.use(express.json());

app.use(async (req, res, next) => {

if (req.url === '/users/authentication') return next();
if (req.url === '/professionals' && req.method === 'POST') return next();
if (req.url === '/clients' && req.method === 'POST') return next();

const accessToken = req.headers['authorization'];

try {
if (accessToken) {
const user = await jsonwebtoken.verify(accessToken, process.env.JWT_SECRET || '');
app.set('user', user);
}
} catch (err) {
// res.status(500).json({ error: 'Token de acesso inválido' })
}
next();
})

app.use(routes);

app.listen(3333,()=>console.log("Server Started!"));
console.log(jsonwebtoken.sign({ id: '1' }, process.env.JWT_SECRET || ''))

app.listen(3333, () => console.log("Server Started!"));
9 changes: 5 additions & 4 deletions frontend/src/services/api.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import axios from "axios";
import { store } from '../store';
import { IP } from '../../evironment';

const api = axios.create({
baseURL: `http://192.168.0.114:3333/`,
headers:{
'accept': 'application/json',
'Access-Control-Allow-Origin': '*',
headers: {
'Access-Control-Allow-Origin': '*',
accept: 'application/json',
Authorization: store.getState().auth.accessToken,
}

});

export default api;
1 change: 0 additions & 1 deletion frontend/src/store/reducers/auth/actions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
interface Tokens {
accessToken: string
refreshToken: string
}

export const SetTokens = (tokens: Tokens) => {
Expand Down
4 changes: 1 addition & 3 deletions frontend/src/store/reducers/auth/reducer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const INITIAL_STATE = {
accessToken: '',
refreshToken: ''
accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJpYXQiOjE2MjU5NTY5OTJ9.1y3VR6CCAYNLoCIoKb_JOxWi7TaPON4o7bDqYUMGem0'
};

const auth = (state = INITIAL_STATE, action: any) => {
Expand All @@ -10,7 +9,6 @@ const auth = (state = INITIAL_STATE, action: any) => {
return {
...state,
accessToken: action.payload.auth.accessToken || "",
refreshToken: action.payload.auth.refreshToken || ""
};
default:
return state;
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/views/ClientList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const ClientList = (props: any) => {
try {
setLoading(true);

const response = await api.get(`professionals/${professional_id}/clients`);
const response = await api.get(`professionals/clients`);
setClients(response.data.clients);
console.log(response)
setLoading(false);
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/views/RecordsList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default function RecordsList() {

try {
setLoading(true)
const reaponse = await api.get(`/clients/${client_id}/reactions`);
const reaponse = await api.get(`clients/reactions`);

const data = reaponse.data as [any];

Expand Down Expand Up @@ -70,7 +70,7 @@ export default function RecordsList() {

async function handleDelete(){

await api.delete(`/reactions/${idCurrent}`)
await api.delete(`reactions/${idCurrent}`)
.then(()=>{
const filteredRecord = records?.filter((record) => record.id != idCurrent );
setRecords(filteredRecord);
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/views/Registration/views/StepZero/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const RegistrationStepZero = (props: any) => {

const createEmotionalReaction = (): void => {
setLoading(true);
api.post(`clients/${'1'}/reactions`)
api.post(`clients/reactions`)
.then((res: AxiosResponse) => {
const id = res.data['id'];

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/views/profile/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default function Profile({ navigation }: any) {
setLoading(true);


const response = await api.get('/users/' + store.getState().user.id); //Busca dados no back com o id do usuário recuperado do redux
const response = await api.get('users'); //Busca dados no back com o id do usuário recuperado do redux
const responseUser = response.data.user;
setUser({ ...responseUser, ...{ isProfessional: (responseUser.type == 1) } });

Expand Down

0 comments on commit f91e10c

Please sign in to comment.