#85 Switched back to debug

master
Keith Irwin 2017-05-08 13:47:53 -04:00
parent 3521c10a49
commit 9b082538c2
No known key found for this signature in database
GPG Key ID: 378933C743E2BBC0
8 changed files with 68 additions and 59 deletions

View File

@ -2,10 +2,6 @@
module.exports = {
// Log level
// See https://www.npmjs.com/package/winston#logging-levels
logLevel: 'verbose',
// Local variables
mode: 'development', // or production
@ -16,7 +12,9 @@ module.exports = {
// Location of your mongoDB
mongoSetup: 'mongodb://localhost:27017/tracman',
// Or use the test database from mLab
//mongoSetup: 'mongodb://tracman:MUPSLXQ34f9cQTc5@ds113841.mlab.com:13841/tracman-dev',
//mongoSetup: 'mongodb://tracman:MUPSLXQ34f9cQTc5@ds133961.mlab.com:33961/tracman',
// You can log in there with:
// mongo ds133961.mlab.com:33961/tracman-dev -u contributor -p opensourcerules
// URL and port where this will run
url: 'https://localhost:8080',

View File

@ -4,7 +4,7 @@ const mongoose = require('mongoose'),
unique = require('mongoose-unique-validator'),
bcrypt = require('bcrypt'),
crypto = require('crypto'),
winston = require('winston');
debug = require('debug')('tracman-models');
const userSchema = new mongoose.Schema({
name: {type:String},
@ -16,9 +16,9 @@ const userSchema = new mongoose.Schema({
password: String,
passToken: String,
passTokenExpires: Date,
google: {type:String, unique:true},
facebook: {type:String, unique:true},
twitter: {type:String, unique:true},
google: String,
facebook: String,
twitter: String,
},
isAdmin: {type:Boolean, required:true, default:false},
isPro: {type:Boolean, required:true, default:false},
@ -53,13 +53,13 @@ const userSchema = new mongoose.Schema({
// Create email confirmation token
userSchema.methods.createEmailToken = function(next){ // next(err,token)
winston.debug('user.createEmailToken() called');
debug('user.createEmailToken() called');
var user = this;
crypto.randomBytes(16, (err,buf)=>{
if (err){ next(err,null); }
if (buf){
winston.debug(`Buffer ${buf.toString('hex')} created`);
debug(`Buffer ${buf.toString('hex')} created`);
user.emailToken = buf.toString('hex');
user.save()
.then( ()=>{
@ -80,7 +80,7 @@ const userSchema = new mongoose.Schema({
// Reuse old token, resetting clock
if ( user.auth.passTokenExpires >= Date.now() ){
winston.debug(`Reusing old password token...`);
debug(`Reusing old password token...`);
user.auth.passTokenExpires = Date.now() + 3600000; // 1 hour
user.save()
.then( ()=>{
@ -93,7 +93,7 @@ const userSchema = new mongoose.Schema({
// Create new token
else {
winston.debug(`Creating new password token...`);
debug(`Creating new password token...`);
crypto.randomBytes(16, (err,buf)=>{
if (err){ return next(err,null,null); }
if (buf) {
@ -101,9 +101,11 @@ const userSchema = new mongoose.Schema({
user.auth.passTokenExpires = Date.now() + 3600000; // 1 hour
user.save()
.then( ()=>{
debug('successfully saved user in createPassToken');
return next(null,user.auth.passToken,user.auth.passTokenExpires);
})
.catch( (err)=>{
debug('error saving user in createPassToken');
return next(err,null,null);
});
}

View File

@ -8,7 +8,7 @@ const
GoogleTokenStrategy = require('passport-google-id-token'),
FacebookTokenStrategy = require('passport-facebook-token'),
TwitterTokenStrategy = require('passport-twitter-token'),
winston = require('winston'),
debug = require('debug')('tracman-passport'),
env = require('./env/env.js'),
mw = require('./middleware.js'),
User = require('./models.js').user;
@ -32,7 +32,7 @@ module.exports = (passport)=>{
passwordField: 'password',
passReqToCallback: true
}, (req,email,password,done)=>{
winston.debug(`Perfoming local login for ${email}`);
debug(`Perfoming local login for ${email}`);
User.findOne({'email':email})
.then( (user)=>{
@ -74,13 +74,13 @@ module.exports = (passport)=>{
// Social login
function socialLogin(req, service, profileId, done) {
winston.debug(`socialLogin() called`);
debug(`socialLogin() called`);
let query = {};
query['auth.'+service] = profileId;
// Intent to log in
if (!req.user) {
winston.debug(`Logging in with ${service}...`);
debug(`Logging in with ${service}...`);
User.findOne(query)
.then( (user)=>{
@ -124,7 +124,7 @@ module.exports = (passport)=>{
// No googleId either
else {
winston.debug(`Couldn't find ${service} user.`);
debug(`Couldn't find ${service} user.`);
req.flash('warning', `There's no user for that ${service} account. `);
return done();
}
@ -132,7 +132,7 @@ module.exports = (passport)=>{
// Successfull social login
else {
winston.debug(`Found user: ${user}`);
debug(`Found user: ${user}`);
req.session.flashType = 'success';
req.session.flashMessage = "You have been logged in.";
return done(null, user);
@ -147,7 +147,7 @@ module.exports = (passport)=>{
// Intent to connect account
else {
winston.debug(`Attempting to connect ${service} account...`);
debug(`Attempting to connect ${service} account...`);
// Check for unique profileId
User.findOne(query)
@ -155,7 +155,7 @@ module.exports = (passport)=>{
// Social account already in use
if (existingUser) {
winston.debug(`${service} account already in use.`);
debug(`${service} account already in use.`);
req.session.flashType = 'warning';
req.session.flashMessage = `Another user is already connected to that ${service} account. `;
return done();
@ -163,7 +163,7 @@ module.exports = (passport)=>{
// Connect to account
else {
winston.debug(`Connecting ${service} account.`);
debug(`Connecting ${service} account.`);
req.user.auth[service] = profileId;
req.user.save()
.then( ()=>{

View File

@ -7,7 +7,7 @@ const
crypto = require('crypto'),
moment = require('moment'),
slugify = require('slug'),
winston = require('winston'),
debug = require('debug')('tracman-routes-auth'),
env = require('../env/env.js');
module.exports = (app, passport) => {
@ -19,14 +19,14 @@ module.exports = (app, passport) => {
failureFlash: true
},
loginCallback = (req,res)=>{
winston.debug(`Login callback called... redirecting to ${req.session.next}`);
debug(`Login callback called... redirecting to ${req.session.next}`);
req.flash(req.session.flashType,req.session.flashMessage);
req.session.flashType = undefined;
req.session.flashMessage = undefined;
res.redirect( req.session.next || '/map' );
},
appLoginCallback = (req,res,next)=>{
winston.debug('appLoginCallback called.');
debug('appLoginCallback called.');
if (req.user){ res.send(req.user); }
else {
let err = new Error("Unauthorized");
@ -62,10 +62,12 @@ module.exports = (app, passport) => {
// Send token and alert user
function sendToken(user){
debug('sendToken(user)');
// Create a password token
user.createPassToken( (err,token,expires)=>{
if (err){
debug('Error creating password token');
mw.throwErr(err,req);
res.redirect('/login#signup');
}
@ -138,6 +140,7 @@ module.exports = (app, passport) => {
if (existingUser){
crypto.randomBytes(6, (err,buf)=>{
if (err) {
debug('Failed to create random bytest for slug');
mw.throwErr(err,req);
reject();
}
@ -152,11 +155,13 @@ module.exports = (app, passport) => {
})
.catch((err)=>{
debug('Failed to create slug');
mw.throwErr(err,req);
reject();
});
})(user.slug, (newSlug)=>{
debug('Successfully created slug');
user.slug = newSlug;
resolve();
});
@ -164,13 +169,16 @@ module.exports = (app, passport) => {
// Generate sk32
const sk32 = new Promise((resolve,reject) => {
debug('Creating sk32');
crypto.randomBytes(32, (err,buf)=>{
if (err) {
debug('Failed to create sk32');
mw.throwErr(err,req);
reject();
}
if (buf) {
user.sk32 = buf.toString('hex');
debug('Successfully created sk32');
resolve();
}
});
@ -178,9 +186,10 @@ module.exports = (app, passport) => {
// Save user and send the token by email
Promise.all([slug, sk32])
.then( ()=>{ user.save(); })
// .then( ()=>{ user.save(); })
.then( ()=>{ sendToken(user); })
.catch( (err)=>{
debug('Failed to save user');
mw.throwErr(err,req);
res.redirect('/login#signup');
});
@ -268,19 +277,19 @@ module.exports = (app, passport) => {
// Social login
if (!req.user) {
winston.debug(`Attempting to login with ${service} with params: ${JSON.stringify(sendParams)}...`);
debug(`Attempting to login with ${service} with params: ${JSON.stringify(sendParams)}...`);
passport.authenticate(service, sendParams)(req,res,next);
}
// Connect social account
else if (!req.user.auth[service]) {
winston.debug(`Attempting to connect ${service} account...`);
debug(`Attempting to connect ${service} account...`);
passport.authorize(service, sendParams)(req,res,next);
}
// Disconnect social account
else {
winston.debug(`Attempting to disconnect ${service} account...`);
debug(`Attempting to disconnect ${service} account...`);
// Make sure the user has a password before they disconnect their google login account
// This is because login used to only be through google, and some people might not have

View File

@ -8,7 +8,7 @@ const slug = require('slug'),
User = require('../models.js').user,
mail = require('../mail.js'),
env = require('../env/env.js'),
winston = require('winston'),
debug = require('debug')('tracman-settings'),
router = require('express').Router();
// Validate email addresses
@ -52,23 +52,23 @@ router.route('/')
// Not unique!
if (existingUser && existingUser.id!==req.user.id) {
winston.debug("Email not unique!");
debug("Email not unique!");
req.flash('warning', `That email, <u>${req.body.email}</u>, is already in use by another user! `);
resolve();
}
// It's unique
else {
winston.debug("Email is unique");
debug("Email is unique");
req.user.newEmail = req.body.email;
// Create token
winston.debug(`Creating email token...`);
debug(`Creating email token...`);
req.user.createEmailToken((err,token)=>{
if (err){ reject(err); }
// Send token to user by email
winston.debug(`Mailing new email token to ${req.body.email}...`);
debug(`Mailing new email token to ${req.body.email}...`);
mail.send({
to: `"${req.user.name}" <${req.body.email}>`,
from: mail.from,
@ -133,7 +133,7 @@ router.route('/')
// Set settings when done
Promise.all([checkEmail, checkSlug])
.then( ()=>{
winston.debug('Setting settings... ');
debug('Setting settings... ');
// Set values
req.user.name = xss(req.body.name);
@ -148,10 +148,10 @@ router.route('/')
};
// Save user and send response
winston.debug(`Saving new settings for user ${req.user.name}...`);
debug(`Saving new settings for user ${req.user.name}...`);
req.user.save()
.then( ()=>{
winston.debug(`DONE! Redirecting user...`);
debug(`DONE! Redirecting user...`);
req.flash('success', 'Settings updated. ');
res.redirect('/settings');
})
@ -265,14 +265,17 @@ router.route('/password/:token')
// Check token
.all( (req,res,next)=>{
debug('/settings/password/:token .all() called');
User
.findOne({'auth.passToken': req.params.token})
.where('auth.passTokenExpires').gt(Date.now())
.then((user) => {
if (!user) {
debug('Bad token');
req.flash('danger', 'Password reset token is invalid or has expired. ');
res.redirect( (req.isAuthenticated)?'/settings':'/login' );
} else {
debug('setting passwordUser');
res.locals.passwordUser = user;
next();
}
@ -285,6 +288,7 @@ router.route('/password/:token')
// Show password change form
.get( (req,res)=>{
debug('/settings/password/:token .get() called');
res.render('password');
} )

View File

@ -1,21 +1,21 @@
'use strict';
// Imports
const winston = require('winston'),
const debug = require('debug')('tracman-sockets'),
User = require('./models.js').user;
// Check for tracking clients
function checkForUsers(io, user) {
winston.silly(`Checking for clients receiving updates for ${user}`);
debug(`Checking for clients receiving updates for ${user}`);
// Checks if any sockets are getting updates for this user
if (Object.values(io.sockets.connected).some( (socket)=>{
return socket.gets===user;
})) {
winston.silly(`Activating updates for ${user}.`);
debug(`Activating updates for ${user}.`);
io.to(user).emit('activate','true');
} else {
winston.silly(`Deactivating updates for ${user}.`);
debug(`Deactivating updates for ${user}.`);
io.to(user).emit('activate', 'false');
}
}
@ -26,7 +26,7 @@ module.exports = {
init: (io)=>{
io.on('connection', (socket)=>{
winston.silly(`${socket.id} connected.`);
debug(`${socket.id} connected.`);
// Set a few variables
//socket.ip = socket.client.request.headers['x-real-ip'];
@ -34,14 +34,14 @@ module.exports = {
/* Log */
socket.on('log', (text)=>{
winston.debug(`LOG: ${text}`);
debug(`LOG: ${text}`);
});
// This socket can set location (app)
socket.on('can-set', (userId)=>{
winston.silly(`${socket.id} can set updates for ${userId}.`);
debug(`${socket.id} can set updates for ${userId}.`);
socket.join(userId, ()=>{
winston.silly(`${socket.id} joined ${userId}`);
debug(`${socket.id} joined ${userId}`);
});
checkForUsers( io, userId );
});
@ -49,17 +49,17 @@ module.exports = {
// This socket can receive location (map)
socket.on('can-get', (userId)=>{
socket.gets = userId;
winston.silly(`${socket.id} can get updates for ${userId}.`);
debug(`${socket.id} can get updates for ${userId}.`);
socket.join(userId, ()=>{
winston.debug(`${socket.id} joined ${userId}`);
debug(`${socket.id} joined ${userId}`);
socket.to(userId).emit('activate', 'true');
});
});
// Set location
socket.on('set', (loc)=>{
winston.debug(`${socket.id} set location for ${loc.usr}`);
winston.silly(`Location was set to: ${JSON.stringify(loc)}`);
debug(`${socket.id} set location for ${loc.usr}`);
debug(`Location was set to: ${JSON.stringify(loc)}`);
// Get android timestamp or use server timestamp
if (loc.ts){ loc.tim = Date(loc.ts); }
@ -85,7 +85,7 @@ module.exports = {
// Broadcast location
io.to(loc.usr).emit('get', loc);
winston.debug(`Broadcasting ${loc.lat}, ${loc.lon} to ${loc.usr}`);
debug(`Broadcasting ${loc.lat}, ${loc.lon} to ${loc.usr}`);
// Save in db as last seen
user.last = {
@ -107,11 +107,11 @@ module.exports = {
// Shutdown (check for remaining clients)
socket.on('disconnect', (reason)=>{
winston.silly(`${socket.id} disconnected because of a ${reason}.`);
debug(`${socket.id} disconnected because of a ${reason}.`);
// Check if client was receiving updates
if (socket.gets){
winston.silly(`${socket.id} left ${socket.gets}`);
debug(`${socket.id} left ${socket.gets}`);
checkForUsers( io, socket.gets );
}

View File

@ -9,6 +9,7 @@
"connect-flash-plus": "^0.2.1",
"cookie-parser": "^1.4.1",
"cookie-session": "^2.0.0-alpha.1",
"debug": "^2.6.6",
"express": "^4.15.2",
"express-validator": "^3.1.3",
"kerberos": "0.0.17",
@ -30,7 +31,6 @@
"passport-twitter-token": "^1.3.0",
"slug": "^0.9.1",
"socket.io": "^1.4.4",
"winston": "^2.3.1",
"xss": "^0.3.3"
},
"devDependencies": {

View File

@ -7,7 +7,7 @@ const
expressValidator = require('express-validator'),
cookieParser = require('cookie-parser'),
cookieSession = require('cookie-session'),
winston = require('winston'),
debug = require('debug')('tracman-server'),
mongoose = require('mongoose'),
nunjucks = require('nunjucks'),
passport = require('passport'),
@ -22,9 +22,6 @@ const
/* SETUP */ {
// Log level
winston.level = process.env.LOGLEVEL || env.logLevel || 'info';
/* Database */ {
// Setup with native ES6 promises
@ -84,7 +81,7 @@ const
let nextPath = ((req.query.next)?req.query.next: req.path.substring(0,req.path.indexOf('#')) || req.path );
if ( nextPath.substring(0,6)!=='/login' && nextPath.substring(0,7)!=='/logout' && nextPath.substring(0,7)!=='/static' ){
req.session.next = nextPath+'#';
winston.debug(`Set redirect path to ${nextPath}#`);
debug(`Set redirect path to ${nextPath}#`);
}
// User account
@ -172,7 +169,6 @@ const
// Listen
http.listen( env.port, ()=>{
console.log(`🌐 Listening in ${env.mode} mode on port ${env.port}... `);
winston.verbose(`Log level set to ${env.logLevel}`);
// Check for clients for each user
User.find({})