Skip to content

Commit

Permalink
feat(auth): set up authentication and authorization
Browse files Browse the repository at this point in the history
- implement endpoint for user signup and login
- implement middleware for authenticating jwt tokens
- implement role checking middleware

[Delivers #2]
  • Loading branch information
jkarenzi committed Jun 10, 2024
1 parent 5ef9f58 commit 0a098d3
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 48 deletions.
28 changes: 14 additions & 14 deletions __tests__/authController.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export {};
const request = require('supertest');
const app = require('../src/server');
const app = require('../src/app');
const bcrypt = require('bcrypt');
const {
signUpSchema,
Expand All @@ -27,12 +27,12 @@ describe('Auth Controller Tests', () => {
};

const returnedUser = {
_id:"some id",
fullName:"mock user",
email:"[email protected]",
password:"password1234",
createdAt: "some date",
updatedAt: "some date"
_id:'some id',
fullName:'mock user',
email:'[email protected]',
password:'password1234',
createdAt: 'some date',
updatedAt: 'some date'
}

it('should return a 201 if signup is successful', async () => {
Expand Down Expand Up @@ -61,12 +61,12 @@ describe('Auth Controller Tests', () => {
signUpSchema.validate.mockReturnValueOnce({ error: null });

User.findOne.mockImplementationOnce(() => Promise.resolve({
_id:"some id",
fullName:"mock user",
email:"[email protected]",
password:"password1234",
createdAt: "some date",
updatedAt: "some date"
_id:'some id',
fullName:'mock user',
email:'[email protected]',
password:'password1234',
createdAt: 'some date',
updatedAt: 'some date'
}));

const response = await request(app).post('/api/auth/signup').send(signUpFormData);
Expand All @@ -89,7 +89,7 @@ describe('Auth Controller Tests', () => {

bcrypt.compare.mockResolvedValueOnce(true)

jwt.sign.mockResolvedValueOnce("fake token")
jwt.sign.mockResolvedValueOnce('fake token')

const response = await request(app).post('/api/auth/login').send(loginFormData);
expect(response.status).toBe(200);
Expand Down
19 changes: 5 additions & 14 deletions __tests__/test.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,11 @@
const { tester } = require('../src/controllers/testController');
export {}
const request = require('supertest');
const app = require('../src/app');

const res: any = {};

(res.json = jest.fn((x: Object) => x)),
(res.status = jest.fn((x: number) => res));

const req: any = {
body: {
name: 'test',
},
};

describe('Test', () => {
it('should return 200 successful upon testing route', async () => {
await tester(req, res);

expect(res.status).toHaveBeenCalledWith(200);
const response = await request(app).get('/api/test')
expect(response.status).toBe(200);
});
});
22 changes: 22 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"start": "node dist/server.js",
"dev": "ts-node-dev src/server.ts",
"lint": "eslint . --ext .ts --fix",
"format": "prettier --write ."
"format": "prettier --write .",
"email":"ts-node src/utils/sendEmail.ts"
},
"repository": {
"type": "git",
Expand All @@ -33,9 +34,11 @@
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.2.1",
"multer": "^1.4.4",
"node-mailer": "^0.1.1",
"supertest": "^7.0.0",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.0",
"ts-node": "^10.9.2",
"ts-node-dev": "^2.0.0",
"typescript": "^5.4.2"
},
Expand Down
15 changes: 15 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export {}
const express = require('express');
const cors = require('cors');
const routes = require('./routes/index');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./docs/swaggerconfig');

const app = express();

app.use(express.json());
app.use(cors());
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.use('/api', routes);

module.exports = app;
5 changes: 2 additions & 3 deletions src/middleware/authenticateToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,11 @@ const authenticateToken = async (
try {
const decoded = await jwt.verify(token, process.env.JWT_SECRET);

//@ts-expect-errors
//@ts-expect-errors still figuring out how to extend request
req.user = decoded.user;

next();
} catch (err: any) {
console.log(err.message);
} catch (err) {
return res.status(403).json({ status: 'error', message: 'Invalid token' });
}
};
Expand Down
3 changes: 2 additions & 1 deletion src/middleware/authorizeAdmin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Request, Response, NextFunction } from 'express';

const authorizeAdmin = (req: any, res: Response, next: NextFunction) => {
const authorizeAdmin = (req: Request, res: Response, next: NextFunction) => {
//@ts-expect-errors still figuring out how to extend request
const user = req.user;
if (user.role !== 'admin') {
return res.status(403).json({ status: 'error', message: 'Forbidden' });
Expand Down
18 changes: 3 additions & 15 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();
const cors = require('cors');
const routes = require('./routes/index');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./docs/swaggerconfig');
const app = require('./app')

const app = express();
app.use(express.json());
app.use(cors());
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

const url = process.env.MONGO_URL as string;
const dbName = process.env.DB_NAME;
Expand All @@ -22,10 +14,6 @@ mongoose
console.log(`Server listening at http://localhost:${port}`);

Check warning on line 14 in src/server.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

Unexpected console statement
});
})
.catch((err: any) => {
.catch((err:Error) => {
console.log(err);

Check warning on line 18 in src/server.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

Unexpected console statement
});

app.use('/api', routes);

module.exports = app;
});

0 comments on commit 0a098d3

Please sign in to comment.