Skip to content

Commit

Permalink
sponsor endpoints layout
Browse files Browse the repository at this point in the history
  • Loading branch information
Dev Patel authored and Dev Patel committed Jul 22, 2024
1 parent 971dc28 commit 0b11ee7
Show file tree
Hide file tree
Showing 8 changed files with 14,439 additions and 337 deletions.
7 changes: 7 additions & 0 deletions dp.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtz
c2gtZWQyNTUxOQAAACDhH2spW9yFyOaa7rxWW6tHP8bRZqeGtQo7T3nZYFuUBQAA
AIjOb/nezm/53gAAAAtzc2gtZWQyNTUxOQAAACDhH2spW9yFyOaa7rxWW6tHP8bR
ZqeGtQo7T3nZYFuUBQAAAEAwUQIBATAFBgMrZXAEIgQgc2wu+olXlSihWByE7lIf
4uEfaylb3IXI5pruvFZbq0c/xtFmp4a1CjtPedlgW5QFAAAAAAECAwQF
-----END OPENSSH PRIVATE KEY-----
13,784 changes: 13,784 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"@types/bcrypt": "^5.0.2",
"@types/dotenv": "^8.2.0",
"@types/express": "^4.17.21",
"@types/express-rate-limit": "^6.0.0",
Expand Down Expand Up @@ -50,6 +51,7 @@
"@types/cors": "^2.8.17",
"aws-sdk": "^2.1604.0",
"axios": "^1.6.8",
"bcrypt": "*",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"crypto": "^1.0.1",
Expand Down
2 changes: 2 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import s3Router from "./services/s3/s3-router";
import statsRouter from "./services/stats/stats-router";
import subscriptionRouter from "./services/subscription/subscription-router";
import speakersRouter from "./services/speakers/speakers-router";
import sponsorRouter from "./services/sponsor/sponsor-router";

AWS.config.update({
region: Config.S3_REGION,
Expand Down Expand Up @@ -54,6 +55,7 @@ app.use("/s3", databaseMiddleware, s3Router);
app.use("/stats", databaseMiddleware, statsRouter);
app.use("/subscription", databaseMiddleware, subscriptionRouter);
app.use("/speakers", databaseMiddleware, speakersRouter);
app.use("/sponsor", databaseMiddleware, sponsorRouter);

app.get("/status", (_, res) => {
return res.status(StatusCodes.OK).send("API is alive!");
Expand Down
9 changes: 9 additions & 0 deletions src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ import {
SpeakerSchema,
SpeakerValidator,
} from "./services/speakers/speakers-schema";
import {
SponsorSchema,
SponsorValidator,
} from "./services/sponsor/sponsor-schema";

mongoose.set("toObject", { versionKey: false });

Expand Down Expand Up @@ -93,5 +97,10 @@ export const Database = {
NotificationsSchema,
NotificationsValidator
),
SPONSOR: initializeModel(

Check failure on line 100 in src/database.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `⏎········"sponsor",⏎········SponsorSchema,⏎········SponsorValidator⏎····` with `"sponsor",·SponsorSchema,·SponsorValidator`
"sponsor",
SponsorSchema,
SponsorValidator
),
SPEAKERS: initializeModel("speakers", SpeakerSchema, SpeakerValidator),
};
126 changes: 126 additions & 0 deletions src/services/sponsor/sponsor-router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { Router } from "express";
import { Database } from "../../database";
import RoleChecker from "../../middleware/role-checker";
import { Role } from "../auth/auth-models";
import { StatusCodes } from "http-status-codes";
import { SponsorValidator } from "./sponsor-schema";
import {sendEmail} from "../ses/ses-utils"

Check failure on line 7 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `sendEmail}·from·"../ses/ses-utils"` with `·sendEmail·}·from·"../ses/ses-utils";`
import jsonwebtoken from "jsonwebtoken";
import { Config } from "../../config";
const bcrypt = require('bcrypt');

Check failure on line 10 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / lint

Require statement not part of import statement

Check failure on line 10 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `'bcrypt'` with `"bcrypt"`
const sponsorRouter = Router();

sponsorRouter.get('/test', (req, res) => {

Check failure on line 13 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `'/test'` with `"/test"`
res.status(200).send({ message: 'Route found' });

Check failure on line 14 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `'Route·found'` with `"Route·found"`
});

Check failure on line 15 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / lint

Delete `··`

// Get favorite events for an attendee
sponsorRouter.get(
"/",
RoleChecker([Role.Enum.CORPORATE]),
async (req, res, next) => {
try {
const resumeUsers = await Database.REGISTRATION.find(
{ hasResume: true },
{ userId: 1 }
);

if (!resumeUsers) {
return res
.status(StatusCodes.NOT_FOUND)
.json({ error: "UserNotFound" });
}

return res.status(StatusCodes.OK).json(resumeUsers);
} catch (error) {
next(error);
}
}
);

function createSixDigitCode() {
let result = '';

Check failure on line 42 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `''` with `""`
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

Check failure on line 43 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / lint

Replace `'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'` with `"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"`
for (let i = 0; i < 6; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}

function encryptSixDigitCode(sixDigitCode) {

Check failure on line 50 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / build

Parameter 'sixDigitCode' implicitly has an 'any' type.
console.log("SixDijit: ", sixDigitCode)

Check failure on line 51 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / lint

Insert `;`
const saltRounds = 10;

try {
const hash = bcrypt.hashSync(sixDigitCode, saltRounds);
return hash
} catch (err) {
console.error('Error encrypting the code:', err);
throw err;
}
}

sponsorRouter.post(
"/login",
async (req, res, next) => {
const { email } = req.body;
try {
console.log("email: ", email)
console.log("req: ", req.body)

const sixDigitCode = createSixDigitCode();
console.log("SixDijit: ", sixDigitCode)
const expTime = Math.floor(Date.now() / 1000) + 120; //2 minutes
console.log("expTime: ", expTime)
const hashedVerificationCode = encryptSixDigitCode(sixDigitCode);
console.log("hashed code: ", hashedVerificationCode)
//create auth collection
//store hashedCode and expTime in mongo auth collection
const validatedData = SponsorValidator.parse({email, hashedVerificationCode, expTime});
console.log("test")
const sponsor = new Database.SPONSOR(validatedData);
await sponsor.save();
//send verification email to email adress
await sendEmail(email, 'RP-Verify your Email', ` Verifiction Code: ${sixDigitCode}`);
return res.sendStatus(StatusCodes.CREATED);
} catch (error) {
next(error);
}
}
);

sponsorRouter.post(
"/verify",
async (req, res, next) => {
const { email, sixDigitCode } = req.body;
try {

const sponsorData = await Database.SPONSOR.findOne({ email: email });
const { hashedVerificationCode, expTime } = sponsorData

Check failure on line 99 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / build

Property 'hashedVerificationCode' does not exist on type '(Document<unknown, {}, modelType> & modelType & Required<{ _id: unknown; }>) | null'.

Check failure on line 99 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / build

Property 'expTime' does not exist on type '(Document<unknown, {}, modelType> & modelType & Required<{ _id: unknown; }>) | null'.
if (new Date() > expTime){
return res.status(401).json({ message: 'Code expired' });
}
const match = await bcrypt.compareSync(sixDigitCode, hashedVerificationCode)
if (!match) {
return res.status(401).json({ message: 'Incorrect Code' });
}
await Database.SPONSOR.deleteOne({ email });

const token = jsonwebtoken.sign(
{
email,
role: 'CORPORATE'
},
Config.JWT_SIGNING_SECRE,

Check failure on line 114 in src/services/sponsor/sponsor-router.ts

View workflow job for this annotation

GitHub Actions / build

Property 'JWT_SIGNING_SECRE' does not exist on type '{ DEFAULT_APP_PORT: number; ALLOWED_CORS_ORIGIN_PATTERNS: RegExp[]; ENV: "PRODUCTION" | "DEVELOPMENT" | "TESTING"; DATABASE_USERNAME: string; DATABASE_PASSWORD: string; DATABASE_HOST: string; ... 14 more ...; OUTGOING_EMAIL_ADDRESSES: ZodEnum<...>; }'. Did you mean 'JWT_SIGNING_SECRET'?
{
expiresIn: Config.JWT_EXPIRATION_TIME,
}
);
res.json({ token });
} catch (error) {
next(error);
}
}
);

export default sponsorRouter;
28 changes: 28 additions & 0 deletions src/services/sponsor/sponsor-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import mongoose from "mongoose";
import { z } from "zod";

// // Zod schema for registration
// export const AuthValidator = z.object({
// email: z.string().email(),
// hashedVerificationCode: z.string(),
// expTime: z.number()
// });

// // Mongoose schema for registration
// export const AuthSchema = new mongoose.Schema({
// email: { type: String, required: true, unique: true },
// hashedVerificationCode: { type: String, required: true },
// expTime: { type: Number, required: true } // Add this line to include expTime
// });

export const SponsorSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true },
hashedVerificationCode: { type: String, required: true }, // Ensure this matches your zod schema
expTime: { type: Number, required: true }
});

export const SponsorValidator = z.object({
email: z.string().email(),
hashedVerificationCode: z.string(), // Ensure this matches your mongoose schema
expTime: z.number().int()
});
Loading

0 comments on commit 0b11ee7

Please sign in to comment.