endpoint renaming paths

This commit is contained in:
2023-10-24 22:46:40 -04:00
parent 66012e9db4
commit 6addd5af30
9 changed files with 129 additions and 160 deletions

View File

@@ -12,9 +12,7 @@ import { createSystemMessages } from '../../data/db';
const prisma = new PrismaClient();
const router = express.Router();
const adminPassword = process.env.PASSWORD
? process.env.PASSWORD
: 'password';
const adminPassword = process.env.PASSWORD ? process.env.PASSWORD : 'password';
const adminAuth = basicAuth({
users: {
@@ -50,20 +48,17 @@ router.post(
'/addcode',
adminAuth,
asyncHandler(async (req: Request, res: Response) => {
const { numCodes, rooms, all, expiresAt, usesLeft, discordId } =
req.body as {
numCodes: number;
rooms: string[];
all: boolean;
expiresAt: number;
usesLeft: number;
discordId: string;
};
const { numCodes, rooms, all, expiresAt, usesLeft, discordId } = req.body as {
numCodes: number;
rooms: string[];
all: boolean;
expiresAt: number;
usesLeft: number;
discordId: string;
};
const currentDate = new Date();
const threeMonthsLater = new Date(currentDate).setMonth(
currentDate.getMonth() + 3
);
const threeMonthsLater = new Date(currentDate).setMonth(currentDate.getMonth() + 3);
const codeExpires = expiresAt ? expiresAt : threeMonthsLater;
const query = all ? undefined : { where: { roomId: { in: rooms } } };
@@ -105,9 +100,7 @@ router.post(
return Promise.all(createCodes)
.then(() => {
res
.status(200)
.json({ message: 'Claim codes added successfully', codes });
res.status(200).json({ message: 'Claim codes added successfully', codes });
})
.catch((err) => {
console.error(err);
@@ -139,9 +132,7 @@ router.post('/:roomId/addcode', adminAuth, (req, res) => {
const codes = genClaimCodeArray(numCodes);
const currentDate = new Date();
const threeMonthsLater = new Date(currentDate).setMonth(
currentDate.getMonth() + 3
);
const threeMonthsLater = new Date(currentDate).setMonth(currentDate.getMonth() + 3);
const codeExpires = expires ? expires : threeMonthsLater;
@@ -174,9 +165,7 @@ router.post('/:roomId/addcode', adminAuth, (req, res) => {
return Promise.all(createCodes);
})
.then(() => {
res
.status(200)
.json({ message: 'Claim codes added successfully', codes });
res.status(200).json({ message: 'Claim codes added successfully', codes });
})
.catch((err) => {
console.error(err);
@@ -228,19 +217,13 @@ router.post(
if (isValid) {
const updatedIdentity = await prisma.gateWayIdentity.update({
where: {
semaphoreIdentity: String(
generatedProof.publicSignals.identityCommitment
)
semaphoreIdentity: String(generatedProof.publicSignals.identityCommitment)
},
data: {
semaphoreIdentity: String(
generatedProof.publicSignals.externalNullifier
)
semaphoreIdentity: String(generatedProof.publicSignals.externalNullifier)
}
});
res
.status(200)
.json({ message: 'Identity updated successfully', updatedIdentity });
res.status(200).json({ message: 'Identity updated successfully', updatedIdentity });
} else {
res.status(500).json({ error: 'Internal Server Error' });
}

View File

@@ -1,12 +1,11 @@
import express from 'express';
import type { Request, Response } from 'express';
import { limiter } from '../middleware';
import { limiter } from '../middleware';
import { PrismaClient } from '@prisma/client';
import { generateRandomClaimCode } from 'discreetly-claimcodes';
import asyncHandler from 'express-async-handler';
import basicAuth from 'express-basic-auth';
const router = express.Router();
const prisma = new PrismaClient();
@@ -17,7 +16,7 @@ const discordPassword = process.env.DISCORD_PASSWORD
const adminAuth = basicAuth({
users: {
admin: discordPassword
discordAdmin: discordPassword
}
});
@@ -137,20 +136,15 @@ router.post(
const filteredRooms: string[] = [];
const filteredNames: string[] = [];
for (const role of roles) {
const discordRoleRoomMapping =
await prisma.discordRoleRoomMapping.findMany({
where: {
roles: {
has: role
}
const discordRoleRoomMapping = await prisma.discordRoleRoomMapping.findMany({
where: {
roles: {
has: role
}
});
const mappingRoomIds = discordRoleRoomMapping.map(
(mapping) => mapping.roomId
);
const newRooms = mappingRoomIds.filter((roomId) =>
roomIds.includes(roomId)
);
}
});
const mappingRoomIds = discordRoleRoomMapping.map((mapping) => mapping.roomId);
const newRooms = mappingRoomIds.filter((roomId) => roomIds.includes(roomId));
const newRoomNames = newRooms.map((roomId) => {
const room = rooms.rooms.find((room) => room.roomId === roomId);
return room?.name;
@@ -164,17 +158,14 @@ router.post(
const roomIds: string[] = [];
for (const role of roles) {
const discordRoleRoomMapping =
await prisma.discordRoleRoomMapping.findMany({
where: {
roles: {
has: role
}
const discordRoleRoomMapping = await prisma.discordRoleRoomMapping.findMany({
where: {
roles: {
has: role
}
});
const mappingRoomIds = discordRoleRoomMapping.map(
(mapping) => mapping.roomId
);
}
});
const mappingRoomIds = discordRoleRoomMapping.map((mapping) => mapping.roomId);
roomIds.push(...mappingRoomIds);
}
const roomNames = await prisma.rooms.findMany({

View File

@@ -25,11 +25,9 @@ const adminAuth = basicAuth({
}
});
const router = express.Router();
const prisma = new PrismaClient();
// Fetches all ethereum groups that exist in the database
router.get('/groups/all', adminAuth, (req: Request, res: Response) => {
prisma.ethereumGroup
@@ -233,7 +231,7 @@ router.post('/group/delete', adminAuth, (req, res) => {
* }
*/
router.post(
'/message/sign',
'/join',
limiter,
asyncHandler(async (req: Request, res: Response) => {
const { message, signature } = req.body as {

View File

@@ -1,13 +1,13 @@
import express from 'express';
import type { Request, Response } from 'express';
import { limiter } from '../middleware';
import { limiter } from '../middleware';
import { PrismaClient } from '@prisma/client';
import asyncHandler from 'express-async-handler';
import {
findClaimCode,
updateClaimCode,
updateRoomIdentities,
findUpdatedRooms,
findUpdatedRooms
} from '../../data/db/';
import { GatewayInviteDataI } from '../../types';
import { RoomI } from 'discreetly-interfaces';
@@ -15,7 +15,6 @@ import { RoomI } from 'discreetly-interfaces';
const router = express.Router();
const prisma = new PrismaClient();
/** This code takes a request from the gateway and joins a user to a room
* It takes in the claim code and the identity commitment of the user
* It checks if the claim code is valid and not expired
@@ -27,7 +26,7 @@ const prisma = new PrismaClient();
* "code": "string",
* "idc": "string"
* }
*/
*/
router.post(
'/join',
limiter,
@@ -89,6 +88,4 @@ router.post(
})
);
export default router;

View File

@@ -12,15 +12,15 @@ const router = express.Router();
const prisma = new PrismaClient();
/**
* This code is the API route used to verify the proof submitted by the user.
* It uses the SNARKProof type and idc from the request body to verify the proof. If it is valid,
* it adds the identity to the room and returns the roomId. If it is invalid, it returns an error.
* @param {SNARKProof} proof - The SNARKProof object from the user
* @param {string} idc - The identity commitment of the user
* @returns {void}
*/
* This code is the API route used to verify the proof submitted by the user.
* It uses the SNARKProof type and idc from the request body to verify the proof. If it is valid,
* it adds the identity to the room and returns the roomId. If it is invalid, it returns an error.
* @param {SNARKProof} proof - The SNARKProof object from the user
* @param {string} idc - The identity commitment of the user
* @returns {void}
*/
router.post(
'/',
'/join',
limiter,
asyncHandler(async (req: Request, res: Response) => {
const { proof, idc } = req.body as { proof: SNARKProof; idc: string };

View File

@@ -0,0 +1,37 @@
import express from 'express';
import type { Request, Response } from 'express';
import { limiter } from '../middleware';
import asyncHandler from 'express-async-handler';
import { verifyIdentityProof } from '../../crypto/idcVerifier/verifier';
import { IDCProof } from 'idc-nullifier/dist/types/types';
import { findRoomsByIdentity } from '../../data/db/';
const router = express.Router();
/** This function gets the rooms that a user is a member of.
* It takes in the identity commitment of the user, and passes it to the findRoomsByIdentity function.
* @param {string} idc - The id of the identity to get rooms for.
* @param {idcProof} proof - The proof of the identity to get rooms for.
* @returns {void}
*/
router.get(
'/:idc',
limiter,
asyncHandler(async (req: Request, res: Response) => {
console.log(req.body);
const isValid = await verifyIdentityProof(req.body as IDCProof);
console.log('VALID', isValid);
if (isValid) {
try {
res.status(200).json(await findRoomsByIdentity(req.params.idc));
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
} else {
res.status(400).json({ error: 'Invalid Proof' });
}
})
);
export default router;

View File

@@ -5,24 +5,24 @@ import { pp } from '../utils';
import discordRouter from './gateways/discord';
import ethRouter from './gateways/ethereumGroup';
import theWordRouter from './gateways/theWord';
import codeRouter from './gateways/inviteCode'
import roomRouter from './rooms/rooms'
import adminRouter from './admin/admin'
import codeRouter from './gateways/inviteCode';
import roomRouter from './rooms/rooms';
import identityRouter from './identity/idc';
import adminRouter from './admin/admin';
export function initEndpoints(app: Express) {
// This code is used to fetch the server info from the api
// This is used to display the server info on the client side
app.use('/gateway/discord', discordRouter)
app.use('/gateway/eth', ethRouter)
app.use('/gateway/theword', theWordRouter)
app.use('/gateway/code', codeRouter)
app.use('/room', roomRouter)
app.use('/admin', adminRouter)
app.use('/gateway/discord', discordRouter);
app.use('/gateway/eth', ethRouter);
app.use('/gateway/theword', theWordRouter);
app.use('/gateway/code', codeRouter);
app.use('/room', roomRouter);
app.use('/identity', identityRouter);
app.use('/admin', adminRouter);
app.get(['/'], (req, res) => {
pp('Express: fetching server info');
res.status(200).json(serverConfig);
});
}
}

View File

@@ -12,7 +12,7 @@ import {
findRoomsByIdentity,
createRoom,
removeRoom,
removeMessage,
removeMessage
} from '../../data/db/';
import { MessageI, RoomI } from 'discreetly-interfaces';
import { RLNFullProof } from 'rlnjs';
@@ -82,32 +82,6 @@ router.get('/:id', limiter, (req, res) => {
}
});
/** This function gets the rooms that a user is a member of.
* It takes in the identity commitment of the user, and passes it to the findRoomsByIdentity function.
* @param {string} idc - The id of the identity to get rooms for.
* @param {idcProof} proof - The proof of the identity to get rooms for.
* @returns {void}
*/
router.get(
'/idc/:idc',
limiter,
asyncHandler(async (req: Request, res: Response) => {
console.log(req.body);
const isValid = await verifyIdentityProof(req.body as IDCProof);
console.log('VALID', isValid);
if (isValid) {
try {
res.status(200).json(await findRoomsByIdentity(req.params.idc));
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
} else {
res.status(400).json({ error: 'Invalid Proof' });
}
})
);
/** createRoom is used to create a new room in the database
* @param {string} roomName - The name of the room
* @param {number} rateLimit - The rate limit of the room
@@ -197,25 +171,21 @@ router.post('/add', adminAuth, (req, res) => {
* @param {string} roomId - The id of the room to be deleted
* @returns {void}
* */
router.post(
'/:roomId/delete',
adminAuth,
(req: Request, res: Response) => {
const { roomId } = req.body as { roomId: string };
removeRoom(roomId)
.then((result) => {
if (result) {
res.status(200).json({ message: 'Room deleted successfully' });
} else {
res.status(500).json({ error: 'Internal Server Error' });
}
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: String(err) });
});
}
);
router.post('/:roomId/delete', adminAuth, (req: Request, res: Response) => {
const { roomId } = req.body as { roomId: string };
removeRoom(roomId)
.then((result) => {
if (result) {
res.status(200).json({ message: 'Room deleted successfully' });
} else {
res.status(500).json({ error: 'Internal Server Error' });
}
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: String(err) });
});
});
/**
* This code deletes a message from a room
@@ -227,27 +197,23 @@ router.post(
* @param {string} messageId - The id of the message to be deleted
* @returns {void}
* */
router.post(
'/:roomId/message/delete',
adminAuth,
(req, res) => {
const { roomId } = req.params;
const { messageId } = req.body as { messageId: string };
router.post('/:roomId/message/delete', adminAuth, (req, res) => {
const { roomId } = req.params;
const { messageId } = req.body as { messageId: string };
removeMessage(roomId, messageId)
.then((result) => {
if (result) {
res.status(200).json({ message: 'Message deleted successfully' });
} else {
res.status(500).json({ error: 'Internal Server Error' });
}
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: String(err) });
});
}
);
removeMessage(roomId, messageId)
.then((result) => {
if (result) {
res.status(200).json({ message: 'Message deleted successfully' });
} else {
res.status(500).json({ error: 'Internal Server Error' });
}
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: String(err) });
});
});
/**
* This code handles the get request to get a list of messages for a particular room.

View File

@@ -9,7 +9,6 @@ import { generateIdentityProof } from '../src/crypto/idcVerifier/verifier';
import { Identity } from '@semaphore-protocol/identity';
import { doesNotReject } from 'assert';
process.env.DATABASE_URL = process.env.DATABASE_URL_TEST;
process.env.PORT = '3001';
@@ -40,7 +39,6 @@ const testIdentity = new Identity();
const username = 'admin';
const password = process.env.PASSWORD;
beforeAll(async () => {
const prismaTest = new PrismaClient();
await prismaTest.messages.deleteMany();
@@ -202,7 +200,7 @@ describe('Endpoints', () => {
const joinTest = {
code: testCode,
idc: testIdentity.getCommitment().toString(),
idc: testIdentity.getCommitment().toString()
};
await request(_app)
@@ -223,17 +221,16 @@ describe('Endpoints', () => {
});
test('It should return all rooms associated with the given identity', async () => {
let proof = await generateIdentityProof(testIdentity, BigInt(Date.now()))
let proof = await generateIdentityProof(testIdentity, BigInt(Date.now()));
await request(_app)
.get(`/room/idc/${testIdentity.getCommitment().toString()}`)
.get(`/identity/${testIdentity.getCommitment().toString()}`)
.send(proof)
.then((res) => {
try {
expect(res.statusCode).toEqual(200);
} catch (error) {
console.error('GET /api/rooms/:idc - ' + error);
}
})
.catch((error) => console.error('GET /api/rooms/:idc - ' + error));