Skip to content

Commit

Permalink
added a restriction middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
deXcripter committed Oct 3, 2024
1 parent b197370 commit 04769a5
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 5 deletions.
3 changes: 3 additions & 0 deletions be/src/controllers/auth/signup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import asyncHandler from '../../utils/async-handler';
import sendToken from '../../services/sendJwtToken';
import { iUser } from '../../interfaces';
import AppError from '../../utils/app-error';
import sendEmail from '../../utils/email';

const signup: RequestHandler = async (req, res, next) => {
const { email, password, role, name } = req.body;
Expand All @@ -18,6 +19,8 @@ const signup: RequestHandler = async (req, res, next) => {
role: role || 'student',
};

sendEmail(email, 'Registration Email', 'Welcome to CLP');

const user: iUser = await User.create(payload);

return sendToken(user, 201, res);
Expand Down
Empty file.
6 changes: 1 addition & 5 deletions be/src/middlewares/protect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ import asyncHandler from '../utils/async-handler';

const protect: RequestHandler = async (req, res, next) => {
const [type, token] = (req.headers.authorization || '').split(' ');

if (!token) {
return next(new AppError('Invalid token. Please login', 401));
}

if (!token) return next(new AppError('Invalid token. Please login', 401));
if (type.toLowerCase() !== 'bearer' || !token) {
return next(
new AppError('You are not logged in. Please login to get access', 401),
Expand Down
16 changes: 16 additions & 0 deletions be/src/middlewares/restrictTo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { RequestHandler } from 'express';
import AppError from '../utils/app-error';

const restrictTo = (...role: string[]) => {
const restrcitFn: RequestHandler = (req, res, next) => {
if (!role.includes(req.user.role)) {
return next(
new AppError('You do not have permission to perform this action', 403),
);
} else return next();
};

return restrcitFn;
};

export default restrictTo;

0 comments on commit 04769a5

Please sign in to comment.