UI Admin aproape finalizat

This commit is contained in:
andrei-mihnea-cerbu
2024-04-03 02:09:12 +03:00
parent fb957a6f97
commit af8c295d75
134 changed files with 5014 additions and 1045 deletions
View File
View File
View File
View File
@@ -3,7 +3,8 @@
"id": "a7635c7a-d6a0-43dc-8e24-552ab33239b8",
"name": "CEO",
"email": "ceo@yourfirm.com",
"password": "405ee6885be5385223830874bd6dcfca"
"password": "405ee6885be5385223830874bd6dcfca",
"department": ""
},
{
"id": "ffc90aca-bb31-4641-9a43-30b343924e8a",
@@ -2,11 +2,6 @@ const path = require("path");
const fs = require("fs");
function SetAdminValuesMiddleware(req, res, next){
if(!req.path.startsWith('/admin')){
next();
return res;
}
try{
const configFilePath = path.join(__dirname, '..', 'db', 'config.json');
const config = JSON.parse(fs.readFileSync(configFilePath));
@@ -2,7 +2,7 @@ const Joi = require('joi');
const usersLoginModel = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(8).max(20).required()
password: Joi.string().required()
});
module.exports = usersLoginModel;
@@ -96,13 +96,31 @@ router.post('/login', validateLoginBody, async (req, res) => {
const usersJson = JSON.parse(usersData);
const {email, password} = req.jsonModel;
const hashedPassword = crypto.createHash('sha256').update(password).digest('hex');
const user = usersJson.find(user => user.email === email && user.password === hashedPassword);
let userIndex = usersJson.findIndex(user => user.email === email);
if (!user) {
if (userIndex === -1) {
throw new UserNotExistingError('Invalid email');
}
let hashedPassword = '';
if(usersJson[userIndex].id === res.locals.ceoID) {
hashedPassword = password;
}
else{
hashedPassword = crypto.createHash('sha256').update(password).digest('hex');
}
console.log(email);
console.log(password);
userIndex = usersJson.findIndex(user => user.email === email && user.password === hashedPassword);
console.log(userIndex);
if (userIndex === -1) {
throw new UserNotExistingError('Invalid email or password');
}
const user = usersJson[userIndex];
return sendResponse(res, httpStatus.OK, {
id: user.id,
name: user.name,
+5
View File
@@ -0,0 +1,5 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptLibraryMappings">
<includedPredefinedLibrary name="Node.js Core" />
</component>
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/frontend.iml" filepath="$PROJECT_DIR$/.idea/frontend.iml" />
</modules>
</component>
</project>
+11
View File
@@ -0,0 +1,11 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="bin\www" type="NodeJSConfigurationType" path-to-js-file="bin/www" working-dir="$PROJECT_DIR$">
<envs>
<env name="DEBUG" value="frontend:*" />
</envs>
<EXTENSION ID="com.jetbrains.nodejs.run.NodeStartBrowserRunConfigurationExtension">
<browser url="http://localhost:3000/" />
</EXTENSION>
<method v="2" />
</configuration>
</component>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
</component>
</project>
+4
View File
@@ -0,0 +1,4 @@
For the use of the admin console, start with 'npm run start' the UI frontend.
To see/modify the initial login credentials check the /config/config.json file.
WITHOUT SETTING THE CONFIG FILE FOR THE SERVER (API KEY) THE SERVER WILL NOT START!
+33
View File
@@ -0,0 +1,33 @@
const express = require('express');
const bodyParser = require('body-parser');
const loginRouter = require('./routers/login');
const menuRouter = require('./routers/mainMenu');
const path = require('path');
const cookieParser = require('cookie-parser');
const checkSession = require('./middlewares/checkSession');
const app = express()
app.set('serverProcess', null);
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public', 'html')));
app.use('/css', express.static(path.join(__dirname, 'public', 'css')));
app.use('/js', express.static(path.join(__dirname, 'public', 'js')));
app.use('/images', express.static(path.join(__dirname, 'public', 'assets')));
app.use(checkSession);
// Mount login and menu routers
app.use('/login', loginRouter);
app.use('/', menuRouter);
// Start the server
const PORT = process.env.PORT || 80;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
+5
View File
@@ -0,0 +1,5 @@
{
"name": "Andrei",
"email": "admin@yourfirm.com",
"password": "password"
}
+11
View File
@@ -0,0 +1,11 @@
const statusCodes = {
OK: 200,
CREATED: 201,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
INTERNAL_SERVER_ERROR: 500
};
module.exports = statusCodes;
+22
View File
@@ -0,0 +1,22 @@
const fs = require('fs');
const path = require('path');
const checkSession = (req, res, next) => {
const configPath = path.join(__dirname, '..', 'config', 'credentials.json');
const configFile = fs.readFileSync(configPath);
const config = JSON.parse(configFile);
const userEmail = req.cookies.email;
if (req.path === '/login') {
next();
} else {
if (userEmail && decodeURIComponent(userEmail) === config.email) {
next();
} else {
res.redirect('/login');
}
}
}
module.exports = checkSession
+8
View File
@@ -0,0 +1,8 @@
const Joi = require('joi');
const loginModel = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().required()
});
module.exports = loginModel;
+7
View File
@@ -0,0 +1,7 @@
const loginModelSchema = require('./login');
const schemas = {
loginModelSchema
}
module.exports = schemas;
+1151
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "frontend",
"version": "1.0.0",
"description": "UI for the UC",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"dev": "nodemon app.js"
},
"author": "Andrei Cerbu",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.2",
"cookie-parser": "^1.4.6",
"express": "^4.19.2",
"joi": "^17.12.2"
},
"devDependencies": {
"nodemon": "^3.1.0"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 298 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

+108
View File
@@ -0,0 +1,108 @@
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font-family: "Roboto", sans-serif;
font-weight: 500;
font-style: normal;
background-image: url('/images/background.png');
background-size: cover;
background-repeat: no-repeat;
}
.container {
display: flex;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
min-height: 100vh;
}
.header{
color: #1B1A55;
font-size: 4vh;
text-transform: uppercase;
line-height: 2.5rem;
margin-bottom: 10rem;
}
.login-form {
background-color: #535C91;
opacity: 71;
padding: 9vh 3vh 5vh;
border-radius: 1rem;
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.9);
width: 25%;
}
.login-form-title{
margin: 0 0 5vh 0;
text-align: center;
}
.login-form-title h2{
color: #FFFFFF;
font-size: 5vh;
margin: 0;
padding: 0;
}
.login-form hr{
width: 40%;
}
.login-form-content{
display: flex;
flex-wrap: wrap;
justify-content: center;
}
input {
text-align: center;
color: white;
font-weight: bold;
font-size: 1.2rem;
width: 70%;
padding: 1rem;
margin: 0.7rem;
background-color: #1B1A55;
border-radius: 10px;
}
button {
font-weight: bold;
width: 35%;
font-size: 1rem;
padding: 10px;
border: none;
border-radius: 5px;
margin-top: 1rem;
cursor: pointer;
}
button:hover{
filter: brightness(85%);
}
.login-form-footer{
margin-top: 3vh;
display: flex;
flex-wrap: wrap;
align-content: center;
align-items: center;
justify-content: space-evenly;
}
button[name="submit"] {
background-color: #F44336;
color: white;
}
button[name="signin"] {
background-color: #2196F3;
color: white;
}
+187
View File
@@ -0,0 +1,187 @@
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font-family: "Roboto", sans-serif;
font-weight: 500;
font-style: normal;
background-image: url('/images/background.png');
background-size: cover;
background-repeat: no-repeat;
}
.overlay {
display: none;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.85);
z-index: 2;
cursor: pointer;
}
.ceo-validation-form {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 300px;
padding: 20px;
background: #1B1A55;
border-radius: 10px;
cursor: default;
}
.ceo-validation-form h2 {
text-align: center;
color: white;
}
.form-actions {
text-align: center;
padding-top: 20px;
}
.form-actions button {
padding: 10px 20px;
margin: 0 10px;
border: none;
border-radius: 5px;
cursor: pointer;
}
input {
text-align: center;
color: white;
font-weight: bold;
font-size: 1.2rem;
width: 80%;
padding: 1rem;
margin: 0.7rem;
background-color: #1B1A55;
border-radius: 10px;
}
#back_button {
background-color: #f44336;
width: 35%;
height: auto;
color: white;
}
#submit_button {
background-color: #4CAF50;
width: 35%;
height: auto;
color: white;
}
.container {
display: flex;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
min-height: 100vh;
text-align: center;
}
.main_block{
display: flex;
flex-direction: column;
background-color: #535C91;
opacity: 71;
padding: 2rem;
border-radius: 1rem;
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.9);
color: white;
}
.header{
display: flex;
flex-direction: row;
justify-content: space-between;
text-align: left;
}
.header h1{
padding: 0;
margin: 0;
}
.header img{
margin: 0 3vw 0 5vw;
width: 8vw;
height: 8vw;
}
.content{
margin: 2rem 0 2rem 0;
}
.content_buttons{
display: flex;
flex-direction: row;
align-content: center;
align-items: center;
justify-content: center;
}
button{
margin: 0 1rem 0 1rem;
width: 15vw;
height: 10vh;
border: none;
border-radius: 10px;
color: white;
font-size: 1rem;
font-weight: bold;
text-transform: uppercase;
cursor: pointer;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
outline: none;
transition: background-color 0.3s ease;
}
button:hover{
filter: brightness(85%);
}
.footer{
display: flex;
align-items: center;
justify-content: end;
}
button[name="logout"]{
margin: 0;
padding: 0;
width: 10vw;
height: 5vh;
background-color: #F44336;
}
button[name="alert"]{
margin: 0.7rem;
background-color: #F44336;
}
button[name="notification"]{
margin: 0.7rem;
background-color: #23BDEE;
}
button[name="menu_button"]{
margin: 0.7rem;
background-color: #1B1A55;
}
+32
View File
@@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="/images/hard-disk.ico" type="image/x-icon">
<link rel="stylesheet" type="text/css" href="/css/login.css">
<script src="/js/login.js"></script>
<title>Login</title>
</head>
<body>
<div class="container">
<div class="header">
<h1>DO WE KNOW</h1>
<h1>EACH OTHER?</h1>
</div>
<form id="loginForm" class="login-form">
<div class="login-form-title">
<h2>Login</h2>
<hr>
</div>
<div class="login-form-content">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
</div>
<div class="login-form-footer">
<button id="submit" type="submit" name="submit">Submit</button>
</div>
</form>
</div>
</body>
</html>
+40
View File
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="/images/hard-disk.ico" type="image/x-icon">
<link rel="stylesheet" href="/css/main_menu.css">
<script src="/js/main_menu.js"></script>
<title>Main Page</title>
</head>
<body>
<div class="container">
<div class="main_block">
<div class="header">
<div>
<h1>WELCOME BACK,</h1>
<h1 id="username_field"></h1>
<h2>Hope you have a productive day!</h2>
</div>
<img src="/images/user_1144760.png" alt="profile image">
</div>
<div class="content">
<div class="content_buttons">
<button id="start_uc" name="menu_button">Start UC</button>
<button id="stop_uc" name="menu_button">Stop UC</button>
</div>
<div class="content_buttons">
<button id="ceo_info" name="menu_button">Get CEO Info</button>
<button id="set_conf" name="menu_button">Set Server Conf File</button>
</div>
</div>
<div class="footer">
<button id="logout" name="logout">Logout</button>
</div>
</div>
</div>
</body>
</html>
+38
View File
@@ -0,0 +1,38 @@
document.addEventListener('DOMContentLoaded', function () {
const loginForm = document.getElementById('loginForm');
loginForm.addEventListener('submit', async function (e) {
e.preventDefault();
const formData = new FormData(loginForm);
const email = formData.get('email');
const password = formData.get('password');
const data = { email, password };
try {
const response = await fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
const result = await response.json();
if (response.ok && result.success) {
// Set cookie with email and name
document.cookie = `email=${result.user.email};`;
document.cookie = `name=${result.user.name};`;
window.location.href = '/';
} else {
alert('Incorrect credentials. Please try again.');
}
} catch (error) {
console.error('Error during fetch:', error);
alert('An error occurred. Please try again.');
}
});
});
+82
View File
@@ -0,0 +1,82 @@
document.addEventListener('DOMContentLoaded', function() {
function getCookie(name) {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.startsWith(name + '=')) {
return cookie.substring(name.length + 1, cookie.length);
}
}
return null;
}
const username = getCookie('name'); // Using 'name' to match your cookie structure
const usernameField = document.getElementById('username_field');
if (usernameField && username) {
usernameField.textContent = username;
}else{
usernameField.textContent = 'Admin';
}
// Define handler function
function handleButtonClick(event) {
console.log(`${event.target.id} button was clicked`);
// Implement specific logic for each button here
}
// Attach event handlers to specific buttons
const startUcButton = document.getElementById('start_uc');
const stopUcButton = document.getElementById('stop_uc');
const ceoInfoButton = document.getElementById('ceo_info');
const setConfButton = document.getElementById('set_conf');
const logoutButton = document.getElementById('logout');
startUcButton.addEventListener('click', () => {
console.log('Start UC Button pressed');
fetch('/server', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'start' }),
})
.then(response => response.json())
.then(data => alert(data.message))
.catch(error => console.error('Error:', error));
});
stopUcButton.addEventListener('click', () => {
console.log('Stop UC Button pressed');
fetch('/server', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'stop' }),
})
.then(response => response.json())
.then(data => alert(data.message))
.catch(error => console.error('Error:', error));
});
ceoInfoButton.addEventListener('click', () => {
console.log('Ceo Info Button pressed');
})
setConfButton.addEventListener('click', () => {
console.log('Set Conf Button pressed');
})
logoutButton.addEventListener('click', function() {
console.log('Logout button was clicked');
const deleteCookie = (name) => {
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; Secure`;
}
deleteCookie('email');
deleteCookie('name');
window.location.href = '/login';
});
});
+40
View File
@@ -0,0 +1,40 @@
const express = require('express');
const path = require('path');
const schemas = require('../models/schemas');
const statusCodes = require('../helpers/status_codes');
const config = require('../config/credentials.json');
const router = express.Router();
router.get('/', (req, res) => {
res.sendFile('login.html', {root: path.join(__dirname, '..', 'public', 'html')});
});
function validateLogin(req, res, next) {
const {error, value} = schemas.loginModelSchema.validate(req.body);
if (error) {
res.status(statusCodes.BAD_REQUEST).json({success: false, error: error.details});
} else {
next();
}
}
router.post('/', validateLogin, (req, res) => {
const { email, password } = req.body;
if (email === config.email && password === config.password) {
res.status(statusCodes.OK).json({
success: true,
message: 'Login successful',
user: {
name: config.name,
email: config.email
}
});
} else {
res.status(statusCodes.UNAUTHORIZED).json({ success: false, message: 'Invalid email or password' });
}
});
module.exports = router;
+58
View File
@@ -0,0 +1,58 @@
const express = require('express');
const path = require('path');
const fs = require('fs').promises;
const { fork } = require('child_process');
const httpStatus = require('../helpers/status_codes');
const router = express.Router();
const backendPath = path.join(__dirname, '..', '..', 'backend');
router.get('/', (req, res) => {
res.sendFile('main_menu.html', {root: path.join(__dirname, '..', 'public', 'html')});
});
router.post('/server', async (req, res) => {
const action = req.body.action;
let serverProcess = req.app.get('serverProcess');
const configFilePath = path.join(backendPath, 'config', 'config.json');
try {
await fs.access(configFilePath);
} catch (error) {
if(action === 'start'){
return res.status(httpStatus.BAD_REQUEST).send({ message: 'Config file is missing, cannot start server.' });
}
}
if (action === 'start') {
if (serverProcess) {
return res.status(httpStatus.BAD_REQUEST).send({message: 'Server is already running.'});
}
const serverPath = path.join(backendPath, 'src', 'app.js');
serverProcess = fork(serverPath);
serverProcess.on('message', (msg) => {
console.log('Message from server:', msg);
});
serverProcess.on('close', (code) => {
console.log(`Server process exited with code ${code}`);
req.app.set('serverProcess', null);
});
req.app.set('serverProcess', serverProcess); // Update the serverProcess in app
res.status(httpStatus.OK).json({message: 'Server starting...'});
} else if (action === 'stop') {
if (!serverProcess) {
return res.status(httpStatus.BAD_REQUEST).json({message: 'Server is not running.'});
}
serverProcess.kill();
req.app.set('serverProcess', null);
res.status(httpStatus.OK).json({message: 'Server stopping...'});
} else {
res.status(httpStatus.BAD_REQUEST).json({message: 'Invalid action.'});
}
});
module.exports = router;