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: Admin can ban users #19

Merged
merged 1 commit into from
Apr 5, 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
24 changes: 23 additions & 1 deletion backend/src/routes/admin.route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Router } from "express";
import { HttpCodes } from "../types/HttpCodes";
import { CustomResponse } from "../types/CustomResponse";
import { getAllUsers, promoteUser, demoteUser } from "../service/admin.service";
import { getAllUsers, promoteUser, demoteUser, banUser } from "../service/admin.service";
import prisma from '../db'
export const adminRouter = Router();

Expand Down Expand Up @@ -89,6 +89,28 @@ adminRouter.put("/demote/:user", async (req, res) => {
data: pro
}

return res.status(HttpCodes.OK).json(response);
}
})

adminRouter.put("/ban/:user", async (req, res) => {
const userEmailId = req.params.user;
const pro = await banUser(userEmailId);

if (pro.error) {
const response: CustomResponse = {
error: true,
message: "Error retrieving users",
data: null
}
return res.status(HttpCodes.INTERNAL_SERVER_ERROR).json(response);
} else {
const response: CustomResponse = {
error: false,
message: "selected user has been banned",
data: pro
}

return res.status(HttpCodes.OK).json(response);
}
})
40 changes: 40 additions & 0 deletions backend/src/service/admin.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { User } from '@prisma/client'
import { CustomReturn } from '../types/CustomReturn'
import prisma from '../db'
import { logger } from '../utils/logger'
//import { getUserByEmail } from './user.service'

export const getAllUsers = async (): Promise<CustomReturn<User[]>> => {
try {
Expand Down Expand Up @@ -63,4 +64,43 @@ export const demoteUser = async (userEmailId: string): Promise<CustomReturn<User
data: "Some error occurred while demoting admin to user role"
}
}
}

export const banUser = async (userEmailId: string): Promise<CustomReturn<User>> => {
try{
let user = await prisma.user.findUnique({
where: {
email: userEmailId
}
});

if (!user) return {
error: true,
data: "User does not exist."
}

if(user.role=="admin"){return{
error:true,
data: "An admin cannot be banned."}
}

const bannedUser = await prisma.user.update({
where: {email: userEmailId},
data: {role: 'banned' }
});
return{
error: false,
data: bannedUser
}
}
catch(err:any){
logger.error(JSON.stringify({
location: "banUser",
message: err.toString()
}));
return {
error: true,
data: "Some error occurred while banning user."
}
}
}
8 changes: 7 additions & 1 deletion backend/src/service/posts.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,13 @@ export const createPost = async (post: {
error: true,
data: "Karma points not enough to create a post."
}


if (user?.role=="banned"){
return{
error:true,
data: "You have been banned from posting for violating our policies."
}
}
let createPost = await prisma.post.create({
data: {
source: post.source,
Expand Down
51 changes: 50 additions & 1 deletion backend/tests/admin.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, expect } from "@jest/globals";
import { prismaMock } from "./_mockdb";
import { User } from ".prisma/client";
import { getAllUsers, promoteUser, demoteUser } from "../src/service/admin.service";
import { getAllUsers, promoteUser, demoteUser, banUser } from "../src/service/admin.service";

const user: User = {
id: "1",
Expand Down Expand Up @@ -33,6 +33,15 @@ const na: User = {
isPublic: true
}

const bu: User= {
id: "2",
name: "ben",
email: "[email protected]",
phoneNumber: "9898989898",
karmaPoints: 0,
role: "banned",
isPublic: true
}

describe("Get all users", () => {
it("should get all users", () => {
Expand Down Expand Up @@ -96,4 +105,44 @@ describe("demote admin to user", () => {
data: "Some error occurred while demoting admin to user role"
})
})
})

describe("ban user", () => {
it("should ban user", () => {
prismaMock.user.findUnique.mockResolvedValue(na);
prismaMock.user.update.mockResolvedValue(bu);

expect(banUser(na.email)).resolves.toEqual({
error: false,
data: bu
})
})

it("should return an error if user does not exist", () => {

expect(banUser("[email protected]")).resolves.toEqual({
error: true,
data: "User does not exist."
})
})

it("should return error if user to be banned is an admin", () => {
prismaMock.user.findUnique.mockResolvedValue(a);
prismaMock.user.update.mockResolvedValue(bu);

expect(banUser(a.email)).resolves.toEqual({
error: true,
data: "An admin cannot be banned."
})
})

it("should return error if any error occured", () => {
prismaMock.user.findUnique.mockResolvedValue(na);
prismaMock.user.update.mockRejectedValue(new Error("Some error occurred"));

expect(banUser(na.email)).resolves.toEqual({
error: true,
data: "Some error occurred while banning user."
})
})
})
20 changes: 20 additions & 0 deletions backend/tests/posts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ const userWith0KarmaPoints: User = {
role: "user"
}

const bannedUser: User = {
id: "1",
name: "ben",
email: "[email protected]",
phoneNumber: "1234567890",
karmaPoints: 10,
isPublic: false,
role: "banned"
}

const post: Post & {
authorEmail: string
} = {
Expand Down Expand Up @@ -86,6 +96,16 @@ describe("Create a new post", () => {
});
})

it("should return an error if user is banned", () => {
prismaMock.user.findUnique.mockResolvedValue(bannedUser);
prismaMock.post.create.mockResolvedValue(post);

expect(createPost(post)).resolves.toEqual({
error: true,
data: "You have been banned from posting for violating our policies."
});
})

it("should catch any error occurred", () => {
prismaMock.user.findUnique.mockResolvedValue(userWith10KarmaPoints);
prismaMock.post.create.mockResolvedValue(post);
Expand Down
14 changes: 14 additions & 0 deletions frontend/app/admin/home/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client"
import { Switch } from "@nextui-org/switch";
import { Button } from "@nextui-org/button"
import axios from "axios";
import React, { useEffect, useState } from 'react';
import { User } from '@/types'
Expand Down Expand Up @@ -30,6 +31,14 @@ const AdminHomepage = () => {
fetchUsers();
}, []);

const banUser = async (usermail: string) => {
try{
await axios.put(siteConfig.server_url + `/admin/ban/${usermail}`);
}catch(error){
setError("Error occurred")
}
}

const changeUserRole = async (usermail: string, admin: boolean) => {
try {
if (admin) {
Expand Down Expand Up @@ -74,6 +83,11 @@ const AdminHomepage = () => {
Admin role
</Switch>
</TableCell>
<TableCell>
<Button variant="bordered" onClick={(u:any)=>banUser(u.email)}>
Ban
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
Expand Down
Loading