Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/feature/email'
Browse files Browse the repository at this point in the history
# Conflicts:
#	endpoints/session.js
#	package.json
  • Loading branch information
Seiwert committed May 10, 2016
2 parents 9b0c5e2 + 25f835f commit 57d3db0
Show file tree
Hide file tree
Showing 1,825 changed files with 265,073 additions and 51 deletions.
114 changes: 63 additions & 51 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
// The MAIN entry point for the application. Launch by calling "node app.js" from the command line.


var express = require('express'),
app = express(),
loadUser = require('./middleware/load_user.js'),
sessions = require('client-sessions'),
bodyParser = require('body-parser'),
CronJob = require('cron').CronJob,
db = require('./db');
app = express(),
loadUser = require('./middleware/load_user.js'),
sessions = require('client-sessions'),
bodyParser = require('body-parser'),
CronJob = require('cron').CronJob,
db = require('./db'),
email = require('./email.js');

// Enable template engine
app.set('view engine', 'ejs');
Expand All @@ -17,14 +17,14 @@ app.use(express.static('public'));

// Enable sessions
app.use(sessions({
cookieName: 'session',
secret: 'donutbarondonutbarondonutbaron',
duration: 24 * 60 * 60 * 1000,
activeDuration: 1000 * 60 * 5
cookieName: 'session',
secret: 'donutbarondonutbarondonutbaron',
duration: 24 * 60 * 60 * 1000,
activeDuration: 1000 * 60 * 5
}));

// Add middleware body parser
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Add routes to the homepage. It will only reach the homepage if the user has been logged in (and has an active session).
Expand All @@ -35,7 +35,7 @@ app.post('/index/rate', loadUser, homepage.RateDonuts);
app.get('/comments', homepage.getComments);
app.post('/comments/add', homepage.addComment);

// Add routes for the login page. Should create an active session if sucsessful.
// Add routes for the login page. Should create an active session if successful.
var login = require('./endpoints/session.js');
app.get('/login', login.new);
app.post('/login', login.create);
Expand All @@ -49,42 +49,56 @@ app.get('/rankings', loadUser, rankings.getRankingsData);

// Launch the application on port 8080.
app.listen(8080, () => {
console.log('Listening on port 8080...');
console.log('Listening on port 8080...');
});

// Updates the database every day at midnight.
new CronJob('00 00 12 * * 0-6', function() {

db.get("SELECT * FROM upcomingList", function(err, row)
{
if (err) {
console.error(err);
return res.sendStatus(500);
}

// Create a new date, and set it to the current date.
var date = new Date();
date.setDate(date.getDate() + 1);

// AUSTIN PUT YOUR EMAIL CODE HERE
if (row.date == date.toISOString().slice(0, 10))
{
console.log("I sent the upcoming donut baron an email!");
// Add emailing code below...
}

date.setDate(date.getDate());
// compare the current date with the next date in the table. If they match, then it's time to switch up the donut baron.
if (row.date == date.toISOString().slice(0, 10))
{
console.log("I updated the donut list!");
var oldDonutBaron;
// Make sure the database calls run in order.
db.serialize(function(){
new CronJob('00 00 12 * * 0-6', function () {

console.log("Starting the cron job");
db.get("SELECT * FROM upcomingList", function (err, row) {
if (err) {
console.error(err);
return res.sendStatus(500);
}

// Create a new date, and set it to tomorrow's date.
var date = new Date();
date.setDate(date.getDate() + 1);

if (row.date == date.toISOString().slice(0, 10)) {
db.get("SELECT * FROM users WHERE userID = ?", row.userID, function (err, user) {
if (err) {
console.error(err);
return res.sendStatus(500);
}
email.getOAuth2Client(function (err, oauth2Client) {
if (err) {
console.log('err:', err);
}
else {
email.sendSampleMail(oauth2Client, user.email_address, function (err, results) {
if (err) {
console.log('err:', err);
}
});
}
console.log("I sent " + user.email_address + " an email!");
});
});
}

date = new Date();
date.setDate(date.getDate());
// compare the current date with the next date in the table. If they match, then it's time to switch up the donut baron.
if (row.date == date.toISOString().slice(0, 10)) {
console.log("I updated the donut list!");
var oldDonutBaron;
// Make sure the database calls run in order.
db.serialize(function () {

// Save the last weeks donut baron so that they can be added to the end of the list.
db.get("SELECT * FROM users WHERE is_donut_baron=?", 1, function(err, previousDonutBaron)
{
db.get("SELECT * FROM users WHERE is_donut_baron=?", 1, function (err, previousDonutBaron) {
if (err) {
console.error(err);
return res.sendStatus(500);
Expand All @@ -93,8 +107,7 @@ new CronJob('00 00 12 * * 0-6', function() {
});

// Assign the new donut baron proper donut baron status.
db.run("UPDATE users SET is_donut_baron=? WHERE userID=?", 1, row.userID, function(err)
{
db.run("UPDATE users SET is_donut_baron=? WHERE userID=?", 1, row.userID, function (err) {
if (err) {
console.error(err);
return res.sendStatus(500);
Expand All @@ -104,8 +117,7 @@ new CronJob('00 00 12 * * 0-6', function() {
// Delete the furst row from the upcomingList, as they are now the donut baron.
db.run("DELETE FROM upcomingList WHERE listID=?", row.listID);
// At the next open slot...
db.get("SELECT * FROM upcomingList WHERE userID=?", -1, function(err, openSlot)
{
db.get("SELECT * FROM upcomingList WHERE userID=?", -1, function (err, openSlot) {
if (err) {
console.error(err);
return res.sendStatus(500);
Expand All @@ -116,9 +128,9 @@ new CronJob('00 00 12 * * 0-6', function() {
db.run("UPDATE users SET is_donut_baron=? WHERE userID=?", 0, oldDonutBaron.userID);
});
});
};
db.run("DELETE FROM comments");
});
};
db.run("DELETE FROM comments");
});
}, null, true);

module.exports = exports = app;
1 change: 1 addition & 0 deletions client_secret.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"installed":{"client_id":"1006555734212-rkleme88durmend2vdal4jln3vjtpqhq.apps.googleusercontent.com","project_id":"the-donut-baron","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"aygwVncKwxpg5s4U7VShxln1","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
65 changes: 65 additions & 0 deletions email.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
//Used tutorial on http://pcarion.com/2015/12/06/gmail-api-node/ to set up email using Gmail API
"use strict"
var fs = require('fs');
var googleAuth = require('googleapis/node_modules/google-auth-library');
var google = require('googleapis');

class Email
{
//Gets authentication from Google to send an email
getOAuth2Client(cb) {
// Load client secrets
fs.readFile('client_secret.json', function(err, data) {
if (err) {
return cb(err);
}
var credentials = JSON.parse(data);
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

// Load credentials
fs.readFile('gmail-credentials.json', function(err, token) {
if (err) {
return cb(err);
} else {
oauth2Client.credentials = JSON.parse(token);
return cb(null, oauth2Client);
}
});
});
}

//Sends an email to the desired email address
sendSampleMail(auth, toEmail, cb) {
var gmailClass = google.gmail('v1');

var email_lines = [];

email_lines.push('From: <thedonutbaron3@gmail.com>');
email_lines.push('To: ' + toEmail);
email_lines.push('Content-type: text/html;charset=iso-8859-1');
email_lines.push('MIME-Version: 1.0');
email_lines.push('Subject: Your Donut Day');
email_lines.push('');
email_lines.push('Just a reminder that tomorrow is your donut day!<br/>');
email_lines.push('<b>-The Donut Baron</b>');

var email = email_lines.join('\r\n').trim();

var base64EncodedEmail = new Buffer(email).toString('base64');
base64EncodedEmail = base64EncodedEmail.replace(/\+/g, '-').replace(/\//g, '_');

gmailClass.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: base64EncodedEmail
}
}, cb);
}
}

module.exports = exports = new Email();
1 change: 1 addition & 0 deletions gmail-credentials.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"access_token":"ya29.CjHXAmTlNv13kR24B5pL2cs2iHV_5aym6Bb_pckRPvcFbv7dwyPf1F5lWHQJ2kudknuM","token_type":"Bearer","refresh_token":"1/NAw3TYTy_IzQW9j8uqw4ZlUVo8Tc7pjsKfMcCQ9R8ao","expiry_date":1462292357949}
14 changes: 14 additions & 0 deletions node_modules/googleapis/.github/CLOSE_ISSUE_TEMPLATE.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

85 changes: 85 additions & 0 deletions node_modules/googleapis/.github/CONTRIBUTING.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions node_modules/googleapis/.github/ISSUE_TEMPLATE.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions node_modules/googleapis/.github/PULL_REQUEST_TEMPLATE.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions node_modules/googleapis/.npmignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions node_modules/googleapis/AUTHORS

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 57d3db0

Please sign in to comment.