diff --git a/SetupApp/index.js b/SetupApp/index.js index 40b7a99b..c800f907 100644 --- a/SetupApp/index.js +++ b/SetupApp/index.js @@ -14,5 +14,4 @@ document.addEventListener('DOMContentLoaded', () => { portForward.addEventListener('click', () => { fetch('/api/setup/portForward'); }); - }); \ No newline at end of file diff --git a/__tests__/ServerRoutes.test.js b/__tests__/ServerRoutes.test.js index af1beba7..0f8ac42f 100644 --- a/__tests__/ServerRoutes.test.js +++ b/__tests__/ServerRoutes.test.js @@ -7,28 +7,17 @@ const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.json()); -import accountRouter from '../server/routes/accountRouter'; -import adminRouter from '../server/routes/adminRouter'; import apiRouter from '../server/routes/apiRouter'; import commandRouter from '../server/routes/commandRouter'; import signupRouter from '../server/routes/signupRouter'; import loginRouter from '../server/routes/loginRouter'; -import dbRouter from '../server/routes/dbRouter'; import initRouter from '../server/routes/initRouter'; import logoutRouter from '../server/routes/logoutRouter'; -// import settingsRouter from '../server/routes/settingsRouter'; -// app.use('/test', (req, res) => { -// res.status(200).json({ -// success: true, -// }); -// }); -app.use('/account', accountRouter); app.use('/gapi', apiRouter); app.use('/api', apiRouter); app.use('command', commandRouter); -app.use('/db', dbRouter); app.use('/init', initRouter); app.use('/login', loginRouter); app.use('/logout', logoutRouter); @@ -46,7 +35,7 @@ let testKey; describe('test test', () => { test('Get request', async () => { const res = await request(app) - .get('/gapi/hello'); + .get('/gapi/test'); expect(res.body.data).toBe('in hello testing'); expect(res.status).toBe(200) @@ -80,29 +69,6 @@ describe('uid test', () => { }); }) -// account route -xdescribe('Account Route', () => { - test('Get request', () => { - request(app) - .get('/account') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200) - .expect(response); - }); -}); - - -// admin route -xdescribe('Admin Route', () => { - test('Get request', () => { - request(app) - .get('/admin') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200) - .expect(response); - }); -}); - // api route xdescribe('Api Route', () => { test('Get request', () => { @@ -125,17 +91,6 @@ xdescribe('Command Route', () => { }); }); -// db route -xdescribe('Db Route', () => { - test('Get request', () => { - request(app) - .get('/db') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200) - .expect(response); - }); -}); - // init route xdescribe('Init Route', () => { test('Get request', () => { @@ -169,29 +124,6 @@ xdescribe('Logout Route', () => { }); }); -// setting route -// describe('Settings Route', () => { -// test('Get request should return empty mem, cpu, stopped', async () => { -// await request(app) -// .get('/settings') -// .expect('Content-Type', 'application/json; charset=utf-8') -// .expect(200) -// .expect(response); -// }); -// xtest('Post request', async () => { -// await request(app) -// .post('/settings/insert') -// .send({ -// container: ['test', 'value'], -// name: 'testname', -// metric: 'hello' -// }) -// .expect('Content-Type', 'application/json; charset=utf-8') -// .expect(200) -// .expect(response); -// }); -// }); - // signup route // describe('Signup Route', () => { // test('get request', async () => { diff --git a/assets/.DS_Store b/assets/.DS_Store index c9870235..a78ff384 100644 Binary files a/assets/.DS_Store and b/assets/.DS_Store differ diff --git a/imageConfigs/postgres/init.sql b/imageConfigs/postgres/init.sql index de8f278c..706af233 100644 --- a/imageConfigs/postgres/init.sql +++ b/imageConfigs/postgres/init.sql @@ -1,25 +1,11 @@ --- CREATE TABLE roles ( --- _id SERIAL NOT NULL, --- role VARCHAR (255) NOT NULL, --- PRIMARY KEY (_id) --- ) WITH ( --- OIDS = FALSE --- ); - CREATE TABLE users ( _id SERIAL NOT NULL, username VARCHAR (255) UNIQUE NOT NULL, - email VARCHAR (255), password VARCHAR (255) NOT NULL, - phone VARCHAR (255), - -- role VARCHAR (255) DEFAULT 'user', - -- role_id INTEGER DEFAULT 3, - contact_pref VARCHAR (255), mem_threshold INTEGER DEFAULT 80, cpu_threshold INTEGER DEFAULT 80, container_stops BOOLEAN DEFAULT true, PRIMARY KEY (_id), - -- FOREIGN KEY (role_id) REFERENCES Roles(_id) ) WITH ( OIDS = FALSE ); @@ -44,25 +30,15 @@ CREATE TABLE containers ( CONSTRAINT unique_id UNIQUE(id) ); -CREATE TABLE notification_settings ( - id SERIAL PRIMARY KEY, - metric_name TEXT NOT NULL, - triggering_value INT, - CONSTRAINT unique_name UNIQUE(metric_name) -); +-- CREATE TABLE notification_settings ( +-- id SERIAL PRIMARY KEY, +-- metric_name TEXT NOT NULL, +-- triggering_value INT, +-- CONSTRAINT unique_name UNIQUE(metric_name) +-- ); CREATE TABLE container_settings ( container_id TEXT REFERENCES containers(id), notification_settings_id INT REFERENCES notification_settings(id), CONSTRAINT container_setting PRIMARY KEY(container_id, notification_settings_id) ); - -INSERT INTO notification_settings (metric_name, triggering_value) VALUES -('memory', 80), -('cpu', 80), -('stopped', 0); - --- INSERT INTO roles (role) VALUES --- ('system admin'), --- ('admin'), --- ('user'); diff --git a/security/sysadmin.js b/security/sysadmin.js deleted file mode 100644 index 3ee0f7a1..00000000 --- a/security/sysadmin.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = { - phone: '', - email: '', -}; diff --git a/server/app.ts b/server/app.ts index e812bcbf..cbfddb21 100644 --- a/server/app.ts +++ b/server/app.ts @@ -31,11 +31,8 @@ exec( ); // Importing routers... -import accountRouter from './routes/accountRouter'; -// import adminRouter from './routes/adminRouter'; import apiRouter from './routes/apiRouter'; import commandRouter from './routes/commandRouter'; -import dbRouter from './routes/dbRouter'; import initRouter from './routes/initRouter'; import loginRouter from './routes/loginRouter'; import logoutRouter from './routes/logoutRouter'; @@ -49,23 +46,18 @@ app.use(express.static('SetupApp')); // Defining routers... - app.use('/k8', (req: Request, res: Response) => { res.status(200).sendFile(path.join(__dirname, '../SetupApp/index.html')); }); -app.use('/account', accountRouter); app.use('/gapi', apiRouter); app.use('/command', commandRouter); -app.use('/db', dbRouter); app.use('/init', initRouter); app.use('/login', loginRouter); app.use('/logout', logoutRouter); app.use('/setup', setupRouter); app.use('/signup', signupRouter); -// app.use('/admin', adminRouter); -// app.use('/api', apiRouter); // Handling requests to unknown endpoints... app.use('/', (req: Request, res: Response): Response => { @@ -89,5 +81,4 @@ app.get( } ); -// Exporting app... export default app; diff --git a/server/controllers/apiController.ts b/server/controllers/apiController.ts deleted file mode 100644 index f3beea46..00000000 --- a/server/controllers/apiController.ts +++ /dev/null @@ -1,152 +0,0 @@ -// ! -// ! -// ! Currently not used, is meant to send email alerts - -import { Request, Response, NextFunction } from 'express'; -import nodemailer from 'nodemailer'; -import email from '../../security/email'; -import { ApiController, ServerError } from '../../types'; - -// ========================================================== -// Function: transporter -// Purpose: create transporter object to make sure these values are filled out in email.js -// ========================================================== - -const transporter = nodemailer.createTransport({ - host: email.host, - port: email.port, - secure: true, - auth: { - user: email.username, - pass: email.password, - }, -}); - -/** - * @module | apiController.ts - * @description | contains middleware that sends emails to user for container issues and signup information - **/ -const apiController: ApiController = { - testing: (req: Request, res: Response, next: NextFunction) => { - res.locals.testingData = 'test'; - return next(); - }, - - // ========================================================== - // Middleware: sendEmailAlert - // Purpose: - // ========================================================== - - sendEmailAlert: (req: Request, res: Response, next: NextFunction) => { - const { email, containerName, time, date, stopped } = req.body; - let emailBody: string; - - if (stopped === 'true') { - emailBody = ` -

Alert: ${containerName} has stopped!

-

Container ${containerName} stopped running at ${time} on ${date}.

-

Please login to Docketeer for more details.

-
-

Warmest regards,

-

Team Docketeer

`; - } else { - const { percent, type, threshold } = req.body; - emailBody = ` -

Alert: ${containerName} has breached the ${type} threshold!

-

Container ${containerName} used ${percent}% ${type} at ${time} on ${date}.

-

This exceeds the ${type} threshold of ${threshold}%.

-

Please login to Docketeer for more details.

-
-

Warmest regards,

-

Team Docketeer

`; - } - - const mailDetails = { - from: 'docketeerxii@@gmail.com', - to: email, - subject: 'Docketeer: Container Issue', - html: `${emailBody}`, - }; - - transporter - .sendMail(mailDetails) - .then(() => { - return next(); - }) - .catch((err: ServerError) => { - return next({ - log: `Error in apiController sendEmailAlert: ${err}`, - message: { - err: 'An error occured creating new user in database. See apiController.sendEmailAlert.', - }, - }); - }); - }, - - // ========================================================== - // Middleware: signupEmail - // Purpose: sends email with username/password when user successfully signs up - // ========================================================== - - signupEmail: (req: Request, res: Response, next: NextFunction) => { - const { email, username, password } = req.body; - - // create an email description and boilerplate with mailDetails - - const mailDetails = { - from: 'docketeerxii@gmail.com', - to: email, - subject: 'Docketeer: Account Details', - html: ` -

Welcome to Docketeer

-

We are so excited to have you onboard!

-

Username: ${username}

-

Password: ${password}

-

For any questions or concerns, please reach out to us at docketeerxii@gmail.com.

-
-

Warmest regards,

-

Team Docketeer

`, - }; - - // create transporter with Nodemailer to send email. - transporter - - // .sendMail is part of nodemailer package, sends an email and returns a promise with details on the email (info) - - .sendMail(mailDetails) - .then(() => { - return next(); - }) - .catch((err: ServerError) => { - return next({ - log: `Error in apiController signupEmail: ${err}`, - message: { - err: 'An error occured creating new user in database. See apiController.signupEmail.', - }, - }); - }); - }, - - - - - - - - - - - - - - - -}; - - - - - - - -export default apiController; diff --git a/server/controllers/bcryptController.ts b/server/controllers/bcryptController.ts index adf6baf0..85d96a2d 100644 --- a/server/controllers/bcryptController.ts +++ b/server/controllers/bcryptController.ts @@ -1,11 +1,12 @@ -import db from "../database/cloudModel"; -import bcrypt from "bcryptjs"; -import { Request, Response, NextFunction } from "express"; -import { BcryptController } from "../../types"; +import db from '../database/cloudModel'; +import bcrypt from 'bcryptjs'; +import { Request, Response, NextFunction } from 'express'; +import { BcryptController } from '../../types'; /** * @description A controller to handle hashing of passwords and cookies */ + const bcryptController: BcryptController = { hashPassword: (req: Request, res: Response, next: NextFunction): void => { const { password }: { password: string } = req.body; @@ -23,7 +24,7 @@ const bcryptController: BcryptController = { return next({ log: `Error in bcryptController hashPassword: ${err}`, message: { - err: "An error occured creating hash with bcrypt. See bcryptController.hashPassword.", + err: 'An error occured creating hash with bcrypt. See bcryptController.hashPassword.', }, }); }); @@ -43,7 +44,7 @@ const bcryptController: BcryptController = { return next({ log: `Error in bcryptController hashNewPassword: ${err}`, message: { - err: "An error occured creating hash with bcrypt. See bcryptController.hashNewPassword.", + err: 'An error occured creating hash with bcrypt. See bcryptController.hashNewPassword.', }, }); }); @@ -57,9 +58,9 @@ const bcryptController: BcryptController = { .then((hash: string): void => { res.locals.user.token = hash; db.query( - "ALTER TABLE users ADD COLUMN IF NOT EXISTS token varchar(250)" + 'ALTER TABLE users ADD COLUMN IF NOT EXISTS token varchar(250)' ); - db.query("UPDATE users SET token=$1 WHERE username=$2", [ + db.query('UPDATE users SET token=$1 WHERE username=$2', [ res.locals.user.token, username, ]); @@ -69,7 +70,7 @@ const bcryptController: BcryptController = { return next({ log: `Error in bcryptController hashCookeis: ${err}`, message: { - err: "An error occured creating hash with bcrypt. See bcryptController.hashCookies.", + err: 'An error occured creating hash with bcrypt. See bcryptController.hashCookies.', }, }); }); diff --git a/server/controllers/commandController.ts b/server/controllers/commandController.ts index 9e46a80d..f7a5f342 100644 --- a/server/controllers/commandController.ts +++ b/server/controllers/commandController.ts @@ -5,9 +5,6 @@ import { composeStacksDockerObject, } from '../../types'; import { exec } from 'child_process'; -import jwt from 'jsonwebtoken'; -import { JWT_SECRET } from '../../config.js'; -const secret = JWT_SECRET; /** * Parse all the stdout output into array to manipulate data properly. @@ -103,9 +100,6 @@ const makeArrayOfObjects = ( * @param {*} num * @note unused */ -// const fn = (num: number): number => { -// return Math.round((num + Number.EPSILON) * 100) / 100; -// }; /** * @description makes our command line functions to return Promise @@ -164,33 +158,7 @@ const convertArrToObj = ( * @description runs terminal commands through execs to interact with our containers, images, volumes, and networks */ const commandController: CommandController = { - checkAdmin: (req, res, next) => { - const token = req.cookies.admin || null; - - if (token) { - jwt.verify(token, secret, (error, decoded) => { - if (error || decoded.verifiedRole !== 'system admin') { - return next({ - log: 'Unauthorized access -- invalid permissions', - status: 401, - message: { - err: 'Unauthorized access --invalid permissions', - error, - }, - }); - } - return next(); - }); - } else { - return next({ - log: 'Unauthorized access -- not logged in', - status: 401, - message: { - err: 'Unauthorized access -- not logged in', - }, - }); - } - }, + getContainers: async ( req: Request, @@ -209,10 +177,10 @@ const commandController: CommandController = { runImage: (req: Request, res: Response, next: NextFunction): void => { // List of running containers (docker ps) - const { imgid, reps, tag } = req.body; + const { reps, tag } = req.body; const containerId: number = Math.floor(Math.random() * 100); const filteredRepo: string = reps - .replace(/[,\/#!$%\^&\*;:{}=\`~()]/g, '.') + .replace(/[,/#!$%^&*;:{}=`~()]/g, '.') .replace(/\s{2,}/g, ' '); exec( `docker run --name ${filteredRepo}-${tag}_${containerId} ${reps}:${tag}`, @@ -253,7 +221,6 @@ const commandController: CommandController = { const result: string = await promisifiedExec('docker images'); const value: string[][] = convert(result); - // Image properties: reps -> repository, tag -> img label, imgid -> image ID, size -> size of the img in bytes const imgPropsArray: string[] = ['reps', 'tag', 'imgid', 'size']; const resultImages: string[][] = []; @@ -297,8 +264,6 @@ const commandController: CommandController = { console.log(`remove stderr: ${stderr}`); return; } - // container deleted move to refreshStopped method - // res.locals.idRemoved = req.body; res.locals.idRemoved = { message: `Container with id ${req.query.id} deleted`, }; diff --git a/server/controllers/configController.ts b/server/controllers/configController.ts deleted file mode 100644 index 96c1266b..00000000 --- a/server/controllers/configController.ts +++ /dev/null @@ -1,150 +0,0 @@ -// ! -// ! -// ! This controller is not currently implement, is used to set thersholds/preferences -import db from '../database/cloudModel'; -import { Request, Response, NextFunction } from 'express'; -import { ConfigController, ServerError } from '../../types'; - -/** - * @description | Contains middleware that updates a user's contact preference, CPU threshold, memory threshold, and container stop preference in database - **/ -const configController: ConfigController = { - // *** I don't believe any of these are currently in use *** - - // update configuration thresholds - // TODO: implement - - configureThresholds: (req: Request, res: Response, next: NextFunction) => { - const { contact_pref, mem_threshold, cpu_threshold, container_stops, _id } = - req.body; - - const inputThresholds = - 'UPDATE users SET contact_pref = $1, mem_threshold = $2, cpu_threshold = $3, container_stops = $4 WHERE _id = $5 RETURNING *;'; - - const thresholdDetails = [ - contact_pref, - mem_threshold, - cpu_threshold, - container_stops, - _id, - ]; - - db.query(inputThresholds, thresholdDetails) - .then((data: any) => { - res.locals.user = data.rows[0]; - return next(); - }) - .catch((err: ServerError) => { - return next({ - log: `Error in userController newUser: ${err}`, - message: { - err: 'An error occured creating new user in database. See userController .newUser.', - }, - }); - }); - }, - - // configure contact preference - // TODO: implement - - updateContactPref: ( - req: Request, - res: Response, - next: NextFunction - ): void => { - const { contact_pref, _id } = req.body; - - const inputPref = - 'UPDATE users SET contact_pref = $1 WHERE _id = $2 RETURNING *;'; - const prefDetails = [contact_pref, _id]; - - db.query(inputPref, prefDetails) - .then((data: any) => { - res.locals.user = data.rows[0]; - return next(); - }) - .catch((err: ServerError) => { - return next({ - log: `Error in configController updateContactPref: ${err}`, - message: { - err: 'An error occured updating contact preferences in database. See configController .updateContactPref.', - }, - }); - }); - }, - - // configure CPU threshold - // TODO: implement - - updateCPUThreshold: (req: Request, res: Response, next: NextFunction) => { - const { cpu_threshold, _id } = req.body; - - const inputCPU = - 'UPDATE users SET cpu_threshold = $1 WHERE _id = $2 RETURNING *;'; - const CPUDetails = [cpu_threshold, _id]; - - db.query(inputCPU, CPUDetails) - .then((data: any) => { - res.locals.user = data.rows[0]; - return next(); - }) - .catch((err: ServerError) => { - return next({ - log: `Error in configController updateCPUThreshold: ${err}`, - message: { - err: 'An error occured updating CPU threshold in database. See configController .updateCPUThreshold.', - }, - }); - }); - }, - - // configure memory threshold - // TODO: implement - updateMemThreshold: (req: Request, res: Response, next: NextFunction) => { - const { mem_threshold, _id } = req.body; - - const inputMem = - 'UPDATE users SET mem_threshold = $1 WHERE _id = $2 RETURNING *;'; - const memDetails = [mem_threshold, _id]; - - db.query(inputMem, memDetails) - .then((data: any) => { - res.locals.user = data.rows[0]; - return next(); - }) - .catch((err: ServerError) => { - return next({ - log: `Error in configController updateMemThreshold: ${err}`, - message: { - err: 'An error occured updating memory threshold in database. See configController .updateMemThreshold.', - }, - }); - }); - }, - - // configure preference to receive notification when a container stops running - // TODO: implement - updateStopPref: (req: Request, res: Response, next: NextFunction) => { - const { container_stops, _id } = req.body; - - const inputStopPref = - 'UPDATE users SET container_stops = $1 WHERE _id = $2 RETURNING *;'; - const stopPrefDetails = [container_stops, _id]; - - db.query(inputStopPref, stopPrefDetails) - .then((data: any) => { - res.locals.user = data.rows[0]; - return next(); - }) - .catch((err: ServerError) => { - return next({ - log: `Error in configController updateStopPref: ${err}`, - message: { - err: 'An error occured updating container stop preference in database. See configController .updateStopPref.', - }, - }); - }); - }, -}; - -export default configController; diff --git a/server/controllers/dbController.ts b/server/controllers/dbController.ts deleted file mode 100644 index d8a1071e..00000000 --- a/server/controllers/dbController.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { Request, Response, NextFunction } from 'express'; -import db from '../database/cloudModel'; -import bcrypt from 'bcryptjs'; -// import sysadmin from "../../security/sysadmin"; // only used in insertAdmin which is not currently used -import { DbController, ServerError } from '../../types'; - -/** - * @description handles middleware functions that manipulate our database; contains middleware that checks if the database has a user table and creates one if it doesn't - */ -const dbController: DbController = { - createRolesTable: (req: Request, res: Response, next: NextFunction): void => { - db.query( - 'CREATE TABLE IF NOT EXISTS roles (_id SERIAL NOT NULL, role VARCHAR (255) NOT NULL, PRIMARY KEY (_id)) WITH (OIDS = FALSE);' - ) - .then(() => { - return next(); - }) - .catch((err: ServerError) => { - if (err) return next(err); - }); - }, - insertRoles: (req: Request, res: Response, next: NextFunction): void => { - db.query( - 'INSERT INTO roles (role) VALUES (\'system admin\'); INSERT INTO roles (role) VALUES (\'admin\'); INSERT INTO roles (role) VALUES (\'user\');' - ) - .then(() => { - return next(); - }) - .catch((err: ServerError) => { - if (err) return next(err); - }); - }, - createUsersTable: (req: Request, res: Response, next: NextFunction): void => { - db.query( - 'CREATE TABLE IF NOT EXISTS users (_id SERIAL NOT NULL, username VARCHAR (255) UNIQUE NOT NULL, email VARCHAR (255) NOT NULL, password VARCHAR (255) NOT NULL, phone VARCHAR (255), role VARCHAR (255) DEFAULT user, role_id INTEGER DEFAULT 3, contact_pref VARCHAR (255), mem_threshold INTEGER DEFAULT 80, cpu_threshold INTEGER DEFAULT 80, container_stops BOOLEAN DEFAULT true, PRIMARY KEY (_id), FOREIGN KEY (role_id) REFERENCES Roles(_id)) WITH (OIDS = FALSE);' - ).catch((err: ServerError) => { - return next(err); - }); - }, - - // below is insert admin; currently not implemented - - // insertAdmin: (req: Request, res: Response, next: NextFunction) => { - // const { password }: { password: string } = res.locals; - // const email: string = - // sysadmin.email === null || sysadmin.email === "" - // - ? "sysadmin@email.com" - // : sysadmin.email; - // const phone: string | number = - // sysadmin.phone === null || sysadmin.phone === "" - // - ? "+15013456789" - // : sysadmin.email; - - // const parameters: (string | number)[] = [email, password, phone]; - - // db.query( - // "INSERT INTO users (username, email, password, phone, role, role_id) VALUES ('sysadmin', $1, $2, $3, 'system admin', '1') ON CONFLICT DO NOTHING;", - // parameters - // ) - // .then(() => { - // return next(); - // }) - // .catch((err: ServerError) => { - // if (err) return next(err); - // }); - // }, - - createAdminPassword: (req: Request, res: Response, next: NextFunction) => { - const saltRounds = 10; - - // make a file called systemAdmin.js, make it have admin details such as password, email, phone number, and add to gitignore - bcrypt - .hash('belugas', saltRounds) - .then((hash: string) => { - res.locals.password = hash; - return next(); - }) - .catch((err: ServerError): void => { - return next({ - log: `Error in bcryptController hashPassword: ${err}`, - message: { - err: 'An error occured creating hash with bcrypt. See bcryptController.hashPassword.', - }, - }); - }); - }, - addToken: (req: Request, res: Response, next: NextFunction) => { - const { username, token }: { username: string; token: string } = req.body; - db.query('UPDATE users SET token=$1 WHERE username=$2', [token, username]) - .then(() => { - res.locals.login = 'Successfully logged in.'; - return next(); - }) - .catch((err: ServerError) => { - if (err) return next(err); - }); - }, - removeToken: (req: Request, res: Response, next: NextFunction) => { - const { username }: { username: string } = req.body; - - db.query('UPDATE users SET token = null WHERE username=$1', [username]) - .then(() => { - res.locals.logout = 'Successfully logged out.'; - return next(); - }) - .catch((err: ServerError) => { - if (err) return next(err); - }); - }, -}; -export default dbController; diff --git a/server/controllers/grafanaApiController.ts b/server/controllers/grafanaApiController.ts index db367877..f7161ab5 100644 --- a/server/controllers/grafanaApiController.ts +++ b/server/controllers/grafanaApiController.ts @@ -1,4 +1,3 @@ -// import { Request, Response, NextFunction } from 'express'; import { GrafanaApiController } from '../../types'; import fetch from 'node-fetch'; @@ -12,19 +11,19 @@ const grafanaApiController: GrafanaApiController = { getApi: async (req, res, next): Promise => { try { const response = await fetch( - "http://host.docker.internal:3000/api/auth/keys", + 'http://host.docker.internal:3000/api/auth/keys', { - method: "POST", + method: 'POST', // mode: 'no-cors', headers: { Authorization: - "Basic " + Buffer.from("admin:prom-operator").toString("base64"), - Accept: "*/*", - "Content-Type": "application/json", + 'Basic ' + Buffer.from('admin:prom-operator').toString('base64'), + Accept: '*/*', + 'Content-Type': 'application/json', }, body: JSON.stringify({ name: Math.random().toString(36).substring(7), - role: "Admin", + role: 'Admin', secondsToLive: 86400, }), } @@ -34,12 +33,12 @@ const grafanaApiController: GrafanaApiController = { return next(); } catch (error) { - console.log("Error:", error); + console.log('Error:', error); return next({ - log: "failed", + log: 'failed', status: 500, message: { - err: "", + err: '', }, }); } @@ -56,10 +55,10 @@ const grafanaApiController: GrafanaApiController = { dashboard )}`, { - method: "GET", + method: 'GET', headers: { Authorization: `Bearer ${key}`, - "Content-Type": "application/json", + 'Content-Type': 'application/json', }, } ); @@ -69,9 +68,9 @@ const grafanaApiController: GrafanaApiController = { return next(); } catch (err) { return next({ - log: "getUid failed", + log: 'getUid failed', status: 200, - message: { err: "Cannot get uid" }, + message: { err: 'Cannot get uid' }, }); } }, diff --git a/server/controllers/signupController.ts b/server/controllers/signupController.ts index 0f055a50..1a76488f 100644 --- a/server/controllers/signupController.ts +++ b/server/controllers/signupController.ts @@ -47,4 +47,5 @@ const signupController: SignupController = { } }, }; + export default signupController; diff --git a/server/controllers/userController.ts b/server/controllers/userController.ts index 57704882..d5295601 100644 --- a/server/controllers/userController.ts +++ b/server/controllers/userController.ts @@ -2,13 +2,10 @@ import { Request, Response, NextFunction } from 'express'; import db from '../database/cloudModel'; import bcrypt from 'bcryptjs'; import { UserController, ServerError, UserInfo } from '../../types'; -// import jwt from 'jsonwebtoken'; -// import { JWT_SECRET } from '../../config.js'; -// const secret = JWT_SECRET; /** * @description Contains middleware that creates new user in database, gets all users from database verifies if user exists before sending back user data to login component - * v12.0 implemented cookies for user sessions and commented out all system admin implementaion since it was nonfunctional + * v12.0 implemented cookies for user sessions and deleted all system admin implementaion since it was nonfunctional */ const userController: UserController = { @@ -22,30 +19,13 @@ const userController: UserController = { const { username, password, - // role_id, }: { username: string; password: string; } = req.body; // hash password const hashedPassword = await bcrypt.hash(password, 10); - // let role: string; - // switch (role_id) { - // case '1': - // role = 'system admin'; - // break; - // case '2': - // role = 'admin'; - // break; - // case '3': - // role = 'user'; - // break; - // default: - // role = ''; - // } const createUser = - // deleted role, role_id from querey and userDetails 'INSERT INTO users (username, password ) VALUES ($1, $2) RETURNING *;'; - // create an array, userDetails, to hold values from our createUser SQL query placeholders. const userDetails: string[] = [username, hashedPassword]; const createdUser = await db.query(createUser, userDetails); res.locals.user = createdUser.rows[0]; @@ -120,26 +100,6 @@ const userController: UserController = { const verifiedUser = data.rows[0]; res.locals.user = verifiedUser; return next(); - - // const verifiedRole = verifiedUser.role; - // if (verifiedRole === 'system admin') { - // await jwt.sign({ verifiedRole }, secret, (err, token) => { - // if (err) { - // return next({ - // log: 'Error in JWT sign in verifyUser', - // status: 400, - // message: { err: 'Unable to verify the User' }, - // }); - // } else { - // res.locals.verifiedUser = { ...verifiedUser, password: null }; - // } - // res.locals.token = token; - // return next(); - // }); - // } else if (verifiedRole === 'user') { - // res.locals.user = { ...verifiedUser, password: null }; - // return next(); - // } }) .catch((err: ServerError) => { return next({ @@ -151,72 +111,6 @@ const userController: UserController = { }); }, - - updatePassword: (req: Request, res: Response, next: NextFunction): void => { - const { newHashedPassword }: { newHashedPassword: string } = res.locals as { - newHashedPassword: string; - }; - const { username }: { username: string } = req.body; - // from v10: have the query return every column but the password column. Might be a security concern to be sending the user's hashed password to the client. - const query = - 'UPDATE users SET password = $1 WHERE username = $2 RETURNING *;'; - const parameters: string[] = [newHashedPassword, username]; - db.query(query, parameters) - .then((data: { rows: UserInfo[] }): void => { - res.locals.user = data.rows[0]; - delete res.locals.user.password; - return next(); - }) - .catch((err: ServerError): void => { - return next({ - log: `Error in userController updatePassword: ${err}`, - message: { - err: 'An error occurred while checking if username exists. See userController.updatePassword.', - }, - }); - }); - }, - - updatePhone: (req: Request, res: Response, next: NextFunction): void => { - const { username, phone }: { username: string; phone: number } = req.body; - const query = - 'UPDATE users SET phone = $1 WHERE username = $2 RETURNING *;'; - const parameters: (string | number)[] = [phone, username]; - db.query(query, parameters) - .then((data: { rows: UserInfo[] }): void => { - res.locals.user = data.rows[0]; - return next(); - }) - .catch((err: ServerError): void => { - return next({ - log: `Error in userController updatePhone: ${err}`, - message: { - err: 'An error occurred while checking if username exists. See userController.updatePhone.', - }, - }); - }); - }, - - updateEmail: (req: Request, res: Response, next: NextFunction): void => { - const { username, email }: { username: string; email: string } = req.body; - const query = - 'UPDATE users SET email = $1 WHERE username = $2 RETURNING *;'; - const parameters: string[] = [email, username]; - db.query(query, parameters) - .then((data: { rows: UserInfo[] }): void => { - res.locals.user = data.rows[0]; - return next(); - }) - .catch((err: ServerError): void => { - return next({ - log: `Error in userController updateEmail: ${err}`, - message: { - err: 'An error occurred while checking if username exists. See userController.updateEmail.', - }, - }); - }); - }, - // adding cookie addCookie: (req: Request, res: Response, next: NextFunction): void => { res.cookie('loggedIn', true); @@ -237,120 +131,5 @@ const userController: UserController = { return next(); }, }; -export default userController; - -// not currently in use (from v12.0) - -// switches role of user upon designation by system admin -// switchUserRole: (req: Request, res: Response, next: NextFunction) => { -// const roleMap: { [k: string]: number } = { -// 'system admin': 1, -// admin: 2, -// user: 3, -// }; - -// const { _id, role } = req.body; - -// if (res.locals.sysAdmins === 1 && _id == res.locals.id) { -// res.locals.hasError = true; -// next(); -// } else { -// const query = -// 'UPDATE users SET role = $1, role_id = $2 WHERE _id = $3 RETURNING *;'; - -// const parameters = [role, roleMap[role], _id]; - -// db.query(query, parameters) -// .then((data: any) => { -// res.locals.role = data.rows[0].role; -// res.locals.hasError = false; -// return next(); -// }) -// .catch((err: ServerError) => { -// return next({ -// log: `Error in userController switchUserRole: ${err}`, -// message: { -// err: 'An error occurred while switching roles. See userController.switchUserRole.', -// }, -// }); -// }); -// } -// }, -// checkSysAdmin: (req: Request, res: Response, next: NextFunction): void => { -// const { username, password } = req.body; - -// const getUser = 'SELECT * FROM users WHERE username=$1;'; - -// db.query(getUser, [username]) -// .then(async (data: any) => { -// const match = await bcrypt.compare(password, data.rows[0].password); -// if (!(data.rows[0] || match)) { -// return next({ -// log: 'Error in userController\'s verifyUser method', -// status: 400, -// message: { -// err: 'Unable to verify user credentials.', -// }, -// }); -// } -// const verifiedUser = data.rows[0]; -// res.locals.verifiedUser = verifiedUser; -// const verifiedRole = verifiedUser.role; -// if (verifiedRole === 'system admin') { -// await jwt.sign({ verifiedRole }, secret, (err, token) => { -// if (err) { -// return next({ -// log: 'Error in JWT sign in verifyUser', -// status: 400, -// message: { err: 'Unable to verify the User' }, -// }); -// } -// res.locals.token = token; -// return next(); -// }); -// } -// }) -// .catch((err: ServerError) => { -// return next({ -// log: `Error in userController checkUserExists: ${err}`, -// message: { -// err: 'An error occurred while checking if username exists. See userController.checkUserExists.', -// }, -// }); -// }); -// }, -// switchUserRole: (req: Request, res: Response, next: NextFunction): void => { -// // ? creates an object that contains roles is this necessary? -// const roleMap: { [k: string]: number } = { -// 'system admin': 1, -// admin: 2, -// user: 3, -// }; -// const { _id, role }: { _id: string; role: string } = req.body; -// // checks if there is only 1 sysAdmin and if their _id is equal to id sent in body; adds hasError prop to locals if so -// if (res.locals.sysAdmins === 1 && _id === res.locals.id) { -// res.locals.hasError = true; -// return next(); -// // otherwise we update the users role (found user from id given in body) to role sent in body; we -// } else { -// const query = -// 'UPDATE users SET role = $1, role_id = $2 WHERE _id = $3 RETURNING *;'; -// const parameters = [role, roleMap[role], _id]; -// // we will return the role that the user was updated to -// db.query(query, parameters) -// .then((data: { rows: UserInfo[] }): void => { -// res.locals.role = data.rows[0].role; -// res.locals.hasError = false; -// return next(); -// }) -// .catch((err: ServerError): void => { -// return next({ -// log: `Error in userController switchUserRole: ${err}`, -// message: { -// err: 'An error occurred while switching roles. See userController.switchUserRole.', -// }, -// }); -// }); -// } -// }, \ No newline at end of file +export default userController; \ No newline at end of file diff --git a/server/routes/accountRouter.ts b/server/routes/accountRouter.ts deleted file mode 100644 index 6842d7d6..00000000 --- a/server/routes/accountRouter.ts +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @module AccountRouter - * @description Routes all requests to change user information - */ -import { Router, Request, Response } from 'express'; -import userController from '../controllers/userController'; -import bcryptController from '../controllers/bcryptController'; - -const router = Router(); - -// updates password - -router.post( - '/password', - userController.verifyUser, - bcryptController.hashNewPassword, - userController.updatePassword, - (req: Request, res: Response): Response => { - if (res.locals.error) return res.status(200).json(res.locals); - return res.status(201).json('Successfully updated your password.'); - } -); - - - -// updates phone number -router.post( - '/phone', - userController.updatePhone, - (req: Request, res: Response): Response => { - return res.status(201).json(res.locals.user); - } -); - -// updates email -router.post( - '/email', - userController.updateEmail, - (req: Request, res: Response): Response => { - return res.status(201).json(res.locals.user); - } -); - -export default router; diff --git a/server/routes/adminRouter.ts b/server/routes/adminRouter.ts deleted file mode 100644 index d0260234..00000000 --- a/server/routes/adminRouter.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** - * @module AdminRouter - * @description Routes all requests to admin endpoint - * v12.0 depreciated all admin / system admin functionality since it was nonfunctional - */ - - -// import { Router, Request, Response } from 'express'; -// import userController from '../controllers/userController'; - -// const router = Router(); - -// Checks if client has sysadmin privilege. Get all users from users table and send back to client (system admin); sends an arr of the users -// * changed to a GET from a POST -// router.get( -// '/', -// userController.getAllUsers, -// (req: Request, res: Response): Response => { -// return res.status(201).json(res.locals.users); -// } -// ); - -// Checks if client has sysadmin privilege. Switch user role from 'user' to 'admin' and vice-versa. -// router.post( -// '/switch', -// userController.checkSysAdmin, -// userController.switchUserRole, -// (req: Request, res: Response): Response => { -// return res.status(201).json(res.locals.hasError); -// } -// ); - -// export default router; diff --git a/server/routes/apiRouter.ts b/server/routes/apiRouter.ts index a56d7ecd..91fc3103 100644 --- a/server/routes/apiRouter.ts +++ b/server/routes/apiRouter.ts @@ -3,22 +3,10 @@ * @description Routes all requests to APIs */ import { Router, Request, Response } from 'express'; -import apiController from '../controllers/apiController'; import grafanaApiController from '../controllers/grafanaApiController'; const router = Router(); -// Sends email notification to user/Sends fetch request from frontend when event emitter finds container issue -// router.post( -// '/', -// from v10: may need depending on what info is sent over in request body -// userController.getOneUser, -// apiController.sendEmailAlert, -// (req: Request, res: Response): Response => { -// return res.status(201).json('alert email sent to user'); -// } -// ); -/// router.get( '/key', grafanaApiController.getApi, @@ -26,7 +14,7 @@ router.get( return res.status(200).json(res.locals.key); } ); -/// + router.post( '/uidkey', grafanaApiController.getUid, @@ -36,13 +24,10 @@ router.post( } ); -router.get('/testing', apiController.testing, (req: Request, res: Response) => { - res.status(200).json(res.locals.testingData); -}); - -router.get('/hello', (req: Request, res: Response) => { +// for testing +router.get('/test', (req: Request, res: Response) => { res.setHeader('Cache-Control', 'no-cache'); - return res.status(200).json({ data: 'in hello testing' }); + return res.status(200).json({ data: 'this tests for false positives' }); }); export default router; diff --git a/server/routes/commandRouter.ts b/server/routes/commandRouter.ts index d6ac783a..e0f50310 100644 --- a/server/routes/commandRouter.ts +++ b/server/routes/commandRouter.ts @@ -25,7 +25,6 @@ router.get( // Route for adding a new running container to runningList state router.post( '/runImage', - commandController.checkAdmin, commandController.runImage, commandController.getContainers, (req: Request, res: Response) => { @@ -54,7 +53,6 @@ router.get( // Route to remove a stopped container router.delete( '/removeContainer', - commandController.checkAdmin, commandController.remove, (req: Request, res: Response) => { return res.status(200).json(res.locals.idRemoved); @@ -64,7 +62,6 @@ router.delete( // Route to stop a running container router.delete( '/stopContainer', - commandController.checkAdmin, commandController.stopContainer, commandController.refreshStopped, (req: Request, res: Response) => { @@ -75,7 +72,6 @@ router.delete( // Route to run a stopped container router.get( '/runStopped', - commandController.checkAdmin, commandController.runStopped, (req: Request, res: Response) => { return res.status(200).json(res.locals.containerRan); @@ -85,7 +81,6 @@ router.get( // Route to remove an image router.delete( '/removeImage', - commandController.checkAdmin, commandController.removeImage, (req: Request, res: Response) => { return res.status(200); @@ -95,7 +90,6 @@ router.delete( // Route for running the docker prune command router.delete( '/dockerPrune', - commandController.checkAdmin, commandController.dockerPrune, (req: Request, res: Response) => { return res.status(200).json(res.locals.pruneMessage); @@ -105,7 +99,6 @@ router.delete( // Route to pull new images router.get( '/pullImage', - commandController.checkAdmin, commandController.pullImage, (req: Request, res: Response) => { return res.status(200).json(res.locals.imgMessage); @@ -133,7 +126,6 @@ router.get( // Route to compose a docker file router.post( '/composeUp', - commandController.checkAdmin, commandController.composeUp, commandController.composeStacks, (req: Request, res: Response) => { @@ -144,7 +136,6 @@ router.post( // Route to compose DOWN a docker file router.post( '/composeDown', - commandController.checkAdmin, commandController.composeDown, commandController.composeStacks, (req: Request, res: Response) => { @@ -155,7 +146,6 @@ router.post( // Route to get list of container networks router.get( '/composeStacks', - commandController.checkAdmin, commandController.composeStacks, (req: Request, res: Response) => { return res.status(200).json(res.locals.output); diff --git a/server/routes/dbRouter.ts b/server/routes/dbRouter.ts deleted file mode 100644 index 10c3c153..00000000 --- a/server/routes/dbRouter.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * @module Database Router - * @description Routes all endpoints for initializing the database for new users - */ -import { Router, Request, Response } from 'express'; -import dbController from '../controllers/dbController'; - -const router = Router(); - -// ========================================================== -// Route: / -// Purpose: instantiates user and roles tables of database. First we CREATE a table for user roles, then we INSERT three roles into table (system admin, admin, and user). Then we CREATE the table. -// ========================================================== -router.get( - '/', - dbController.createRolesTable, - dbController.insertRoles, - dbController.createUsersTable, - (req: Request, res: Response): Response => { - return res.status(200).json('Database initialized successfully'); - } -); - -export default router; diff --git a/server/routes/initRouter.ts b/server/routes/initRouter.ts index e5c14df0..b85ed38a 100644 --- a/server/routes/initRouter.ts +++ b/server/routes/initRouter.ts @@ -2,6 +2,7 @@ * @module initRouter Router * @description Initializes the Docketeer local database */ + import { Router, Request, Response } from 'express'; import initController from '../controllers/initController'; diff --git a/server/routes/logoutRouter.ts b/server/routes/logoutRouter.ts index d3a61147..cf562fe7 100644 --- a/server/routes/logoutRouter.ts +++ b/server/routes/logoutRouter.ts @@ -3,22 +3,17 @@ * @description Routes all requests to logout endpoint */ import { Router, Request, Response } from 'express'; -// import dbController from '../controllers/dbController'; import userController from '../controllers/userController'; const router = Router(); -// Note: we remove a token, though tokens are added in bcryptController.hashCookie and hashCookie mw is never used in any of our routes // ========================================================== // Route: / // Purpose: Removes token (sets token to null) after user logs out. -// Note: tokens and cookies not currently implemented // ========================================================== router.post( '/', - // dbController.removeToken, userController.removeCookie, (req: Request, res: Response): Response => { - // res.clearCookie('admin', { httpOnly: true }); return res.status(201).json({ loggedOut: 'true' }); } ); diff --git a/server/routes/signupRouter.ts b/server/routes/signupRouter.ts index 25ccfb27..824ec794 100644 --- a/server/routes/signupRouter.ts +++ b/server/routes/signupRouter.ts @@ -1,16 +1,14 @@ /** - * @module | signupRouter.ts + * @module | Signup router * @description | Routes all requests to signup endpoint **/ import { Router, Request, Response } from 'express'; import userController from '../controllers/userController'; -// import apiController from '../controllers/apiController'; // controller for sending email notification const router = Router(); -// Only trigger this endpoint when sysAdmin logs in; gets all users router.get( '/', userController.getAllUsers, diff --git a/server/routes/testingroute.ts b/server/routes/testingroute.ts index f6ad123e..e35fa428 100644 --- a/server/routes/testingroute.ts +++ b/server/routes/testingroute.ts @@ -2,6 +2,7 @@ import { Router } from 'express'; const router = Router(); import fetch from 'node-fetch'; +// This route is only for testing purposes router.get('/api-key', async (req, res, next) => { try { const response = await fetch('http://localhost:3000/api/auth/keys', { diff --git a/src/components/SharedLayout/SharedLayout.tsx b/src/components/SharedLayout/SharedLayout.tsx index 249723b8..6bc9ef8e 100644 --- a/src/components/SharedLayout/SharedLayout.tsx +++ b/src/components/SharedLayout/SharedLayout.tsx @@ -10,24 +10,18 @@ import * as history from '../../helpers/volumeHistoryHelper'; import Alert from '../Alert/Alert'; import styles from './SharedLayout.module.scss'; -// import globalStyles from '../global.module.scss'; - -// const activeStyle = 'background - color: color(background, darker);'; function SharedLayout(): JSX.Element { const navigate = useNavigate(); const dispatch = useAppDispatch(); const { handlePruneClick } = useHelper(); - const { logoutUser } = useSurvey(); - - const { isLoggedIn } = useAppSelector((state) => state.sessions); + const { logoutUser } = useSurvey(); const logOut = async (): Promise => { - // updateSession(); + logoutUser(); - try { const response = await fetch('/api/logout', { method: 'POST', @@ -108,14 +102,12 @@ function SharedLayout(): JSX.Element { refreshImages, writeToDb, networkContainers, - // below function never called - // setDbSessionTimeZone, getAllDockerVolumes, getVolumeContainers, } = useHelper(); // Deconstructs dispatch functions from custom hook - const { updateUser, getVolumeContainerList } = useSurvey(); + const { getVolumeContainerList } = useSurvey(); useEffect(() => { refreshRunning(); @@ -124,7 +116,6 @@ function SharedLayout(): JSX.Element { writeToDb(); networkContainers(); getAllDockerVolumes(); - // setAdminToken(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); @@ -149,27 +140,6 @@ function SharedLayout(): JSX.Element { // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - // Pertains to sysAdmin only - // const setAdminToken = async (): Promise => { - // try { - // const response = await fetch('/api/admin', { - // method: 'POST', - // headers: { - // 'Content-Type': 'application/json', - // }, - // body: JSON.stringify({ - // token: userData.token, - // username: userData.username, - // }), - // }); - // const parsedData = await response.json(); - - // updateUser(parsedData); - // } catch (e) { - // console.log(e); - // } - // }; - return (
- ); diff --git a/src/components/SignUp/SignUp.tsx b/src/components/SignUp/SignUp.tsx index 834449f4..b53145a8 100644 --- a/src/components/SignUp/SignUp.tsx +++ b/src/components/SignUp/SignUp.tsx @@ -11,7 +11,7 @@ import { SignUpValues } from '../../../types'; /** * @module | SignUp - * @description | Facilitates registration of new users (admins) to Docketeer + * @description | Facilitates registration of new users to Docketeer **/ const SignUp = (): JSX.Element => { diff --git a/src/helpers/commands.tsx b/src/helpers/commands.tsx index 8fd5870e..d5856123 100644 --- a/src/helpers/commands.tsx +++ b/src/helpers/commands.tsx @@ -85,18 +85,6 @@ const useHelper = () => { }); }, - getUpdatedUserList() { - const { updateUsers } = dispatch; - fetch('/api/admin') - .then((response) => response.json()) - .then((data) => { - updateUsers(data); - }) - .catch((err) => { - console.log('error in getUpdatedUserList: ', err); - }); - }, - /* Refreshes running containers */ refreshRunning() { const { refreshRunningContainers } = dispatch; diff --git a/src/helpers/dispatch.tsx b/src/helpers/dispatch.tsx index fd9aef8c..94458c94 100644 --- a/src/helpers/dispatch.tsx +++ b/src/helpers/dispatch.tsx @@ -4,7 +4,6 @@ import { useAppDispatch } from '../reducers/hooks'; import { getNetworkContainers, getContainerStacks, - /* composeYml, */ composeDown, } from '../reducers/composeReducer'; @@ -30,29 +29,15 @@ import { refreshImages } from '../reducers/imageReducer'; import { getLogs } from '../reducers/logReducer'; -import { - addPhoneNumber, - addMemoryNotification, - addCpuNotification, - addStopNotification, - removeMemoryNotification, - removeCpuNotification, - removeStoppedNotification, -} from '../reducers/notificationReducer'; - import { updateSession, updateUser, logoutUser, } from '../reducers/sessionReducer'; -import { updateUsers, updateRoles } from '../reducers/userReducer'; - import { getVolumes, getVolumeContainersList } from '../reducers/volumeReducer'; import { - // ContainerObj, - // StoppedContainerObj, ImageObj, VolumeObj, NetworkObj, @@ -92,9 +77,6 @@ const useSurvey = () => { logoutUser() { dispatch(logoutUser()); }, - updateUsers(data: UserInfo[]) { - dispatch(updateUsers(data)); - }, getVolumes(data: VolumeNameObj[]) { dispatch(getVolumes(data)); }, @@ -115,35 +97,10 @@ const useSurvey = () => { // Note: refreshImagesList, refreshRunningContainers (both already exported) // Dispatch functions used in Settings.tsx // Note: removeMemory..., removeCpu..., and removeStopped... were previously declared in Settings but not used - addPhoneNumber(data: string) { - dispatch(addPhoneNumber(data)); - }, - updateUser(userInfo: UserInfo) { dispatch(updateUser(userInfo)); }, - addMemoryNotification(data: any) { - dispatch(addMemoryNotification(data)); - }, - addCpuNotification(data: any) { - dispatch(addCpuNotification(data)); - }, - addStopNotification(data: any) { - dispatch(addStopNotification(data)); - }, - removeMemoryNotification(data: object[]) { - dispatch(removeMemoryNotification(data)); - }, - removeCpuNotification(data: object[]) { - dispatch(removeCpuNotification(data)); - }, - removeStoppedNotification(data: object[]) { - dispatch(removeStoppedNotification(data)); - }, - // Dispatch functions used in Users.tsx - updateRoles(data: any) { - dispatch(updateRoles(data)); - }, + // Dispatch functions used in Yml.tsx getContainerStacks(data: any) { dispatch(getContainerStacks(data)); diff --git a/src/reducers/notificationReducer.ts b/src/reducers/notificationReducer.ts deleted file mode 100644 index 5b111e06..00000000 --- a/src/reducers/notificationReducer.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { PayloadAction, createSlice } from '@reduxjs/toolkit'; -import { notificationStateType } from '../../types'; - -const initialState: notificationStateType = { - phoneNumber: '', - memoryNotificationList: new Set(), - cpuNotificationList: new Set(), - stoppedNotificationList: new Set(), -}; - -export const notificationSlice = createSlice({ - name: 'notifications', - initialState, - reducers: { - addPhoneNumber: (state, action: PayloadAction) => { - state.phoneNumber = action.payload; - }, - addMemoryNotification: (state, action: PayloadAction) => { - console.log('addMemoryNotification action.payload: ', action.payload); - state.memoryNotificationList = new Set(action.payload); - }, - addCpuNotification: (state, action: PayloadAction) => { - console.log('addCpuNotification action.payload: ', action.payload); - state.cpuNotificationList = new Set(action.payload); - }, - addStopNotification: (state, action: PayloadAction) => { - console.log('addStopNotification action.payload: ', action.payload); - state.stoppedNotificationList = new Set(action.payload); - }, - removeMemoryNotification: (state, action: PayloadAction) => { - console.log('removeMemoryNotification action.payload: ', action.payload); - state.memoryNotificationList.forEach((container) => { - if (container === action.payload) { - state.memoryNotificationList.delete(container); - } - }); - }, - removeCpuNotification: (state, action: PayloadAction) => { - console.log('removeCpuNotification action.payload: ', action.payload); - state.cpuNotificationList.forEach((container) => { - if (container === action.payload) { - state.cpuNotificationList.delete(container); - } - }); - }, - removeStoppedNotification: (state, action: PayloadAction) => { - console.log('removeStoppedNotification action.payload: ', action.payload); - state.stoppedNotificationList.forEach((container) => { - if (container === action.payload) { - state.stoppedNotificationList.delete(container); - } - }); - }, - }, -}); - -export const { - addPhoneNumber, - addMemoryNotification, - addCpuNotification, - addStopNotification, - removeMemoryNotification, - removeCpuNotification, - removeStoppedNotification, -} = notificationSlice.actions; - -export default notificationSlice.reducer; diff --git a/src/reducers/userReducer.ts b/src/reducers/userReducer.ts index b6996c0f..6e4d3814 100644 --- a/src/reducers/userReducer.ts +++ b/src/reducers/userReducer.ts @@ -12,18 +12,9 @@ export const userSlice = createSlice({ updateUsers: (state, action: PayloadAction) => { state.userList = action.payload; }, - updateRoles: (state, action: PayloadAction) => { - const { _id, role }: { _id: string; role: string } = action.payload; - for (const user of state.userList) { - if (user._id === _id) { - user.role = role; - break; - } - } - }, }, }); -export const { updateUsers, updateRoles } = userSlice.actions; +export const { updateUsers } = userSlice.actions; export default userSlice.reducer; diff --git a/src/reducers/volumeReducer.ts b/src/reducers/volumeReducer.ts index a737813c..d7a4eba5 100644 --- a/src/reducers/volumeReducer.ts +++ b/src/reducers/volumeReducer.ts @@ -1,4 +1,4 @@ -import { PayloadAction, createSlice, current } from '@reduxjs/toolkit'; +import { PayloadAction, createSlice } from '@reduxjs/toolkit'; import { VolumeStateType, VolumeObj, VolumeNameObj } from '../../types'; /* diff --git a/src/store.ts b/src/store.ts index a83c6b32..69143714 100644 --- a/src/store.ts +++ b/src/store.ts @@ -5,9 +5,8 @@ import containerReducer from './reducers/containerReducer'; import graphReducer from './reducers/graphReducer'; import imageReducer from './reducers/imageReducer'; import logReducer from './reducers/logReducer'; -import notificationReducer from './reducers/notificationReducer'; -import sessionReducer from './reducers/sessionReducer'; import userReducer from './reducers/userReducer'; +import sessionReducer from './reducers/sessionReducer'; import volumeReducer from './reducers/volumeReducer'; const store = configureStore({ @@ -16,11 +15,10 @@ const store = configureStore({ images: imageReducer, graphs: graphReducer, composes: composeReducer, - notifications: notificationReducer, sessions: sessionReducer, - users: userReducer, volumes: volumeReducer, logs: logReducer, + users: userReducer, alerts: alertReducer, }, middleware: (getDefaultMiddleware) => diff --git a/types.ts b/types.ts index 20dd097b..062b7a80 100644 --- a/types.ts +++ b/types.ts @@ -62,7 +62,6 @@ export interface userReducerStateType { mem_threshold: string; cpu_threshold: string; container_stops: boolean; - isSysAdmin: boolean; } // ============================================== @@ -291,7 +290,6 @@ export type MiddleWareFunction = ( // Controller Types // ========================================================== export interface ApiController { - sendEmailAlert: MiddleWareFunction; signupEmail: MiddleWareFunction; testing: MiddleWareFunction } @@ -417,18 +415,6 @@ export interface CommandController { * @description runs docker logs with timestamps and presists 'containerLogs' though locals, invokes makeArrayOfObjects passing in stdout/err to add to the 'containerLogs' obj */ getLogs: MiddleWareFunction; - - /** - * @description verifies admin status before executing docker commands (i.e. remove image, docker stop) - */ - - checkAdmin: MiddleWareFunction; -} - -// this is not used -export interface CookieController { - setSSIDCookie: (req: Request, res: Response, next: NextFunction) => void; - setAdminCookie: (req: Request, res: Response, next: NextFunction) => void; } export interface ConfigController { @@ -443,46 +429,6 @@ export interface ConfigController { updateStopPref: (req: Request, res: Response, next: NextFunction) => void; } -export interface DbController { - /** - * @description creates a database table called "roles" if it doesn't exist. db.query executes SQL query. - * @note OIDS is optional for this middleware - */ - createRolesTable: MiddleWareFunction; - - /** - * @description inserts 3 rows into databse for "roles": "system admin" (1), "admin" (2), "user" (3) - * @note uses single SQl query for all 3 rows in terms of string query - */ - insertRoles: MiddleWareFunction; - - /** - * @description Creates a table in database called "users" with user and container info - */ - createUsersTable: MiddleWareFunction; - - // not used - // insertAdmin: (req: Request, res: Response, next: NextFunction) => void; - - /** - * @description Creates a hashed password for the system admin user with 10 salt rounds (decrease for faster processing) - * @note adds the password as a string for the res.locals object - */ - createAdminPassword: MiddleWareFunction; - - /** - * @description Updates user token in the database - * @note Destructures username and token from request body - */ - addToken: MiddleWareFunction; - - /** - * @description Removes token (sets token to null) after user logs out. - * @note Destructures username from request body. Logout propery is created if SQL query is able to update users token to null. - */ - removeToken: MiddleWareFunction; -} - export interface GrafanaApiController { /** * @description Gets API key from Grafana API @@ -604,36 +550,7 @@ export interface UserController { * @note Extract the username and password from req.body. Any errors get passed onto an error object. */ verifyUser: MiddleWareFunction; - - /** - * @description grabs all users that have a role of system admin and adds rowCount and id of the users to locals - * @note System admin ID has a role_id of 1 - */ - checkSysAdmin?: MiddleWareFunction; - - /** - * @description switches role of user in database upon designation by system admin; must be provided id of user and role - * @note roleMap maps role strings to the role ID's. If there is only one system admin and the _id's match, it results in an error from hasError being true. - */ - switchUserRole?: MiddleWareFunction; - - // TODO: update description. no more res.locals.error - /** - * @description Checks for error prop in locals; if none, updates password and adds user with updated pw to locals - * @note If incorrect password is entered, then res.locals error property will exist and next() will occur because error. - */ - updatePassword: MiddleWareFunction; - - /** - * @description updates the phone number of a user; column is 'phone' - */ - updatePhone: MiddleWareFunction; - - /** - * @description updates the email of a user - */ - updateEmail: MiddleWareFunction; - + /** * @description adds a cookie to our user's browser to signify they are logged in */