beautified

This commit is contained in:
xfarrow 2024-03-04 16:49:36 +01:00
parent 3ea41c82d4
commit d9c3f6f55a
18 changed files with 427 additions and 300 deletions

View File

@ -38,7 +38,9 @@ app.use(cors()); // Enable CORS for all routes
app.use(rateLimit({
windowMs: process.env.LIMITER_WINDOW,
max: process.env.LIMITER_MAXIMUM_PER_WINDOW,
message: { error: 'Too many requests from this IP, please try again later' }
message: {
error: 'Too many requests from this IP, please try again later'
}
})); // Apply the rate limiter middleware to all routes
/*

View File

@ -71,7 +71,9 @@ async function removeOrganizationAdmin (personId, organizationId) {
// TODO: If the user instead deletes their entire profile, the organization will not be deleted. Fix. (database schema)
const remainingAdministrators = await transaction('OrganizationAdministrator')
.where({ id_organization: organizationId });
.where({
id_organization: organizationId
});
if (remainingAdministrators.length === 0) {
// If no more users, delete the organization

View File

@ -98,7 +98,9 @@ async function updateOrganization (organization, organizationId, requester) {
*/
async function deleteOrganization(organizationId, requester) {
const numberOfDeletedRows = await knex('Organization')
.where({ id: organizationId })
.where({
id: organizationId
})
.whereExists(function () {
this.select('*')
.from('OrganizationAdministrator')

View File

@ -59,7 +59,9 @@ async function getPersonByEmail (email) {
async function getPersonById(id) {
return await knex('Person')
.select('*')
.where({ id })
.where({
id
})
.first();
}
@ -124,7 +126,9 @@ async function updatePerson (person, person_id) {
*/
async function deletePerson(personId) {
await knex('Person')
.where({ id: personId })
.where({
id: personId
})
.del();
}
@ -132,7 +136,9 @@ async function confirmActivation (personId) {
await knex.transaction(async (tr) => {
await knex('Person')
.where('id', personId)
.update({enabled: true});
.update({
enabled: true
});
await tr('ActivationLink')
.where('person_id', personId)

View File

@ -26,18 +26,26 @@ const jwtUtils = require('../utils/middleware_utils');
async function addOrganizationAdmin(req, res) {
// Ensure that the required fields are present before proceeding
if (!req.body.organization_id || !req.body.person_id) {
return res.status(400).json({ error: 'Invalid request' });
return res.status(400).json({
error: 'Invalid request'
});
}
try {
const success = await organizationAdminModel.addOrganizationAdministrator(req.body.person_id, req.body.organization_id, req.jwt.person_id);
if (success) {
return res.status(200).json({ success: true });
return res.status(200).json({
success: true
});
}
return res.status(403).json({ error: 'Forbidden' });
return res.status(403).json({
error: 'Forbidden'
});
} catch (error) {
console.error(`Error in function ${addOrganizationAdmin.name}: ${error}`);
res.status(500).json({ error: 'Internal server error' });
res.status(500).json({
error: 'Internal server error'
});
}
}
@ -53,15 +61,21 @@ async function addOrganizationAdmin (req, res) {
async function removeOrganizationAdmin(req, res) {
// Ensure that the required fields are present before proceeding
if (!req.body.organization_id) {
return res.status(400).json({ error: 'Invalid request' });
return res.status(400).json({
error: 'Invalid request'
});
}
try {
await organizationAdminModel.removeOrganizationAdmin(req.jwt.person_id, req.body.organization_id);
return res.status(200).json({ success: true });
return res.status(200).json({
success: true
});
} catch (error) {
console.error(`Error in function ${removeOrganizationAdmin.name}: ${error}`);
return res.status(500).json({ error: 'Internal server error' });
return res.status(500).json({
error: 'Internal server error'
});
}
}

View File

@ -26,7 +26,9 @@ const jwtUtils = require('../utils/middleware_utils');
async function createOrganizationPost(req, res) {
// Ensure that the required fields are present before proceeding
if (!req.body.organization_id || !req.body.content) {
return res.status(400).json({ error: 'Invalid request' });
return res.status(400).json({
error: 'Invalid request'
});
}
const organization = organizationPostModel.createOrganizationPost(
@ -39,7 +41,9 @@ async function createOrganizationPost (req, res) {
return res.status(200).json(insertedOrganization);
} catch (error) {
console.error(`Error in function ${createOrganizationPost.name}: ${error}`);
return res.status(500).json({ error: 'Internal server error' });
return res.status(500).json({
error: 'Internal server error'
});
}
}
@ -56,13 +60,19 @@ async function deleteOrganizationPost (req, res) {
const success = await organizationPostModel.deleteOrganizationPost(req.params.id, req.jwt.person_id);
if (success) {
return res.status(200).json({ success: true });
return res.status(200).json({
success: true
});
}
return res.status(401).json({ error: 'Forbidden' });
return res.status(401).json({
error: 'Forbidden'
});
} catch (error) {
console.error(`Error in function ${deleteOrganizationPost.name}: ${error}`);
res.status(500).json({ error: 'Internal server error' });
res.status(500).json({
error: 'Internal server error'
});
}
}

View File

@ -27,7 +27,9 @@ const jwtUtils = require('../utils/middleware_utils');
async function createOrganization(req, res) {
// Ensure that the required fields are present before proceeding
if (!req.body.name) {
return res.status(400).json({ error: 'Invalid request' });
return res.status(400).json({
error: 'Invalid request'
});
}
try {
@ -36,7 +38,9 @@ async function createOrganization (req, res) {
return res.status(200).json(insertedOrganization);
} catch (error) {
console.error(`Error in function ${createOrganization.name}: ${error}`);
res.status(500).json({ error: 'Internal server error' });
res.status(500).json({
error: 'Internal server error'
});
}
}
@ -66,19 +70,27 @@ async function updateOrganization (req, res) {
}
if (Object.keys(updateOrganization).length === 0) {
return res.status(400).json({ error: 'Bad request. No data to update' });
return res.status(400).json({
error: 'Bad request. No data to update'
});
}
try {
const isUpdateSuccessful = organizationModel.updateOrganization(updateOrganization, req.params.id, req.jwt.person_id);
if (isUpdateSuccessful) {
return res.status(200).json({ success: 'true' });
return res.status(200).json({
success: 'true'
});
} else {
return res.status(404).json({ error: 'Organization either not found or insufficient permissions' });
return res.status(404).json({
error: 'Organization either not found or insufficient permissions'
});
}
} catch (error) {
console.error(`Error in function ${updateOrganization.name}: ${error}`);
return res.status(500).json({ error: 'Internal server error' });
return res.status(500).json({
error: 'Internal server error'
});
}
}
@ -92,12 +104,18 @@ async function deleteOrganization (req, res) {
try {
const isDeleteSuccessful = await organizationModel.deleteOrganization(req.params.id, req.jwt.person_id);
if (isDeleteSuccessful) {
return res.status(200).json({ success: true });
return res.status(200).json({
success: true
});
}
return res.status(403).json({ error: 'Forbidden' });
return res.status(403).json({
error: 'Forbidden'
});
} catch (error) {
console.error(`Error in function ${deleteOrganization.name}: ${error}`);
return res.status(500).json({ error: 'Internal server error' });
return res.status(500).json({
error: 'Internal server error'
});
}
}
@ -116,11 +134,15 @@ async function getOrganization (req, res) {
if (organization) {
return res.status(200).json(organization);
} else {
return res.status(404).json({ error: 'Not found' });
return res.status(404).json({
error: 'Not found'
});
}
} catch (error) {
console.error(`Error in function ${getOrganization.name}: ${error}`);
return res.status(500).json({ error: 'Internal server error' });
return res.status(500).json({
error: 'Internal server error'
});
}
}

View File

@ -31,14 +31,20 @@ const express = require('express');
async function registerPerson(req, res) {
// Does this server allow users to register?
if (process.env.ALLOW_USER_REGISTRATION === 'false') {
return res.status(403).json({ error: 'Users cannot register on this server' });
return res.status(403).json({
error: 'Users cannot register on this server'
});
}
// Ensure that the required fields are present before proceeding
if (!req.body.display_name || !req.body.email || !req.body.password) {
return res.status(400).json({ error: 'Some or all required fields are missing' });
return res.status(400).json({
error: 'Some or all required fields are missing'
});
}
if (!validator.validateEmail(req.body.email)) {
return res.status(400).json({ error: 'The email is not in a valid format' });
return res.status(400).json({
error: 'The email is not in a valid format'
});
}
// Generate activation link token
@ -50,7 +56,9 @@ async function registerPerson (req, res) {
// Check whether e-mail exists already (enforced by database constraints)
const existingUser = await personModel.getPersonByEmail(req.body.email);
if (existingUser) {
return res.status(409).json({ error: 'E-mail already in use' });
return res.status(409).json({
error: 'E-mail already in use'
});
}
const personToInsert = personModel.createPerson(
req.body.email,
@ -63,10 +71,14 @@ async function registerPerson (req, res) {
req.body.about_me,
req.body.qualification);
await personModel.registerPerson(personToInsert, activationLink);
return res.status(200).json({ activationLink });
return res.status(200).json({
activationLink
});
} catch (error) {
console.error(`Error in function ${registerPerson.name}: ${error}`);
res.status(500).json({ error: 'Internal server error' });
res.status(500).json({
error: 'Internal server error'
});
}
}
@ -83,20 +95,28 @@ async function registerPerson (req, res) {
async function login(req, res) {
// Ensure that the required fields are present before proceeding
if (!req.body.email || !req.body.password) {
return res.status(400).json({ error: 'Invalid request' });
return res.status(400).json({
error: 'Invalid request'
});
}
try {
const person = await personModel.getPersonByEmailAndPassword(req.body.email, req.body.password);
if (person) {
const token = jwtUtils.generateToken(person.id);
return res.status(200).json({ token });
return res.status(200).json({
token
});
} else {
return res.status(401).json({ error: 'Invalid credentials' });
return res.status(401).json({
error: 'Invalid credentials'
});
}
} catch (error) {
console.error(`Error in function ${login.name}: ${error}`);
return res.status(500).json({ error: 'Internal server error' });
return res.status(500).json({
error: 'Internal server error'
});
}
}
@ -116,10 +136,14 @@ async function getPerson (req, res) {
delete person.password; // remove password field for security reasons
return res.status(200).send(person);
}
return res.status(404).json({ error: 'Not found' });
return res.status(404).json({
error: 'Not found'
});
} catch (error) {
console.error(`Error in function ${getPerson.name}: ${error}`);
return res.status(500).json({ error: 'Internal server error' });
return res.status(500).json({
error: 'Internal server error'
});
}
}
@ -138,10 +162,14 @@ async function getMyself (req, res) {
delete person.password;
return res.status(200).send(person);
}
return res.status(404).json({ error: 'Not found' });
return res.status(404).json({
error: 'Not found'
});
} catch (error) {
console.error(`Error in function ${getMyself.name}: ${error}`);
return res.status(500).json({ error: 'Internal server error' });
return res.status(500).json({
error: 'Internal server error'
});
}
}
@ -167,7 +195,9 @@ async function updatePerson (req, res) {
if (validator.isPostgresDateFormatValid(req.body.date_of_birth)) {
updatePerson.date_of_birth = req.body.date_of_birth;
} else {
return res.status(400).json({ error: 'Date of birth format not valid. Please specify a YYYY-MM-DD date' });
return res.status(400).json({
error: 'Date of birth format not valid. Please specify a YYYY-MM-DD date'
});
}
}
@ -190,30 +220,42 @@ async function updatePerson (req, res) {
// If we are tying to change password, the old password must be provided
if (req.body.old_password || req.body.new_password) {
if (!req.body.old_password) {
return res.status(401).json({ error: 'The old password must be specified' });
return res.status(401).json({
error: 'The old password must be specified'
});
}
if (!req.body.new_password) {
return res.status(401).json({ error: 'The new password must be specified' });
return res.status(401).json({
error: 'The new password must be specified'
});
}
const user = await personModel.getPersonById(req.jwt.person_id);
const passwordMatches = await bcrypt.compare(req.body.old_password, user.password);
if (passwordMatches) {
updatePerson.password = await bcrypt.hash(req.body.new_password, 10);
} else {
return res.status(401).json({ error: 'Password verification failed' });
return res.status(401).json({
error: 'Password verification failed'
});
}
}
if (Object.keys(updatePerson).length === 0) {
return res.status(400).json({ error: 'Bad request. No data to update' });
return res.status(400).json({
error: 'Bad request. No data to update'
});
}
try {
await personModel.updatePerson(updatePerson, req.jwt.person_id);
return res.status(200).json({ success: 'true' });
return res.status(200).json({
success: 'true'
});
} catch (error) {
console.error(`Error in function ${updatePerson.name}: ${error}`);
return res.status(500).json({ error: 'Internal server error' });
return res.status(500).json({
error: 'Internal server error'
});
}
}
@ -230,10 +272,14 @@ async function deletePerson (req, res) {
// TODO: Delete Organization if this user was its only administrator
try {
await personModel.deletePerson(req.jwt.person_id);
return res.status(200).json({ success: true });
return res.status(200).json({
success: true
});
} catch (error) {
console.error(`Error in function ${deletePerson.name}: ${error}`);
return res.status(500).json({ error: 'Internal server error' });
return res.status(500).json({
error: 'Internal server error'
});
}
}
@ -249,13 +295,19 @@ async function confirmActivation(req, res){
try {
const personId = await activationModel.getPersonIdByIdentifier(req.query.q);
if (!personId) {
return res.status(401).json({error: 'Activation Link either not valid or expired'});
return res.status(401).json({
error: 'Activation Link either not valid or expired'
});
}
await personModel.confirmActivation(personId);
return res.status(200).json({ success: true });
return res.status(200).json({
success: true
});
} catch (error) {
console.error(`Error in function ${confirmActivation.name}: ${error}`);
return res.status(500).json({ error: 'Internal server error' });
return res.status(500).json({
error: 'Internal server error'
});
}
}

View File

@ -30,12 +30,16 @@ function verifyToken (req, res, next) {
const token = req.headers.authorization;
if (!token) {
return res.status(401).send({ error: 'No token provided' });
return res.status(401).send({
error: 'No token provided'
});
}
jwt.verify(token, process.env.JWT_SECRET_KEY, (err, decoded) => {
if (err) {
return res.status(401).send({ error: 'Failed to authenticate token' });
return res.status(401).send({
error: 'Failed to authenticate token'
});
}
// If the token is valid, store the decoded data in the request object

View File

@ -1,10 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log in - Blink</title>
<link rel="stylesheet" href="../css/login-register.css">
</head>
<body>
<!-- partial:index.partial.html -->
<div id="login-form-wrap">
@ -12,11 +14,13 @@
<form id="login-form" method="POST">
<p>
<input type="email" id="email" name="email" placeholder="Email Address" required><i class="validation"><span></span><span></span></i>
<input type="email" id="email" name="email" placeholder="Email Address" required><i
class="validation"><span></span><span></span></i>
</p>
<p>
<input type="password" id="password" name="password" placeholder="Password" required><i class="validation"><span></span><span></span></i>
<input type="password" id="password" name="password" placeholder="Password" required><i
class="validation"><span></span><span></span></i>
</p>
<p>
@ -24,7 +28,8 @@
</p>
</form>
<div id="create-account-wrap">
<p>Not a member? <a href="./register.html">Create Account</a><p>
<p>Not a member? <a href="./register.html">Create Account</a>
<p>
</div>
</div>
@ -42,7 +47,8 @@
method: "POST",
body: JSON.stringify({
email: email,
password: password }),
password: password
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
@ -54,12 +60,12 @@
console.log(`Login was successful. Token is ${data.token}`);
document.cookie = `token=${data.token};`;
window.location.href = 'userprofile.html?id=myself';
}
else{
} else {
alert(data.error);
}
}
</script>
</body>
</html>

View File

@ -1,11 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<link rel="stylesheet" href="../css/organization.css">
</head>
<body style="display: none;">
<div class="container">
<div class="hiring-badge" style="display: none;" id="isHiringBadge">Now Hiring</div>
@ -45,8 +47,7 @@
if (response.ok) {
populateFields(data.name, data.location, data.description, data.is_hiring);
document.body.style.display = "block"; // Show page
}
else {
} else {
alert(data.error);
}
}
@ -59,17 +60,15 @@
if (isHiring === true) {
document.getElementById('isHiring').textContent = 'Yes';
document.getElementById('isHiringBadge').style.display = 'block';
}
else if (isHiring === false) {
} else if (isHiring === false) {
document.getElementById('isHiring').textContent = 'No';
}
else {
} else {
document.getElementById('isHiring').textContent = 'Not specified';
}
}
</script>
</body>
</html>

View File

@ -1,11 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up to Blink</title>
<link rel="stylesheet" href="../css/login-register.css">
<script src=""></script>
</head>
<body>
<!-- partial:index.partial.html -->
<div id="login-form-wrap">
@ -13,15 +15,18 @@
<form id="login-form">
<p>
<input type="text" id="displayname" name="displayname" placeholder="Your name" required><i class="validation"><span></span><span></span></i>
<input type="text" id="displayname" name="displayname" placeholder="Your name" required><i
class="validation"><span></span><span></span></i>
</p>
<p>
<input type="email" id="email" name="email" placeholder="Email Address" required><i class="validation"><span></span><span></span></i>
<input type="email" id="email" name="email" placeholder="Email Address" required><i
class="validation"><span></span><span></span></i>
</p>
<p>
<input type="password" id="password" name="password" placeholder="Password" required><i class="validation"><span></span><span></span></i>
<input type="password" id="password" name="password" placeholder="Password" required><i
class="validation"><span></span><span></span></i>
</p>
<p>
@ -29,7 +34,8 @@
</p>
</form>
<div id="create-account-wrap">
<p>Already a member? <a href="./login.html">Login</a><p>
<p>Already a member? <a href="./login.html">Login</a>
<p>
</div>
</div>
@ -37,7 +43,6 @@
<script src="../js/utils.js"></script>
<script>
function register() {
const display_name = document.getElementById('displayname').value;
const email = document.getElementById('email').value;
@ -53,7 +58,11 @@
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ display_name, email, password }),
body: JSON.stringify({
display_name,
email,
password
}),
};
fetch(`${API_URL}/register`, options)
@ -73,4 +82,5 @@
</script>
</body>
</html>

View File

@ -1,11 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Title</title>
<link rel="stylesheet" href="../css/profile.css">
</head>
<body style="display: none;">
<div class="container">
<div class="edit-badge" style="display: none;" id="editBadge" onclick="editProfile()">Edit</div>
@ -69,8 +71,7 @@
"authorization": token
}
});
}
else {
} else {
response = await fetch(`${API_URL}/person/${idToDisplay}/details`, {
headers: {
"Content-type": "application/json; charset=UTF-8",
@ -82,11 +83,9 @@
if (response.ok) {
populateFields(data.display_name, data.email, data.about_me, data.qualification);
document.body.style.display = 'block'; // Show page
}
else if (response.status == 401){
} else if (response.status == 401) {
window.location.href = 'login.html';
}
else{
} else {
alert(`Unable to load profile. Error: ${data.error}`);
}
}
@ -102,9 +101,8 @@
function editProfile() {
alert('Editing');
}
</script>
</body>
</html>
</html>