Skip to content

Commit

Permalink
Updating user role and authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
mugishaj092 committed May 28, 2024
1 parent 1576301 commit 344756f
Show file tree
Hide file tree
Showing 17 changed files with 420 additions and 135 deletions.
38 changes: 33 additions & 5 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
version: 2.1


orbs:
node: circleci/[email protected]
coveralls: coveralls/[email protected]

executors:
node-executor:
Expand All @@ -13,26 +11,56 @@ executors:
jobs:
build:
executor: node-executor
environment:
CC_TEST_REPORTER_ID: b996f145a438f80141cfcc86bb35a2c212a2a24c394abee18da6add05eaaee7e
steps:
- checkout
- run: npm install

- run:
name: Install Code Climate test reporter
command: |
curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
chmod +x ./cc-test-reporter
- run:
name: Initialize Code Climate test reporter
command: ./cc-test-reporter before-build
- run:
name: Run Tests
command: npm test
name: Run Tests with Coverage
command: npx nyc npm run test:coverage
- run:
name: Format Coverage Report
command: npx nyc report --reporter=text-lcov > coverage.lcov
- run:
name: Upload Coverage Report to Code Climate
command : ./cc-test-reporter after-build -t lcov
when: always
- store_artifacts: # upload test coverage as artifact
path: ./coverage/lcov.info


deploy:
executor: node-executor
steps:

- checkout
- run: npm install
- run:
name: Install TypeScript
command: sudo npm install -g typescript
- run:
name: Build Project
command: tsc

command: npx tsc


- run:
name: Compile TypeScript
command: ./node_modules/.bin/tsc




workflows:
version: 2
build_and_deploy:
Expand Down
36 changes: 0 additions & 36 deletions .github/workflows/job.yaml

This file was deleted.

30 changes: 0 additions & 30 deletions .github/workflows/test.yml

This file was deleted.

12 changes: 0 additions & 12 deletions __test__/home.test.ts

This file was deleted.

4 changes: 3 additions & 1 deletion app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import express, { Request, Response } from "express";
import userRoutes from "./src/routes/user.route";
import swaggerUi from 'swagger-ui-express';
import specs from './swagger.config';
import morgan from "morgan";

const app = express();

app.use(express.json());
app.use(morgan("dev"))

app.get('/', (_req: Request, res: Response) => {
app.get('/',(_req: Request, res: Response) => {
return res.json({ message: "welcome to ATLP Backend APIs" });
});
app.use('/api/users', userRoutes);
Expand Down
6 changes: 3 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version: '3.8'
version: '3.9'

services:
postgresdb:
Expand Down Expand Up @@ -27,5 +27,5 @@ services:
- DB_NAME=${DB_NAME}
- DB_PORT=${POSTGRESDB_LOCAL_PORT}

volumes:
db_data:
volumes:
db_data:
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = {
resetMocks: true,
restoreMocks: true,
clearMocks: true,
testTimeout:30000,
testTimeout:60000,
coverageReporters: ['html', 'text', 'lcov'],
coverageDirectory: 'coverage',
testPathIgnorePatterns: ['/node_modules/']
Expand Down
64 changes: 64 additions & 0 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"express": "^4.19.2",
"joi": "^17.13.1",
"jsonwebtoken": "^9.0.2",
"morgan": "^1.10.0",
"nodemailer": "^6.9.13",
"nodemon": "^3.1.0",
"pg": "^8.11.5",
Expand All @@ -26,6 +27,7 @@
"dev": "nodemon server.ts",
"start": "ts-node server.ts",
"test": "jest --detectOpenHandles --coverage",
"test:coverage": "nyc jest --coverage",
"build": "tsc",
"migrate": "sequelize db:migrate"
},
Expand Down
95 changes: 95 additions & 0 deletions src/__test__/authMiddleware.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { Request, Response, NextFunction } from "express";
import { protectRoute, restrictTo } from "../middlewares/auth.middleware";
// import jwt from "jsonwebtoken";

type Headers = {
authorization?: string;
};

const mockRequest = (headers: Headers = {}) => {
return {
headers: {
authorization: headers.authorization || "",
},
user: undefined,
} as Partial<Request>;
};

const mockResponse = () => {
const res = {} as Partial<Response>;
res.status = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
return res;
};

const mockNext = () => jest.fn() as NextFunction;

describe("Authontication middleware", () => {
test("should throw missing authorization error", () => {
const req = mockRequest({ authorization: "" });
const res = mockResponse();
const next = mockNext();

protectRoute(req as Request, res as Response, next);

expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({
message: "Authorization header missing",
});
});
test("should return 401 if JWT_SECRET is missing", async () => {
const req = mockRequest({
authorization: "Bearer valid.token.here",
});
const res = mockResponse();
const next = mockNext();

const originalSecret = process.env.JWT_SECRET;
delete process.env.JWT_SECRET;
await protectRoute(req as Request, res as Response, next as NextFunction);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({ message: "JWT_SECRET is missing" });

process.env.JWT_SECRET = originalSecret;
});
test("should return 401 if token is invalid", async () => {
const req = mockRequest({
authorization: "Bearer invalid.token.here",
});
const res = mockResponse();
const next = mockNext();

await protectRoute(req as Request, res as Response, next);

expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({
message: "Unauthorized request, Try again",
});
});
});
describe("restrictTo middleware", () => {
let req: Partial<Request>;
let res: Partial<Response>;
let next: jest.Mock;

beforeEach(() => {
req = {
user: {
role: "admin", // Simulate an admin user
},
};
res = {
status: jest.fn(),
json: jest.fn(),
};
next = jest.fn();
});

test("should allow access for permitted roles", () => {
const middleware = restrictTo("admin");

middleware(req as Request, res as Response, next);

expect(next).toHaveBeenCalled();
});
});
Loading

0 comments on commit 344756f

Please sign in to comment.