Skip to content

Commit

Permalink
session (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jaysalgado authored Apr 22, 2023
1 parent ce9e8e9 commit 31afd42
Show file tree
Hide file tree
Showing 11 changed files with 256 additions and 180 deletions.
28 changes: 14 additions & 14 deletions imageConfigs/postgres/init.sql
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
CREATE TABLE roles (
_id SERIAL NOT NULL,
role VARCHAR (255) NOT NULL,
PRIMARY KEY (_id)
) WITH (
OIDS = FALSE
);
-- 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,
-- 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)
-- FOREIGN KEY (role_id) REFERENCES Roles(_id)
) WITH (
OIDS = FALSE
);
Expand Down Expand Up @@ -62,7 +62,7 @@ INSERT INTO notification_settings (metric_name, triggering_value) VALUES
('cpu', 80),
('stopped', 0);

INSERT INTO roles (role) VALUES
('system admin'),
('admin'),
('user');
-- INSERT INTO roles (role) VALUES
-- ('system admin'),
-- ('admin'),
-- ('user');
11 changes: 8 additions & 3 deletions server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ const app = express();
// allow requests from other domains
app.use(cors());
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// run commands in an exec (terminal instance); restarts containers running from the docketeerx/docketeer image using their ID
exec(
Expand All @@ -30,7 +32,7 @@ exec(

// Importing routers...
import accountRouter from './routes/accountRouter';
import adminRouter from './routes/adminRouter';
// import adminRouter from './routes/adminRouter';
import apiRouter from './routes/apiRouter';
import commandRouter from './routes/commandRouter';
import dbRouter from './routes/dbRouter';
Expand All @@ -51,8 +53,10 @@ app.use(express.static('SetupApp'));
// app.use('/', userController.checkCookie, (req: Request, res: Response): void => {
// console.log('cookffffffs', req.headers.cookie, req.cookies);
// if (res.locals.notSignedIn) res.redirect('/login');
// else res.redirect('/');
// });
// console.log('exited cookie check');


// Defining routers...

app.use('/k8', (req: Request, res: Response) => {
Expand All @@ -66,7 +70,6 @@ app.use('/k8', (req: Request, res: Response) => {


app.use('/account', accountRouter);
app.use('/admin', adminRouter);
app.use('/gapi', apiRouter);
app.use('/command', commandRouter);
app.use('/db', dbRouter);
Expand All @@ -75,6 +78,8 @@ 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 => {
Expand Down
252 changes: 130 additions & 122 deletions server/controllers/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ 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;
// 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 for system admin, and verifies user exists before sending back user data to login component
Expand All @@ -22,32 +22,31 @@ const userController: UserController = {
const {
username,
password,
role_id,
}: { username: string; password: string; role_id: string } = req.body;
// 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 = '';
}

console.log('ab to query to create user');
// 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 =
'INSERT INTO users (username, password, role, role_id) VALUES ($1, $2, $3, $4) RETURNING *;';
// 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, role, role_id];
const userDetails: string[] = [username, hashedPassword];
const createdUser = await db.query(createUser, userDetails);

console.log('createdUser: ', createdUser.rows[0]);
Expand Down Expand Up @@ -124,71 +123,32 @@ const userController: UserController = {
});
}
const verifiedUser = data.rows[0];
// console.log('verified user', 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' },
});
} 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({
log: `Error in userController checkUserExists: ${err}`,
message: {
err: 'An error occurred while checking if username exists. See userController.checkUserExists.',
},
});
});
},

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.user = verifiedUser;
console.log('verified user', verifiedUser);
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();
});
}
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({
Expand All @@ -200,40 +160,7 @@ const userController: UserController = {
});
},

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.',
},
});
});
}
},


updatePassword: (req: Request, res: Response, next: NextFunction): void => {
// if there is an error property on res.locals, return next(). i.e., incorrect password entered
Expand Down Expand Up @@ -303,12 +230,14 @@ const userController: UserController = {
},

addCookie: (req: Request, res: Response, next: NextFunction): void => {
console.log('we are adding the cookie here right now');
res.cookie('loggedIn', true);
return next();
},

checkCookie: (req: Request, res: Response, next: NextFunction): void => {
if (!req.cookies.loggedIn) res.locals.notSignedIn = true;
if (req.cookies.loggedIn) res.locals.signedIn = true;
else res.locals.signedIn = false;
return next();
},

Expand Down Expand Up @@ -359,3 +288,82 @@ export default userController;
// });
// }
// },
// 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];
// console.log('verified user', verifiedUser);
// 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.',
// },
// });
// });
// }
// },
Loading

0 comments on commit 31afd42

Please sign in to comment.