mirror of
https://github.com/xfarrow/blink
synced 2025-06-27 09:03:02 +02:00
npx eslint --fix
This commit is contained in:
@ -20,10 +20,9 @@ const rateLimit = require('express-rate-limit');
|
|||||||
const personRoutes = require('./routes/person_routes.js');
|
const personRoutes = require('./routes/person_routes.js');
|
||||||
const organizationRoutes = require('./routes/organization_routes.js');
|
const organizationRoutes = require('./routes/organization_routes.js');
|
||||||
const organizationAdminRoutes = require('./routes/organization_admin_routes.js');
|
const organizationAdminRoutes = require('./routes/organization_admin_routes.js');
|
||||||
const organizationPostRoutes = require('./routes/organization_post_routes.js')
|
const organizationPostRoutes = require('./routes/organization_post_routes.js');
|
||||||
const jwt_utils = require('./utils/jwt_utils.js');
|
const jwt_utils = require('./utils/jwt_utils.js');
|
||||||
|
|
||||||
|
|
||||||
// Application configuration
|
// Application configuration
|
||||||
const app = express();
|
const app = express();
|
||||||
app.use(express.json()); // Middleware which parses JSON for POST requests
|
app.use(express.json()); // Middleware which parses JSON for POST requests
|
||||||
@ -31,7 +30,7 @@ app.use(cors()); // Enable CORS for all routes
|
|||||||
app.use(rateLimit({
|
app.use(rateLimit({
|
||||||
windowMs: process.env.LIMITER_WINDOW,
|
windowMs: process.env.LIMITER_WINDOW,
|
||||||
max: process.env.LIMITER_MAXIMUM_PER_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
|
})); // Apply the rate limiter middleware to all routes
|
||||||
|
|
||||||
const publicRoutes = express.Router();
|
const publicRoutes = express.Router();
|
||||||
|
@ -23,10 +23,10 @@ const knex = require('../utils/knex_config');
|
|||||||
*/
|
*/
|
||||||
function organization (name, location, description, is_hiring) {
|
function organization (name, location, description, is_hiring) {
|
||||||
const organization = {
|
const organization = {
|
||||||
name: name,
|
name,
|
||||||
location: location,
|
location,
|
||||||
description: description,
|
description,
|
||||||
is_hiring: is_hiring
|
is_hiring
|
||||||
};
|
};
|
||||||
return organization;
|
return organization;
|
||||||
}
|
}
|
||||||
@ -59,7 +59,7 @@ async function insertOrganization(organization, organizationAdministratorId){
|
|||||||
await trx('OrganizationAdministrator')
|
await trx('OrganizationAdministrator')
|
||||||
.insert({
|
.insert({
|
||||||
id_person: organizationAdministratorId,
|
id_person: organizationAdministratorId,
|
||||||
id_organization: organizationResult[0].id,
|
id_organization: organizationResult[0].id
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -108,7 +108,7 @@ async function updateOrganizationIfAdministrator(organization, organizationId, p
|
|||||||
this.select('*')
|
this.select('*')
|
||||||
.from('OrganizationAdministrator')
|
.from('OrganizationAdministrator')
|
||||||
.where('id_person', personId)
|
.where('id_person', personId)
|
||||||
.where('id_organization', organizationId)
|
.where('id_organization', organizationId);
|
||||||
})
|
})
|
||||||
.update(organization);
|
.update(organization);
|
||||||
return numberOfUpdatedRows == 1;
|
return numberOfUpdatedRows == 1;
|
||||||
@ -128,7 +128,7 @@ async function deleteOrganizationIfAdmin(organizationId, personId){
|
|||||||
this.select('*')
|
this.select('*')
|
||||||
.from('OrganizationAdministrator')
|
.from('OrganizationAdministrator')
|
||||||
.where('id_person', personId)
|
.where('id_person', personId)
|
||||||
.where('id_organization', organizationId)
|
.where('id_organization', organizationId);
|
||||||
})
|
})
|
||||||
.del();
|
.del();
|
||||||
return numberOfDeletedRows == 1;
|
return numberOfDeletedRows == 1;
|
||||||
|
@ -28,12 +28,12 @@ const bcrypt = require('bcrypt');
|
|||||||
function person (email, password, display_name, date_of_birth, available, enabled, place_of_living) {
|
function person (email, password, display_name, date_of_birth, available, enabled, place_of_living) {
|
||||||
const person = {
|
const person = {
|
||||||
email: email.toLowerCase(),
|
email: email.toLowerCase(),
|
||||||
password: password,
|
password,
|
||||||
display_name: display_name,
|
display_name,
|
||||||
date_of_birth: date_of_birth,
|
date_of_birth,
|
||||||
available: available,
|
available,
|
||||||
enabled: enabled,
|
enabled,
|
||||||
place_of_living: place_of_living
|
place_of_living
|
||||||
};
|
};
|
||||||
return person;
|
return person;
|
||||||
}
|
}
|
||||||
@ -57,7 +57,7 @@ async function getPersonByEmail(email){
|
|||||||
async function getPersonById (id) {
|
async function getPersonById (id) {
|
||||||
return await knex('Person')
|
return await knex('Person')
|
||||||
.select('*')
|
.select('*')
|
||||||
.where({ id: id })
|
.where({ id })
|
||||||
.first();
|
.first();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -81,7 +81,7 @@ async function registerPerson(person, activationLink){
|
|||||||
enabled: person.enabled,
|
enabled: person.enabled,
|
||||||
place_of_living: person.place_of_living
|
place_of_living: person.place_of_living
|
||||||
})
|
})
|
||||||
.returning("id");
|
.returning('id');
|
||||||
await tr('ActivationLink')
|
await tr('ActivationLink')
|
||||||
.insert({
|
.insert({
|
||||||
person_id: personIdResult[0].id,
|
person_id: personIdResult[0].id,
|
||||||
@ -134,7 +134,6 @@ async function deletePerson(person_id){
|
|||||||
.del();
|
.del();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Exporting a function
|
// Exporting a function
|
||||||
// means making a JavaScript function defined in one
|
// means making a JavaScript function defined in one
|
||||||
// module available for use in another module.
|
// module available for use in another module.
|
||||||
|
@ -23,24 +23,22 @@ const organization_admin_model = require('../models/organization_admin_model');
|
|||||||
* Required field(s): organization_id, person_id
|
* Required field(s): organization_id, person_id
|
||||||
*/
|
*/
|
||||||
async function addOrganizationAdmin (req, res) {
|
async function addOrganizationAdmin (req, res) {
|
||||||
|
|
||||||
// Ensure that the required fields are present before proceeding
|
// Ensure that the required fields are present before proceeding
|
||||||
if (!req.body.organization_id || !req.body.person_id) {
|
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 {
|
try {
|
||||||
const isPersonAdmin = await organization_admin_model.isPersonAdmin(req.jwt.person_id, req.body.organization_id);
|
const isPersonAdmin = await organization_admin_model.isPersonAdmin(req.jwt.person_id, req.body.organization_id);
|
||||||
// TOC/TOU
|
// TOC/TOU
|
||||||
if (!isPersonAdmin) {
|
if (!isPersonAdmin) {
|
||||||
return res.status(401).json({error : "Forbidden"});
|
return res.status(401).json({ error: 'Forbidden' });
|
||||||
}
|
}
|
||||||
await organization_admin_model.addOrganizationAdministrator(req.body.person_id, req.body.organization_id);
|
await organization_admin_model.addOrganizationAdministrator(req.body.person_id, req.body.organization_id);
|
||||||
return res.status(200).json({ success: true });
|
return res.status(200).json({ success: true });
|
||||||
}
|
} catch (error) {
|
||||||
catch (error) {
|
|
||||||
console.error('Error while adding organization admin: ' + error);
|
console.error('Error while adding organization admin: ' + error);
|
||||||
res.status(500).json({error : "Internal server error"});
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -54,19 +52,17 @@ async function addOrganizationAdmin(req, res){
|
|||||||
* Required field(s): organization_id
|
* Required field(s): organization_id
|
||||||
*/
|
*/
|
||||||
async function removeOrganizationAdmin (req, res) {
|
async function removeOrganizationAdmin (req, res) {
|
||||||
|
|
||||||
// Ensure that the required fields are present before proceeding
|
// Ensure that the required fields are present before proceeding
|
||||||
if (!req.body.organization_id) {
|
if (!req.body.organization_id) {
|
||||||
return res.status(400).json({ error : "Invalid request"});
|
return res.status(400).json({ error: 'Invalid request' });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await organization_admin_model.removeOrganizationAdmin(req.jwt.person_id, req.body.organization_id);
|
await organization_admin_model.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) {
|
||||||
catch (error){
|
|
||||||
console.error(error);
|
console.error(error);
|
||||||
return res.status(500).json({ error: "Internal server error"});
|
return res.status(500).json({ error: 'Internal server error' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -22,10 +22,9 @@ const knex = require('../utils/knex_config');
|
|||||||
* @returns the inserted Post
|
* @returns the inserted Post
|
||||||
*/
|
*/
|
||||||
async function createOrganizationPost (req, res) {
|
async function createOrganizationPost (req, res) {
|
||||||
|
|
||||||
// Ensure that the required fields are present before proceeding
|
// Ensure that the required fields are present before proceeding
|
||||||
if (!req.body.organization_id || !req.body.content) {
|
if (!req.body.organization_id || !req.body.content) {
|
||||||
return res.status(400).json({ error : "Invalid request"});
|
return res.status(400).json({ error: 'Invalid request' });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -39,7 +38,7 @@ async function createOrganizationPost(req, res){
|
|||||||
// Non-exploitable TOC/TOU weakness
|
// Non-exploitable TOC/TOU weakness
|
||||||
// For more information https://softwareengineering.stackexchange.com/questions/451038/when-should-i-be-worried-of-time-of-check-time-of-use-vulnerabilities-during-dat
|
// For more information https://softwareengineering.stackexchange.com/questions/451038/when-should-i-be-worried-of-time-of-check-time-of-use-vulnerabilities-during-dat
|
||||||
if (!isOrganizationAdmin) {
|
if (!isOrganizationAdmin) {
|
||||||
return res.status(403).json({error : "Forbidden"});
|
return res.status(403).json({ error: 'Forbidden' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const organizationPost = await knex('OrganizationPost')
|
const organizationPost = await knex('OrganizationPost')
|
||||||
@ -50,10 +49,9 @@ async function createOrganizationPost(req, res){
|
|||||||
})
|
})
|
||||||
.returning('*');
|
.returning('*');
|
||||||
return res.status(200).json(organizationPost[0]);
|
return res.status(200).json(organizationPost[0]);
|
||||||
}
|
} catch (error) {
|
||||||
catch (error) {
|
console.log('Error while creating Organization Post: ' + error);
|
||||||
console.log("Error while creating Organization Post: " + error);
|
return res.status(500).json({ error: 'Internal server error' });
|
||||||
return res.status(500).json({error : "Internal server error"});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,7 +64,6 @@ async function createOrganizationPost(req, res){
|
|||||||
* Required field(s): none.
|
* Required field(s): none.
|
||||||
*/
|
*/
|
||||||
async function deleteOrganizationPost (req, res) {
|
async function deleteOrganizationPost (req, res) {
|
||||||
|
|
||||||
const organizationPostIdToDelete = req.params.id;
|
const organizationPostIdToDelete = req.params.id;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -83,14 +80,12 @@ async function deleteOrganizationPost(req, res){
|
|||||||
.where('id', organizationPostIdToDelete)
|
.where('id', organizationPostIdToDelete)
|
||||||
.del();
|
.del();
|
||||||
return res.status(200).json({ success: true });
|
return res.status(200).json({ success: true });
|
||||||
|
} else {
|
||||||
|
return res.status(401).json({ error: 'Forbidden' });
|
||||||
}
|
}
|
||||||
else{
|
} catch (error) {
|
||||||
return res.status(401).json({error : "Forbidden"});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
console.log(error);
|
console.log(error);
|
||||||
res.status(500).json({error : "Internal server error"});
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -23,20 +23,18 @@ const organization_model = require('../models/organization_model');
|
|||||||
* @returns the inserted organization
|
* @returns the inserted organization
|
||||||
*/
|
*/
|
||||||
async function createOrganization (req, res) {
|
async function createOrganization (req, res) {
|
||||||
|
|
||||||
// Ensure that the required fields are present before proceeding
|
// Ensure that the required fields are present before proceeding
|
||||||
if (!req.body.name) {
|
if (!req.body.name) {
|
||||||
return res.status(400).json({ error : "Invalid request"});
|
return res.status(400).json({ error: 'Invalid request' });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const organization = organization_model.organization(req.body.name, req.body.location, req.body.description, req.body.is_hiring);
|
const organization = organization_model.organization(req.body.name, req.body.location, req.body.description, req.body.is_hiring);
|
||||||
await organization_model.insertOrganization(organization, req.jwt.person_id);
|
await organization_model.insertOrganization(organization, req.jwt.person_id);
|
||||||
return res.status(200).json({ Organization: organization });
|
return res.status(200).json({ Organization: organization });
|
||||||
}
|
} catch (error) {
|
||||||
catch (error){
|
|
||||||
console.error('Error creating Organization:', error);
|
console.error('Error creating Organization:', error);
|
||||||
res.status(500).json({error : "Internal server error"});
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -47,7 +45,6 @@ async function createOrganization(req, res){
|
|||||||
* Required field(s): none.
|
* Required field(s): none.
|
||||||
*/
|
*/
|
||||||
async function updateOrganization (req, res) {
|
async function updateOrganization (req, res) {
|
||||||
|
|
||||||
const updateOrganization = {};
|
const updateOrganization = {};
|
||||||
|
|
||||||
if (req.body.name) {
|
if (req.body.name) {
|
||||||
@ -67,21 +64,19 @@ async function updateOrganization(req, res){
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (Object.keys(updateOrganization).length === 0) {
|
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 {
|
try {
|
||||||
const isUpdateSuccessful = organization_model.updateOrganizationIfAdministrator(updateOrganization, req.params.id, req.jwt.person_id);
|
const isUpdateSuccessful = organization_model.updateOrganizationIfAdministrator(updateOrganization, req.params.id, req.jwt.person_id);
|
||||||
if (isUpdateSuccessful) {
|
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' });
|
||||||
}
|
}
|
||||||
else{
|
} catch (error) {
|
||||||
return res.status(404).json({error : "Organization either not found or insufficient permissions"});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
console.log(error);
|
console.log(error);
|
||||||
return res.status(500).json({error : "Internal server error"});
|
return res.status(500).json({ error: 'Internal server error' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -95,15 +90,13 @@ async function deleteOrganization(req, res){
|
|||||||
try {
|
try {
|
||||||
const isDeleteSuccessful = organization_model.deleteOrganizationIfAdmin(req.params.id, req.jwt.person_id);
|
const isDeleteSuccessful = organization_model.deleteOrganizationIfAdmin(req.params.id, req.jwt.person_id);
|
||||||
if (isDeleteSuccessful) {
|
if (isDeleteSuccessful) {
|
||||||
return res.status(403).json({error: "Forbidden"});
|
return res.status(403).json({ error: 'Forbidden' });
|
||||||
}
|
} else {
|
||||||
else{
|
|
||||||
return res.status(200).json({ success: true });
|
return res.status(200).json({ success: true });
|
||||||
}
|
}
|
||||||
}
|
} catch (error) {
|
||||||
catch (error) {
|
|
||||||
console.error(error);
|
console.error(error);
|
||||||
return res.status(500).json({error : "Internal server error"});
|
return res.status(500).json({ error: 'Internal server error' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -121,14 +114,12 @@ async function getOrganization(req, res){
|
|||||||
const organization = await organization_model.getOrganizationById(req.params.id);
|
const organization = await organization_model.getOrganizationById(req.params.id);
|
||||||
if (organization) {
|
if (organization) {
|
||||||
return res.status(200).json(organization);
|
return res.status(200).json(organization);
|
||||||
|
} else {
|
||||||
|
return res.status(404).json({ error: 'Not found' });
|
||||||
}
|
}
|
||||||
else{
|
} catch (error) {
|
||||||
return res.status(404).json({error : "Not found"});
|
console.error('Error retrieving an organization: ' + error);
|
||||||
}
|
return res.status(500).json({ error: 'Internal server error' });
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
console.error("Error retrieving an organization: " + error);
|
|
||||||
return res.status(500).json({error : "Internal server error"});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -138,4 +129,3 @@ module.exports = {
|
|||||||
updateOrganization,
|
updateOrganization,
|
||||||
deleteOrganization
|
deleteOrganization
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -28,17 +28,16 @@ const person_model = require('../models/person_model');
|
|||||||
* @returns The activationlink identifier
|
* @returns The activationlink identifier
|
||||||
*/
|
*/
|
||||||
async function registerPerson (req, res) {
|
async function registerPerson (req, res) {
|
||||||
|
|
||||||
// Does this server allow users to register?
|
// Does this server allow users to register?
|
||||||
if (process.env.ALLOW_USER_REGISTRATION === 'false') {
|
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
|
// Ensure that the required fields are present before proceeding
|
||||||
if (!req.body.display_name || !req.body.email || !req.body.password) {
|
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)) {
|
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
|
// Generate activation link token
|
||||||
@ -50,7 +49,7 @@ async function registerPerson(req, res){
|
|||||||
// Check whether e-mail exists already (enforced by database constraints)
|
// Check whether e-mail exists already (enforced by database constraints)
|
||||||
const existingUser = await person_model.getPersonByEmail(req.body.email);
|
const existingUser = await person_model.getPersonByEmail(req.body.email);
|
||||||
if (existingUser) {
|
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 = person_model.person(
|
const personToInsert = person_model.person(
|
||||||
req.body.email,
|
req.body.email,
|
||||||
@ -61,11 +60,10 @@ async function registerPerson(req, res){
|
|||||||
true,
|
true,
|
||||||
req.body.place_of_living);
|
req.body.place_of_living);
|
||||||
await person_model.registerPerson(personToInsert, activationLink);
|
await person_model.registerPerson(personToInsert, activationLink);
|
||||||
return res.status(200).json({ activationLink: activationLink });
|
return res.status(200).json({ activationLink });
|
||||||
}
|
} catch (error) {
|
||||||
catch (error){
|
|
||||||
console.error('Error registering person:', error);
|
console.error('Error registering person:', error);
|
||||||
res.status(500).json({error : "Internal server error"});
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -80,24 +78,22 @@ async function registerPerson(req, res){
|
|||||||
* @returns The token
|
* @returns The token
|
||||||
*/
|
*/
|
||||||
async function login (req, res) {
|
async function login (req, res) {
|
||||||
|
|
||||||
// Ensure that the required fields are present before proceeding
|
// Ensure that the required fields are present before proceeding
|
||||||
if (!req.body.email || !req.body.password) {
|
if (!req.body.email || !req.body.password) {
|
||||||
return res.status(400).json({error : "Invalid request"});
|
return res.status(400).json({ error: 'Invalid request' });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const person = await person_model.getPersonByEmailAndPassword(req.body.email, req.body.password);
|
const person = await person_model.getPersonByEmailAndPassword(req.body.email, req.body.password);
|
||||||
if (person) {
|
if (person) {
|
||||||
const token = jwt_utils.generateToken(person.id);
|
const token = jwt_utils.generateToken(person.id);
|
||||||
res.status(200).json({token: token });
|
res.status(200).json({ token });
|
||||||
}
|
} else {
|
||||||
else{
|
res.status(401).json({ error: 'Unauthorized' });
|
||||||
res.status(401).json({error : "Unauthorized"});
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error logging in: ', error);
|
console.error('Error logging in: ', error);
|
||||||
res.status(500).json({error : "Internal server error"});
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -116,15 +112,14 @@ async function getPerson(req, res){
|
|||||||
if (person) {
|
if (person) {
|
||||||
// I am retrieving either myself or an enabled user
|
// I am retrieving either myself or an enabled user
|
||||||
if (person.id == req.jwt.person_id || person.enabled) {
|
if (person.id == req.jwt.person_id || person.enabled) {
|
||||||
delete person['password']; // remove password field for security reasons
|
delete person.password; // remove password field for security reasons
|
||||||
return res.status(200).send(person);
|
return res.status(200).send(person);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return res.status(404).json({error: "Not found"});
|
return res.status(404).json({ error: 'Not found' });
|
||||||
}
|
} catch (error) {
|
||||||
catch (error) {
|
console.log('Error while getting person: ' + error);
|
||||||
console.log("Error while getting person: " + error);
|
return res.status(500).json({ error: 'Internal server error' });
|
||||||
return res.status(500).json({error : "Internal server error"});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -140,14 +135,13 @@ async function getMyself(req, res){
|
|||||||
try {
|
try {
|
||||||
const person = await person_model.getPersonById(req.jwt.person_id);
|
const person = await person_model.getPersonById(req.jwt.person_id);
|
||||||
if (person) {
|
if (person) {
|
||||||
delete person['password'];
|
delete person.password;
|
||||||
return res.status(200).send(person);
|
return res.status(200).send(person);
|
||||||
}
|
}
|
||||||
return res.status(404).json({error: "Not found"});
|
return res.status(404).json({ error: 'Not found' });
|
||||||
}
|
} catch (error) {
|
||||||
catch (error){
|
console.log('Error while getting myself: ' + error);
|
||||||
console.log("Error while getting myself: " + error);
|
return res.status(500).json({ error: 'Internal server error' });
|
||||||
return res.status(500).json({error : "Internal server error"});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -162,9 +156,8 @@ async function getMyself(req, res){
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
async function updatePerson (req, res) {
|
async function updatePerson (req, res) {
|
||||||
|
|
||||||
if (req.jwt.person_id != req.params.id) {
|
if (req.jwt.person_id != req.params.id) {
|
||||||
return res.status(403).json({ error : "Forbidden"});
|
return res.status(403).json({ error: 'Forbidden' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const updatePerson = {};
|
const updatePerson = {};
|
||||||
@ -176,9 +169,8 @@ async function updatePerson(req, res){
|
|||||||
if (req.body.date_of_birth) {
|
if (req.body.date_of_birth) {
|
||||||
if (validator.isPostgresDateFormatValid(req.body.date_of_birth)) {
|
if (validator.isPostgresDateFormatValid(req.body.date_of_birth)) {
|
||||||
updatePerson.date_of_birth = req.body.date_of_birth;
|
updatePerson.date_of_birth = req.body.date_of_birth;
|
||||||
}
|
} else {
|
||||||
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"});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -199,23 +191,21 @@ async function updatePerson(req, res){
|
|||||||
const passwordMatches = await bcrypt.compare(req.body.old_password, user.password);
|
const passwordMatches = await bcrypt.compare(req.body.old_password, user.password);
|
||||||
if (passwordMatches) {
|
if (passwordMatches) {
|
||||||
updatePerson.password = await bcrypt.hash(req.body.new_password, 10);
|
updatePerson.password = await bcrypt.hash(req.body.new_password, 10);
|
||||||
}
|
} else {
|
||||||
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) {
|
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 {
|
try {
|
||||||
await person_model.updatePerson(updatePerson, req.params.id);
|
await person_model.updatePerson(updatePerson, req.params.id);
|
||||||
return res.status(200).json({ success : "true"});
|
return res.status(200).json({ success: 'true' });
|
||||||
}
|
} catch (error) {
|
||||||
catch (error) {
|
console.log('Error while updating a Person: ' + error);
|
||||||
console.log("Error while updating a Person: " + error);
|
return res.status(500).json({ error: 'Internal server error' });
|
||||||
return res.status(500).json({ error : "Internal server error"});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -233,10 +223,9 @@ async function deletePerson(req, res) {
|
|||||||
try {
|
try {
|
||||||
await person_model.deletePerson(req.jwt.person_id);
|
await person_model.deletePerson(req.jwt.person_id);
|
||||||
return res.status(200).json({ success: true });
|
return res.status(200).json({ success: true });
|
||||||
}
|
} catch (error) {
|
||||||
catch (error) {
|
console.log('Error deleting a Person: ' + error);
|
||||||
console.log("Error deleting a Person: " + error);
|
return res.status(500).json({ error: 'Internal server error' });
|
||||||
return res.status(500).json({error : "Internal server error"});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -16,7 +16,7 @@ const jwt = require('jsonwebtoken');
|
|||||||
function generateToken (person_id) {
|
function generateToken (person_id) {
|
||||||
// The payload the JWT will carry within itself
|
// The payload the JWT will carry within itself
|
||||||
const payload = {
|
const payload = {
|
||||||
person_id: person_id
|
person_id
|
||||||
};
|
};
|
||||||
|
|
||||||
const token = jwt.sign(payload, process.env.JWT_SECRET_KEY, {
|
const token = jwt.sign(payload, process.env.JWT_SECRET_KEY, {
|
||||||
|
@ -9,10 +9,10 @@ describe('Person Tests', () => {
|
|||||||
const response = await request(app)
|
const response = await request(app)
|
||||||
.post('/api/register')
|
.post('/api/register')
|
||||||
.send({
|
.send({
|
||||||
email : "johntestdoe@mail.org",
|
email: 'johntestdoe@mail.org',
|
||||||
password : "password",
|
password: 'password',
|
||||||
display_name : "John Doe"
|
display_name: 'John Doe'
|
||||||
})
|
});
|
||||||
expect(response.status).toBe(200);
|
expect(response.status).toBe(200);
|
||||||
expect(response.body).toEqual({ activationLink: expect.any(String) });
|
expect(response.body).toEqual({ activationLink: expect.any(String) });
|
||||||
});
|
});
|
||||||
@ -21,10 +21,10 @@ describe('Person Tests', () => {
|
|||||||
const response = await request(app)
|
const response = await request(app)
|
||||||
.post('/api/register')
|
.post('/api/register')
|
||||||
.send({
|
.send({
|
||||||
email : "this is not an email",
|
email: 'this is not an email',
|
||||||
password : "password",
|
password: 'password',
|
||||||
display_name : "John Doe"
|
display_name: 'John Doe'
|
||||||
})
|
});
|
||||||
expect(response.status).toBe(400);
|
expect(response.status).toBe(400);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -1 +1 @@
|
|||||||
const apiUrl = "http://localhost:3000/blinkapi";
|
const apiUrl = 'http://localhost:3000/blinkapi';
|
||||||
|
@ -1,30 +1,27 @@
|
|||||||
// https://javascript.info/callbacks
|
// https://javascript.info/callbacks
|
||||||
|
|
||||||
function execute_action (param, callback) {
|
function execute_action (param, callback) {
|
||||||
|
if (param == 'something') {
|
||||||
if(param == "something"){
|
console.log('Executing action: ' + param);
|
||||||
console.log("Executing action: " + param);
|
|
||||||
callback(null, Date.now());
|
callback(null, Date.now());
|
||||||
}
|
} else {
|
||||||
else{
|
|
||||||
// We can call callback with one argument even if
|
// We can call callback with one argument even if
|
||||||
// the signature states two parameters
|
// the signature states two parameters
|
||||||
callback(new Error("Invalid parameter"))
|
callback(new Error('Invalid parameter'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function entryPoint () {
|
function entryPoint () {
|
||||||
/* ===== Begin Simple callback ===== */
|
/* ===== Begin Simple callback ===== */
|
||||||
|
|
||||||
execute_action("something", function (error, time_of_completion){
|
execute_action('something', function (error, time_of_completion) {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.log("Something happened");
|
console.log('Something happened');
|
||||||
}
|
} else {
|
||||||
else{
|
console.log('Time of completion: ' + new Date(time_of_completion).toDateString());
|
||||||
console.log("Time of completion: " + new Date(time_of_completion).toDateString());
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
console.log("I started here!");
|
console.log('I started here!');
|
||||||
/*
|
/*
|
||||||
Ciò è utile se ad esempio execute_action fa operazioni lente (ad esempio
|
Ciò è utile se ad esempio execute_action fa operazioni lente (ad esempio
|
||||||
scrittura su database, connessioni HTTP ecc..) ma abbiamo bisogno
|
scrittura su database, connessioni HTTP ecc..) ma abbiamo bisogno
|
||||||
|
@ -10,8 +10,8 @@
|
|||||||
|
|
||||||
Remember that Promises are not intrensically asyncronous
|
Remember that Promises are not intrensically asyncronous
|
||||||
*/
|
*/
|
||||||
let promise = new Promise(function(resolve, reject) {
|
const promise = new Promise(function (resolve, reject) {
|
||||||
setTimeout(() => resolve("done"), 500);
|
setTimeout(() => resolve('done'), 500);
|
||||||
});
|
});
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@ -19,15 +19,15 @@ let promise = new Promise(function(resolve, reject) {
|
|||||||
The second argument of .then is a function that runs when the promise is rejected and receives the error.
|
The second argument of .then is a function that runs when the promise is rejected and receives the error.
|
||||||
*/
|
*/
|
||||||
promise.then(
|
promise.then(
|
||||||
result => console.log("The operation was successful. It returned " + result),
|
result => console.log('The operation was successful. It returned ' + result),
|
||||||
error => console.log("The operation was not successful: " + error)
|
error => console.log('The operation was not successful: ' + error)
|
||||||
);
|
);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Or we can pass only one argument if we're interested only in a positive result
|
Or we can pass only one argument if we're interested only in a positive result
|
||||||
*/
|
*/
|
||||||
promise.then(
|
promise.then(
|
||||||
result => console.log("The operation was successful. It returned " + result)
|
result => console.log('The operation was successful. It returned ' + result)
|
||||||
);
|
);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@ -44,5 +44,5 @@ promise.catch(
|
|||||||
finally gets always called
|
finally gets always called
|
||||||
*/
|
*/
|
||||||
promise.finally(
|
promise.finally(
|
||||||
() => console.log("The execution has terminated. Bye")
|
() => console.log('The execution has terminated. Bye')
|
||||||
);
|
);
|
@ -4,24 +4,16 @@
|
|||||||
// internally calling resolve().
|
// internally calling resolve().
|
||||||
|
|
||||||
new Promise(function (resolve, reject) {
|
new Promise(function (resolve, reject) {
|
||||||
|
|
||||||
setTimeout(() => resolve(1), 1);
|
setTimeout(() => resolve(1), 1);
|
||||||
|
|
||||||
}).then(function (result) {
|
}).then(function (result) {
|
||||||
|
|
||||||
console.log(result);
|
console.log(result);
|
||||||
return result * 2;
|
return result * 2;
|
||||||
|
|
||||||
}).then(function (result) {
|
}).then(function (result) {
|
||||||
|
|
||||||
console.log(result);
|
console.log(result);
|
||||||
return result * 2;
|
return result * 2;
|
||||||
|
|
||||||
}).then(function (result) {
|
}).then(function (result) {
|
||||||
|
|
||||||
console.log(result);
|
console.log(result);
|
||||||
return result * 2;
|
return result * 2;
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
@ -14,12 +14,11 @@ async function f1() {
|
|||||||
// Let’s emphasize: await literally suspends the function execution until the promise settles,
|
// Let’s emphasize: await literally suspends the function execution until the promise settles,
|
||||||
// and then resumes it with the promise result.
|
// and then resumes it with the promise result.
|
||||||
async function f2 () {
|
async function f2 () {
|
||||||
|
const promise = new Promise((resolve, reject) => {
|
||||||
let promise = new Promise((resolve, reject) => {
|
setTimeout(() => resolve('done!'), 1000);
|
||||||
setTimeout(() => resolve("done!"), 1000)
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let result = await promise; // wait until the promise resolves (*)
|
const result = await promise; // wait until the promise resolves (*)
|
||||||
|
|
||||||
console.log(result); // "done!"
|
console.log(result); // "done!"
|
||||||
}
|
}
|
||||||
@ -34,7 +33,7 @@ async function f2() {
|
|||||||
async function exampleAsyncFunction () {
|
async function exampleAsyncFunction () {
|
||||||
console.log('Before await');
|
console.log('Before await');
|
||||||
await new Promise(function (resolve, reject) {
|
await new Promise(function (resolve, reject) {
|
||||||
setTimeout(() => resolve("done"), 500);
|
setTimeout(() => resolve('done'), 500);
|
||||||
}); // Pauses execution here until the promise resolves.
|
}); // Pauses execution here until the promise resolves.
|
||||||
console.log('After await');
|
console.log('After await');
|
||||||
}
|
}
|
||||||
|
@ -9,4 +9,4 @@ function delay(ms){
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
delay(1000).then(() => console.log("Hello world!"));
|
delay(1000).then(() => console.log('Hello world!'));
|
||||||
|
Reference in New Issue
Block a user