Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: api modified for app #3

Merged
merged 9 commits into from
Feb 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7,855 changes: 0 additions & 7,855 deletions package-lock.json

This file was deleted.

78 changes: 58 additions & 20 deletions src/controllers/adminController.ts
Original file line number Diff line number Diff line change
@@ -8,6 +8,9 @@ import {
getEventAdminPassword,
getUsersforEvent,
insertEvent,
addEventAdmin,
insertEvents4Admin,
getAdminEvents
} from "../queries/adminQueries.js";
import {
EventIdValidator,
@@ -55,21 +58,29 @@ const VerifyPaid = async (req: Request, res: Response) => {
}

const { user_email } = UserEmailValidator.parse(req.body);
const { event_id } = EventIdValidator.parse(req.body.admin);
const { event_id } = EventIdValidator.parse(req.body);
console.log(req.body.admin)

const client = await pool.connect();
const result = await client.query(allowIfPaid, [user_email, event_id]);
client.release();
if(req.body.admin.is_super_admin || (req.body.admin.events_id.includes(event_id))){
const client = await pool.connect();
const result = await client.query(allowIfPaid, [user_email, event_id]);
client.release();

if (result.rows.length == 1)
return res
.status(200)
.json({ statusCode: 200, body: { message: "Sucessfull" } });
else
return res.status(404).json({
statusCode: 404,
body: { message: "User not Paid, User not allowed" },
});
if (result.rows.length == 1)
return res
.status(200)
.json({ statusCode: 200, body: { message: "Sucessfull" } });
else
return res.status(404).json({
statusCode: 404,
body: { message: "User not Paid, User not allowed" },
});
}else{
return res.status(401).json({
statusCode: 401,
body: { message: "Admin not Authorized" },
});
}
};

/* TO CREATE USER - "USER REGISTRATION"
@@ -114,28 +125,33 @@ const UserLogIn = async (req: Request, res: Response, next: NextFunction) => {
/* FOR EVENT CORDINATOR LOGIN
*/
const EventLogin = async (req: Request, res: Response, next: NextFunction) => {
const { event_id, password } = EventLoginValidator.parse(req.body);
const { admin_id, password } = EventLoginValidator.parse(req.body);

const client = await pool.connect();
const data = await client.query(getEventAdminPassword, [event_id]);
const data = await client.query(getEventAdminPassword, [admin_id]);

client.release();

if (data.rows.length == 0)
return res
.status(400)
.json({ statusCode: 400, body: { message: "Bad Request" } });
.json({ statusCode: 400, body: { message: "No Such Admin" } });

const user = data.rows[0];
if (await bcrypt.compare(password, user.password)) next();
if (await bcrypt.compare(password, user.password)){
const events = await client.query(getAdminEvents, [admin_id])
let events_id : Array<string> = []
events.rows.forEach(ele=>events_id.push(ele.event_id))
req.body.events_id = events_id
next();
}
else
return res
.status(401)
.json({ statusCode: 401, body: { message: "Wrong Password" } });
};

/* FOR GETTING USERS FROM A PARTICULAR EVENT
*/
/* FOR GETTING USERS FROM A PARTICULAR EVENT */
const GetUsersFromEvent = async (req: Request, res: Response) => {
if (!req.body.admin.is_event_admin) {
return res
@@ -144,7 +160,7 @@ const GetUsersFromEvent = async (req: Request, res: Response) => {
}

const client = await pool.connect();
const { event_id } = EventIdValidator.parse(req.body.admin);
const { event_id } = EventIdValidator.parse(req.body);
const data = await client.query(getUsersforEvent, [event_id]);

return res.status(200).json({
@@ -201,6 +217,27 @@ const CreateEvent = async (req: Request, res: Response) => {
.json({ statusCode: 200, body: { message: "Sucessfull" } });
};

const EventAdminSignUp = async(req: Request, res: Response) => {
const client = await pool.connect()
try{
const {admin_id, password, events_id} = req.body
const hashedPass = await bcrypt.hash(password, 10);
await client.query(begin)
await client.query(addEventAdmin, [admin_id, hashedPass])
await client.query(insertEvents4Admin, [admin_id, events_id])
await client.query(commit)
return res
.status(200)
.json({ statusCode: 200, body: { message: "Admin added with Events ID" } });
}catch(err){
console.log(err)
await client.query(rollback)
return res
.status(500)
.json({ statusCode: 500, body: { message: "Something went wrong" } });
}
}

export {
UpdatePaid,
VerifyPaid,
@@ -210,4 +247,5 @@ export {
GetUsersFromEvent,
UpdateUserCart,
CreateEvent,
EventAdminSignUp
};
3 changes: 1 addition & 2 deletions src/controllers/sesController.ts
Original file line number Diff line number Diff line change
@@ -329,8 +329,7 @@ const Sendotp = async (req: Request, res: Response) => {
const {otp,email} = req.body;
transporter.sendMail({
from: process.env.VERIFIED_EMAIL,
to: process.env.VERIFIED_EMAIL,
bcc: email,
to: email,
subject: `OTP`,
html: `<html>
<body style="width: 900px; padding: 0; margin: 0; box-sizing: border-box">
42 changes: 29 additions & 13 deletions src/controllers/userController.ts
Original file line number Diff line number Diff line change
@@ -27,16 +27,26 @@ const GetUserDetails = async (req: Request, res: Response) => {
};

const CreateUser = async (req: Request, res: Response) => {
const data = createUserValidator.parse(req.body);
const user = emailValidator.parse(req.body.user);
const sql_arr = [data.name, user.email, data.phone_no, data.clg_name];
const client = await pool.connect();
await client.query(createUser, [...sql_arr]).then(() => {
client.release();
});
return res
.status(200)
.json({ statusCode: 200, message: "User Created Sucessfully" });
try{
const data = createUserValidator.parse(req.body);
const user = emailValidator.parse(req.body.user);
const sql_arr = [data.name, user.email, data.phone_no, data.clg_name];
const client = await pool.connect();
await client.query(createUser, [...sql_arr]).then(() => {
client.release();
});
return res
.status(200)
.json({ statusCode: 200, message: "User Created Sucessfully" });
}catch(err){
if (err && (err as PostgresError).code === "23505")
return res
.status(550)
.json({ statusCode: 550, body: { message: "User Already Found" } });
}
return res
.status(500)
.json({ statusCode: 500, body: { message: "Internal Server Error" } });
};

const GetUserCart = async (req: Request, res: Response) => {
@@ -75,10 +85,16 @@ const UpdateUserCart = async (
});
} catch (err) {
await client.query(rollback);
if (err && (err as PostgresError).code === "23503") {
if (err && (err as PostgresError).code === "23503" &&
(err as PostgresError).constraint === "users_events_user_email_fkey") {
return res
.status(550)
.json({ statusCode: 550, body: { message: "Event or User Not Found" } });
.status(551)
.json({ statusCode: 551, body: { message: "User Not Found" } });
}else if(err && (err as PostgresError).code === "23503" &&
(err as PostgresError).constraint === "users_events_event_id_fkey"){
return res
.status(552)
.json({ statusCode: 552, body: { message: "Event Not Found" } });
}
next(err);

36 changes: 0 additions & 36 deletions src/index.ts

This file was deleted.

5 changes: 3 additions & 2 deletions src/interfaces/eventInterface.ts
Original file line number Diff line number Diff line change
@@ -28,7 +28,8 @@ export type EventsHome = {
date: string;
};

export type tokenAdminToken = {
export type eventAdminToken = {
is_event_admin: boolean;
event_id: string;
is_super_admin: boolean;
events_id: Array<string>;
};
1 change: 1 addition & 0 deletions src/interfaces/userInterface.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export interface PostgresError extends Error {
code: string;
constraint: string;
}

export interface cartType {
7 changes: 4 additions & 3 deletions src/middlewares/authHandler.ts
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@ import axios from "axios";
import jwt from "jsonwebtoken";
import { SECRET } from "../../config/tokenSecret.js";
import { tokenType } from "../interfaces/adminInterface.js";
import { tokenAdminToken } from "../interfaces/eventInterface.js";
import { eventAdminToken } from "../interfaces/eventInterface.js";
import { NextFunction, Response, Request } from "express";

export const AuthourizeAdmin = (
@@ -54,9 +54,10 @@ export const CreateAdminToken = async (req: Request, res: Response) => {
};

export const CreateEventAdminToken = async (req: Request, res: Response) => {
const tokenData: tokenAdminToken = {
const tokenData: eventAdminToken= {
is_event_admin: true,
event_id: req.body.event_id,
is_super_admin: (req.body.events_id.length === 0),
events_id: req.body.events_id
};
const token: string = jwt.sign(tokenData, SECRET);
return res.status(200).json({
8 changes: 7 additions & 1 deletion src/queries/adminQueries.ts
Original file line number Diff line number Diff line change
@@ -6,8 +6,14 @@ export const insertAdmin: string =
"INSERT INTO admin (uname, password) VALUES ($1, $2)";
export const getAdminPassword: string =
"SELECT password FROM admin WHERE uname = $1";
export const getEventAdminPassword: string = `SELECT password FROM events WHERE id = $1`;
export const getUsersforEvent: string = `select u.name, u.phone_no, u.clg_name, ue.is_present from users u join
users_events ue on ue.user_email = u.email where ue.event_id = $1`;
export const insertEvent: string = `insert into events (name, id, fee, pass_id, password) values
($1, $2, $3, $4, $5)`;
export const addEventAdmin: string = `insert into event_admin (id, password) values ($1, $2);`
export const insertEvents4Admin: string = `
INSERT INTO admin_events(admin_id, event_id)
SELECT $1::varchar, unnest($2::varchar[])
ON CONFLICT (admin_id, event_id) DO NOTHING`;
export const getEventAdminPassword: string = `SELECT password FROM event_admin WHERE id = $1`;
export const getAdminEvents: string = `SELECT event_id FROM admin_events WHERE admin_id = $1`;
4 changes: 3 additions & 1 deletion src/routes/adminRoute.ts
Original file line number Diff line number Diff line change
@@ -8,7 +8,8 @@ import {
EventLogin,
GetUsersFromEvent,
UpdateUserCart,
CreateEvent
CreateEvent,
EventAdminSignUp
} from "../controllers/adminController.js";
import asyncMiddleware from "../middlewares/asyncMiddleware.js";
import {
@@ -28,6 +29,7 @@ router.get("/get-users", AuthourizeAdmin, asyncMiddleware(GetUsersFromEvent));

//Comment this while PRODUCTION
router.post("/signup", asyncMiddleware(UserSignUp));
router.post("/event/signup", asyncMiddleware(EventAdminSignUp));
router.post("/create-event", asyncMiddleware(CreateEvent))

router.post("/login", asyncMiddleware(UserLogIn), CreateAdminToken);
3 changes: 2 additions & 1 deletion src/validators/adminValidators.ts
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@ const AdminSchema = z.object({
.string({ required_error: "uname is required" })
.max(10, "user name should be atmost 10 characters"),
password: z.string(),
admin_id: z.string(),
event_id: z.string(),
user_email: z
.string({ required_error: "email is required" })
@@ -12,7 +13,7 @@ const AdminSchema = z.object({
const EventIdValidator = AdminSchema.pick({ event_id: true });
const UserEmailValidator = AdminSchema.pick({ user_email: true });
const EventLoginValidator = AdminSchema.pick({
event_id: true,
admin_id: true,
password: true,
});
const UserSignUpValidator = AdminSchema.pick({ uname: true, password: true });