Skip to content

Commit

Permalink
Merge pull request #26 from Eccoar/165_login_user
Browse files Browse the repository at this point in the history
Solve #165 - Autenticação de usuário
  • Loading branch information
Phe0 authored May 14, 2021
2 parents cd65166 + f3b54ef commit 0593ded
Show file tree
Hide file tree
Showing 6 changed files with 296 additions and 25 deletions.
14 changes: 14 additions & 0 deletions src/api/complaint/ComplaintProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,18 @@ export class ComplaintProxy {
return error;
}
}

async deleteComplaint(req: Request, resp: Response): Promise<Response> {
try {
const res = await axios.delete(this.path + '/complaints', {
params: {
userId: req.query.userId,
id: Number(req.query.id),
},
});
return resp.status(res.status).json({ msg: 'OK' });
} catch (err) {
return resp.status(err.response.status).json(err.response.data);
}
}
}
27 changes: 27 additions & 0 deletions src/api/middlewares/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Request, Response, NextFunction } from 'express';
import { paths } from '../../config/enviroments';
import { UsersProxy } from '../users/UsersProxy';

const userProxy = new UsersProxy(paths.configUsers());

export default class AuthValidator {
checkJWT = async (
req: Request,
resp: Response,
next: NextFunction,
): Promise<Response | void> => {
const token: string = req.headers['authorization'];
if (!token)
return resp
.status(401)
.json({ status: 'error', message: 'Access Denied' });
try {
await userProxy.authorization(token);
} catch (err) {
return resp
.status(403)
.json({ status: 'error', message: 'Access Denied' });
}
next();
};
}
20 changes: 20 additions & 0 deletions src/api/users/UsersProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,24 @@ export class UsersProxy {
return resp.status(err.response.status).json(err.response.data);
}
}

async signIn(req: Request, resp: Response): Promise<Response> {
try {
const res = await axios.post(this.path + '/signin', {
...req.body,
});
return resp.status(res.status).json(res.data);
} catch (err) {
return resp.status(err.response.status).json(err.response.data);
}
}

async authorization(token: string): Promise<string> {
const res = await axios.get(this.path + '/authorization', {
headers: {
authorization: token,
},
});
return res.data.userId;
}
}
92 changes: 76 additions & 16 deletions src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import { UsersProxy } from './api/users/UsersProxy';
import { ComplaintProxy } from './api/complaint/ComplaintProxy';
import { ReportProxy } from './api/report/ReportProxy';
import { MailerProxy } from './api/mailer/MailerProxy';
import AuthValidator from './api/middlewares/auth';
import { emailJob } from './cron/jobs/emailJob';

const routers = Router();
const usersProxy = new UsersProxy(paths.configUsers());
const complaintProxy = new ComplaintProxy(paths.configComplaint());
const reportProxy = new ReportProxy(paths.configReport());
const mailerProxy = new MailerProxy(paths.configMailer());
const usersProxy = new UsersProxy(paths.configUsers());
const authValidator = new AuthValidator();

routers.get('/api/users/ping', async (req: Request, resp: Response) => {
return await usersProxy.pingUser(req, resp);
Expand All @@ -20,34 +22,79 @@ routers.get('/api/complaints/ping', async (req: Request, resp: Response) => {
return await complaintProxy.pingComplaint(req, resp);
});

routers.post('/api/complaints', async (req: Request, resp: Response) => {
return await complaintProxy.createComplaint(req, resp);
});
routers.post(
'/api/complaints',
authValidator.checkJWT,
async (req: Request, resp: Response) => {
return await complaintProxy.createComplaint(req, resp);
},
);

routers.post('/api/votes', async (req: Request, resp: Response) => {
return await complaintProxy.addVote(req, resp);
});
routers.post(
'/api/votes',
authValidator.checkJWT,
async (req: Request, resp: Response) => {
return await complaintProxy.addVote(req, resp);
},
);

routers.get('/api/votes', async (req: Request, resp: Response) => {
return await complaintProxy.listVote(req, resp);
});
routers.get(
'/api/votes',
authValidator.checkJWT,
async (req: Request, resp: Response) => {
return await complaintProxy.listVote(req, resp);
},
);

routers.get('/api/mailer/ping', async (req: Request, resp: Response) => {
const response = await mailerProxy.pingMailer(resp);
resp.status(200).json(response);
});

routers.get('/api/complaints', async (req: Request, resp: Response) => {
return await complaintProxy.listComplaints(req, resp);
});
routers.get(
'/api/complaints',
authValidator.checkJWT,
async (req: Request, resp: Response) => {
return await complaintProxy.listComplaints(req, resp);
},
);

routers.get('/api/reports/ping', async (req: Request, resp: Response) => {
return await reportProxy.pingReport(req, resp);
});

routers.get('/api/complaints/votes', async (req: Request, resp: Response) => {
return await complaintProxy.getComplaintWithVote(req, resp);
});
routers.get(
'/api/complaints/votes',
authValidator.checkJWT,
async (req: Request, resp: Response) => {
return await complaintProxy.getComplaintWithVote(req, resp);
},
);

routers.post(
'/api/mailer/send',
authValidator.checkJWT,
async (req: Request, resp: Response) => {
try {
const reportRequest = {} as Request;
const complaintResponse = await complaintProxy.getWaitComplaints(
req,
);
reportRequest.body = {
complaints: complaintResponse,
category: String(req.query.category),
};
const reportResponse = await reportProxy.createReport(
reportRequest,
);
const mailerRequest = {} as Request;
mailerRequest.body = reportResponse;
return await mailerProxy.sendMail(mailerRequest, resp);
} catch (error) {
return resp.status(400).json({ error: error });
}
},
);

routers.delete('/api/vote', async (req: Request, resp: Response) => {
return await complaintProxy.removeVote(req, resp);
Expand All @@ -57,7 +104,20 @@ routers.post('/api/mailer/send', async (req: Request, resp: Response) => {
return await emailJob(req, resp);
});

routers.delete(
'/api/complaints',
authValidator.checkJWT,
async (req: Request, resp: Response) => {
return await complaintProxy.deleteComplaint(req, resp);
},
);

routers.post('/api/signin', async (req: Request, resp: Response) => {
return await usersProxy.signIn(req, resp);
});

routers.post('/api/users', async (req: Request, resp: Response) => {
return usersProxy.createUser(req, resp);
});

export default routers;
89 changes: 80 additions & 9 deletions test/Routes.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import axios from 'axios';
import * as request from 'supertest';
import { UsersProxy } from '../src/api/users/UsersProxy';
import app from '../src/server';

const agent = request(app);

const headers = {
authorization:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtb2NrIjoidG9rZW4ifQ.XXx47Hiq9qlQgyNyhZ6-z2MGTH7e2L0kfaB17YXPsKA',
};

describe('test get ping endpoint', () => {
const pingMock = {
status: 200,
Expand All @@ -12,7 +20,7 @@ describe('test get ping endpoint', () => {
jest.spyOn(axios, 'get').mockImplementationOnce(() =>
Promise.resolve(pingMock),
);
const result = await request(app).get('/api/users/ping').send({});
const result = await agent.get('/api/users/ping').send({});
expect(result.status).toEqual(200);
expect(result.body).toContain(pingMock.body);
});
Expand All @@ -21,7 +29,7 @@ describe('test get ping endpoint', () => {
jest.spyOn(axios, 'get').mockImplementationOnce(() =>
Promise.resolve(pingMock),
);
const result = await request(app).get('/api/complaints/ping').send({});
const result = await agent.get('/api/complaints/ping').send({});
expect(result.status).toEqual(200);
expect(result.body).toContain(pingMock.body);
});
Expand All @@ -30,13 +38,19 @@ describe('test get ping endpoint', () => {
jest.spyOn(axios, 'get').mockImplementationOnce(() =>
Promise.resolve(pingMock),
);
const result = await request(app).get('/api/reports/ping').send({});
const result = await agent.get('/api/reports/ping').send({});
expect(result.status).toEqual(200);
expect(result.body).toContain(pingMock.body);
});
});

describe('test complaints route', () => {
beforeEach(() => {
UsersProxy.prototype.authorization = jest
.fn()
.mockImplementationOnce(() => '123123');
});

const mockStatus = {
status: 200,
};
Expand All @@ -51,23 +65,37 @@ describe('test complaints route', () => {
jest.spyOn(axios, 'get').mockImplementationOnce(() =>
Promise.resolve(mockStatus),
);
const result = await request(app).get('/api/complaints').send({});
const result = await agent.get('/api/complaints').set(headers).send({});
expect(result.status).toEqual(200);
});

it('Test delete complaints API', async () => {
jest.spyOn(axios, 'delete').mockImplementationOnce(() =>
Promise.resolve(mockStatus),
);
const result = await agent
.delete('/api/complaints')
.set(headers)
.send({});
expect(result.status).toEqual(200);
});

it('Test create complaints API', async () => {
jest.spyOn(axios, 'post').mockImplementationOnce(() =>
Promise.resolve(mockStatus),
);
const result = await request(app).post('/api/complaints').send({});
const result = await agent
.post('/api/complaints')
.set(headers)
.send({});
expect(result.status).toEqual(200);
});

it('Test adds vote API', async () => {
jest.spyOn(axios, 'post').mockImplementationOnce(() =>
Promise.resolve(mockStatus),
);
const result = await request(app).post('/api/votes').send({});
const result = await agent.post('/api/votes').set(headers).send({});
expect(result.status).toEqual(200);
});

Expand All @@ -91,17 +119,44 @@ describe('test complaints route', () => {
jest.spyOn(axios, 'get').mockImplementationOnce(() =>
Promise.resolve(mockStatus),
);
const result = await request(app).get('/api/votes').send({});
const result = await agent.get('/api/votes').set(headers).send({});
expect(result.status).toEqual(200);
});

it('Test gets complaints with votes API', async () => {
jest.spyOn(axios, 'get').mockImplementationOnce(() =>
Promise.resolve(mockStatus),
);
const result = await request(app).get('/api/complaints/votes').send({});
const result = await agent
.get('/api/complaints/votes')
.set(headers)
.send({});
expect(result.status).toEqual(200);
});

it('Test return JWT token', async () => {
jest.spyOn(axios, 'post').mockImplementationOnce(() => {
return Promise.resolve({ status: 200 });
});
const result = await agent
.post('/api/signin')
.send({ email: 'mockEmail', password: 'mockPassword' });
expect(result.status).toEqual(200);
});

it('Test fail to login', async () => {
const mockError = {
response: {
status: 400,
},
data: {},
};
jest.spyOn(axios, 'post').mockImplementationOnce(() => {
return Promise.reject(mockError);
});
const result = await agent.post('/api/signin').send({});
expect(result.status).toEqual(400);
});
});

describe('Test User route', () => {
Expand All @@ -113,7 +168,23 @@ describe('Test User route', () => {
jest.spyOn(axios, 'post').mockImplementationOnce(() =>
Promise.resolve(mockStatus),
);
const result = await request(app).post('/api/users').send({});
const result = await agent.post('/api/users').send({});
expect(result.status).toEqual(200);
});
});

describe('Test mailer routes', () => {
it('Ping mailer', async () => {
jest.spyOn(axios, 'get').mockImplementationOnce(() => Promise.resolve({
status: 200,
data: {
ping: 'pong'
}
}));

const result = await agent
.get('/api/mailer/ping')
.send({});
expect(result.status).toEqual(200);
});
});
Loading

0 comments on commit 0593ded

Please sign in to comment.