Commit 6aea15c9 authored by Methmi Ranasinghe's avatar Methmi Ranasinghe

Added Face Detection Implementation

parent 00cd94a6
......@@ -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 };
<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>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<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>
</component>
\ No newline at end of file
<?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):
......
/** @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 diff is collapsed.
......@@ -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"
}
}
......@@ -9,15 +9,6 @@ import {
ReactNode,
} from "react";
type DataType = {
name: string;
};
//name
//username
//email
//password
//terms
interface TechData {
value: string;
frontend: string;
......@@ -29,6 +20,15 @@ interface TechData {
[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>>;
......@@ -41,13 +41,15 @@ interface ContextProps {
terms: boolean;
setTerms: Dispatch<SetStateAction<boolean>>;
techData: TechData;
setTechData: (newTechData: TechData) => void; // Define the setter function
setTechData: (newTechData: TechData) => void;
quizResults: QuizResults[];
setQuizResults: Dispatch<SetStateAction<QuizResults[]>>;
activeItem: string;
setActiveItem: Dispatch<SetStateAction<string>>;
netdata: any[];
setNetData: React.Dispatch<React.SetStateAction<any[]>>;
}
// Include techData in the ContextProps
// userId: string;
// setUserId: Dispatch<SetStateAction<string>>;
// data: DataType[];
// setData: Dispatch<SetStateAction<DataType[]>>;
const GlobalContext = createContext<ContextProps>({
name: "",
setName: (): string => "",
......@@ -59,7 +61,6 @@ const GlobalContext = createContext<ContextProps>({
setPassword: (): string => "",
terms: false,
setTerms: (): boolean => false,
techData: {
value: "",
frontend: "",
......@@ -69,21 +70,20 @@ const GlobalContext = createContext<ContextProps>({
others: "",
webAppType: "",
},
setTechData: (newTechData: TechData) => {},
quizResults: [],
setQuizResults: (): QuizResults[] => [],
activeItem: "",
setActiveItem: (): string => "",
netdata: [],
setNetData: () => {},
});
// userId: "",
// setUserId: (): string => "",
// data: [],
// setData: (): DataType[] => [],
export const GlobalContextProvider = ({
children,
}: {
children: ReactNode;
}) => {
// const [userId, setUserId] = useState("");
// const [data, setData] = useState<[] | DataType[]>([]);
const [name, setName] = useState("");
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
......@@ -98,6 +98,9 @@ export const GlobalContextProvider = ({
others: "",
webAppType: "",
});
const [activeItem, setActiveItem] = useState("");
const [quizResults, setQuizResults] = useState<QuizResults[]>([]);
const [netdata, setNetData] = useState<any[]>([]);
return (
<GlobalContext.Provider
......@@ -114,6 +117,12 @@ export const GlobalContextProvider = ({
setTerms,
techData,
setTechData,
quizResults,
setQuizResults,
activeItem,
setActiveItem,
netdata,
setNetData,
}}
>
{children}
......
import { NextApiRequest, NextApiResponse } from 'next';
import fetch from 'node-fetch';
export default async (req: NextApiRequest, res: NextApiResponse) => {
const { tech } = req.query;
const url = `https://api.cvesearch.com/search?q=${tech}`;
const response = await fetch(url);
const data = await response.json();
res.status(response.status).json(data);
};
......@@ -4,6 +4,7 @@ import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/navigation";
import VideoCapture from "./videoCapture/page"; // Import the VideoCapture component
import NoSSR from "react-no-ssr";
// Define the FaceDetection functional component
const FaceDetection: React.FC = () => {
......@@ -14,7 +15,10 @@ const FaceDetection: React.FC = () => {
return (
<div className="flex flex-row h-screen bg-gradient-to-b from-blue-900 to-pink-400">
<div className="hidden md:block basis-1/2">
<img src="/images/login/loginbg.jpg" className="h-full object-cover" />
<img
src="/images/login/faceRecognition.jpg"
className="h-full object-cover"
/>
</div>
<div className="flex flex-col basis-1/2 flex-grow my-auto mx-auto px-10 md:px-20 lg:px-20 xl:px-52">
......@@ -23,12 +27,14 @@ const FaceDetection: React.FC = () => {
className="absolute bottom-0 right-0 h-60"
/>
<p className="text-5xl text-white my-2">Face Detection</p>
<label className="text-white mt-4 text-sm">
Click start button to start face detection
<label className="text-white mt-4 text-sm mb-4">
Click start button to "Turn my camera ON"
</label>
{/* Render the VideoCapture component */}
<VideoCapture />
<NoSSR>
<VideoCapture />
</NoSSR>
</div>
</div>
);
......
import { useReactMediaRecorder } from "react-media-recorder";
import VideoRecorder from "react-video-recorder";
import {
RecordWebcam,
useRecordWebcam,
CAMERA_STATUS,
} from "react-record-webcam";
const OPTIONS = {
filename: "test-filename",
fileType: "mp4",
width: 1920,
height: 1080,
};
export default function VideoCapture() {
const recordWebcam = useRecordWebcam(OPTIONS);
const getRecordingFileHooks = async () => {
const blob = await recordWebcam.getRecording();
console.log({ blob });
};
const getRecordingFileRenderProp = async (blob) => {
console.log({ blob });
};
return (
<div>
<VideoRecorder
mimeType="video/mp4"
onRecordingComplete={(videoBlob) => {
// Do something with the video...
console.log("videoBlob", videoBlob);
}}
/>
</div>
);
}
......@@ -2,7 +2,6 @@
import React, { useState } from "react";
import { RecordWebcam, useRecordWebcam } from "react-record-webcam";
import fs from "fs";
import axios from "axios";
import { useRouter } from "next/navigation";
......@@ -140,7 +139,7 @@ export default function VideoCapture() {
<div className="mt-4">
{/* animation */}
<div className="flex justify-center">
<div className="animate-spin rounded-full h-32 w-32 border-b-2 border-gray-900"></div>
<div className="animate-spin rounded-full h-16 w-16 border-b-2 border-gray-900"></div>
</div>
</div>
) : null}
......
import { useReactMediaRecorder } from "react-media-recorder";
import VideoRecorder from "react-video-recorder";
import {
RecordWebcam,
useRecordWebcam,
CAMERA_STATUS,
} from "react-record-webcam";
import { useState } from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { useRouter } from "next/navigation";
const OPTIONS = {
filename: "test-filename",
fileType: "mp4",
width: 1920,
height: 1080,
};
export default function VideoCapture() {
const [recordedBlob, setRecordedBlob] = useState(null);
const [isUploading, setIsUploading] = useState(false);
const router = useRouter();
const handleRecordingComplete = (videoBlob) => {
setRecordedBlob(videoBlob);
};
const uploadVideo = async () => {
if (recordedBlob) {
setIsUploading(true);
const formData = new FormData();
formData.append("file", recordedBlob, "recorded.mp4"); // Append the Blob as a file
formData.append("title", `${localStorage.getItem("email")}`); // Add other form data fields as needed
try {
const response = await fetch("http://127.0.0.1:5000/addnew", {
method: "POST",
body: formData,
});
if (response.ok) {
// Handle successful response
notifySuccess();
setIsUploading(false);
router.push("/customerOnboarding/basicInfo");
} else {
// Handle error response
notifyUploadingError();
console.error("Error uploading video");
}
} catch (error) {
// Handle network error
console.error("Network error:", error);
notifyNetworkError();
}
} else {
notifyError();
}
};
const notifyError = () =>
toast.error(`Please complete Face ID process. Click "Turn my camera ON"`, {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: undefined,
theme: "colored",
});
const notifyUploadingError = () =>
toast.error("Error in uploading", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: 0,
theme: "colored",
});
const notifySuccess = () =>
toast.success("Face ID video sent", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: 0,
theme: "colored",
});
const notifyNetworkError = () =>
toast.error("Network Error", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: undefined,
theme: "colored",
});
return (
<div>
<ToastContainer />
<VideoRecorder
mimeType="video/webm"
onRecordingComplete={handleRecordingComplete}
/>
<div className="flex flex-row ">
<button
className="bg-sky-600 hover:bg-sky-500 mt-4 p-4 rounded-md text-white"
onClick={uploadVideo}
>
Upload For Face Id
</button>
{/* is uploading */}
{isUploading ? (
<div className="m-4 animate-spin rounded-full h-12 w-12 border-b-2 border-white"></div>
) : null}
</div>
</div>
);
}
......@@ -14,7 +14,7 @@ const FaceDetection: React.FC = () => {
return (
<div className="flex flex-row h-screen bg-gradient-to-b from-blue-900 to-pink-400">
<div className="hidden md:block basis-1/2">
<img src="/images/login/loginbg.jpg" className="h-full object-cover" />
<img src="/images/login/faceRecognition.jpg" className="h-full object-cover" />
</div>
<div className="flex flex-col basis-1/2 flex-grow my-auto mx-auto px-10 md:px-20 lg:px-20 xl:px-52">
......
......@@ -35,6 +35,10 @@ const FaceDetectionLogin: React.FC = () => {
const handleUpload = async (e: any) => {
e.preventDefault();
// await capture();
// handleFileChange(e);
if (!selectedFile) {
alert("Please select a file.");
return;
......@@ -59,6 +63,24 @@ const FaceDetectionLogin: React.FC = () => {
console.log("File uploaded successfully:", response.data);
if (response.data.success == "detection success") {
// axios post localhost:5000/api/v1/user/isfaceid to this json body
// {
// "userid":"64f3a828d63f6211d95a0a53",
// "isFaceid":true
// }
await axios.post(
"http://localhost:5000/api/v1/user/isfaceid",
{
userid: localStorage.getItem("userid"),
isFaceid: true,
},
{
headers: {
"Content-Type": "application/json",
},
}
);
console.log("Login Success");
router.push("/dashboard");
}
......
// Import required modules and libraries
"use client";
import Link from "next/link";
import { useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import axios from "axios";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
// Define the Login functional component
export default function Login() {
// State variables to hold email and password
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [device, setDevice] = useState("");
const [logTime, setLogTime] = useState("");
const videoRef = useRef();
const [file, setFile] = useState();
useEffect(() => {
setDevice( navigator.userAgent);
setLogTime(new Date().toLocaleString());
}, []);
// Router instance for navigation
const router = useRouter();
const logins = (email: any, password: any) => {
console.log("value=>", email, password);
// console.log("value=>", email, password);
const data = axios
.post("http://localhost:5000/api/v1/user/", {
email: email,
password: password,
device: device,
logTime: logTime,
"username":localStorage.getItem("email")
})
.then((res) => {
console.log(res);
.then(async (res) => {
// Assuming the login was successful based on your server response
notifySuccess();
if (res.data.email === email) {
localStorage.setItem("userid", res.data._id);
localStorage.setItem("email", email);
localStorage.setItem("companyid", res.data.companyId);
localStorage.setItem("userid", res.data._id);
router.push("/auth/twoFactorLogin"); // Redirect to the twoFactor route
} else {
// Handle unsuccessful login here
......@@ -39,14 +51,40 @@ export default function Login() {
}
})
.catch((err) => {
alert("Login failed" + err);
// alert("Login failed" + err);
notifyError();
console.log("error=>", err);
});
};
const notifySuccess = () =>
toast.success("User Login Successfully", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: undefined,
theme: "colored",
});
const notifyError = () =>
toast.error("User Login Failed", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: undefined,
theme: "colored",
});
// Render the login UI
return (
<div className="flex flex-row h-screen bg-gradient-to-b from-blue-900 to-pink-400">
<ToastContainer />
<div className="hidden md:block basis-1/2">
<img src="/images/login/loginbg.jpg" className="h-full object-cover" />
</div>
......@@ -66,6 +104,7 @@ export default function Login() {
value={email}
className="w-full mt-2 px-2 border h-10 border-gray-300 rounded-md focus:outline-none focus:border-indigo-700"
></input>
{/* <p className="text-xs m-1 pl-2 text-white bg-red-600 rounded-md">*Enter a valid email</p> */}
{/* Password input */}
<label className="text-white mt-4 p-1 text-sm">PASSWORD</label>
......
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, useEffect, useRef } from "react";
import { useGlobalContext } from "../../Context/store";
import axios from "axios";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
export default function Signup() {
//define context
......@@ -19,32 +20,10 @@ export default function Signup() {
terms,
setTerms,
} = useGlobalContext();
const videoRef = useRef<HTMLVideoElement | null>(null);
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
const [isRecording, setIsRecording] = useState(false);
const [recordedChunks, setRecordedChunks] = useState<Blob[]>([])
//define router
const router = useRouter();
// useEffect(() => {
// }, []);
const handleSubmit = () => {
if (name === "" || username === "" || email === "" || password === "") {
alert("Please fill in all fields");
return;
} else if (!terms) {
alert("You must agree to the terms and conditions");
return;
} else {
router.push("/auth/step2");
}
};
const signup = (
name: any,
username: any,
......@@ -53,10 +32,10 @@ export default function Signup() {
terms: any
) => {
if (name === "" || username === "" || email === "" || password === "") {
alert("Please fill in all fields");
notifyError();
return;
} else if (!terms) {
alert("You must agree to the terms and conditions");
notifyErrorTerms();
return;
} else {
console.log("log data", name, username, email, password, terms);
......@@ -69,6 +48,14 @@ export default function Signup() {
terms: terms,
})
.then((res) => {
// if (res.data == `"User with provided email already exists"`) {
// console.log("User with provided email already exists");
// notifyDuplError();
// }
console.log(res.data);
notifySuccess();
console.log(res);
localStorage.setItem("email", email);
localStorage.setItem("userid", res.data._id);
......@@ -78,12 +65,60 @@ export default function Signup() {
}
};
const notifySuccess = () =>
toast.success("User Signup Successfully", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: undefined,
theme: "colored",
});
const notifyError = () =>
toast.error("Please fill in all fields", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: undefined,
theme: "colored",
});
const notifyDuplError = () =>
toast.error("User with provided email already exists", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: undefined,
theme: "colored",
});
const notifyErrorTerms = () =>
toast.error("You must agree to the terms and conditions", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: undefined,
theme: "colored",
});
return (
<div className="flex flex-row h-screen bg-gradient-to-b from-blue-900 to-pink-400">
<ToastContainer />
<div className="hidden md:block basis-1/2">
<img src="/images/login/loginbg.jpg" className="h-full object-cover" />
<img src="/images/login/signup.jpg" className="h-full object-cover" />
</div>
{/* */}
<div className="flex flex-col basis-1/2 flex-grow my-auto mx-auto px-10 md:px-20 lg:px-20 xl:px-52">
<img
src="/images/webguardian logo.png"
......@@ -127,7 +162,14 @@ export default function Signup() {
type="checkbox"
onChange={(e) => setTerms(e.target.checked)}
></input>
<p className="text-white ml-2">I agree to the terms and conditions</p>
<p className="text-white ml-2">
I agree to the {" "}
<u>
<a href="http://localhost:3000/auth/signup/termsConditions">
terms and conditions
</a>
</u>
</p>
</div>
<div className="flex flex-row space-x-3">
......
"use client";
import { useRouter } from "next/navigation";
export default function TermsConditions() {
const router = useRouter();
const handleBackToSignup = () => {
router.push("/auth/signup");
};
return (
<div className="bg-gray-100 min-h-screen p-4">
<div className="max-w-2xl mx-auto bg-white p-8 rounded shadow">
{/* Back to Signup button */}
<button
className="mb-4 text-blue-500 hover:underline"
onClick={handleBackToSignup}
>
&lt; Back to Signup
</button>
<h1 className="text-3xl font-semibold mb-6">Terms and Conditions</h1>
<p className="mb-4">
Please read these terms and conditions carefully before using our
website.
</p>
<h2 className="text-xl font-semibold mb-2">1. Acceptance of Terms</h2>
<p className="mb-4">
By using this website, you agree to comply with and be bound by these
terms and conditions.
</p>
<h2 className="text-xl font-semibold mb-2">2. Use License</h2>
<p className="mb-4">
Permission is granted to temporarily download one copy of the
materials on this website.
</p>
{/* Add more sections as needed for your terms and conditions */}
<p className="mt-8 text-gray-600">Last updated: 09/07/2023</p>
</div>
</div>
);
}
......@@ -3,6 +3,7 @@ import Link from "next/link";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useGlobalContext } from "../../Context/store";
import axios from "axios";
export default function Step2() {
const [pnum, setPnum] = useState("");
......@@ -18,14 +19,47 @@ export default function Step2() {
const { name, username, email, password } = useGlobalContext();
// const handleSubmit = () => {
// if (pnum == "") {
// alert("Please enter your mobile number");
// return;
// } else {
// router.push("/auth/twoFactor");
// console.log(name, username, email, password, location, pnum, device, os);
// }
// };
const handleSubmit = () => {
if (pnum == "") {
alert("Please enter your mobile number");
return;
} else {
router.push("/auth/twoFactor");
console.log(name, username, email, password, location, pnum, device, os);
}
// Create the request body
const requestBody = {
location: {
long: location?.longitude,
lang: location?.latitude,
},
companyId: localStorage.getItem("companyid"),
device: device,
shift: "9.30 - 6.30",
companyid: localStorage.getItem("companyid"),
timeShift: "9.30 - 6.30",
};
// Make the API request using Axios
axios
.put(
`http://localhost:5000/api/v1/user/profile/${localStorage.getItem(
"userid"
)}`,
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("/auth/twoFactor");
})
.catch((error) => {
// Handle errors here
console.error("API error:", error);
});
};
function handleLocationClick() {
......@@ -82,14 +116,10 @@ export default function Step2() {
return (
<div className="flex flex-row h-screen bg-gradient-to-b from-blue-900 to-pink-400">
<div className="hidden md:block basis-1/2">
<img src="/images/login/loginbg.jpg" className="h-full object-cover" />
<img src="/images/login/step2.jpg" className="h-full object-cover" />
</div>
<div className="flex flex-col basis-1/2 flex-grow my-auto mx-auto px-10 md:px-20 lg:px-20 xl:px-52">
{/* <p>{name}</p>
<p>{username}</p>
<p>{email}</p>
<p>{password}</p> */}
<img
src="/images/webguardian logo.png"
className="absolute bottom-0 right-0 h-60"
......
......@@ -7,11 +7,12 @@ import axios from "axios";
export default function TwoFactor() {
const [otp, setOtp] = useState<number>();
const router = useRouter();
const [isMailLoading, setIsMailLoading] = useState(false);
// Sent OTP email when page loads
// Sent OTP email when page loads
// useEffect(() => {
// handleSubmit();
// resendOtp();
// }, []);
const handleSubmit = () => {
......@@ -38,6 +39,9 @@ export default function TwoFactor() {
};
const resendOtp = () => {
// isMailLoading
setIsMailLoading(true);
console.log(localStorage.getItem("email"));
const data = axios
.post("http://localhost:5000/api/v1/otp", {
......@@ -48,7 +52,8 @@ export default function TwoFactor() {
})
.then((res) => {
console.log(res);
router.push("/auth/twoFactor");
// isMailLoading
setIsMailLoading(false);
})
.catch((err) => {
console.log("error=>", err);
......@@ -58,7 +63,7 @@ export default function TwoFactor() {
return (
<div className="flex flex-row h-screen bg-gradient-to-b from-blue-900 to-pink-400">
<div className="hidden md:block basis-1/2">
<img src="/images/login/loginbg.jpg" className="h-full object-cover" />
<img src="/images/login/two-stepts.jpg" className="h-full object-cover" />
</div>
<div className="flex flex-col basis-1/2 flex-grow my-auto mx-auto px-10 md:px-20 lg:px-20 xl:px-30">
......@@ -83,6 +88,15 @@ export default function TwoFactor() {
Resend the OTP
</p>
</button>
{/* isMailLoading */}
{isMailLoading ? (
// animation
<div className="flex justify-center">
<div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-900"></div>
</div>
) : (
<p></p>
)}
<button
onClick={() => handleSubmit()}
className="mt-14 bg-white hover:bg-slate-200 border hover:border-blue-950 shadow-sm rounded-full"
......
"use client";
import Link from "next/link";
import { useState } from "react";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import axios from "axios";
......@@ -8,6 +8,14 @@ export default function TwoFactorLogin() {
const [otp, setOtp] = useState<number>();
const router = useRouter();
const [isMailLoading, setIsMailLoading] = useState(false);
// Sent OTP email when page loads
// useEffect(() => {
// resendOtp();
// }, []);
const handleSubmit = () => {
console.log(localStorage.getItem("email"));
console.log(otp);
......@@ -32,6 +40,8 @@ export default function TwoFactorLogin() {
};
const resendOtp = () => {
// isMailLoading
setIsMailLoading(true);
console.log(localStorage.getItem("email"));
const data = axios
.post("http://localhost:5000/api/v1/otp", {
......@@ -42,7 +52,8 @@ export default function TwoFactorLogin() {
})
.then((res) => {
console.log(res);
// router.push("/auth/faceDetectionLogin");
// isMailLoading
setIsMailLoading(false);
})
.catch((err) => {
console.log("error=>", err);
......@@ -52,7 +63,7 @@ export default function TwoFactorLogin() {
return (
<div className="flex flex-row h-screen bg-gradient-to-b from-blue-900 to-pink-400">
<div className="hidden md:block basis-1/2">
<img src="/images/login/loginbg.jpg" className="h-full object-cover" />
<img src="/images/login/two-stepts.jpg" className="h-full object-cover" />
</div>
<div className="flex flex-col basis-1/2 flex-grow my-auto mx-auto px-10 md:px-20 lg:px-20 xl:px-30">
......@@ -77,6 +88,15 @@ export default function TwoFactorLogin() {
Resend the OTP
</p>
</button>
{/* isMailLoading */}
{isMailLoading ? (
<div className="flex justify-center">
<div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-gray-900"></div>
</div>
) : (
<div></div>
)}
<button
onClick={() => handleSubmit()}
className="mt-14 bg-white hover:bg-slate-200 border hover:border-blue-950 shadow-sm rounded-full"
......
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";
export default function LogReport() {
// get logdata from local storage
const logdata: any[] = JSON.parse(localStorage.getItem("logdata") || "[]");
console.log(logdata);
return (
<div className="m-10">
<div>
{/* Loggin log data table userEmail, username, logTime, device */}
<div className="flex flex-row">
<p className="text-xl font-bold mb-5">Login Attempts Log Report</p>
<button
className="bg-[#B200B6] hover:bg-[#960f98] text-white rounded-lg px-4 py-2 ml-10"
onClick={window.print}
>
Generate Report
</button>
</div>
<div className="rounded-lg bg-[#F4F4F4] hover:bg-[#f5f4f4a5] hover:shadow-lg p-5 mb-10">
<div className="flex flex-col">
<div className="flex flex-row items-center">
<p className="text-lg font-semibold text-[#B200B6]">
Login Details
</p>
</div>
<table className="mt-4">
<thead>
<tr>
<th className="text-left">User Email</th>
<th className="text-left">Username</th>
<th className="text-left">Log Time</th>
<th className="text-left">Device</th>
</tr>
</thead>
<tbody>
{Array.isArray(logdata) &&
logdata.map((item, index) => (
<tr key={index}>
<td>{item.userId}</td>
<td>{item.username}</td>
<td>{new Date(item.logTime).toLocaleString()}</td>
<td>{item.device}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
</div>
);
}
This diff is collapsed.
......@@ -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"]
}
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