Skip to content

Commit

Permalink
--- Complete redesign of architecture --- (#245)
Browse files Browse the repository at this point in the history
  • Loading branch information
alllenshibu authored Jan 31, 2024
1 parent 63e89a9 commit 4249500
Show file tree
Hide file tree
Showing 160 changed files with 1,746 additions and 7,858 deletions.
4 changes: 2 additions & 2 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/apps/core"
directory: "/apps/core-admin"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/apps/web-client"
directory: "/apps/web-admin"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ jobs:
steps:
- uses: actions/checkout@v2
- run: |
docker build -t techno-event-management-core .
docker build -t techno-event-core-admin .
- run: |
docker login -u ${{ secrets.DOCKER_USER }} -p ${{ secrets.DOCKER_PASSWORD }}
- run: |
docker tag techno-event-management-core ${{ secrets.DOCKER_USER }}/techno-event-management-core:latest
docker push ${{ secrets.DOCKER_USER }}/techno-event-management-core:latest
docker tag techno-event-core-admin ${{ secrets.DOCKER_USER }}/techno-event-core-admin:latest
docker push ${{ secrets.DOCKER_USER }}/techno-event-core-admin:latest
redeploy-backend:
needs: build-and-push
Expand Down
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
auto-install-peers = true
public-hoist-pattern[] = *prisma*
9 changes: 6 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@ COPY . .

RUN pnpm install

RUN pnpm run build --filter=techno-event-core...
RUN pnpm run build --filter=techno-event-core-admin...

FROM gcr.io/distroless/nodejs20-debian11
RUN ls -la node_modules

COPY --from=builder /app/apps/core/dist .
FROM node:18-alpine

COPY --from=builder /app/apps/core-admin/dist .
COPY --from=builder /app/node_modules/.pnpm/@prisma+client*/node_modules/.prisma/client/*.node .

ENV PORT=80

Expand Down
File renamed without changes.
4 changes: 4 additions & 0 deletions apps/core-admin/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
root: true,
extends: ['custom'],
};
8 changes: 4 additions & 4 deletions apps/core/package.json → apps/core-admin/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "techno-event-core",
"version": "2.0.0",
"name": "techno-event-core-admin",
"version": "0.0.0",
"description": "",
"main": "build/index.js",
"scripts": {
Expand All @@ -17,15 +17,15 @@
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.2",
"common": "workspace:*",
"cors": "^2.8.5",
"database": "workspace:*",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-oauth2-jwt-bearer": "^1.6.0",
"jsonwebtoken": "^9.0.0",
"passport": "^0.7.0",
"passport-local": "^1.0.0",
"pg": "^8.11.0",
"pgdatabase": "workspace:*",
"uuid": "^9.0.0"
},
"devDependencies": {
Expand Down
74 changes: 74 additions & 0 deletions apps/core-admin/src/controllers/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { Request, Response } from 'express';

import prisma from '../utils/database';

export const getEvents = async (req: Request, res: Response) => {
try {
const userId = req?.auth?.payload?.sub;
const orgId = req?.params?.orgId;

const organization = await prisma.organization.findUnique({
where: {
id: orgId,
},
});

if (!organization) {
return res.status(404).json({ error: 'Organization not found' });
}

if (organization?.organizationUsers?.some((ou: any) => ou.userId === userId)) {
return res.status(403).json({ error: 'Forbidden' });
}

const events = await prisma.event.findMany({
where: {
organizationId: orgId,
},
});

return res.status(200).json({ events });
} catch (err: any) {
console.error(err);
return res.status(500).json({ error: 'Something went wrong' });
}
};

export const createNewEvent = async (req: Request, res: Response) => {
try {
const userId = req?.auth?.payload?.sub;
const { id, name } = req.body;
const { orgId } = req?.params;

const organization = await prisma.organization.findUnique({
where: {
id: orgId,
},
});

if (!organization) {
return res.status(404).json({ error: 'Organization not found' });
}

if (organization?.organizationUsers?.some((ou: any) => ou.userId === userId)) {
return res.status(403).json({ error: 'Forbidden' });
}

const newEvent = await prisma.event.create({
data: {
name,
organizationId: orgId,
},
});

if (!newEvent) {
return res.status(500).json({ error: 'Something went wrong' });
}

return res.status(200).json(newEvent);
} catch (err: any) {
console.error(err);

return res.status(500).json({ error: 'Something went wrong' });
}
};
31 changes: 31 additions & 0 deletions apps/core-admin/src/controllers/newuser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Request, Response } from 'express';

import prisma from '../utils/database';

export const addNewUserToDatabaseOnRegister = async (req: Request, res: Response) => {
try {
const { userId, email } = req.body;

console.log(req.body);

if (!userId || !email) {
return res.status(400).send('Invalid Request');
}

const newUser = await prisma.user.create({
data: {
email: email,
id: userId,
},
});

if (!newUser) {
return res.status(500).send('Error creating user');
}

return res.status(200).send(newUser);
} catch (err) {
console.error(err);
return res.status(500);
}
};
56 changes: 56 additions & 0 deletions apps/core-admin/src/controllers/organizations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { Request, Response } from 'express';

import prisma from '../utils/database';

export const createNewOrganization = async (req: Request, res: Response) => {
try {
const userId = req?.auth?.payload?.sub;
const { id, name } = req.body;

const newOrganization = await prisma.organization.create({
data: {
id,
name,
OrganizationUser: {
create: {
userId,
role: 'ADMIN',
},
},
},
});

if (!newOrganization) {
return res.status(500).json({ error: 'Something went wrong' });
}

return res.status(200).json(newOrganization);
} catch (err: any) {
console.error(err);
if (err.code === 'P2002') {
return res.status(400).json({ error: 'Organization with the same id already exists' });
}
return res.status(500).json({ error: 'Something went wrong' });
}
};

export const getUsersOrganizations = async (req: Request, res: Response) => {
try {
const userId = req?.auth?.payload?.sub;

const organizations = await prisma.organization.findMany({
where: {
OrganizationUser: {
some: {
userId,
},
},
},
});

return res.status(200).json({ organizations });
} catch (err: any) {
console.error(err);
return res.status(500).json({ error: 'Something went wrong' });
}
};
31 changes: 18 additions & 13 deletions apps/core/src/index.ts → apps/core-admin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const port: any = process.env.PORT;

const app: Express = express();

const { auth } = require('express-oauth2-jwt-bearer');

app.use(
cors({
origin: '*',
Expand All @@ -18,22 +20,27 @@ app.use(

app.use(bodyParser.json());

import { router } from './routes/routes';
import { organizationRouter } from './routes/organization.route';
import { userRouter } from './routes/user.route';
import { authrouter } from './routes/auth.route';

app.use('/', organizationRouter);
app.use('/', userRouter);

import { authorize } from './middlewares/auth.middleware';
const jwtCheck = auth({
audience: 'https://core.techno.iedcmec.in/api',
issuerBaseURL: 'https://dev-techno.jp.auth0.com',
tokenSigningAlg: 'RS256',
});

app.use('/core', authorize, router);
import { addNewUserToDatabaseOnRegister } from './controllers/newuser';

app.get('/', (req: Request, res: Response) => {
res.send('Techno Event Server');
return res.send('Techno Event Server');
});

app.post('/api/auth/newuser', addNewUserToDatabaseOnRegister);

app.use(jwtCheck);

import router from './routes';
import { decodeUserInfo } from './middlewares/auth0';

app.use('/core', decodeUserInfo, router);

app.get('/health', (req: Request, res: Response) => {
const healthcheck: any = {
resource: 'Techno Event Server',
Expand All @@ -50,8 +57,6 @@ app.get('/health', (req: Request, res: Response) => {
}
});

app.use('/auth', authrouter);

app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Expand Down
46 changes: 46 additions & 0 deletions apps/core-admin/src/middlewares/auth0.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import * as dotenv from 'dotenv';
import { NextFunction, Request, Response } from 'express';
import { auth, claimCheck, InsufficientScopeError } from 'express-oauth2-jwt-bearer';

dotenv.config();

export const validateAccessToken = auth({
issuerBaseURL: `https://${process.env.AUTH0_DOMAIN}`,
audience: process.env.AUTH0_AUDIENCE,
});

export const checkRequiredPermissions = (requiredPermissions: string[]) => {
return (req: Request, res: Response, next: NextFunction) => {
const permissionCheck = claimCheck((payload) => {
const permissions = payload.permissions as string[];

const hasPermissions = requiredPermissions.every((requiredPermission) =>
permissions.includes(requiredPermission),
);

if (!hasPermissions) {
throw new InsufficientScopeError();
}

return hasPermissions;
});

permissionCheck(req, res, next);
};
};

export const decodeUserInfo = (req: Request, res: Response, next: NextFunction) => {
try {
const userId = req?.auth?.payload?.sub;

if (!userId) {
console.error('User ID not found in the payload');
return res.status(500).send('Internal Server Error');
}

next();
} catch (err) {
console.error(err);
return res.status(500).send('Internal Server Error');
}
};
21 changes: 21 additions & 0 deletions apps/core-admin/src/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import express, { Router } from 'express';
import { createNewOrganization, getUsersOrganizations } from './controllers/organizations';
import { createNewEvent, getEvents } from './controllers/events';
const router: Router = express.Router();

router.get('/', (req: any, res: any) => {
try {
return res.send('Hello World!');
} catch (err) {
console.error(err);
return res.status(500);
}
});

router.get('/organizations', getUsersOrganizations);
router.post('/organizations', createNewOrganization);

router.get('/organizations/:orgId/events', getEvents);
router.post('/organizations/:orgId/events', createNewEvent);

export default router;
7 changes: 7 additions & 0 deletions apps/core-admin/src/utils/database.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const { PrismaClient } = require('database');

const prisma = new PrismaClient({
datasourceUrl: process.env.DATABASE_URL,
});

export default prisma;
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
9 changes: 0 additions & 9 deletions apps/core/.env.example

This file was deleted.

4 changes: 0 additions & 4 deletions apps/core/.eslintrc.js

This file was deleted.

Loading

0 comments on commit 4249500

Please sign in to comment.