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: Added admin login logic in backend successfully issue 343 #345

Merged
merged 2 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ model User {
passwordHash String
verified Boolean @default(false)
otp Int?
isAdmin Boolean @default(false)
posts Post[] @relation("authorPosts")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Expand Down
41 changes: 41 additions & 0 deletions backend/src/middleware/adminAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Response, NextFunction } from 'express';
import prisma from '../db';
import { decodeJWT,verifyJWT } from '../helpers/jwt';
import { JwtPayload } from 'jsonwebtoken';
import { UserAuthRequest } from '../helpers/types';

export const isAdmin = async (req: UserAuthRequest, res: Response, next: NextFunction) => {
try {
const token = req.headers.authorization?.split(' ')[1];

if (!token) {
return res.status(403).json({ error: "No token provided" });
}

const isValid = verifyJWT(token);
if (!isValid) {
return res.status(403).json({
error: "Invalid token/format",
});
}

const decoded = decodeJWT(token);

if (!decoded || typeof decoded === 'string' || !('id' in decoded)) {
return res.status(401).json({ error: "Invalid token" });
}

const user = await prisma.user.findFirst({
where: { id: (decoded as JwtPayload).id },
});

if (!user || !user.isAdmin) {
return res.status(403).json({ error: "Access denied" });
}

req.userId = user?.id;
next();
} catch (error) {
return res.status(500).json({ error: "An unexpected error occurred" });
}
};
78 changes: 78 additions & 0 deletions backend/src/routes/admin/controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { Request, Response } from "express";
import prisma from "../../db";
import { adminLoginSchema } from './zodSchema';
import { createJWT } from "../../helpers/jwt";
import { validatePassword } from "../../helpers/hash";
import { UserAuthRequest } from "../../helpers/types";

export const adminLoginController = async (req: Request, res: Response) => {
try {
const payload = req.body;
const result = adminLoginSchema.safeParse(payload);

if (!result.success) {
const formattedError: any = {};
result.error.errors.forEach((e:any) => {
formattedError[e.path[0]] = e.message;
});
return res.status(400).json({ error: { ...formattedError, message: "Invalid Inputs" } });
}

const data = result.data;

const user = await prisma.user.findFirst({
where: {
email: data.email,
isAdmin: true,
},
select: {
id: true,
email: true,
passwordHash: true,
isAdmin:true
},
});

if (!user) {
return res.status(404).json({ error: { message: "No such admin exists" } });
}

const matchPassword = await validatePassword(data.password, user.passwordHash);

if (!matchPassword) {
return res.status(401).json({ error: { message: "Wrong Password" } });
}

const token = createJWT({ id: user.id, isAdmin: user.isAdmin });

res.status(200).json({ message: "Admin logged in Successfully.", token });
} catch (error) {
return res.status(500).json({ error: { message: "An unexpected exception occurred!" } });
}
};

export const adminProfileController = async (req: UserAuthRequest, res: Response) => {
const userId = req.userId;

const user = await prisma.user.findFirst({
where: {
id: userId,
isAdmin:true
},
select: {
id: true,
email: true,
isAdmin:true
},
});

if (!user) {
return res.status(411).json({
error: "Invalid token",
});
}

res.status(200).json({
user,
});
};
11 changes: 11 additions & 0 deletions backend/src/routes/admin/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {Router} from 'express';
import { adminLoginController, adminProfileController } from './controller';
import { isAdmin } from '../../middleware/adminAuth';

const adminRouter = Router();

adminRouter.post("/login", adminLoginController);

adminRouter.get("/me", isAdmin,adminProfileController );

export default adminRouter;
6 changes: 6 additions & 0 deletions backend/src/routes/admin/zodSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import zod from "zod";

export const adminLoginSchema = zod.object({
email: zod.string().email(),
password: zod.string().min(6),
});
2 changes: 2 additions & 0 deletions backend/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Router } from "express";
import userRouter from "./user/route";
import postRouter from "./post/route";
import adminRouter from "./admin/route"

const rootRouter = Router();
rootRouter.use('/user',userRouter);
rootRouter.use('/posts',postRouter);
rootRouter.use('/admin',adminRouter);

export default rootRouter;
Loading