Commit e4435f53 authored by Pasindu Bandara's avatar Pasindu Bandara

final commit for vulnerability scanning branch

parent d368635d
......@@ -115,8 +115,6 @@ export const getCompanyById = async (id) => {
}
};
export const getVulnerabilities = async (id) => {
try {
const company = await Company.findById(id);
......@@ -132,19 +130,29 @@ export const getVulnerabilities = async (id) => {
const results = [];
const config = {
headers: {
apikey: "57207422-e8b1-4e84-8ba3-7bc3029a14f8",
},
};
for (const tech of techinfoArray) {
const response = await axios.get(
`https://services.nvd.nist.gov/rest/json/cves/2.0/?keywordSearch=${tech}&lastModStartDate=2023-08-19T13:00:00.000%2B01:00&lastModEndDate=2023-09-03T13:36:00.000%2B01:00`
`https://services.nvd.nist.gov/rest/json/cves/2.0/?keywordSearch=${tech}&lastModStartDate=2023-08-19T13:00:00.000%2B01:00&lastModEndDate=2023-09-03T13:36:00.000%2B01:00`,
config
);
const vulnerabilities = response.data.vulnerabilities || [];
const vulnerabilitiesData = vulnerabilities.map((vuln) => {
const baseSeverity = vuln.cve?.metrics?.cvssMetricV31?.[0]?.cvssData?.baseSeverity || "none";
const baseSeverity =
vuln.cve?.metrics?.cvssMetricV31?.[0]?.cvssData?.baseSeverity ||
"none";
return {
id: vuln.cve ? vuln.cve.id : "none",
description: vuln.cve
? vuln.cve.descriptions.find((desc) => desc.lang === "en")?.value || "none"
? vuln.cve.descriptions.find((desc) => desc.lang === "en")?.value ||
"none"
: "none",
baseSeverity,
};
......@@ -166,6 +174,169 @@ export const getVulnerabilities = async (id) => {
}
};
// Function to get vulnerabilities by sorting date in the last 7 days
export const getVulnerabilitiesByLastSevenDays = async (id) => {
try {
const company = await Company.findById(id);
if (!company) {
throw new Error("Company not found");
}
const { frontend, backend, database, others, application } =
company.techinfo;
const techinfoArray = [frontend, backend, database, others, application];
const results = [];
// Calculate the start and end dates for the last 7 days
const endDate = new Date(); // Today's date
const startDate = new Date();
startDate.setDate(endDate.getDate() - 7); // 7 days ago
const config = {
headers: {
apikey: "57207422-e8b1-4e84-8ba3-7bc3029a14f8",
},
};
for (const tech of techinfoArray) {
const response = await axios.get(
`https://services.nvd.nist.gov/rest/json/cves/2.0/?keywordSearch=${tech}&lastModStartDate=${startDate.toISOString()}&lastModEndDate=${endDate.toISOString()}`,
config
);
const vulnerabilities = response.data.vulnerabilities || [];
const vulnerabilitiesData = vulnerabilities.map((vuln) => {
const baseSeverity =
vuln.cve?.metrics?.cvssMetricV31?.[0]?.cvssData?.baseSeverity ||
"none";
return {
id: vuln.cve ? vuln.cve.id : "none",
description: vuln.cve
? vuln.cve.descriptions.find((desc) => desc.lang === "en")?.value ||
"none"
: "none",
baseSeverity,
};
});
if (vulnerabilitiesData.length > 0) {
// If there are vulnerabilities, add the tech name and baseSeverity to the results
results.push({
tech,
vulnerabilities: vulnerabilitiesData,
count: vulnerabilitiesData.length,
});
} else {
// If there are no vulnerabilities, add the tech name with an empty array
results.push({
tech,
vulnerabilities: [],
count: vulnerabilitiesData.length,
});
}
}
return results;
} catch (error) {
console.log(error);
throw error;
}
};
// Function to get vulnerabilities for a specific day
export const getVulnerabilitiesForSpecificDay = async (id, specificDate) => {
try {
const company = await Company.findById(id);
if (!company) {
throw new Error("Company not found");
}
const { frontend, backend, database, others, application } =
company.techinfo;
const techinfoArray = [frontend, backend, database, others, application];
const results = [];
// Calculate the start and end dates for the last 7 days
const endDate = new Date(); // Today's date
const startDate = new Date();
startDate.setDate(endDate.getDate() - 1);
const config = {
headers: {
apikey: "57207422-e8b1-4e84-8ba3-7bc3029a14f8",
},
};
for (const tech of techinfoArray) {
const response = await axios.get(
`https://services.nvd.nist.gov/rest/json/cves/2.0/?keywordSearch=${tech}&lastModStartDate=${startDate.toISOString()}&lastModEndDate=${endDate.toISOString()}`,
config
);
const vulnerabilities = response.data.vulnerabilities || [];
const vulnerabilitiesData = await Promise.all(
vulnerabilities.map(async (vuln) => {
const baseSeverity =
vuln.cve?.metrics?.cvssMetricV31?.[0]?.cvssData?.baseSeverity ||
"none";
const formData = new FormData();
formData.append(
"severity",
vuln.cve
? vuln.cve.descriptions.find((desc) => desc.lang === "en")
?.value || "none"
: "none"
);
const serres = await axios.post(
"http://127.0.0.1:5000/severity",
formData
);
return {
id: vuln.cve ? vuln.cve.id : "none",
description: vuln.cve
? vuln.cve.descriptions.find((desc) => desc.lang === "en")
?.value || "none"
: "none",
baseSeverity,
secondApiseverity: serres.data.result, // Modify this as needed
};
})
);
if (vulnerabilitiesData.length > 0) {
// If there are vulnerabilities, add the tech name and baseSeverity to the results
results.push({
tech,
vulnerabilities: vulnerabilitiesData,
count: vulnerabilitiesData.length,
});
} else {
// If there are no vulnerabilities, add the tech name with an empty array
results.push({
tech,
vulnerabilities: [],
count: vulnerabilitiesData.length,
});
}
}
return results;
} catch (error) {
console.log(error);
throw error;
}
};
import Log from "../models/log-model.js";
import OTP from "../models/otp-model.js";
import User from "../models/user-model.js";
import { generateOTP } from "../utils/generateOTP.js";
......@@ -105,3 +106,13 @@ export const sendOTP = async ({ email, subject, message, duration = 1 }) => {
}
};
// get log data
export const getAllLogData = async () => {
try {
const logData = await Log.find();
return logData;
} catch (error) {
throw error;
}
};
import Log from "../models/log-model.js";
import User from "../models/user-model.js";
import { createToken } from "../utils/create-token.js";
import { hashData, verifyHashedData } from "../utils/hash-data.js";
export const authenticateUser = async (data) => {
try {
const { email, password } = data;
const { email, password, device, logTime } = data;
const fetchedUser = await User.findOne({
email,
});
......@@ -26,6 +27,17 @@ export const authenticateUser = async (data) => {
// assign user token
fetchedUser.token = token;
const newLog = new Log({
userId: fetchedUser._id,
device,
logTime,
username: fetchedUser.username,
});
fetchedUser.device = device;
fetchedUser.logTime = logTime;
console.log({ logTime });
await newLog.save();
console.log({ logTime });
return fetchedUser;
} catch (error) {
throw error; // Rethrow the error to be caught by the calling function
......@@ -66,7 +78,7 @@ export const createNewUser = async (data) => {
export const faceidChangeStatus = async (data) => {
try {
const { userid, isFaceid } = data;
console.log({userid})
console.log({ userid });
const user = await User.findByIdAndUpdate(
userid,
......@@ -79,3 +91,92 @@ export const faceidChangeStatus = async (data) => {
throw error;
}
};
export const updateProfile = async (userId, data) => {
try {
console.log({ data });
// Define the fields that are allowed to be updated
const allowedFields = {
location: {
long: data.location.long,
lang: data.location.lang,
},
companyId: data.companyId,
device: data.device,
shift: data.shift,
isVerified: data.isVerified,
companyid: data.companyid,
isFaceid: data.isFaceid,
timeShift: data.timeShift,
name : data.name,
username: data.username,
};
// Find the user by their ID
const user = await User.findById(userId);
console.log({ user });
if (!user) {
throw Error("User not found");
}
// Update the allowed fields
Object.assign(user, allowedFields);
// Save the updated user profile
const updatedUser = await user.save();
return updatedUser;
} catch (error) {
console.log(error);
throw error;
}
};
export const usernameNameUpdate = async (userId, data) => {
try{
const allowedFields = {
username: data.username,
name : data.name,
shift: data.shift,
timeShift: data.shift,
}
const user = await User.findById(userId);
console.log({ user });
if (!user) {
throw Error("User not found");
}
Object.assign(user, allowedFields);
const updatedUser = await user.save();
return updatedUser;
}catch{
}
}
export const getUserById = async (userId) => {
try {
const user = await User.findById(userId); // Use the User model to find a user by ID
if (!user) {
throw new Error("User not found"); // Handle the case where the user is not found
}
return user; // Return the user details
} catch (error) {
console.error("Error fetching user by ID:", error);
throw error; // Rethrow the error for handling it elsewhere
}
};
import mongoose from "mongoose";
const logSchema = new mongoose.Schema(
{
userId: {
type: String,
required: true,
},
device: {
type: String,
},
logTime: {
type: Date,
},
username: {
type: String,
},
email: {
type: String,}
},
{
collection: "log",
}
);
const Log = mongoose.model("Log", logSchema);
export default Log;
import mongoose from "mongoose";
const locationSchema = mongoose.Schema({
long: {
type: String,
},
lang: {
type: String,
},
});
const userSchema = mongoose.Schema(
{
name: {
type: String,
},
username:{
username: {
type: String,
},
email: {
type: String,
unique: true,
},
location: {
type: String,
},
location: locationSchema,
password: {
type: String,
},
......@@ -36,9 +43,15 @@ const userSchema = mongoose.Schema(
companyid: {
type: String,
},
isFaceid:{
isFaceid: {
type: Boolean,
default: false,
},
timeShift: {
type: String,
},
logTime: {
type: String,
}
},
{
......
......@@ -15,6 +15,7 @@
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-rate-limit": "^7.0.0",
"jsonwebtoken": "^9.0.1",
"mongoose": "^7.4.0",
"nodemailer": "^6.9.4",
......@@ -525,6 +526,17 @@
"node": ">= 0.10.0"
}
},
"node_modules/express-rate-limit": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.0.0.tgz",
"integrity": "sha512-zKMQ9meikj7j3ILeVvHIaBejAYljgDBtGuCfbzNS2d0VCW4s68ONdtEhBJnOGW/Ty1wGeNXgC4m/C1bBUIX0LA==",
"engines": {
"node": ">= 16"
},
"peerDependencies": {
"express": "^4 || ^5"
}
},
"node_modules/express/node_modules/body-parser": {
"version": "1.20.1",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz",
......
......@@ -18,6 +18,7 @@
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-rate-limit": "^7.0.0",
"jsonwebtoken": "^9.0.1",
"mongoose": "^7.4.0",
"nodemailer": "^6.9.4",
......
......@@ -5,7 +5,10 @@ import {
createTechnicalInformation,
getCompanyById,
getVulnerabilities,
getVulnerabilitiesByLastSevenDays,
getVulnerabilitiesForSpecificDay,
} from "../controllers/company-controller.js";
import rateLimit from "express-rate-limit";
const router = Router();
router.post("/createcompanybasic/:id", async (req, res) => {
......@@ -105,4 +108,34 @@ router.post("/vulnurabilities/:id", async (req, res) => {
}
});
router.post("/vulnurabilitiesbyweek/:id", async (req, res) => {
try {
const companyId = req.params.id;
const createCompany = await getVulnerabilitiesByLastSevenDays(
companyId,
);
res.status(200).json(createCompany);
} catch (error) {
res.status(400).json(error.message);
}
});
const limiter = rateLimit({
windowMs: 60 * 200, // 15 minutes
max: 100, // Max requests per windowMs
message: 'Too many requests from this IP, please try again later.',
});
router.post("/vulnurabilitiesbyday/:id",limiter, async (req, res) => {
try {
const companyId = req.params.id;
const createCompany = await getVulnerabilitiesForSpecificDay(
companyId,
);
res.status(200).json(createCompany);
} catch (error) {
res.status(400).json(error.message);
}
});
export { router as companyRouter };
import { Router } from "express";
import { sendOTP, verifyOTP } from "../controllers/otp-controller.js";
import {
getAllLogData,
sendOTP,
verifyOTP,
} from "../controllers/otp-controller.js";
const router = Router();
router.post("/verify", async (req, res) => {
......@@ -29,6 +33,13 @@ router.post("/", async (req, res) => {
}
});
router.get("/getlogdata", async (req, res) => {
try {
const getalllogData = await getAllLogData();
res.status(200).json(getalllogData);
} catch (error) {
console.log(error);
}
});
export { router as otpRouter };
......@@ -3,13 +3,16 @@ import {
authenticateUser,
createNewUser,
faceidChangeStatus,
getUserById,
updateProfile,
usernameNameUpdate,
} from "../controllers/user-controller.js";
import { verifyToken } from "../middleware/auth.js";
const router = Router();
router.post("/signup", async (req, res) => {
let { name, email, password,username } = req.body;
let { name, email, password, username } = req.body;
name = name.trim();
email = email.trim();
......@@ -28,7 +31,7 @@ router.post("/signup", async (req, res) => {
name,
email,
password,
username
username,
});
res.status(200).json(newUser);
}
......@@ -39,14 +42,19 @@ router.post("/signup", async (req, res) => {
router.post("/", async (req, res) => {
try {
let { email, password } = req.body;
let { email, password, device, logTime } = req.body;
email = email.trim();
password = password.trim();
if (!(email && password)) {
throw new Error("Empty credentials supplied!"); // Create an Error object
}
const authenticatedUserss = await authenticateUser({ email, password });
const authenticatedUserss = await authenticateUser({
email,
password,
device,
logTime,
});
res.status(200).json(authenticatedUserss);
} catch (error) {
console.log({ error });
......@@ -54,7 +62,6 @@ router.post("/", async (req, res) => {
}
});
// protected route
router.get("/private_data", verifyToken, (req, res) => {
res
......@@ -62,16 +69,15 @@ router.get("/private_data", verifyToken, (req, res) => {
.send("Youre in the private territory of ${req.currentUser.email}");
});
router.post("/isfaceid", async (req, res) => {
try {
const { userid, isFaceid } = req.body;
console.log({ userid, isFaceid })
console.log({ userid, isFaceid });
// Call the faceidChangeStatus function to update the user's isFaceid status
const updatedUser = await faceidChangeStatus({ userid, isFaceid });
console.log({ updatedUser })
console.log({ updatedUser });
// Return the updated user
res.json(updatedUser);
} catch (error) {
......@@ -80,10 +86,57 @@ router.post("/isfaceid", async (req, res) => {
}
});
router.put("/profile/:userId", async (req, res) => {
const userId = req.params.userId;
const data = req.body;
try {
// Ensure that the user exists
// const existingUser = await User.findById(userId);
// console.log({existingUser})
// if (!existingUser) {
// throw Error("User not found");
// }
// Call the updateProfile function to update the user's profile
const updatedUser = await updateProfile(userId, data);
res.status(200).json(updatedUser);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
router.put("/profileonlyusernameandname/:userId", async (req, res) => {
const userId = req.params.userId;
const data = req.body;
try {
// Ensure that the user exists
// const existingUser = await User.findById(userId);
// console.log({existingUser})
// if (!existingUser) {
// throw Error("User not found");
// }
// Call the updateProfile function to update the user's profile
const updatedUser = await usernameNameUpdate(userId, data);
res.status(200).json(updatedUser);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
router.get("/getuserdetails/:id", async (req, res) => {
try {
const userDetails = await getUserById(req.params.id);
res.status(200).json(userDetails);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
export { router as userRouter };
/** @type {import('next').NextConfig} */
const nextConfig = {
images:{
domains: ['images.unsplash.com','static.vecteezy.com']
}
}
images: {
domains: ["images.unsplash.com", "static.vecteezy.com"],
},
};
module.exports = nextConfig
module.exports = nextConfig;
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -9,14 +9,24 @@
"lint": "next lint"
},
"dependencies": {
"@react-google-maps/api": "^2.19.2",
"@types/node": "20.4.2",
"@types/react": "18.2.15",
"@types/react-dom": "18.2.7",
"@uppy/core": "^3.5.0",
"@uppy/dashboard": "^3.5.2",
"@uppy/drag-drop": "^3.0.3",
"@uppy/file-input": "^3.0.3",
"@uppy/progress-bar": "^3.0.3",
"@uppy/react": "^3.1.3",
"@uppy/webcam": "^3.3.2",
"@uppy/xhr-upload": "^3.4.0",
"autoprefixer": "10.4.14",
"axios": "^1.5.0",
"chart.js": "^4.3.3",
"faker": "^6.6.6",
"fs": "^0.0.1-security",
"debug": "^4.3.4",
"faker": "^5.5.3",
"google-map-react": "^2.2.1",
"html2canvas": "^1.4.1",
"lodash": "^4.17.21",
"next": "^13.4.19",
......@@ -27,13 +37,22 @@
"react-chartjs-2": "^5.2.0",
"react-dom": "18.2.0",
"react-gauge-chart": "^0.4.1",
"react-record-webcam": "^0.0.18",
"react-media-recorder": "^1.6.6",
"react-no-ssr": "^1.1.0",
"react-record-webcam": "0.0.14",
"react-toastify": "^9.1.3",
"react-video-recorder": "^3.19.4",
"react-webcam": "^7.1.1",
"recordrtc": "^5.6.2",
"styled-components": "^6.0.8",
"supports-color": "^8.1.1",
"tailwindcss": "3.3.3",
"typescript": "5.1.6"
},
"devDependencies": {
"@faker-js/faker": "^8.0.2",
"@types/react-gauge-chart": "^0.4.0"
"@types/react-gauge-chart": "^0.4.0",
"@types/react-no-ssr": "^1.1.3",
"@types/react-video-recorder": "^3.19.0"
}
}
"use client";
import {
createContext,
useContext,
Dispatch,
SetStateAction,
useState,
ReactNode,
} from "react";
interface TechData {
value: string;
frontend: string;
backend: string;
database: string;
application: string;
others: string;
webAppType: string;
[key: string]: string; // Index signature for any string key
}
interface QuizResults {
expectedAnswer: string;
marks: number;
question: string;
recommendation: string;
status: string;
userAnswer: string;
}
interface ContextProps {
name: string;
setName: Dispatch<SetStateAction<string>>;
username: string;
setUsername: Dispatch<SetStateAction<string>>;
email: string;
setEmail: Dispatch<SetStateAction<string>>;
password: string;
setPassword: Dispatch<SetStateAction<string>>;
terms: boolean;
setTerms: Dispatch<SetStateAction<boolean>>;
techData: TechData;
setTechData: (newTechData: TechData) => void;
quizResults: QuizResults[];
setQuizResults: Dispatch<SetStateAction<QuizResults[]>>;
activeItem: string;
setActiveItem: Dispatch<SetStateAction<string>>;
netdata: any[];
setNetData: React.Dispatch<React.SetStateAction<any[]>>;
}
const GlobalContext = createContext<ContextProps>({
name: "",
setName: (): string => "",
username: "",
setUsername: (): string => "",
email: "",
setEmail: (): string => "",
password: "",
setPassword: (): string => "",
terms: false,
setTerms: (): boolean => false,
techData: {
value: "",
frontend: "",
backend: "",
database: "",
application: "",
others: "",
webAppType: "",
},
setTechData: (newTechData: TechData) => {},
quizResults: [],
setQuizResults: (): QuizResults[] => [],
activeItem: "",
setActiveItem: (): string => "",
netdata: [],
setNetData: () => {},
});
export const GlobalContextProvider = ({
children,
}: {
children: ReactNode;
}) => {
const [name, setName] = useState("");
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [terms, setTerms] = useState(false);
const [techData, setTechData] = useState<TechData>({
value: "",
frontend: "",
backend: "",
database: "",
application: "",
others: "",
webAppType: "",
});
const [activeItem, setActiveItem] = useState("");
const [quizResults, setQuizResults] = useState<QuizResults[]>([]);
const [netdata, setNetData] = useState<any[]>([]);
return (
<GlobalContext.Provider
value={{
name,
setName,
username,
setUsername,
email,
setEmail,
password,
setPassword,
terms,
setTerms,
techData,
setTechData,
quizResults,
setQuizResults,
activeItem,
setActiveItem,
netdata,
setNetData,
}}
>
{children}
</GlobalContext.Provider>
);
};
export const useGlobalContext = () => useContext(GlobalContext);
......@@ -95,7 +95,7 @@ export default function BasicInfo() {
{/* Input fields for basic information */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-5 pl-10 pr-10 w-full">
<div className="flex flex-col">
<label className=" mb-3">Application</label>
<label className=" mb-3">Application URL</label>
<input
name="appicationURL"
type="text"
......
import Image from "next/image";
export default function Navbar() {
return (
<div className="flex flex-col sm:flex-row w-full mb-5">
{/* Logo */}
<div className="flex flex-grow justify-center items-center sm:justify-start">
<Image
src="/images/customerOnboarding/webguardin-logo.png"
width={250}
height={150}
alt="logo"
/>
</div>
</div>
);
}
"use client";
import { useGlobalContext } from "@/app/Context/store";
import axios from "axios";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
export default function Navigation() {
const router = useRouter();
const [appStatus, setAppStatus] = useState("");
const [loadingStatus, setLoadingStatus] = useState(true);
const { activeItem, setActiveItem } = useGlobalContext();
useEffect(() => {
handleLogout();
handleAppStatus();
}, []);
const handleAppStatus = async () => {
const response = await axios.get("http://localhost:8000/net-work-status", {
params: {
enter_addr: localStorage.getItem("ipAddress"),
},
headers: {
accept: "application/json",
},
});
setLoadingStatus(false);
setAppStatus(response.data.hosts[0][1]);
console.log(response.data.hosts[0][1]);
};
// check if the user is logged in or not using local storage
const handleLogout = () => {
if (localStorage.getItem("userid") === null) {
router.push("/auth/login");
} else {
null;
}
};
// Function to conditionally render the active item
if (activeItem === "vulnerability") {
router.push("/dashboard/vulnerability");
} else if (activeItem === "risk") {
router.push("/dashboard/risk");
} else if (activeItem === "tools") {
router.push("/dashboard/tools");
} else if (activeItem === "profile") {
router.push("/dashboard/profile");
}
return (
<div className="flex flex-col sm:flex-row w-full mb-10">
{/* Logo */}
<div className="flex flex-grow justify-center items-center sm:justify-start pr-10">
<Image
src="/images/customerOnboarding/webguardin-logo.png"
width={250}
height={150}
alt="logo"
className="ml-10"
/>
{loadingStatus ? (
// loaading animation
<div className="flex flex-row justify-center items-center ml-10">
<div className="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-purple-500"></div>
</div>
) : (
// app status
<div className="flex flex-row justify-center items-center ml-10">
<p className="text-sm sm:text-2xl font-semibold text-[#B200B6]">
App Status :{" "}
</p>
{/* app status with emoji */}
{appStatus === "up" ? (
<p className="text-sm sm:text-2xl font-semibold text-[#00FF00]">
{" "}
UP ⬆️
</p>
) : (
<p className="text-sm sm:text-2xl font-semibold text-[#FF0000]">
{" "}
DOWN ⬇️
</p>
)}
</div>
)}
</div>
{/* Navigation items */}
<div className="flex flex-row justify-center align-middle items-center px-5 sm:px-10 bg-[#FEDDFF] rounded-lg sm:rounded-bl-3xl">
{/* Vulnerability Dashboard item */}
<p
onClick={() => setActiveItem("vulnerability")}
className={`mr-10 font-semibold text-sm sm:text-2xl ${
activeItem === "vulnerability" ? "text-[#ee39f1]" : "text-[#B200B6]"
} hover:text-[#db33de] cursor-pointer`}
>
VULNERABILITY
</p>
{/* Risk Dashboard item */}
<p
onClick={() => setActiveItem("risk")}
className={`mr-10 font-semibold text-sm sm:text-2xl ${
activeItem === "risk" ? "text-[#ee39f1]" : "text-[#B200B6]"
} hover:text-[#db33de] cursor-pointer`}
>
RISK
</p>
{/* Tools */}
<p
onClick={() => setActiveItem("tools")}
className={`mr-10 font-semibold text-sm sm:text-2xl ${
activeItem === "tools" ? "text-[#ee39f1]" : "text-[#B200B6]"
} hover:text-[#db33de] cursor-pointer`}
>
TOOLS
</p>
{/* Profile item */}
<p
onClick={() => setActiveItem("profile")}
className={`mr-10 font-semibold text-sm sm:text-2xl ${
activeItem === "profile" ? "text-[#ee39f1]" : "text-[#B200B6]"
} hover:text-[#db33de] cursor-pointer`}
>
PROFILE
</p>
</div>
</div>
);
}
// Import required modules and components
"use client";
import Image from "next/image";
import Profile from "./profile/page";
import { useEffect, useState } from "react";
import Vulnerability from "./vulnerability/page";
import Risk from "./risk/page";
import axios from "axios";
// Define the Dashboard component
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import Navigation from "./components/navigation/page";
export default function Dashboard() {
// State to manage active dashboard item
const [activeItem, setActiveItem] = useState("vulnerability");
const [appStatus, setAppStatus] = useState("");
const [loadingStatus, setLoadingStatus] = useState(true);
const router = useRouter();
useEffect(() => {
handleAppStatus();
}, []);
const handleAppStatus = async () => {
const response = await axios.get("http://localhost:8000/net-work-status", {
params: {
enter_addr: "128.210.13.35",
},
headers: {
accept: "application/json",
},
});
setLoadingStatus(false);
setAppStatus(response.data.hosts[0][1]);
console.log(response.data.hosts[0][1]);
};
// Function to conditionally render the active item
function SetRender() {
if (activeItem === "vulnerability") {
return <Vulnerability />;
} else if (activeItem === "risk") {
return <Risk />;
} else {
return <Profile />;
}
}
router.push("/dashboard/vulnerability");
}, [])
// Render the Dashboard UI
return (
<div>
{/* Navigation bar */}
<div className="flex flex-col sm:flex-row w-full mb-10">
{/* Logo */}
<div className="flex flex-grow justify-center items-center sm:justify-start pr-10">
<Image
src="/images/customerOnboarding/webguardin-logo.png"
width={250}
height={150}
alt="logo"
className="ml-10"
/>
{loadingStatus ?
// loaading animation
<div className="flex flex-row justify-center items-center ml-10">
<div className="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-purple-500"></div>
</div>
:
// app status
<div className="flex flex-row justify-center items-center ml-10">
<p className="text-sm sm:text-2xl font-semibold text-[#B200B6]">App Status : </p>
{/* app status with emoji */}
{appStatus === "up" ?
<p className="text-sm sm:text-2xl font-semibold text-[#00FF00]"> UP ⬆️</p>
:
<p className="text-sm sm:text-2xl font-semibold text-[#FF0000]"> DOWN ⬇️</p>
}
</div>
}
{/* <p className="">App Status : DOWN ⬇️</p> */}
</div>
{/* Navigation items */}
<div className="flex flex-row justify-center align-middle items-center px-5 sm:px-10 bg-[#FEDDFF] rounded-lg sm:rounded-bl-3xl">
{/* Vulnerability Dashboard item */}
<p
onClick={() => setActiveItem("vulnerability")}
className={`mr-10 font-semibold text-sm sm:text-2xl ${
activeItem === "vulnerability"
? "text-[#ee39f1]"
: "text-[#B200B6]"
} hover:text-[#db33de] cursor-pointer`}
>
VULNERABILITY DASHBOARD
</p>
{/* Risk Dashboard item */}
<p
onClick={() => setActiveItem("risk")}
className={`mr-10 font-semibold text-sm sm:text-2xl ${
activeItem === "risk" ? "text-[#ee39f1]" : "text-[#B200B6]"
} hover:text-[#db33de] cursor-pointer`}
>
RISK DASHBOARD
</p>
{/* Profile item */}
<p
onClick={() => setActiveItem("profile")}
className={`mr-10 font-semibold text-sm sm:text-2xl ${
activeItem === "profile" ? "text-[#ee39f1]" : "text-[#B200B6]"
} hover:text-[#db33de] cursor-pointer`}
>
PROFILE
</p>
</div>
</div>
{/* Render the active dashboard item */}
<SetRender />
{/* <SetRender /> */}
</div>
);
}
"use client";
import Image from "next/image";
import { useRouter } from "next/navigation";
export default function Plugins() {
// Router instance for navigation
const router = useRouter();
const handleBackToHome = () => {
router.push("/dashboard");
};
return (
<div>
<div className="flex flex-col">
<button
className="border-[#B200B6] border-solid border-2 text-[#B200B6] bg-[#fdcdfc] hover:bg-[#f0f0f0] w-40 m-4 rounded-lg px-4 py-2"
onClick={handleBackToHome}
>
Back
</button>
<p className="ml-4 text-sm">Dashboard/ Plugins</p>
</div>
<div>
{/* 05 cards for plugins */}
<div className="grid grid-rows-5 sm:grid-cols-3 gap-4 mx-4 mt-6">
<div className="rounded-lg bg-[#F4F4F4] hover:bg-[#ffffff] hover:shadow-2xl p-5">
{/* plugin details with an image */}
<div className="flex flex-col">
<div className="flex flex-row justify-between">
<div className="flex flex-col">
{/* image */}
<div className="rounded-md">
<Image
src="/images/login/loginbg.jpg"
width={500}
height={500}
alt="Picture of the author"
/>
</div>
<p className="text-lg my-4">Security Header Configurations</p>
<p className="text-sm">
You need to integrate this middleware into your Flask
application. Define your routes and other application logic
below the <i> app.run() </i>line. The <i>flask-talisman </i>
library will automatically add security headers to your
responses based on the defined policy.
</p>
</div>
</div>
</div>
{/* button */}
<div className="flex flex-row justify-end mt-4">
<button
className="bg-[#B200B6] hover:bg-[#960f98] text-white w-40 rounded-full px-4 py-2"
onClick={() => {
window.open(
"http://localhost:3000/plugins/Security_Header_Configurations.pdf"
);
}}
>
Download
</button>
</div>
</div>
<div className="rounded-lg bg-[#F4F4F4] hover:bg-[#ffffff] hover:shadow-2xl p-5">
{/* plugin details with an image */}
<div className="flex flex-col">
<div className="flex flex-row justify-between">
<div className="flex flex-col">
{/* image */}
{/* <img src="/images/login/loginbg.jpg" alt="" className="h-9" /> */}
<div className="rounded-md">
<Image
src="/images/login/loginbg.jpg"
width={500}
height={500}
alt="Picture of the author"
/>
</div>
<p className="text-lg my-4">
Access Control and Authorization
</p>
<p className="text-sm">
This is a Python script that creates a web application using
the Flask framework, which is commonly used to build
websites. The purpose of this script is to set up a basic
web application with user authentication and access control.
</p>
</div>
</div>
{/* button */}
<div className="flex flex-row justify-end mt-4">
<button
className="bg-[#B200B6] hover:bg-[#960f98] text-white w-40 rounded-full px-4 py-2"
onClick={() => {
window.open(
"http://localhost:3000/plugins/Access_Control_and_Authorization.pdf"
);
}}
>
Download
</button>
</div>
</div>
</div>
<div className="rounded-lg bg-[#F4F4F4] hover:bg-[#ffffff] hover:shadow-2xl p-5">
{/* plugin details with an image */}
<div className="flex flex-col">
<div className="flex flex-row justify-between">
<div className="flex flex-col">
{/* image */}
{/* <img src="/images/login/loginbg.jpg" alt="" className="h-9" /> */}
<div className="rounded-md">
<Image
src="/images/login/loginbg.jpg"
width={500}
height={500}
alt="Picture of the author"
/>
</div>
<p className="text-lg my-4">
Input Validation and Sanitization
</p>
<p className="text-sm">
This Python script, used in a web app, validates and secures
incoming user data. It checks data like usernames and emails
for correctness and safety, sending error messages if
necessary. This ensures only valid data enters the app,
enhancing security and data integrity.
</p>
</div>
</div>
{/* button */}
<div className="flex flex-row justify-end mt-4">
<button className="bg-[#B200B6] hover:bg-[#960f98] text-white w-40 rounded-full px-4 py-2"
onClick={() => {
window.open(
"http://localhost:3000/plugins/Input_Validation_and_Sanitization.pdf"
);
}}
>
Download
</button>
</div>
</div>
</div>
<div className="rounded-lg bg-[#F4F4F4] hover:bg-[#ffffff] hover:shadow-2xl p-5">
{/* plugin details with an image */}
<div className="flex flex-col">
<div className="flex flex-row justify-between">
<div className="flex flex-col">
{/* image */}
{/* <img src="/images/login/loginbg.jpg" alt="" className="h-9" /> */}
<div className="rounded-md">
<Image
src="/images/login/loginbg.jpg"
width={500}
height={500}
alt="Picture of the author"
/>
</div>
<p className="text-lg my-4">Plugin Name</p>
<p className="text-sm">
Lorem ipsum dolor sit, amet consectetur adipisicing elit.
Nulla accusantium similique laudantium saepe necessitatibus
magni consequatur amet reiciendis totam non dolores quisquam
vitae sapiente quo, obcaecati aliquam culpa nobis fuga.
</p>
</div>
</div>
{/* button */}
<div className="flex flex-row justify-end mt-4">
<button className="bg-[#B200B6] hover:bg-[#960f98] text-white w-40 rounded-full px-4 py-2">
Download
</button>
</div>
</div>
</div>
<div className="rounded-lg bg-[#F4F4F4] hover:bg-[#ffffff] hover:shadow-2xl p-5">
{/* plugin details with an image */}
<div className="flex flex-col">
<div className="flex flex-row justify-between">
<div className="flex flex-col">
{/* image */}
{/* <img src="/images/login/loginbg.jpg" alt="" className="h-9" /> */}
<div className="rounded-md">
<Image
src="/images/login/loginbg.jpg"
width={500}
height={500}
alt="Picture of the author"
/>
</div>
<p className="text-lg my-4">Plugin Name</p>
<p className="text-sm">
Lorem ipsum dolor sit, amet consectetur adipisicing elit.
Nulla accusantium similique laudantium saepe necessitatibus
magni consequatur amet reiciendis totam non dolores quisquam
vitae sapiente quo, obcaecati aliquam culpa nobis fuga.
</p>
</div>
</div>
{/* button */}
<div className="flex flex-row justify-end mt-4">
<button className="bg-[#B200B6] hover:bg-[#960f98] text-white w-40 rounded-full px-4 py-2">
Download
</button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
This diff is collapsed.
"use client";
import { useRouter } from "next/navigation";
export default function VulnerabilityReport() {
const router = useRouter();
const handleBackToHome = () => {
router.push("/dashboard");
};
// net data
const netData: any[] = JSON.parse(localStorage.getItem("netData") || "[]");
// spider data
const spiderData: any[] = JSON.parse(
localStorage.getItem("spiderData") || "[]"
);
// getInfo data
const getInfo: any[] = JSON.parse(localStorage.getItem("getInfo") || "[]");
//vulnerability data
const vulnData: any[] = JSON.parse(localStorage.getItem("vulnData") || "[]");
return (
<div className="m-10">
<div className="flex flex-row">
<button
className="border-[#B200B6] border-solid border-2 text-[#B200B6] bg-[#fdcdfc] hover:bg-[#f0f0f0] w-40 m-4 rounded-lg px-4 py-2"
onClick={handleBackToHome}
>
Back
</button>
<button
className="bg-[#B200B6] hover:bg-[#960f98] text-white rounded-lg px-4 py-2 mt-5 ml-10"
onClick={window.print}
>
Generate Report
</button>
</div>
<div className="flex flex-col">
<div>
<div className="rounded-lg bg-[#F4F4F4] hover:bg-[#f5f4f4a5] hover:shadow-lg p-5">
{/*center title */}
<div className="flex flex-row">
<p className="text-xl font-semibold mb-4 text-[#B200B6]">
NET-SCAN
</p>
</div>
{/* button named Run Net-Scan with loadingNet */}
<div className="flex flex-col">
{/* List down all ports and state in table*/}
<div className="flex flex-col mt-5">
<div className="grid grid-cols-2 gap-5 w-fit">
{/* port and state table */}
<div className="flex flex-row">
<p className="text-lg font-semibold text-[#B200B6]">PORT</p>
</div>
<div className="flex flex-row">
<p className="text-lg font-semibold text-[#B200B6]">
STATE
</p>
</div>
</div>
<div>
{/* app-index.js:31 Warning: Encountered two children with the same key, `[object Object]`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version. */}
{netData.map((item, index) => (
<div
key={index}
className="grid grid-cols-2 gap-5 w-fit"
>
<div className="flex flex-row">
<p className="text-lg font-semibold text-[#B200B6]">
{item["port"]}
</p>
</div>
<div className="flex flex-row">
<p className="text-lg font-semibold text-[#B200B6]">
{item["state"]}
</p>
</div>
</div>
))}
</div>
{/* port and state table data */}
</div>
</div>
</div>
</div>
{/* spider_results list card*/}
<div className="rounded-lg bg-[#F4F4F4] hover:bg-[#f5f4f4a5] hover:shadow-lg p-5">
<p className="text-lg font-semibold mb-4 text-[#B200B6]">
SPIDER RESULTS
</p>
<div className="flex flex-col">
{/* isloading or spider results map */}
<div>
{/* spider results map */}
{spiderData.map((item, index) => (
<p key={index} className="col-span-5">
{item}
</p>
))}
</div>
</div>
</div>
{/* get-info list table cweid | description | risk*/}
<div className="rounded-lg bg-[#F4F4F4] hover:bg-[#f5f4f4a5] hover:shadow-lg p-5 mt-4">
<p className="text-lg font-semibold mb-4 text-[#B200B6]">
GET-INFO RESULTS
</p>
<div className="flex flex-col">
{/* isloading or get-info map */}
<div className="flex flex-col">
<div className="overflow-x-auto sm:mx-0.5 lg:mx-0.5">
<div className="py-2 inline-block min-w-full sm:px-6 lg:px-8">
<div className="overflow-hidden">
<table className="min-w-full">
<thead className="bg-white border-b">
<tr>
<th
scope="col"
className="text-sm font-medium text-gray-900 px-6 py-4 text-left"
>
CWEID
</th>
<th
scope="col"
className="text-sm font-medium text-gray-900 px-6 py-4 text-left"
style={{ maxWidth: "300px" }} // Set max-width for DESCRIPTION column
>
DESCRIPTION
</th>
<th
scope="col"
className="text-sm font-medium text-gray-900 px-6 py-4 text-left"
>
RISK
</th>
</tr>
</thead>
<tbody>
{/* get info map */}
{getInfo.map((item, index) => (
<tr key={index} className="bg-white border-b">
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{item["cweid"]}
</td>
<td
className="text-sm text-gray-900 font-light px-6 py-4 whitespace-wrap" // Apply 'whitespace-wrap' class to enable text wrapping
>
{item["description"]}
</td>
<td
className={`text-sm font-bold px-6 py-4 whitespace-nowrap ${
item["risk"] === "Critical"
? "bg-[#800000]"
: item["risk"] === "High"
? "bg-[#FF0000]"
: item["risk"] === "Medium"
? "bg-[#FFA500]"
: item["risk"] === "Low"
? "bg-[#FFFF00]"
: item["risk"] === "Informational"
? "bg-[#0000FF]"
: ""
}`}
>
{item["risk"]}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
......@@ -23,6 +23,6 @@
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "src/app/auth/faceDetection/videoCapture/page.jsx"],
"exclude": ["node_modules"]
}
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N802" />
</list>
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="52">
<item index="0" class="java.lang.String" itemvalue="protobuf" />
<item index="1" class="java.lang.String" itemvalue="threadpoolctl" />
<item index="2" class="java.lang.String" itemvalue="pydivert" />
<item index="3" class="java.lang.String" itemvalue="h11" />
<item index="4" class="java.lang.String" itemvalue="MarkupSafe" />
<item index="5" class="java.lang.String" itemvalue="dlib" />
<item index="6" class="java.lang.String" itemvalue="certifi" />
<item index="7" class="java.lang.String" itemvalue="PyAudio" />
<item index="8" class="java.lang.String" itemvalue="passlib" />
<item index="9" class="java.lang.String" itemvalue="SpeechRecognition" />
<item index="10" class="java.lang.String" itemvalue="pyperclip" />
<item index="11" class="java.lang.String" itemvalue="python-owasp-zap-v2.4" />
<item index="12" class="java.lang.String" itemvalue="Werkzeug" />
<item index="13" class="java.lang.String" itemvalue="cryptography" />
<item index="14" class="java.lang.String" itemvalue="reportlab" />
<item index="15" class="java.lang.String" itemvalue="click" />
<item index="16" class="java.lang.String" itemvalue="wsproto" />
<item index="17" class="java.lang.String" itemvalue="contourpy" />
<item index="18" class="java.lang.String" itemvalue="fonttools" />
<item index="19" class="java.lang.String" itemvalue="regex" />
<item index="20" class="java.lang.String" itemvalue="urwid" />
<item index="21" class="java.lang.String" itemvalue="matplotlib" />
<item index="22" class="java.lang.String" itemvalue="charset-normalizer" />
<item index="23" class="java.lang.String" itemvalue="pypiwin32" />
<item index="24" class="java.lang.String" itemvalue="pyfiglet" />
<item index="25" class="java.lang.String" itemvalue="msgpack" />
<item index="26" class="java.lang.String" itemvalue="freetype-py" />
<item index="27" class="java.lang.String" itemvalue="pyttsx3" />
<item index="28" class="java.lang.String" itemvalue="h2" />
<item index="29" class="java.lang.String" itemvalue="numpy" />
<item index="30" class="java.lang.String" itemvalue="pyasn1" />
<item index="31" class="java.lang.String" itemvalue="pyOpenSSL" />
<item index="32" class="java.lang.String" itemvalue="ruamel.yaml.clib" />
<item index="33" class="java.lang.String" itemvalue="wikipedia" />
<item index="34" class="java.lang.String" itemvalue="djangorestframework" />
<item index="35" class="java.lang.String" itemvalue="itsdangerous" />
<item index="36" class="java.lang.String" itemvalue="Flask" />
<item index="37" class="java.lang.String" itemvalue="blinker" />
<item index="38" class="java.lang.String" itemvalue="kaitaistruct" />
<item index="39" class="java.lang.String" itemvalue="scipy" />
<item index="40" class="java.lang.String" itemvalue="opencv-python" />
<item index="41" class="java.lang.String" itemvalue="rlPyCairo" />
<item index="42" class="java.lang.String" itemvalue="ruamel.yaml" />
<item index="43" class="java.lang.String" itemvalue="tzdata" />
<item index="44" class="java.lang.String" itemvalue="mitmproxy_wireguard" />
<item index="45" class="java.lang.String" itemvalue="packaging" />
<item index="46" class="java.lang.String" itemvalue="publicsuffix2" />
<item index="47" class="java.lang.String" itemvalue="Django" />
<item index="48" class="java.lang.String" itemvalue="cmake" />
<item index="49" class="java.lang.String" itemvalue="pytz" />
<item index="50" class="java.lang.String" itemvalue="Pillow" />
<item index="51" class="java.lang.String" itemvalue="scikit-learn" />
</list>
</value>
</option>
</inspection_tool>
</profile>
......
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="webguard0" project-jdk-type="Python SDK" />
<component name="ProjectRootManager" version="2" project-jdk-name="webguard0 (2)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
......@@ -2,7 +2,7 @@
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/webguard.iml" filepath="$PROJECT_DIR$/.idea/webguard.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/webguardian-ML-v2.iml" filepath="$PROJECT_DIR$/.idea/webguardian-ML-v2.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<module version="4">
<component name="Flask">
<option name="enabled" value="true" />
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="webguard0" jdkType="Python SDK" />
<orderEntry type="jdk" jdkName="webguard0 (2)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Jinja2" />
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/../webguard\templates" />
<option value="$MODULE_DIR$/templates" />
</list>
</option>
</component>
......
......@@ -16,7 +16,7 @@ nmap <br>
```bash
python3 -m pip install fastapi
```
#### Install server
#### Install server[scan.py](scan.py)
```bash
pip install uvicorn
```
......
import json
from builtins import print
from flask import Flask, render_template, request, url_for, send_from_directory, jsonify
from werkzeug.utils import secure_filename
from flask_cors import CORS, cross_origin
......@@ -17,10 +19,14 @@ def hello_world(): # put application's code here
@app.route('/addnew', methods=['POST'])
def upload_file():
if request.method == 'POST':
print('----------------------------------------------------------------')
f = request.files['file']
name = (request.form['title'])
f.save(secure_filename("input." + f.filename.split('.')[-1]))
filename = str("input." + f.filename.split('.')[-1])
faces_directory = os.path.join("faces", name)
if not os.path.exists(faces_directory):
os.makedirs(faces_directory)
serve.extract_frames("input.mp4", "faces/"+name)
os.remove("input.mp4")
return jsonify({"success": "new face added"})
......@@ -29,15 +35,18 @@ def upload_file():
@app.route('/predict', methods=['POST'])
def predict():
if request.method == 'POST':
f = request.files['file']
f.save(secure_filename("input." + f.filename.split('.')[-1]))
filename = str("input." + f.filename.split('.')[-1])
known_encodings, known_names = serve.load_known_faces()
# Identify faces in a new image
name = serve.identify_faces(filename, known_encodings, known_names)
# serve.extract_frames("input.mp4", "faces/"+name)
os.remove(filename)
return jsonify({"success": "detection success", "id": name})
try:
f = request.files['file']
f.save(secure_filename("input." + f.filename.split('.')[-1]))
filename = str("input." + f.filename.split('.')[-1])
known_encodings, known_names = serve.load_known_faces()
# Identify faces in a new image
name = serve.identify_faces(filename, known_encodings, known_names)
# serve.extract_frames("input.mp4", "faces/"+name)
os.remove(filename)
return jsonify({"success": "detection success", "id": name})
except Exception as e:
return jsonify({"error": str(e)})
@app.route('/severity', methods=['POST'])
def check_severity():
......
This diff is collapsed.
......@@ -71,6 +71,23 @@ def load_known_faces():
known_names = pickle.load(f_names)
return known_encodings, known_names
# def identify_faces(image_path, known_encodings, known_names):
# image = cv2.imread(image_path)
# rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#
# face_locations = face_recognition.face_locations(rgb_image)
# face_encodings = face_recognition.face_encodings(rgb_image, face_locations)
#
# for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# matches = face_recognition.compare_faces(known_encodings, face_encoding)
# name = "Unknown"
#
# if True in matches:
# matched_index = matches.index(True)
# name = known_names[matched_index]
#
# return name
def identify_faces(image_path, known_encodings, known_names):
image = cv2.imread(image_path)
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
......@@ -78,16 +95,18 @@ def identify_faces(image_path, known_encodings, known_names):
face_locations = face_recognition.face_locations(rgb_image)
face_encodings = face_recognition.face_encodings(rgb_image, face_locations)
name = "Unknown" # Initialize with a default value
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
matches = face_recognition.compare_faces(known_encodings, face_encoding)
name = "Unknown"
if True in matches:
matched_index = matches.index(True)
name = known_names[matched_index]
name = known_names[matched_index] # Update the name when a match is found
return name
loaded_model = joblib.load("severity_classifier.pkl")
def get_severity(data):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment