Skip to content

Commit 954593b

Browse files
refactor-krishnaacharyaa#418: Added role type in frontend and backend (krishnaacharyaa#422)
2 parents 6fa9d77 + dc20c6b commit 954593b

File tree

8 files changed

+60
-55
lines changed

8 files changed

+60
-55
lines changed

Diff for: backend/controllers/user-controller.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { HTTP_STATUS, RESPONSE_MESSAGES } from '../utils/constants.js';
22
import User from '../models/user.js';
3+
import { Role } from '../types/role-type.js';
34

45
export const getAllUserHandler = async (req, res) => {
56
try {
@@ -17,7 +18,7 @@ export const changeUserRoleHandler = async (req, res) => {
1718
try {
1819
const userId = req.params.userId;
1920
const { role } = req.body;
20-
if (role === 'USER' || role === 'ADMIN') {
21+
if (role === Role.User || role === Role.Admin) {
2122
const user = await User.findById(userId);
2223
if (!user)
2324
return res

Diff for: backend/middlewares/auth-middleware.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { JWT_SECRET } from '../config/utils.js';
22
import { ApiError } from '../utils/api-error.js';
33
import { HTTP_STATUS, RESPONSE_MESSAGES } from '../utils/constants.js';
44
import jwt from 'jsonwebtoken';
5+
import { Role } from '../types/role-type.js';
56

67
export const authMiddleware = async (req, res, next) => {
78
const token = req.cookies?.access_token;
@@ -22,7 +23,7 @@ export const authMiddleware = async (req, res, next) => {
2223

2324
export const isAdminMiddleware = async (req, res, next) => {
2425
const role = req.user.role;
25-
if (role !== 'ADMIN') {
26+
if (role !== Role.Admin) {
2627
return new ApiError(HTTP_STATUS.UNAUTHORIZED, RESPONSE_MESSAGES.USERS.UNAUTHORIZED_USER);
2728
}
2829
next();

Diff for: backend/models/user.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import JWT from 'jsonwebtoken';
33
import bcrypt from 'bcryptjs';
44
import crypto from 'crypto';
55
import { ACCESS_TOKEN_EXPIRES_IN, JWT_SECRET, REFRESH_TOKEN_EXPIRES_IN } from '../config/utils.js';
6+
import { Role } from '../types/role-type.js';
67

78
const userSchema = new Schema(
89
{
@@ -47,8 +48,8 @@ const userSchema = new Schema(
4748
},
4849
role: {
4950
type: String,
50-
default: 'USER',
51-
enum: ['USER', 'ADMIN'],
51+
default: Role.User,
52+
enum: [Role.User, Role.Admin],
5253
},
5354
posts: [
5455
{

Diff for: backend/types/role-type.js

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export const Role = {
2+
Admin: 'ADMIN',
3+
User: 'USER',
4+
};

Diff for: frontend/src/App.tsx

+3-2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { useLayoutEffect } from 'react';
1414
import RequireAuth from './components/require-auth';
1515
import useThemeClass from './utils/theme-changer';
1616
import AdminContainer from './components/admin-container';
17+
import { Role } from './types/role-type.tsx';
1718

1819
function App() {
1920
useLayoutEffect(() => {
@@ -31,10 +32,10 @@ function App() {
3132
<Route path="signin" element={<SignIn />} />
3233
<Route path="signup" element={<SignUp />} />
3334
</Route>
34-
<Route element={<RequireAuth allowedRole={['ADMIN', 'USER']} />}>
35+
<Route element={<RequireAuth allowedRole={[Role.Admin, Role.User]} />}>
3536
<Route path="add-blog" element={<AddBlog />} />
3637
</Route>
37-
<Route path="admin" element={<RequireAuth allowedRole={['ADMIN']} />}>
38+
<Route path="admin" element={<RequireAuth allowedRole={[Role.Admin]} />}>
3839
<Route element={<AdminContainer />}>
3940
<Route path="users" element={<AdminUsers />} />
4041
<Route path="blogs" element={<AdminBlogs />} />

Diff for: frontend/src/layouts/header-layout.tsx

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import Loader from '@/components/skeletons/loader';
1212
import useAuthData from '@/hooks/useAuthData';
1313
import userState from '@/utils/user-state';
1414
import { Link } from 'react-router-dom';
15+
import { Role } from '@/types/role-type.tsx';
1516

1617
function header() {
1718
const navigate = useNavigate();
@@ -74,7 +75,7 @@ function header() {
7475
<Loader />
7576
) : token ? (
7677
<div className="flex gap-2">
77-
{user?.role === 'ADMIN' && (
78+
{user?.role === Role.Admin && (
7879
<button
7980
className="active:scale-click hidden rounded border border-slate-50 px-4 py-2 hover:bg-slate-500/25 md:inline-block"
8081
onClick={() => {

Diff for: frontend/src/pages/admin-users.tsx

+40-48
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,12 @@ import axiosInstance from '@/helpers/axios-instance';
22
import { useEffect, useState } from 'react';
33
import { toast } from 'react-toastify';
44
import 'react-toastify/dist/ReactToastify.css';
5-
6-
enum role {
7-
admin = 'ADMIN',
8-
user = 'USER',
9-
}
5+
import { Role } from '@/types/role-type';
106

117
type User = {
128
_id: string;
139
fullName: string;
14-
role: role;
10+
role: Role;
1511
email: string;
1612
};
1713

@@ -27,9 +23,9 @@ const AdminUsers = () => {
2723
}
2824
};
2925

30-
const handleClick = async (userId: string, role: role) => {
26+
const handleClick = async (userId: string, role: Role) => {
3127
try {
32-
const response = await axiosInstance.patch('/api/user/' + userId, { role: role });
28+
const response = await axiosInstance.patch('/api/user/' + userId, { role });
3329
if (response.status === 200) {
3430
fetchData();
3531
toast.success('User updated successfully!');
@@ -44,48 +40,44 @@ const AdminUsers = () => {
4440
}, []);
4541

4642
return (
47-
<>
48-
<div className="w-full p-3 px-5 sm:p-12">
49-
<h1 className="absolute left-16 top-3 text-2xl font-bold text-light-title dark:text-dark-title sm:static">
50-
Users
51-
</h1>
52-
<div className="mt-2 sm:mt-12">
53-
{users?.map((user: User) => {
54-
return (
55-
<div
56-
key={user?._id}
57-
className="mb-3 flex w-full flex-row items-center justify-between gap-5 rounded-lg border-b border-gray-300 bg-light px-3 py-4 shadow-md dark:border-gray-700 dark:bg-dark-card"
43+
<div className="w-full p-3 px-5 sm:p-12">
44+
<h1 className="absolute left-16 top-3 text-2xl font-bold text-light-title dark:text-dark-title sm:static">
45+
Users
46+
</h1>
47+
<div className="mt-2 sm:mt-12">
48+
{users?.map((user: User) => (
49+
<div
50+
key={user?._id}
51+
className="mb-3 flex w-full flex-row items-center justify-between gap-5 rounded-lg border-b border-gray-300 bg-light px-3 py-4 shadow-md dark:border-gray-700 dark:bg-dark-card"
52+
>
53+
<div className="flex flex-col gap-[10px]">
54+
<p className="text-base font-medium text-light-title dark:text-dark-title">
55+
{user?.fullName}
56+
</p>
57+
<p className="text-base font-medium text-light-description dark:text-dark-description">
58+
{user?.email}
59+
</p>
60+
</div>
61+
{user.role === Role.Admin && (
62+
<button
63+
onClick={() => handleClick(user._id, Role.User)}
64+
className="h-fit rounded-xl border border-black bg-black px-4 py-2 text-sm font-semibold text-white"
65+
>
66+
Admin
67+
</button>
68+
)}
69+
{user.role === Role.User && (
70+
<button
71+
onClick={() => handleClick(user._id, Role.Admin)}
72+
className="h-fit rounded-xl border border-black bg-transparent px-4 py-2 text-sm font-semibold text-black dark:text-white"
5873
>
59-
<div className="flex flex-col gap-[10px] ">
60-
<p className="text-base font-medium text-light-title dark:text-dark-title">
61-
{user?.fullName}
62-
</p>
63-
<p className="text-base font-medium text-light-description dark:text-dark-description">
64-
{user?.email}
65-
</p>
66-
</div>
67-
{user.role === role.admin && (
68-
<button
69-
onClick={() => handleClick(user._id, role.user)}
70-
className="h-fit rounded-xl border border-black bg-black px-4 py-2 text-sm font-semibold text-white"
71-
>
72-
Admin
73-
</button>
74-
)}
75-
{user.role === role.user && (
76-
<button
77-
onClick={() => handleClick(user._id, role.admin)}
78-
className="h-fit rounded-xl border border-black bg-transparent px-4 py-2 text-sm font-semibold text-white"
79-
>
80-
Admin
81-
</button>
82-
)}
83-
</div>
84-
);
85-
})}
86-
</div>
74+
User
75+
</button>
76+
)}
77+
</div>
78+
))}
8779
</div>
88-
</>
80+
</div>
8981
);
9082
};
9183

Diff for: frontend/src/types/role-type.tsx

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export enum Role {
2+
Admin = 'ADMIN',
3+
User = 'USER',
4+
}

0 commit comments

Comments
 (0)