Skip to content

Commit

Permalink
server side role based authentication added
Browse files Browse the repository at this point in the history
  • Loading branch information
sinanptm committed Sep 11, 2024
1 parent 47e2073 commit ed94faf
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 21 deletions.
16 changes: 11 additions & 5 deletions server/src/presentation/middlewares/AdminAuthMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { NextFunction, Response } from "express";
import ITokenService from "../../domain/interface/services/ITokenService";
import { CustomRequest, StatusCode } from "../../types";
import { CustomRequest, StatusCode, UserRole } from "../../types";
import logger from "../../utils/logger";

export default class AdminAuthMiddleware {
constructor(private tokenService: ITokenService) {}
constructor(private tokenService: ITokenService) { }

exec(req: CustomRequest, res: Response, next: NextFunction) {
try {
Expand All @@ -19,14 +19,20 @@ export default class AdminAuthMiddleware {
if (!token) {
return res.status(StatusCode.Unauthorized).json({ message: "Unauthorized: Access Token is missing" });
}
const { id, email } = this.tokenService.verifyAccessToken(token);
if (!id || !email) {
const { id, email, role } = this.tokenService.verifyAccessToken(token);
if (!id || !email || !role) {
logger.warn("Unauthorized: Invalid Access Token Attempt");
return res.status(StatusCode.Unauthorized).json({ message: "Unauthorized: Invalid Access Token" });
}


if (role !== UserRole.Admin) {
return res.status(StatusCode.Forbidden).json({ message: "Forbidden: Access restricted to admins" });
}
req.admin = { email, id };

console.log(role);


next();
} catch (error: any) {
if (error.message === "Token Expired") {
Expand Down
20 changes: 13 additions & 7 deletions server/src/presentation/middlewares/PatientAuthMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { NextFunction, Response } from "express";
import ITokenService from "../../domain/interface/services/ITokenService";
import { CustomRequest, StatusCode } from "../../types";
import { CustomRequest, StatusCode, UserRole } from "../../types";
import logger from "../../utils/logger";

export default class PatientAuthMiddleware {
constructor(private tokenService: ITokenService) {}
constructor(private tokenService: ITokenService) { }

exec(req: CustomRequest, res: Response, next: NextFunction) {
try {
Expand All @@ -22,11 +23,16 @@ export default class PatientAuthMiddleware {
return res.status(StatusCode.Unauthorized).json({ message: "Unauthorized: Access Token is missing" });
}

const decodedToken = this.tokenService.verifyAccessToken(token);
req.patient = {
email: decodedToken.email,
id: decodedToken.id,
};
const { email, id, role } = this.tokenService.verifyAccessToken(token);
if (!id || !email || !role) {
logger.warn("Unauthorized: Invalid Access Token Attempt");
return res.status(StatusCode.Unauthorized).json({ message: "Unauthorized: Invalid Access Token" });
}
if (role !== UserRole.Patient) {
return res.status(StatusCode.Forbidden).json({ message: "Forbidden: Access restricted to patients" });
}

req.patient = { email, id };
next();
} catch (error: any) {
if (error.message === "Token Expired") {
Expand Down
5 changes: 3 additions & 2 deletions server/src/use_case/admin/AuthenticationUseCase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import IEmailService from "../../domain/interface/services/IEmailService";
import ITokenService from "../../domain/interface/services/ITokenService";
import { IPasswordServiceRepository } from "../../domain/interface/services/IPasswordServiceRepository";
import { generateOTP } from "../../utils";
import { UserRole } from "../../types";
export default class AuthenticationUseCase {
constructor(
private adminRepository: IDoctorRepository,
Expand Down Expand Up @@ -41,7 +42,7 @@ export default class AuthenticationUseCase {
const admin = await this.adminRepository.findByEmailWithCredentials(email);
if (!admin) throw new Error("Not Found");

const accessToken = this.tokenService.createAccessToken(email, admin._id!);
const accessToken = this.tokenService.createAccessToken(email, admin._id!, UserRole.Admin);
const refreshToken = this.tokenService.createRefreshToken(email, admin._id!);

admin!.token = refreshToken;
Expand Down Expand Up @@ -77,7 +78,7 @@ export default class AuthenticationUseCase {
if (!admin) {
throw new Error("Unauthorized");
}
const accessToken = this.tokenService.createAccessToken(admin.email!, admin._id!);
const accessToken = this.tokenService.createAccessToken(admin.email!, admin._id!, UserRole.Admin);

return { accessToken };
}
Expand Down
8 changes: 4 additions & 4 deletions server/src/use_case/doctor/AuthenticationUseCase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import IEmailService from "../../domain/interface/services/IEmailService";
import ITokenService from "../../domain/interface/services/ITokenService";
import { IPasswordServiceRepository } from "../../domain/interface/services/IPasswordServiceRepository";
import { generateOTP } from "../../utils";
import { UserRole } from "../../types";

export default class AuthenticationUseCase {
constructor(
Expand Down Expand Up @@ -48,7 +49,7 @@ export default class AuthenticationUseCase {
if (!doctor) throw new Error("Unauthorized");

const refreshToken = this.tokenService.createRefreshToken(doctor?.email!, doctor?._id!);
const accessToken = this.tokenService.createAccessToken(doctor?.email!, doctor?._id!);
const accessToken = this.tokenService.createAccessToken(doctor?.email!, doctor?._id!, UserRole.Doctor);

doctor!.token = refreshToken;

Expand Down Expand Up @@ -128,14 +129,13 @@ export default class AuthenticationUseCase {
}

async refresh(token: string): Promise<{ accessToken: string }> {
const { id } = this.tokenService.verifyAccessToken(token);

const { id } = this.tokenService.verifyRefreshToken(token);
const doctor = await this.doctorRepository.findByID(id);
if (!doctor) throw new Error("Unauthorized");

if (doctor.isBlocked) throw new Error("Doctor is Blocked");

const accessToken = this.tokenService.createAccessToken(doctor.email!, doctor._id!);
const accessToken = this.tokenService.createAccessToken(doctor.email!, doctor._id!, UserRole.Doctor);

return { accessToken };
}
Expand Down
7 changes: 4 additions & 3 deletions server/src/use_case/patient/AuthenticationUseCase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import IEmailService from "../../domain/interface/services/IEmailService";
import { IPatient } from "../../domain/entities/IPatient";
import { IPasswordServiceRepository } from "../../domain/interface/services/IPasswordServiceRepository";
import { generateOTP } from "../../utils";
import { UserRole } from "../../types";

type TokensResponse = {
accessToken: string;
Expand Down Expand Up @@ -66,7 +67,7 @@ export default class AuthenticationUseCase {
if (patient.isBlocked) {
throw new Error("Patient is Blocked");
}
let accessToken = this.tokenService.createAccessToken(email, patient._id!);
let accessToken = this.tokenService.createAccessToken(email, patient._id!, UserRole.Patient);
let refreshToken = this.tokenService.createRefreshToken(email, patient._id!);

return { accessToken, refreshToken };
Expand Down Expand Up @@ -99,7 +100,7 @@ export default class AuthenticationUseCase {
if (patient && patient?.isBlocked) throw new Error("Unauthorized");

const refreshToken = this.tokenService.createRefreshToken(patient?.email!, patient?._id!);
const accessToken = this.tokenService.createAccessToken(patient?.email!, patient?._id!);
const accessToken = this.tokenService.createAccessToken(patient?.email!, patient?._id!, UserRole.Patient);

patient!.token = refreshToken;

Expand All @@ -118,7 +119,7 @@ export default class AuthenticationUseCase {

if (patient.isBlocked) throw new Error("Patient is Blocked");

const accessToken = this.tokenService.createAccessToken(patient.email!, patient._id!);
const accessToken = this.tokenService.createAccessToken(patient.email!, patient._id!, UserRole.Patient);

return { accessToken };
}
Expand Down

1 comment on commit ed94faf

@vercel
Copy link

@vercel vercel bot commented on ed94faf Sep 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.