Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions api/main_endpoints/models/ChatMessage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ChatMessageSchema = new Schema(
{
createdAt: {
type: Date,
default: Date.now(),
},
expiresAt: {
type: Date,
default: ()=> Date.now() + 24 * 3600 * 1000, // expires in 24 hours
},
chatroomId: {
type: String,
required: true,
},
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
text: {
type: String,
required: true,
}
}
);

ChatMessageSchema.index({chatroomId: 1, createdAt: -1}); // sort by whatever is created most currently
ChatMessageSchema.index({expiresAt: 1}, {expireAfterSeconds: 0}); // TTL index for automatic expiration

module.exports = mongoose.model('ChatMessage', ChatMessageSchema);


77 changes: 59 additions & 18 deletions api/main_endpoints/routes/Advertisement.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ const {
decodeToken,
checkIfTokenSent,
} = require('../util/token-functions.js');
const logger = require('../../util/logger');
const Advertisement = require('../models/Advertisement');
const AuditLog = require('../models/AuditLog.js');
const AuditLogActions = require('../util/auditLogActions.js');

router.get('/', async (req, res) => {
const count = await Advertisement.countDocuments();
Expand Down Expand Up @@ -36,21 +39,35 @@ router.get('/getAllAdvertisements', async (req, res) => {
router.post('/createAdvertisement', async (req, res) => {
if (!checkIfTokenSent(req)) {
return res.sendStatus(FORBIDDEN);
} else if (!await decodeToken(req)) {
}

const user = await decodeToken(req);
if (!user) {
return res.sendStatus(UNAUTHORIZED);
}

const newAd = new Advertisement({
message: req.body.message,
expireDate: req.body.expireDate
});

Advertisement.create(newAd)
.then((post) => {
return res.json(post);
})
.catch(
(error) => res.sendStatus(BAD_REQUEST)
);
try {
const createdAd = await Advertisement.create(newAd);
AuditLog.create({
userId: user._id,
action: AuditLogActions.CREATE_AD,
details: {
message: createdAd.message,
expireDate: createdAd.expireDate,
advertisementId: createdAd._id
}
}).catch(logger.error);

res.status(OK).send(createdAd);
} catch (error) {
logger.error('Error creating ad:', error);
res.sendStatus(BAD_REQUEST);
}
});

router.post('/deleteAdvertisement', async (req, res) => {
Expand All @@ -59,17 +76,41 @@ router.post('/deleteAdvertisement', async (req, res) => {
} else if (!await decodeToken(req)) {
return res.sendStatus(UNAUTHORIZED);
}
Advertisement.deleteOne({ _id: req.body._id })
.then(result => {
if (result.n < 1) {
res.sendStatus(NOT_FOUND);
} else {
res.sendStatus(OK);

const user = await decodeToken(req);
if (!user) {
return res.sendStatus(UNAUTHORIZED);
}

try {
const adToDelete = await Advertisement.findById(req.body._id);

if (!adToDelete) {
return res.sendStatus(NOT_FOUND);
}

const deleteResult = await Advertisement.deleteOne({_id: req.body._id});

if(deleteResult.deletedCount < 1) {
return res.sendStatus(NOT_FOUND);
}

AuditLog.create({
userId: user._id,
action: AuditLogActions.DELETE_AD,
details: {
deletedAd: {
id: adToDelete._id,
message: adToDelete.message,
}
}
})
.catch(() => {
res.sendStatus(BAD_REQUEST);
});
}).catch(logger.error);

res.sendStatus(OK);
} catch (error) {
logger.error('Error deleting ad:', error);
res.sendStatus(BAD_REQUEST);
}
});

module.exports = router;
139 changes: 71 additions & 68 deletions api/main_endpoints/routes/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,81 +146,84 @@ router.post('/login', function(req, res) {
}

if (!user) {
res
return res
.status(UNAUTHORIZED)
.send({
message: 'Username or password does not match our records.'
});
} else {
// Check if password matches database
user.comparePassword(req.body.password, function(error, isMatch) {
if (isMatch && !error) {
if (user.accessLevel === membershipState.BANNED) {
return res
.status(UNAUTHORIZED)
.send({
message: 'The account with email ' +
}

// Check if password matches database
user.comparePassword(req.body.password, function(error, isMatch) {
if (!isMatch && !error) {
return res.status(UNAUTHORIZED).send({
message: 'Username or password does not match our records.'
});
}

if (user.accessLevel === membershipState.BANNED) {
return res
.status(UNAUTHORIZED)
.send({
message: 'The account with email ' +
req.body.email +
' is banned',
});
}

// Check if the user's email has been verified
if (!user.emailVerified) {
return res
.status(UNAUTHORIZED)
.send({ message: `The email ${req.body.email} has not been verified` });
}

// If the username and password matches the database, assign and
// return a jwt token
const jwtOptions = {
expiresIn: '2h'
};

// check here to see if we should reset the pagecount. If so, do it
if (checkIfPageCountResets(user.lastLogin)) {
user.pagesPrinted = 0;
}

// Include fields from the User model that should
// be passed to the JSON Web Token (JWT)
const userToBeSigned = {
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
accessLevel: user.accessLevel,
pagesPrinted: user.pagesPrinted,
_id: user._id
};
user
.save()
.then(() => {
const token = jwt.sign(
userToBeSigned, config.secretKey, jwtOptions
);
// Create audit log on successful sign-in
AuditLog.create({
userId: user._id,
action: AuditLogActions.LOG_IN,
details: { email: user.email }
}).catch(logger.error);

res.json({ token: 'JWT ' + token });
})
.catch((error) => {
logger.error('unable to login user', error);
res.sendStatus(SERVER_ERROR);
});
} else {
res.status(UNAUTHORIZED).send({
message: 'Username or password does not match our records.'
});
}
});
}
}
);
}

// Check if the user's email has been verified
if (!user.emailVerified) {
return res
.status(UNAUTHORIZED)
.send({ message: `The email ${req.body.email} has not been verified` });
}

// If the username and password matches the database, assign and
// return a jwt token
const jwtOptions = {
expiresIn: '2h'
};

// check here to see if we should reset the pagecount. If so, do it
if (checkIfPageCountResets(user.lastLogin)) {
user.pagesPrinted = 0;
}

// set last login date here!!!!
user.lastLogin = new Date();


// Include fields from the User model that should
// be passed to the JSON Web Token (JWT)
const userToBeSigned = {
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
accessLevel: user.accessLevel,
pagesPrinted: user.pagesPrinted,
_id: user._id
};
user
.save()
.then(() => {
const token = jwt.sign(
userToBeSigned, config.secretKey, jwtOptions
);
// Create audit log on successful sign-in
AuditLog.create({
userId: user._id,
action: AuditLogActions.LOG_IN,
details: { email: user.email }
}).catch(logger.error);

res.json({ token: 'JWT ' + token });
})
.catch((error) => {
logger.error('unable to login user', error);
res.sendStatus(SERVER_ERROR);
});
});
});
});

// Verifies the users session if they have an active jwtToken.
Expand Down
15 changes: 13 additions & 2 deletions api/main_endpoints/routes/LedSign.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ const {
} = require('../util/token-functions.js');
const logger = require('../../util/logger');
const { updateSign, healthCheck, turnOffSign } = require('../util/LedSign.js');
const AuditLogActions = require('../util/auditLogActions.js');
const AuditLog = require('../models/AuditLog.js');

const runningInDevelopment = process.env.NODE_ENV !== 'production'
&& process.env.NODE_ENV !== 'test';
Expand All @@ -36,7 +38,8 @@ router.post('/updateSignText', async (req, res) => {
logger.warn('/updateSignText was requested without a token');
return res.sendStatus(UNAUTHORIZED);
}
if (!await decodeToken(req)) {
const user = await decodeToken(req); // Store the user here
if (!user) {
logger.warn('/updateSignText was requested with an invalid token');
return res.sendStatus(UNAUTHORIZED);
}
Expand All @@ -56,8 +59,16 @@ router.post('/updateSignText', async (req, res) => {
if(!result) {
status = SERVER_ERROR;
}

AuditLog.create({
userId: user._id,
action: AuditLogActions.UPDATE_SIGN,
details: {
newSignText: req.body.text,
}
}).catch(logger.error);

return res.sendStatus(status);
});


module.exports = router;
Loading