Brought API responses up to standards and added API documentation

This commit is contained in:
Ceferino Patino 2022-12-15 17:39:51 -06:00
commit 52b76a760c
12 changed files with 377 additions and 919 deletions

View file

@ -1,26 +1,23 @@
{ {
"errorGeneric": { "errorGeneric": {
"error": "Oops! Something went wrong." "error": "Oops! Something went wrong. Please try again later."
}, },
"errorIncomplete": { "errorIncomplete": {
"error": "Your request is missing information." "error": "Your request is missing information."
}, },
"errorUnauthed": {
"error": "You are unauthenticated, please log in and try again."
},
"errorForbidden": { "errorForbidden": {
"error": "You are not authorized to do that." "error": "You are not authorized to do that."
}, },
"errorFailed": {
"error": "Request failed. Please check form and try again."
},
"errorNotFound": { "errorNotFound": {
"error": "That resource was not found. Please check the URL and try again." "error": "That resource was not found. Please try again."
},
"errorUnauthed": {
"error": "Your session has expired. Please login and try again."
}, },
"errorUserNotFound": { "errorUserNotFound": {
"error": "A user with that email does not exist. Create an account to get started." "error": "A user with that email does not exist. Create an account to get started."
}, },
"errorDuplicateUser": { "errorDuplicateName": {
"error": "A user with that email already exists. Please log in or use a different email." "error": "Something already exists with that name. Please try again with a different name."
} }
} }

View file

@ -7,18 +7,18 @@ async function basicAuth(req, res, next) {
const authHeader = req.get('Authorization'); const authHeader = req.get('Authorization');
const b64Encoded = authHeader.split(' ')[1]; const b64Encoded = authHeader.split(' ')[1];
if (!b64Encoded) return res.status(401).send(config.errorIncomplete); if (!b64Encoded) return res.status(400).send(config.errorIncomplete);
// Isolate username and password // Isolate username and password
const [email, password] = Buffer.from(b64Encoded, 'base64').toString().split(':'); const [email, password] = Buffer.from(b64Encoded, 'base64').toString().split(':');
if (!email || !password) return res.status(403).send(config.errorFailed); if (!email || !password) return res.status(400).send(config.errorIncomplete);
// Make sure that a user exists with that email // Make sure that a user exists with that email
const result = await User.findOne({ const result = await User.findOne({
where: { email: email }, where: { email: email },
}); });
if (!result) { if (!result) {
return res.status(403).send(config.errorUserNotFound); return res.status(404).send(config.errorNotFound);
} }
// Hash the password and verify that the user hash is identical // Hash the password and verify that the user hash is identical

View file

@ -2,7 +2,7 @@ const { Organization } = require('../db/models/index');
const config = require('../config/error.json'); const config = require('../config/error.json');
async function GetOrg(req, res, next) { async function checkKnownOrg(req, res, next) {
const user = req.user; const user = req.user;
const orgID = req.params.orgID || req.query.orgID || req.body.orgID; const orgID = req.params.orgID || req.query.orgID || req.body.orgID;
@ -35,4 +35,4 @@ async function GetOrg(req, res, next) {
return next(); return next();
} }
module.exports = GetOrg; module.exports = checkKnownOrg;

View file

@ -2,30 +2,28 @@ const { Token } = require('../db/models/index');
const config = require('../config/error.json'); const config = require('../config/error.json');
async function tokenAuth(req, res, next) { async function tokenAuth(req, res, next) {
const token = req.query.token || req.body.token; const authHeader = req.get('Authorization');
// Verify that a token exists on the request const token = authHeader?.split(' ')[1];
if (!token) {
return res.status(403).send(config.errorForbidden);
}
// Find token and make sure that it is not expired // Verify token is included in request
const result = await Token.findByPk(token); if (!token) return res.status(400).send(config.errorIncomplete);
const result = await Token.findOne({ token });
// Verify token expiration
const date = new Date(); const date = new Date();
// Destroy token if it is expired or does not exist
if (!result) { if (!result) {
return res.status(403).send(config.errorFailed); return res.status(401).send(config.errorUnauthed);
} else if (result.expires && date.setDate(date.getDate + 1) > result.createdAt) {
await Token.findOneAndDelete({ token });
return res.status(401).send(config.errorUnauthed);
} }
if (token.expires == true && date.setDate(date.getDate() - 1) > result.createdAt) { const user = await token.getUser();
await Token.destroy({ where: { id: token } });
return res.status(511).send(config.errorUnauthed); if (!user) return res.status(500).send(config.errorGeneric);
}
// Attach user object to request
const user = await result.getUser();
req.user = user; req.user = user;
return next(); return next();

File diff suppressed because it is too large Load diff

View file

@ -3,7 +3,7 @@ const forge = require('node-forge');
const { User, Organization } = require('../../db/models/index'); const { User, Organization } = require('../../db/models/index');
const config = require('../../config/error.json'); const config = require('../../config/error.json');
async function CreateUser(req, res, next) { async function Register(req, res, next) {
const body = req.body; const body = req.body;
// Verify that the object body contains all SQL required fields // Verify that the object body contains all SQL required fields
@ -19,7 +19,7 @@ async function CreateUser(req, res, next) {
}); });
if (existingUsers > 0) { if (existingUsers > 0) {
return res.status(500).send(config.errorDuplicateUser); return res.status(400).send(config.errorDuplicateName);
} }
// Hash password for storage into database // Hash password for storage into database
@ -42,12 +42,12 @@ async function CreateUser(req, res, next) {
const { orgID, ...filteredBody } = body; const { orgID, ...filteredBody } = body;
const result = await org.createMember({ await org.createMember({
...filteredBody, ...filteredBody,
password: passwordHash, password: passwordHash,
}); });
return res.send({ user: result, orgID }); return res.sendStatus(200);
} catch (e) { } catch (e) {
console.log(e); console.log(e);
@ -55,13 +55,13 @@ async function CreateUser(req, res, next) {
} }
} else { } else {
try { try {
// Create user regularly if their is not orgID // Create user regularly if their is no orgID
const result = await User.create({ await User.create({
...body, ...body,
password: passwordHash, password: passwordHash,
}); });
return res.send({ user: result }); return res.sendStatus(200);
} catch (e) { } catch (e) {
console.log(e); console.log(e);
@ -70,4 +70,4 @@ async function CreateUser(req, res, next) {
} }
} }
module.exports = CreateUser; module.exports = Register;

View file

@ -18,12 +18,12 @@ async function UpdateUserDetails(req, res, next) {
}); });
if (result) { if (result) {
return res.status(500).send(config.errorDuplicateUser); return res.status(409).send(config.errorDuplicateName);
} }
} }
req.user.update({ ...body }); await req.user.update({ ...body });
return res.send(req.user); return res.sendStatus(200);
} }
module.exports = UpdateUserDetails; module.exports = UpdateUserDetails;

View file

@ -6,7 +6,7 @@ const basicAuth = require('../middleware/basicAuth');
const tokenAuth = require('../middleware/tokenAuth'); const tokenAuth = require('../middleware/tokenAuth');
const checkKnownUser = require('../middleware/checkKnownUser'); const checkKnownUser = require('../middleware/checkKnownUser');
const CreateUser = require('./auth/CreateUser'); const Register = require('./auth/Register');
const UpdateUserDetails = require('./auth/UpdateUserDetails'); const UpdateUserDetails = require('./auth/UpdateUserDetails');
const Login = require('./auth/Login'); const Login = require('./auth/Login');
const Remember = require('./auth/Remember'); const Remember = require('./auth/Remember');
@ -18,19 +18,19 @@ const GetOwnedOrgs = require('./auth/GetOwnedOrgs');
const GetMemberOrgs = require('./auth/GetMemberOrgs'); const GetMemberOrgs = require('./auth/GetMemberOrgs');
const GetUserDetails = require('./auth/GetUserDetails'); const GetUserDetails = require('./auth/GetUserDetails');
router.post('/register', CreateUser); router.post('/register', Register);
router.patch('/update', tokenAuth, UpdateUserDetails);
router.post('/login', basicAuth, Login); router.post('/login', basicAuth, Login);
router.post('/remember', tokenAuth, Remember);
router.post('/logout', tokenAuth, Logout); router.post('/logout', tokenAuth, Logout);
router.get('/reset-password', RequestReset); router.post('/remember', tokenAuth, Remember);
router.patch('/reset-password/:id', ResetPassword);
router.patch('/update', tokenAuth, UpdateUserDetails);
router.post('/audio', parseFormData, tokenAuth, SetAudio); router.post('/audio', parseFormData, tokenAuth, SetAudio);
router.get('/', tokenAuth, GetOwnedOrgs); router.get('/reset', RequestReset);
router.get('/orgs', tokenAuth, GetMemberOrgs); router.patch('/reset/:id', ResetPassword);
router.get('/:userID', tokenAuth, checkKnownUser, GetUserDetails); router.get('/:userID', tokenAuth, checkKnownUser, GetUserDetails);
router.get('/orgs', tokenAuth, GetOwnedOrgs);
router.get('/orgs/member', tokenAuth, GetMemberOrgs);
module.exports = router; module.exports = router;

View file

@ -14,14 +14,14 @@ async function CreateOrg(req, res, next) {
where: { name: orgName }, where: { name: orgName },
}); });
if (existing > 0) { if (existing > 0) {
return res.status(500).send(config.errorFailed); return res.status(500).send(config.errorGeneric);
} }
const org = await user.createOwnedOrg({ await user.createOwnedOrg({
name: orgName, name: orgName,
}); });
return res.status(200).send({ org }); return res.sendStatus(200);
} }
module.exports = CreateOrg; module.exports = CreateOrg;

View file

@ -4,7 +4,7 @@ const config = require('../../config/error.json');
async function DeleteOrg(req, res, next) { async function DeleteOrg(req, res, next) {
const user = req.user; const user = req.user;
const orgID = req.query.orgID; const orgID = req.params.orgID;
// Error if an organization id was not provided // Error if an organization id was not provided
if (!orgID) { if (!orgID) {

View file

@ -2,25 +2,25 @@ const config = require('../../config/error.json');
async function UpdateOrgDetails(req, res, next) { async function UpdateOrgDetails(req, res, next) {
const user = req.user; const user = req.user;
const orgName = req.body.orgName; const id = req.params.id;
const orgID = req.body.orgID; const name = req.body.name;
// Verify that an name and id exist on the form // Verify that an name and id exist on the form
if (!orgName || !orgID) { if (!name) {
return res.status(400).send(config.errorIncomplete); return res.status(400).send(config.errorIncomplete);
} }
// Confirm that an organization exists with that ID // Confirm that an organization exists with that ID
const result = await user.getOwnedOrg({ where: { id: orgID } }); const result = await user.getOwnedOrg({ where: { id } });
if (result.length < 1) { if (result.length < 1) {
return res.status(403).send(config.errorForbidden); return res.status(404).send(config.errorNotFound);
} }
// Update the name fo the organization // Update the name of the organization
result[0].update({ name: orgName }); result[0].update({ name });
return res.send(result[0]); return res.sendStatus(200);
} }
module.exports = UpdateOrgDetails; module.exports = UpdateOrgDetails;

View file

@ -11,11 +11,11 @@ const GetOrg = require('./org/GetOrg');
const AddOrgMember = require('./org/AddOrgMember'); const AddOrgMember = require('./org/AddOrgMember');
const RemoveOrgMember = require('./org/RemoveOrgMember'); const RemoveOrgMember = require('./org/RemoveOrgMember');
router.post('/create', tokenAuth, CreateOrg); router.post('/', tokenAuth, CreateOrg);
router.delete('/delete', tokenAuth, DeleteOrg);
router.patch('/update', tokenAuth, UpdateOrgDetails);
router.get('/:orgID', tokenAuth, checkKnownOrg, GetOrg); router.get('/:orgID', tokenAuth, checkKnownOrg, GetOrg);
router.patch('/:orgID', tokenAuth, UpdateOrgDetails);
router.delete('/:orgID', tokenAuth, DeleteOrg);
router.post('/:orgID/add', tokenAuth, AddOrgMember); router.post('/:orgID/add', tokenAuth, AddOrgMember);
router.post('/:orgID/delete', tokenAuth, RemoveOrgMember); router.post('/:orgID/remove', tokenAuth, RemoveOrgMember);
module.exports = router; module.exports = router;