Commit 0c07a892 authored by Hansa Ranaweera's avatar Hansa Ranaweera

Final Implementation

parent 089a81fd
......@@ -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);
"use client";
import axios from "axios";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useState } from "react";
export default function ContactInfo() {
const [companyName, setCompanyName] = useState("");
const router = useRouter();
const handleNext = () => {
// Create the request body
const requestBody = {
companyName: companyName,
companyid: localStorage.getItem("companyid"),
};
// Make the API request using Axios
axios
.post("http://localhost:5000/api/v1/company/contactinformation", requestBody)
.then((response) => {
// Handle the response here if needed
console.log("API response:", response.data);
// Now you can navigate to the next step
router.push("/dashboard");
})
.catch((error) => {
// Handle errors here
console.error("API error:", error);
});
};
return (
<div>
<div className="flex flex-row w-full">
<div className="flex flex-col flex-grow pl-10 mt-4">
<p className="text-2xl font-medium">Customer Onboarding</p>
<p className="text-lg font-medium text-[#DE51F7]">
Contact Information
</p>
</div>
<div className="flex flex-grow justify-end pr-10">
<Image
src="/images/customerOnboarding/webguardin-logo.png"
width={250}
height={150}
alt="logo"
/>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-4 gap-4 mt-5 pl-10 mr-10 w-full">
<div className="flex flex-col">
<label className=" mb-3">Company Name</label>
<input
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
value={companyName}
onChange={(e) => setCompanyName(e.target.value)}
></input>
</div>
</div>
<p className="text-lg font-medium pl-10 mt-10">Administrator Details</p>
{/* Primary responcible administrator */}
<div className="mt-5 pl-10 w-full">
<label className="mb-3">Primary Responsible Administrator</label>
<div className="flex flex-row gap-5 flex-wrap mt-4">
<input
placeholder="Name"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Email Address"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Contact Number"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Role"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
</div>
</div>
{/* Secondary responcible administrator */}
<div className="mt-10 pl-10 mr-10 w-full">
<label className="mb-3">Secondary Responsible Administrator</label>
<div className="flex flex-row gap-5 flex-wrap mt-4">
<input
placeholder="Name"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Email Address"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Contact Number"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Role"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
</div>
</div>
{/* Backup administrator */}
<div className="mt-10 pl-10 mr-10 w-full">
<label className="mb-3">Backup Administrator</label>
<div className="flex flex-row gap-5 flex-wrap mt-4">
<input
placeholder="Name"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Email Address"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Contact Number"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Role"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
</div>
</div>
{/* Supervisor */}
<div className="mt-10 pl-10 mr-10 w-full">
<label className="mb-3">Supervisor</label>
<div className="flex flex-row gap-5 flex-wrap mt-4">
<input
placeholder="Name"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Email Address"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Contact Number"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
<input
placeholder="Role"
className="rounded-md border border-[#e0e0e0] bg-white py-3 px-6 text-base font-medium text-[#6B7280] outline-none focus:border-[#DE51F7] focus:shadow-md"
></input>
</div>
</div>
<div className="flex justify-end pr-10 sm:pr-80 pb-10">
<button
onClick={handleNext}
className="bg-[#DE51F7] hover:bg-[#b730cf] text-white rounded-md py-3 px-6 mt-10"
>
Next Step
</button>
</div>
</div>
);
}
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>
);
}
This diff is collapsed.
"use client";
import { useRouter } from "next/navigation";
import RiskTable from "./riskTable/page";
export default function RiskReport() {
const router = useRouter();
const handleBackToHome = () => {
router.push("/dashboard");
};
// daily data
const dailyCount: any[] = JSON.parse(
localStorage.getItem("dailyCount") || "[]"
);
// weekly data
const weeklyCount: any[] = JSON.parse(
localStorage.getItem("weeklyCount") || "[]"
);
//vulnerability data
const vulnData: any[] = JSON.parse(localStorage.getItem("vulnData") || "[]");
return (
<div>
<div className="flex flex-col">
<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>
<p className="ml-4 text-sm">Dashboard/ Risk Report</p>
</div>
<div>
{/* 05 cards for plugins */}
<div className="flex flex-col mx-10 mt-6 ">
{/* Overall Risk */}
<div className="mb-10">
<p className="text-2xl font-bold mb-5">Overall Risk</p>
<div className="flex flex-row">
<div className="flex flex-col">
<p className="text-4xl font-bold">
{localStorage.getItem("overallRiskPercentage")}%
</p>
<p className="text-sm">Overall System Risk Precentage</p>
</div>
<div className="flex flex-col ml-10">
<p className="text-4xl font-bold">
{localStorage.getItem("overallRiskValue")}
</p>
<p className="text-sm">Overall Risk Value</p>
</div>
</div>
</div>
{/* Daily threats with tech */}
<div className="mb-10">
<p className="text-2xl font-bold mt-10 mb-5">
Daily Threats with Technologies
</p>
<div className="flex flex-row gap-10">
{dailyCount.map((item, index) => (
<div className="flex flex-col" key={index}>
<p className="text-4xl font-bold">{item.count}</p>
<p className="text-sm">{item.tech}</p>
</div>
))}
<div className="flex flex-col">
<p className="text-4xl font-bold">0</p>
<p className="text-sm">React</p>
</div>
</div>
</div>
{/* Weekly threats with tech */}
<div className="mb-10">
<p className="text-2xl font-bold mt-10 mb-5">
Weekly Threats with Technologies
</p>
<div className="flex flex-row gap-10">
{weeklyCount.map((item, index) => (
<div className="flex flex-col" key={index}>
<p className="text-4xl font-bold">{item.count}</p>
<p className="text-sm">{item.tech}</p>
</div>
))}
</div>
</div>
{/* <div className="w-1/2">
<table className="min-w-full border-collapse block md:table">
<thead className="block md:table-header-group">
<tr className="border border-grey-500 md:border-none block md:table-row absolute -top-full md:top-auto -left-full md:left-auto md:relative ">
<th className="font-bold md:border md:border-grey-500 text-left block md:table-cell">
Name
</th>
<th className="font-bold md:border md:border-grey-500 text-left block md:table-cell">
User Name
</th>
</tr>
</thead>
<tbody className="block md:table-row-group">
<tr className="bg-gray-300 border border-grey-500 md:border-none block md:table-row">
<td className="p-2 md:border md:border-grey-500 text-left block md:table-cell">
<span className="inline-block w-1/3 md:hidden font-bold">
Name
</span>
Jamal Rios
</td>
<td className="p-2 md:border md:border-grey-500 text-left block md:table-cell">
<span className="inline-block w-1/3 md:hidden font-bold">
User Name
</span>
jrios1
</td>
</tr>
</tbody>
</table>
</div> */}
<div>
<h1 className="text-2xl font-bold mb-5 mt-10">
Vulnerability Data
</h1>
<RiskTable data={vulnData} />
</div>
</div>
</div>
</div>
);
}
import React from "react";
interface Vulnerability {
id: string;
description: string;
baseSeverity: string;
}
interface TechVulnerabilities {
tech: string;
vulnerabilities: Vulnerability[];
}
interface Props {
data: TechVulnerabilities[];
}
const RiskTable: React.FC<Props> = ({ data }) => {
console.log(data);
return (
<div className="w-full overflow-x-auto mx-4">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Tech
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
ID
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Description
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Base Severity
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{data.map((item, index) => (
<React.Fragment key={index}>
{item.vulnerabilities.map((vulnerability, idx) => (
<tr key={idx}>
{idx === 0 && (
<td
rowSpan={item.vulnerabilities.length}
className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"
>
{item.tech}
</td>
)}
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{vulnerability.id}
</td>
<td className="px-6 py-4 max-w-sm break-words whitespace-wrap text-sm text-gray-900">
{vulnerability.description}
</td>
<td
className={`px-6 py-4 whitespace-nowrap text-sm text-gray-900 ${
vulnerability.baseSeverity === "CRITICAL"
? "bg-[#FF0000]"
: vulnerability.baseSeverity === "HIGH"
? "bg-[#FF0000]"
: vulnerability.baseSeverity === "MEDIUM"
? "bg-[#FFA500]"
: vulnerability.baseSeverity === "LOW"
? "bg-[#FFFF00]"
: vulnerability.baseSeverity === "Informational"
? "bg-[#0000FF]"
: ""
}`}
>
{vulnerability.baseSeverity}
</td>
</tr>
))}
</React.Fragment>
))}
</tbody>
</table>
</div>
);
};
export default RiskTable;
\ No newline at end of file
import React from 'react';
import React from "react";
interface Vulnerability {
id: string;
......@@ -16,63 +16,70 @@ interface Props {
}
const VulnerabilityTable: React.FC<Props> = ({ data }) => {
console.log(data);
return (
<div className="w-full overflow-x-auto mx-4">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Tech
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
ID
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Description
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Base Severity
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{data.map((item, index) => (
<React.Fragment key={index}>
<tr>
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Tech
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
ID
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Description
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Base Severity
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{data.map((item, index) => (
<React.Fragment key={index}>
{item.vulnerabilities.map((vulnerability, idx) => (
<tr key={idx}>
{idx === 0 && (
<td
rowSpan={item.vulnerabilities.length}
className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"
>
{item.tech}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{item.vulnerabilities[0].id}
</td>
<td className="px-6 py-4 max-w-sm break-words whitespace-wrap text-sm text-gray-900">
{item.vulnerabilities[0].description}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{item.vulnerabilities[0].baseSeverity}
</td>
</tr>
{item.vulnerabilities.slice(1).map((vulnerability, idx) => (
<tr key={idx}>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{vulnerability.id}
</td>
<td className="px-6 py-4 max-w-sm break-words whitespace-wrap text-sm text-gray-900">
{vulnerability.description}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{vulnerability.baseSeverity}
</td>
</tr>
))}
</React.Fragment>
)}
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{vulnerability.id}
</td>
<td className="px-6 py-4 max-w-sm break-words whitespace-wrap text-sm text-gray-900">
{vulnerability.description}
</td>
<td
className={`px-6 py-4 whitespace-nowrap text-sm text-gray-900 ${
vulnerability.baseSeverity === "CRITICAL"
? "bg-[#FF0000]"
: vulnerability.baseSeverity === "HIGH"
? "bg-[#FF0000]"
: vulnerability.baseSeverity === "MEDIUM"
? "bg-[#FFA500]"
: vulnerability.baseSeverity === "LOW"
? "bg-[#FFFF00]"
: vulnerability.baseSeverity === "Informational"
? "bg-[#0000FF]"
: ""
}`}
>
{vulnerability.baseSeverity}
</td>
</tr>
))}
</tbody>
</table>
</div>
</React.Fragment>
))}
</tbody>
</table>
</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