#110 Implemented StandardJS

master
Keith Irwin 2017-12-13 00:40:07 +00:00
parent f137835870
commit 016378d807
No known key found for this signature in database
GPG Key ID: 378933C743E2BBC0
29 changed files with 2631 additions and 2852 deletions

View File

@ -1,6 +1,8 @@
# Tracman Server Changelog # Tracman Server Changelog
###### v 0.7.12 ###### v 0.7.12
#### develop
* [#110](https://github.com/Tracman-org/Server/issues/110) Implemented [StandardJS](https://standardjs.com/)
#### v0.7.12 #### v0.7.12
* Fixed altitude sign * Fixed altitude sign

View File

@ -3,6 +3,7 @@
node.js application to display a sharable map with user's location. node.js application to display a sharable map with user's location.
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
## Installation ## Installation
@ -52,6 +53,9 @@ Tracman will be updated according to [this branching model](http://nvie.com/post
[view full changelog](CHANGELOG.md) [view full changelog](CHANGELOG.md)
#### develop
* [#110](https://github.com/Tracman-org/Server/issues/110) Implemented [StandardJS](https://standardjs.com/)
#### v0.7.12 #### v0.7.12
* Fixed altitude sign * Fixed altitude sign

View File

@ -1,38 +1,34 @@
'use strict'; 'use strict'
// Imports // Imports
const fs = require('fs'), const fs = require('fs')
debug = require('debug')('tracman-demo'); const path = require('path')
const debug = require('debug')('tracman-demo')
module.exports = (io)=>{ module.exports = (io) => {
// File is space-seperated: delay, lat, lon, dir, spd
// File is space-seperated: delay, lat, lon, dir, spd fs.readFile(path.join(__dirname, '/demo.txt'), (err, data) => {
fs.readFile(__dirname+'/demo.txt', (err,data)=>{ if (err) { console.error(`${err.stack}`) }
if (err){ console.error(`${err.stack}`); }
const lines = data.toString().split('\n');
const lines = data.toString().split('\n');
(function sendLoc (ln) {
(function sendLoc(ln) { if (ln > 20754) { sendLoc(0) } else {
if (ln>20754){ sendLoc(0) } let loc = lines[ln].split(' ')
else { debug(`Sending demo location: ${loc[1]}, ${loc[2]}`)
io.to('demo').emit('get', {
let loc = lines[ln].split(' '); tim: new Date(),
debug(`Sending demo location: ${loc[1]}, ${loc[2]}`); lat: loc[1],
io.to('demo').emit('get', { lon: loc[2],
tim: new Date(), dir: loc[3],
lat: loc[1], spd: loc[4]
lon: loc[2], })
dir: loc[3],
spd: loc[4] // Repeat after delay in milliseconds
}); setTimeout(() => {
sendLoc(ln + 1) // next line of file
// Repeat after delay in milliseconds }, loc[0])
setTimeout(()=>{ }
sendLoc(ln+1); // next line of file })(5667)
}, loc[0]); })
}
}
})(5667);
});
};

88
config/env/sample.js vendored
View File

@ -1,46 +1,46 @@
'use strict'; 'use strict'
module.exports = { module.exports = {
// Local variables // Local variables
mode: 'development', // or production mode: 'development', // or production
// Random strings to prevent hijacking // Random strings to prevent hijacking
session: 'SomeSecret', session: 'SomeSecret',
cookie: 'SomeOtherSecret', cookie: 'SomeOtherSecret',
// Location of your mongoDB // Location of your mongoDB
mongoSetup: 'mongodb://localhost:27017/tracman', mongoSetup: 'mongodb://localhost:27017/tracman',
// Or use the test database from mLab // Or use the test database from mLab
//mongoSetup: 'mongodb://tracman:MUPSLXQ34f9cQTc5@ds133961.mlab.com:33961/tracman', // mongoSetup: 'mongodb://tracman:MUPSLXQ34f9cQTc5@ds133961.mlab.com:33961/tracman',
// You can log in there with: // You can log in there with:
// mongo ds133961.mlab.com:33961/tracman-dev -u contributor -p opensourcerules // mongo ds133961.mlab.com:33961/tracman-dev -u contributor -p opensourcerules
// URL and port where this will run // URL and port where this will run
url: 'https://localhost:8080', url: 'https://localhost:8080',
port: 8080, port: 8080,
// Mailserver // Mailserver
mailserver: 'example.org', mailserver: 'example.org',
mailport: 587, mailport: 587,
mailauth: { mailauth: {
user: 'mailusername', user: 'mailusername',
pass: 'XXXXXXXXXX', pass: 'XXXXXXXXXX'
}, },
// OAuth API keys // OAuth API keys
facebookAppId: 'XXXXXXXXXXXXXXXX', facebookAppId: 'XXXXXXXXXXXXXXXX',
facebookAppSecret: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', facebookAppSecret: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
twitterConsumerKey: 'XXXXXXXXXXXXXXXXXXXXXXXXX', twitterConsumerKey: 'XXXXXXXXXXXXXXXXXXXXXXXXX',
twitterConsumerSecret: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', twitterConsumerSecret: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
googleClientId: '############-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com', googleClientId: '############-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com',
googleClientSecret: 'XXXXXXXXX_XXXXXXXXXXXXXX', googleClientSecret: 'XXXXXXXXX_XXXXXXXXXXXXXX',
// Google maps API key // Google maps API key
googleMapsAPI: 'XXXXXXXXXXXXXXX_XXXXXXXXXXXXXXXXXXXXXXX', googleMapsAPI: 'XXXXXXXXXXXXXXX_XXXXXXXXXXXXXXXXXXXXXXX',
// reCaptcha API key // reCaptcha API key
recaptchaSitekey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', recaptchaSitekey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
recaptchaSecret: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', recaptchaSecret: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
}; }

View File

@ -1,41 +1,41 @@
'use strict'; 'use strict'
const nodemailer = require('nodemailer'), const nodemailer = require('nodemailer')
env = require('./env/env.js'); const env = require('./env/env.js')
let transporter = nodemailer.createTransport({ let transporter = nodemailer.createTransport({
host: env.mailserver, host: env.mailserver,
port: env.mailport, port: env.mailport,
secure: false, secure: false,
requireTLS: true, requireTLS: true,
auth: env.mailauth, auth: env.mailauth
// logger: true, // logger: true,
// debug: true // debug: true
}); })
module.exports = { module.exports = {
verify: ()=>{ verify: () => {
transporter.verify( (err,success)=>{ transporter.verify((err, success) => {
if (err){ console.error(`SMTP Error: ${err}`); } if (err) { console.error(`SMTP Error: ${err}`) }
console.log(`📧 SMTP ${!success?'not ':''}ready`); console.log(`📧 SMTP ${!success ? 'not ' : ''}ready`)
} ); })
}, },
send: transporter.sendMail.bind(transporter), send: transporter.sendMail.bind(transporter),
text: (text)=>{ text: (text) => {
return `Tracman\n\n${text}\n\nDo not reply to this email\nFor information about why you received this email, see the privacy policy at ${env.url}/privacyy#email`; return `Tracman\n\n${text}\n\nDo not reply to this email\nFor information about why you received this email, see the privacy policy at ${env.url}/privacyy#email`
}, },
html: (text)=>{ html: (text) => {
return `<h1><a href="/" style="text-decoration:none;"><span style="color:#000;font-family:sans-serif;font-size:36px;font-weight:bold"><img src="${env.url}/static/img/icon/by/32.png" alt="+" style="margin-right:10px">Tracman</span></a></h1>${text}<p style="font-size:8px;">Do not reply to this email. For information about why you recieved this email, see our <a href="${env.url}/privacy#email">privacy policy</a>. </p>`; return `<h1><a href="/" style="text-decoration:none;"><span style="color:#000;font-family:sans-serif;font-size:36px;font-weight:bold"><img src="${env.url}/static/img/icon/by/32.png" alt="+" style="margin-right:10px">Tracman</span></a></h1>${text}<p style="font-size:8px;">Do not reply to this email. For information about why you recieved this email, see our <a href="${env.url}/privacy#email">privacy policy</a>. </p>`
}, },
noReply: `"Tracman" <NoReply@tracman.org>`, noReply: `"Tracman" <NoReply@tracman.org>`,
to: (user)=>{ to: (user) => {
return `"${user.name}" <${user.email}>`; return `"${user.name}" <${user.email}>`
} }
}; }

View File

@ -1,47 +1,45 @@
'use strict'; 'use strict'
const env = require('./env/env.js'); const env = require('./env/env.js')
module.exports = { module.exports = {
// Throw error // Throw error
throwErr: (err,req=null)=>{ throwErr: (err, req = null) => {
console.error(`❌️ ${err.stack}`); console.error(`❌️ ${err.stack}`)
if (req){ if (req) {
if (env.mode==='production') { if (env.mode === 'production') {
req.flash('danger', 'An error occured. <br>Would you like to <a href="https://github.com/Tracman-org/Server/issues/new">report it</a>?'); req.flash('danger', 'An error occured. <br>Would you like to <a href="https://github.com/Tracman-org/Server/issues/new">report it</a>?')
} else { // development } else { // development
req.flash('danger', err.message); req.flash('danger', err.message)
} }
} }
}, },
// Capitalize the first letter of a string // Capitalize the first letter of a string
capitalize: (str)=>{ capitalize: (str) => {
return str.charAt(0).toUpperCase() + str.slice(1); return str.charAt(0).toUpperCase() + str.slice(1)
}, },
// Validate an email address
validateEmail: (email)=>{
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
},
// Ensure authentication // Validate an email address
ensureAuth: (req,res,next)=>{ validateEmail: (email) => {
if (req.isAuthenticated()) { return next(); } var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
else { res.redirect('/login'); } return re.test(email)
}, },
// Ensure administrator // Ensure authentication
ensureAdmin: (req,res,next)=>{ ensureAuth: (req, res, next) => {
if (req.isAuthenticated() && req.user.isAdmin){ return next(); } if (req.isAuthenticated()) { return next() } else { res.redirect('/login') }
else { },
let err = new Error("Unauthorized");
err.status = 401;
next(err);
}
//TODO: test this by logging in as !isAdmin and go to /admin
}
}; // Ensure administrator
ensureAdmin: (req, res, next) => {
if (req.isAuthenticated() && req.user.isAdmin) { return next() } else {
let err = new Error('Unauthorized')
err.status = 401
next(err)
}
// TODO: test this by logging in as !isAdmin and go to /admin
}
}

View File

@ -1,150 +1,142 @@
'use strict'; 'use strict'
const mongoose = require('mongoose'), const mongoose = require('mongoose')
unique = require('mongoose-unique-validator'), const unique = require('mongoose-unique-validator')
bcrypt = require('bcrypt'), const bcrypt = require('bcrypt')
crypto = require('crypto'), const crypto = require('crypto')
debug = require('debug')('tracman-models'); const debug = require('debug')('tracman-models')
const userSchema = new mongoose.Schema({ const userSchema = new mongoose.Schema({
name: {type:String}, name: {type: String},
email: {type:String, unique:true}, email: {type: String, unique: true},
newEmail: String, newEmail: String,
emailToken: String, emailToken: String,
slug: {type:String, required:true, unique:true}, slug: {type: String, required: true, unique: true},
auth: { auth: {
password: String, password: String,
passToken: String, passToken: String,
passTokenExpires: Date, passTokenExpires: Date,
google: String, google: String,
facebook: String, facebook: String,
twitter: String, twitter: String
}, },
isAdmin: {type:Boolean, required:true, default:false}, isAdmin: {type: Boolean, required: true, default: false},
isPro: {type:Boolean, required:true, default:false}, isPro: {type: Boolean, required: true, default: false},
created: {type:Date, required:true}, created: {type: Date, required: true},
lastLogin: Date, lastLogin: Date,
settings: { settings: {
units: {type:String, default:'standard'}, units: {type: String, default: 'standard'},
defaultMap: {type:String, default:'road'}, defaultMap: {type: String, default: 'road'},
defaultZoom: {type:Number, default:11}, defaultZoom: {type: Number, default: 11},
showScale: {type:Boolean, default:false}, showScale: {type: Boolean, default: false},
showSpeed: {type:Boolean, default:false}, showSpeed: {type: Boolean, default: false},
showTemp: {type:Boolean, default:false}, showTemp: {type: Boolean, default: false},
showAlt: {type:Boolean, default:false}, showAlt: {type: Boolean, default: false},
showStreetview: {type:Boolean, default:false}, showStreetview: {type: Boolean, default: false},
marker: {type:String, default:'red'} marker: {type: String, default: 'red'}
}, },
last: { last: {
time: Date, time: Date,
lat: {type:Number, default:0}, lat: {type: Number, default: 0},
lon: {type:Number, default:0}, lon: {type: Number, default: 0},
dir: {type:Number, default:0}, dir: {type: Number, default: 0},
alt: {type:Number}, alt: {type: Number},
spd: {type:Number, default:0} spd: {type: Number, default: 0}
}, },
sk32: {type:String, required:true, unique:true} sk32: {type: String, required: true, unique: true}
}).plugin(unique); }).plugin(unique)
/* User methods */ { /* User methods */
// TODO: Return promises instead of taking callbacks
//TODO: Return promises instead of taking callbacks // See https://gist.github.com/7h1b0/5154fda207e68ad1cefc#file-random-js
// See https://gist.github.com/7h1b0/5154fda207e68ad1cefc#file-random-js // For an example
// For an example
// Create email confirmation token
userSchema.methods.createEmailToken = function(next){ // next(err,token)
debug('user.createEmailToken() called');
var user = this;
crypto.randomBytes(16, (err,buf)=>{
if (err){ next(err,null); }
if (buf){
debug(`Buffer ${buf.toString('hex')} created`);
user.emailToken = buf.toString('hex');
user.save()
.then( ()=>{
return next(null,user.emailToken);
})
.catch( (err)=>{
return next(err,null);
});
}
});
};
// Create password reset token // Create email confirmation token
userSchema.methods.createPassToken = function(next){ // next(err,token,expires) userSchema.methods.createEmailToken = function (next) { // next(err,token)
var user = this; debug('user.createEmailToken() called')
var user = this
// Reuse old token, resetting clock
if ( user.auth.passTokenExpires >= Date.now() ){ crypto.randomBytes(16, (err, buf) => {
debug(`Reusing old password token...`); if (err) { next(err, null) }
user.auth.passTokenExpires = Date.now() + 3600000; // 1 hour if (buf) {
user.save() debug(`Buffer ${buf.toString('hex')} created`)
.then( ()=>{ user.emailToken = buf.toString('hex')
return next(null,user.auth.passToken,user.auth.passTokenExpires); user.save()
}) .then(() => {
.catch( (err)=>{ return next(null, user.emailToken)
return next(err,null,null); })
}); .catch((err) => {
} return next(err, null)
})
// Create new token }
else { })
debug(`Creating new password token...`); }
crypto.randomBytes(16, (err,buf)=>{
if (err){ return next(err,null,null); } // Create password reset token
if (buf) { userSchema.methods.createPassToken = function (next) { // next(err,token,expires)
user.auth.passToken = buf.toString('hex'); var user = this
user.auth.passTokenExpires = Date.now() + 3600000; // 1 hour
user.save() // Reuse old token, resetting clock
.then( ()=>{ if (user.auth.passTokenExpires >= Date.now()) {
debug('successfully saved user in createPassToken'); debug(`Reusing old password token...`)
return next(null,user.auth.passToken,user.auth.passTokenExpires); user.auth.passTokenExpires = Date.now() + 3600000 // 1 hour
}) user.save()
.catch( (err)=>{ .then(() => {
debug('error saving user in createPassToken'); return next(null, user.auth.passToken, user.auth.passTokenExpires)
return next(err,null,null); })
}); .catch((err) => {
} return next(err, null, null)
}); })
}
// Create new token
}; } else {
debug(`Creating new password token...`)
// Generate hash for new password and save it to the database crypto.randomBytes(16, (err, buf) => {
userSchema.methods.generateHashedPassword = function(password,next){ if (err) { return next(err, null, null) }
// next(err); if (buf) {
user.auth.passToken = buf.toString('hex')
// Delete token user.auth.passTokenExpires = Date.now() + 3600000 // 1 hour
this.auth.passToken = undefined; user.save()
this.auth.passTokenExpires = undefined; .then(() => {
debug('successfully saved user in createPassToken')
// Generate hash return next(null, user.auth.passToken, user.auth.passTokenExpires)
bcrypt.genSalt(8, (err,salt)=>{ })
if (err){ return next(err); } .catch((err) => {
bcrypt.hash(password, salt, (err,hash)=>{ debug('error saving user in createPassToken')
if (err){ return next(err); } return next(err, null, null)
this.auth.password = hash; })
this.save(); }
next(); })
}); }
}); }
}; // Generate hash for new password and save it to the database
userSchema.methods.generateHashedPassword = function (password, next) {
// Check for valid password // next(err);
userSchema.methods.validPassword = function(password,next){
// next(err,res); // Delete token
// res = true/false this.auth.passToken = undefined
bcrypt.compare(password, this.auth.password, next); this.auth.passTokenExpires = undefined
};
// Generate hash
bcrypt.genSalt(8, (err, salt) => {
if (err) { return next(err) }
bcrypt.hash(password, salt, (err, hash) => {
if (err) { return next(err) }
this.auth.password = hash
this.save()
next()
})
})
}
// Check for valid password
userSchema.methods.validPassword = function (password, next) {
// next(err,res);
// res = true/false
bcrypt.compare(password, this.auth.password, next)
} }
module.exports = { module.exports = {
'user': mongoose.model('User', userSchema) 'user': mongoose.model('User', userSchema)
}; }

View File

@ -1,252 +1,229 @@
'use strict'; 'use strict'
const const LocalStrategy = require('passport-local').Strategy
LocalStrategy = require('passport-local').Strategy, const GoogleStrategy = require('passport-google-oauth20').Strategy
GoogleStrategy = require('passport-google-oauth20').Strategy, const FacebookStrategy = require('passport-facebook').Strategy
FacebookStrategy = require('passport-facebook').Strategy, const TwitterStrategy = require('passport-twitter').Strategy
TwitterStrategy = require('passport-twitter').Strategy, const GoogleTokenStrategy = require('passport-google-id-token')
GoogleTokenStrategy = require('passport-google-id-token'), const FacebookTokenStrategy = require('passport-facebook-token')
FacebookTokenStrategy = require('passport-facebook-token'), const TwitterTokenStrategy = require('passport-twitter-token')
TwitterTokenStrategy = require('passport-twitter-token'), const debug = require('debug')('tracman-passport')
debug = require('debug')('tracman-passport'), const env = require('./env/env.js')
env = require('./env/env.js'), const mw = require('./middleware.js')
mw = require('./middleware.js'), const User = require('./models.js').user
User = require('./models.js').user;
module.exports = (passport)=>{
// Serialize/deserialize users
passport.serializeUser((user,done)=>{
done(null, user.id);
});
passport.deserializeUser((id,done)=>{
User.findById(id, (err,user)=>{
if(!err){ done(null, user); }
else { done(err, null); }
});
});
// Local
passport.use('local', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, (req,email,password,done)=>{
debug(`Perfoming local login for ${email}`);
User.findOne({'email':email})
.then( (user)=>{
// No user with that email
if (!user) {
req.session.next = undefined;
return done( null, false, req.flash('warning','Incorrect email or password.') );
}
// User exists
else {
// Check password
user.validPassword( password, (err,res)=>{
if (err){ return done(err); }
// Password incorrect
if (!res) {
req.session.next = undefined;
return done( null, false, req.flash('warning','Incorrect email or password.') );
}
// Successful login
else {
user.lastLogin = Date.now();
user.save();
return done(null,user);
}
} );
}
})
.catch( (err)=>{
return done(err);
});
}
));
// Social login
function socialLogin(req, service, profileId, done) {
debug(`socialLogin() called for ${service} account ${profileId}`);
let query = {};
query['auth.'+service] = profileId;
// Intent to log in
if (!req.user) {
debug(`Searching for user with query ${query}...`);
User.findOne(query)
.then( (user)=>{
// Can't find user
if (!user){
// Lazy update from old googleId field
if (service==='google') {
User.findOne({ 'googleID': parseInt(profileId,10) })
.then( (user)=>{
// User exists with old schema
if (user) {
debug(`User ${user.id} exists with old schema. Lazily updating...`);
user.auth.google = profileId;
user.googleId = undefined;
user.save()
.then( ()=>{
debug(`Lazily updated ${user.id}...`);
req.session.flashType = 'success';
req.session.flashMessage = "You have been logged in. ";
return done(null, user);
})
.catch( (err)=>{
debug(`Failed to save user that exists with old googleId schema!`);
mw.throwErr(err,req);
return done(err);
});
}
// No such user
else {
debug(`User with ${service} account of ${profileId} not found.`);
req.flash('warning', `There's no user for that ${service} account. `);
return done();
}
})
.catch ( (err)=>{
debug(`Failed to search for user with old googleID of ${profileId}. `);
mw.throwErr(err,req);
return done(err);
});
}
// No googleId either
else {
debug(`Couldn't find ${service} user with profileID ${profileId}.`);
req.flash('warning', `There's no user for that ${service} account. `);
return done();
}
}
// Successfull social login
else {
debug(`Found user: ${user.id}; logging in...`);
req.session.flashType = 'success';
req.session.flashMessage = "You have been logged in.";
return done(null, user);
}
})
.catch( (err)=>{
debug(`Failed to find user with query: ${query}`);
mw.throwErr(err,req);
return done(err);
});
}
// Intent to connect account
else {
debug(`Attempting to connect ${service} account to ${req.user.id}...`);
// Check for unique profileId
debug(`Checking for unique account with query ${query}...`);
User.findOne(query)
.then( (existingUser)=>{
// Social account already in use
if (existingUser) {
debug(`${service} account already in use with user ${existingUser.id}`);
req.session.flashType = 'warning';
req.session.flashMessage = `Another user is already connected to that ${service} account. `;
return done();
}
// Connect to account
else {
debug(`${service} account (${profileId}) is unique; Connecting to ${req.user.id}...`);
req.user.auth[service] = profileId;
req.user.save()
.then( ()=>{
debug(`Successfully connected ${service} account to ${req.user.id}`);
req.session.flashType = 'success';
req.session.flashMessage = `${mw.capitalize(service)} account connected. `;
return done(null,req.user);
} )
.catch( (err)=>{
debug(`Failed to connect ${service} account to ${req.user.id}!`);
return done(err);
} );
}
})
.catch( (err)=>{
debug(`Failed to check for unique ${service} profileId of ${profileId}!`);
mw.throwErr(err,req);
return done(err);
});
}
}
// Google module.exports = (passport) => {
passport.use('google', new GoogleStrategy({ // Serialize/deserialize users
clientID: env.googleClientId, passport.serializeUser((user, done) => {
clientSecret: env.googleClientSecret, done(null, user.id)
callbackURL: env.url+'/login/google/cb', })
passReqToCallback: true passport.deserializeUser((id, done) => {
}, (req, accessToken, refreshToken, profile, done)=>{ User.findById(id, (err, user) => {
socialLogin(req, 'google', profile.id, done); if (!err) { done(null, user) } else { done(err, null) }
} })
)).use('google-token', new GoogleTokenStrategy({ })
clientID: env.googleClientId,
passReqToCallback: true
}, (req, parsedToken, googleId, done)=>{
socialLogin(req,'google', googleId, done);
}
));
// Facebook
passport.use('facebook', new FacebookStrategy({
clientID: env.facebookAppId,
clientSecret: env.facebookAppSecret,
callbackURL: env.url+'/login/facebook/cb',
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done)=>{
socialLogin(req, 'facebook', profile.id, done);
}
)).use('facebook-token', new FacebookTokenStrategy({
clientID: env.facebookAppId,
clientSecret: env.facebookAppSecret,
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done)=>{
socialLogin(req,'facebook', profile.id, done);
}
));
// Twitter
passport.use(new TwitterStrategy({
consumerKey: env.twitterConsumerKey,
consumerSecret: env.twitterConsumerSecret,
callbackURL: env.url+'/login/twitter/cb',
passReqToCallback: true
}, (req, token, tokenSecret, profile, done)=>{
socialLogin(req, 'twitter', profile.id, done);
}
)).use('twitter-token', new TwitterTokenStrategy({
consumerKey: env.twitterConsumerKey,
consumerSecret: env.twitterConsumerSecret,
passReqToCallback: true
}, (req, token, tokenSecret, profile, done)=>{
socialLogin(req,'twitter', profile.id, done);
}
));
return passport; // Local
}; passport.use('local', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, (req, email, password, done) => {
debug(`Perfoming local login for ${email}`)
User.findOne({'email': email})
.then((user) => {
// No user with that email
if (!user) {
req.session.next = undefined
return done(null, false, req.flash('warning', 'Incorrect email or password.'))
// User exists
} else {
// Check password
user.validPassword(password, (err, res) => {
if (err) { return done(err) }
// Password incorrect
if (!res) {
req.session.next = undefined
return done(null, false, req.flash('warning', 'Incorrect email or password.'))
// Successful login
} else {
user.lastLogin = Date.now()
user.save()
return done(null, user)
}
})
}
})
.catch((err) => {
return done(err)
})
}
))
// Social login
function socialLogin (req, service, profileId, done) {
debug(`socialLogin() called for ${service} account ${profileId}`)
let query = {}
query['auth.' + service] = profileId
// Intent to log in
if (!req.user) {
debug(`Searching for user with query ${query}...`)
User.findOne(query)
.then((user) => {
// Can't find user
if (!user) {
// Lazy update from old googleId field
if (service === 'google') {
User.findOne({ 'googleID': parseInt(profileId, 10) })
.then((user) => {
// User exists with old schema
if (user) {
debug(`User ${user.id} exists with old schema. Lazily updating...`)
user.auth.google = profileId
user.googleId = undefined
user.save()
.then(() => {
debug(`Lazily updated ${user.id}...`)
req.session.flashType = 'success'
req.session.flashMessage = 'You have been logged in. '
return done(null, user)
})
.catch((err) => {
debug(`Failed to save user that exists with old googleId schema!`)
mw.throwErr(err, req)
return done(err)
})
// No such user
} else {
debug(`User with ${service} account of ${profileId} not found.`)
req.flash('warning', `There's no user for that ${service} account. `)
return done()
}
})
.catch((err) => {
debug(`Failed to search for user with old googleID of ${profileId}. `)
mw.throwErr(err, req)
return done(err)
})
// No googleId either
} else {
debug(`Couldn't find ${service} user with profileID ${profileId}.`)
req.flash('warning', `There's no user for that ${service} account. `)
return done()
}
// Successfull social login
} else {
debug(`Found user: ${user.id}; logging in...`)
req.session.flashType = 'success'
req.session.flashMessage = 'You have been logged in.'
return done(null, user)
}
})
.catch((err) => {
debug(`Failed to find user with query: ${query}`)
mw.throwErr(err, req)
return done(err)
})
// Intent to connect account
} else {
debug(`Attempting to connect ${service} account to ${req.user.id}...`)
// Check for unique profileId
debug(`Checking for unique account with query ${query}...`)
User.findOne(query)
.then((existingUser) => {
// Social account already in use
if (existingUser) {
debug(`${service} account already in use with user ${existingUser.id}`)
req.session.flashType = 'warning'
req.session.flashMessage = `Another user is already connected to that ${service} account. `
return done()
// Connect to account
} else {
debug(`${service} account (${profileId}) is unique; Connecting to ${req.user.id}...`)
req.user.auth[service] = profileId
req.user.save()
.then(() => {
debug(`Successfully connected ${service} account to ${req.user.id}`)
req.session.flashType = 'success'
req.session.flashMessage = `${mw.capitalize(service)} account connected. `
return done(null, req.user)
})
.catch((err) => {
debug(`Failed to connect ${service} account to ${req.user.id}!`)
return done(err)
})
}
})
.catch((err) => {
debug(`Failed to check for unique ${service} profileId of ${profileId}!`)
mw.throwErr(err, req)
return done(err)
})
}
}
// Google
passport.use('google', new GoogleStrategy({
clientID: env.googleClientId,
clientSecret: env.googleClientSecret,
callbackURL: env.url + '/login/google/cb',
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
socialLogin(req, 'google', profile.id, done)
}
)).use('google-token', new GoogleTokenStrategy({
clientID: env.googleClientId,
passReqToCallback: true
}, (req, parsedToken, googleId, done) => {
socialLogin(req, 'google', googleId, done)
}
))
// Facebook
passport.use('facebook', new FacebookStrategy({
clientID: env.facebookAppId,
clientSecret: env.facebookAppSecret,
callbackURL: env.url + '/login/facebook/cb',
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
socialLogin(req, 'facebook', profile.id, done)
}
)).use('facebook-token', new FacebookTokenStrategy({
clientID: env.facebookAppId,
clientSecret: env.facebookAppSecret,
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
socialLogin(req, 'facebook', profile.id, done)
}
))
// Twitter
passport.use(new TwitterStrategy({
consumerKey: env.twitterConsumerKey,
consumerSecret: env.twitterConsumerSecret,
callbackURL: env.url + '/login/twitter/cb',
passReqToCallback: true
}, (req, token, tokenSecret, profile, done) => {
socialLogin(req, 'twitter', profile.id, done)
}
)).use('twitter-token', new TwitterTokenStrategy({
consumerKey: env.twitterConsumerKey,
consumerSecret: env.twitterConsumerSecret,
passReqToCallback: true
}, (req, token, tokenSecret, profile, done) => {
socialLogin(req, 'twitter', profile.id, done)
}
))
return passport
}

View File

@ -1,39 +1,35 @@
'use strict'; 'use strict'
const router = require('express').Router(), const router = require('express').Router()
mw = require('../middleware.js'), const mw = require('../middleware.js')
debug = require('debug')('tracman-routes-admin'), const debug = require('debug')('tracman-routes-admin')
User = require('../models.js').user; const User = require('../models.js').user
router.get('/', mw.ensureAdmin, (req,res)=>{ router.get('/', mw.ensureAdmin, (req, res) => {
User.find({}).sort({lastLogin: -1})
User.find({}).sort({lastLogin:-1}) .then((found) => {
.then( (found)=>{ res.render('admin', {
res.render('admin', { active: 'admin',
active: 'admin', noFooter: '1',
noFooter: '1', users: found,
users: found, total: found.length
total: found.length })
}); })
}) .catch((err) => { mw.throwErr(err, req) })
.catch( (err)=>{ mw.throwErr(err,req); }); })
});
router.get('/delete/:usrid', mw.ensureAdmin, (req,res,next)=>{
debug(`/delete/${req.params.usrid} called`);
User.findOneAndRemove({'_id':req.params.usrid})
.then( (user)=>{
req.flash('success', `<i>${req.params.usrid}</i> deleted.`);
res.redirect('/admin');
})
.catch( (err)=>{
mw.throwErr(err,req);
res.redirect('/admin');
});
});
module.exports = router; router.get('/delete/:usrid', mw.ensureAdmin, (req, res, next) => {
debug(`/delete/${req.params.usrid} called`)
User.findOneAndRemove({'_id': req.params.usrid})
.then((user) => {
req.flash('success', `<i>${req.params.usrid}</i> deleted.`)
res.redirect('/admin')
})
.catch((err) => {
mw.throwErr(err, req)
res.redirect('/admin')
})
})
module.exports = router

View File

@ -1,345 +1,309 @@
'use strict'; 'use strict'
const const mw = require('../middleware.js')
mw = require('../middleware.js'), const mail = require('../mail.js')
mail = require('../mail.js'), const User = require('../models.js').user
User = require('../models.js').user, const crypto = require('crypto')
crypto = require('crypto'), const moment = require('moment')
moment = require('moment'), const slugify = require('slug')
slugify = require('slug'), const debug = require('debug')('tracman-routes-auth')
debug = require('debug')('tracman-routes-auth'), const env = require('../env/env.js')
env = require('../env/env.js');
module.exports = (app, passport) => { module.exports = (app, passport) => {
// Methods for success and failure
const loginOutcome = {
failureRedirect: '/login',
failureFlash: true
}
const loginCallback = (req, res) => {
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')
}
const appLoginCallback = (req, res, next) => {
debug('appLoginCallback called.')
if (req.user) { res.send(req.user) } else {
let err = new Error('Unauthorized')
err.status = 401
next(err)
}
}
// Methods for success and failure // Login/-out
const app.route('/login')
loginOutcome = { .get((req, res) => {
failureRedirect: '/login', // Already logged in
failureFlash: true if (req.isAuthenticated()) {
}, loginCallback(req, res)
loginCallback = (req,res)=>{
debug(`Login callback called... redirecting to ${req.session.next}`); // Show login page
req.flash(req.session.flashType,req.session.flashMessage); } else { res.render('login') }
req.session.flashType = undefined; })
req.session.flashMessage = undefined; .post(passport.authenticate('local', loginOutcome), loginCallback)
res.redirect( req.session.next || '/map' ); app.get('/logout', (req, res) => {
}, req.logout()
appLoginCallback = (req,res,next)=>{ req.flash('success', `You have been logged out.`)
debug('appLoginCallback called.'); res.redirect(req.session.next || '/')
if (req.user){ res.send(req.user); } })
else {
let err = new Error("Unauthorized"); // Signup
err.status = 401; app.route('/signup')
next(err); .get((req, res) => {
} res.redirect('/login#signup')
}; })
.post((req, res, next) => {
// Login/-out // Send token and alert user
app.route('/login') function sendToken (user) {
.get( (req,res)=>{ debug(`sendToken() called for user ${user.id}`)
// Already logged in // Create a password token
if (req.isAuthenticated()) { loginCallback(req,res); } user.createPassToken((err, token, expires) => {
if (err) {
// Show login page debug(`Error creating password token for user ${user.id}!`)
else { res.render('login'); } mw.throwErr(err, req)
res.redirect('/login#signup')
}) } else {
.post( passport.authenticate('local',loginOutcome), loginCallback ); debug(`Created password token for user ${user.id} successfully`)
app.get('/logout', (req,res)=>{
req.logout(); // Figure out expiration time
req.flash('success',`You have been logged out.`); let expirationTimeString = (req.query.tz)
res.redirect( req.session.next || '/' ); ? moment(expires).utcOffset(req.query.tz).toDate().toLocaleTimeString(req.acceptsLanguages[0])
}); : moment(expires).toDate().toLocaleTimeString(req.acceptsLanguages[0]) + ' UTC'
// Signup // Email the instructions to continue
app.route('/signup') debug(`Emailing new user ${user.id} at ${user.email} instructions to create a password...`)
.get( (req,res)=>{ mail.send({
res.redirect('/login#signup'); from: mail.noReply,
}) to: `<${user.email}>`,
.post( (req,res,next)=>{ subject: 'Complete your Tracman registration',
text: mail.text(`Welcome to Tracman! \n\nTo complete your registration, follow this link and set your password:\n${env.url}/settings/password/${token}\n\nThis link will expire at ${expirationTimeString}. `),
// Send token and alert user html: mail.html(`<p>Welcome to Tracman! </p><p>To complete your registration, follow this link and set your password:<br><a href="${env.url}/settings/password/${token}">${env.url}/settings/password/${token}</a></p><p>This link will expire at ${expirationTimeString}. </p>`)
function sendToken(user){ })
debug(`sendToken() called for user ${user.id}`); .then(() => {
debug(`Successfully emailed new user ${user.id} instructions to continue`)
// Create a password token req.flash('success', `An email has been sent to <u>${user.email}</u>. Check your inbox and follow the link to complete your registration. (Your registration link will expire in one hour). `)
user.createPassToken( (err,token,expires)=>{ res.redirect('/login')
if (err){ })
debug(`Error creating password token for user ${user.id}!`); .catch((err) => {
mw.throwErr(err,req); debug(`Failed to email new user ${user.id} instructions to continue!`)
res.redirect('/login#signup'); mw.throwErr(err, req)
} res.redirect('/login#signup')
else { })
debug(`Created password token for user ${user.id} successfully`); }
})
// Figure out expiration time }
let expirationTimeString = (req.query.tz)?
moment(expires).utcOffset(req.query.tz).toDate().toLocaleTimeString(req.acceptsLanguages[0]): // Validate email
moment(expires).toDate().toLocaleTimeString(req.acceptsLanguages[0])+" UTC"; req.checkBody('email', 'Please enter a valid email address.').isEmail()
// Email the instructions to continue // Check if somebody already has that email
debug(`Emailing new user ${user.id} at ${user.email} instructions to create a password...`); debug(`Searching for user with email ${req.body.email}...`)
mail.send({ User.findOne({'email': req.body.email})
from: mail.noReply, .then((user) => {
to: `<${user.email}>`, // User already exists
subject: 'Complete your Tracman registration', if (user && user.auth.password) {
text: mail.text(`Welcome to Tracman! \n\nTo complete your registration, follow this link and set your password:\n${env.url}/settings/password/${token}\n\nThis link will expire at ${expirationTimeString}. `), debug(`User ${user.id} has email ${req.body.email} and has a password`)
html: mail.html(`<p>Welcome to Tracman! </p><p>To complete your registration, follow this link and set your password:<br><a href="${env.url}/settings/password/${token}">${env.url}/settings/password/${token}</a></p><p>This link will expire at ${expirationTimeString}. </p>`) req.flash('warning', `A user with that email already exists! If you forgot your password, you can <a href="/login/forgot?email=${req.body.email}">reset it here</a>.`)
}) res.redirect('/login#login')
.then(()=>{ next()
debug(`Successfully emailed new user ${user.id} instructions to continue`);
req.flash('success', `An email has been sent to <u>${user.email}</u>. Check your inbox and follow the link to complete your registration. (Your registration link will expire in one hour). `); // User exists but hasn't created a password yet
res.redirect('/login'); } else if (user) {
}) debug(`User ${user.id} has email ${req.body.email} but doesn't have a password`)
.catch((err)=>{ // Send another token (or the same one if it hasn't expired)
debug(`Failed to email new user ${user.id} instructions to continue!`); sendToken(user)
mw.throwErr(err,req);
res.redirect('/login#signup'); // Create user
}); } else {
debug(`User with email ${req.body.email} doesn't exist; creating one`)
}
}); user = new User()
user.created = Date.now()
} user.email = req.body.email
user.slug = slugify(user.email.substring(0, user.email.indexOf('@')))
// Validate email
req.checkBody('email', 'Please enter a valid email address.').isEmail(); // Generate unique slug
const slug = new Promise((resolve, reject) => {
// Check if somebody already has that email debug(`Creating new slug for user...`);
debug(`Searching for user with email ${req.body.email}...`);
User.findOne({'email':req.body.email}) (function checkSlug (s, cb) {
.then( (user)=>{ debug(`Checking to see if slug ${s} is taken...`)
User.findOne({slug: s})
// User already exists .then((existingUser) => {
if (user && user.auth.password) { // Slug in use: generate a random one and retry
debug(`User ${user.id} has email ${req.body.email} and has a password`); if (existingUser) {
req.flash('warning',`A user with that email already exists! If you forgot your password, you can <a href="/login/forgot?email=${req.body.email}">reset it here</a>.`); debug(`Slug ${s} is taken; generating another...`)
res.redirect('/login#login'); crypto.randomBytes(6, (err, buf) => {
next(); if (err) {
} debug('Failed to create random bytes for slug!')
mw.throwErr(err, req)
// User exists but hasn't created a password yet reject()
else if (user) { }
debug(`User ${user.id} has email ${req.body.email} but doesn't have a password`); if (buf) {
// Send another token (or the same one if it hasn't expired) checkSlug(buf.toString('hex'), cb)
sendToken(user); }
} })
// Create user // Unique slug: proceed
else { } else {
debug(`User with email ${req.body.email} doesn't exist; creating one`); debug(`Slug ${s} is unique`)
cb(s)
user = new User(); }
user.created = Date.now(); })
user.email = req.body.email; .catch((err) => {
user.slug = slugify(user.email.substring(0, user.email.indexOf('@'))); debug('Failed to create slug!')
mw.throwErr(err, req)
// Generate unique slug reject()
const slug = new Promise((resolve,reject) => { })
debug(`Creating new slug for user...`); })(user.slug, (newSlug) => {
debug(`Successfully created slug: ${newSlug}`)
(function checkSlug(s,cb){ user.slug = newSlug
resolve()
debug(`Checking to see if slug ${s} is taken...`); })
User.findOne({slug:s}) })
.then((existingUser)=>{
// Generate sk32
// Slug in use: generate a random one and retry const sk32 = new Promise((resolve, reject) => {
if (existingUser){ debug('Creating sk32 for user...')
debug(`Slug ${s} is taken; generating another...`); crypto.randomBytes(32, (err, buf) => {
crypto.randomBytes(6, (err,buf)=>{ if (err) {
if (err) { debug('Failed to create sk32!')
debug('Failed to create random bytes for slug!'); mw.throwErr(err, req)
mw.throwErr(err,req); reject()
reject(); }
} if (buf) {
if (buf) { user.sk32 = buf.toString('hex')
checkSlug(buf.toString('hex'),cb); debug(`Successfully created sk32: ${user.sk32}`)
} resolve()
}); }
} })
})
// Unique slug: proceed
else { // Save user and send the token by email
debug(`Slug ${s} is unique`); Promise.all([slug, sk32])
cb(s); .then(() => { sendToken(user) })
} .catch((err) => {
debug('Failed to save user after creating slug and sk32!')
}) mw.throwErr(err, req)
.catch((err)=>{ res.redirect('/login#signup')
debug('Failed to create slug!'); })
mw.throwErr(err,req); }
reject(); })
}); .catch((err) => {
debug(`Failed to check if somebody already has the email ${req.body.email}`)
})(user.slug, (newSlug)=>{ mw.throwErr(err, req)
debug(`Successfully created slug: ${newSlug}`); res.redirect('/signup')
user.slug = newSlug; })
resolve(); })
});
}); // Forgot password
app.route('/login/forgot')
// Generate sk32
const sk32 = new Promise((resolve,reject) => { // Check if user is already logged in
debug('Creating sk32 for user...'); .all((req, res, next) => {
crypto.randomBytes(32, (err,buf)=>{ if (req.isAuthenticated()) { loginCallback(req, res) } else { next() }
if (err) { })
debug('Failed to create sk32!');
mw.throwErr(err,req); // Show forgot password page
reject(); .get((req, res, next) => {
} res.render('forgot', {email: req.query.email})
if (buf) { })
user.sk32 = buf.toString('hex');
debug(`Successfully created sk32: ${user.sk32}`); // Submitted forgot password form
resolve(); .post((req, res, next) => {
} // Validate email
}); req.checkBody('email', 'Please enter a valid email address.').isEmail()
});
// Check if somebody has that email
// Save user and send the token by email User.findOne({'email': req.body.email})
Promise.all([slug, sk32]) .then((user) => {
.then( ()=>{ sendToken(user); }) // No user with that email
.catch( (err)=>{ if (!user) {
debug('Failed to save user after creating slug and sk32!'); // Don't let on that no such user exists, to prevent dictionary attacks
mw.throwErr(err,req); req.flash('success', `If an account exists with the email <u>${req.body.email}</u>, an email has been sent there with a password reset link. `)
res.redirect('/login#signup'); res.redirect('/login')
});
// User with that email does exist
} } else {
// Create reset token
}) user.createPassToken((err, token) => {
.catch( (err)=>{ if (err) { next(err) }
debug(`Failed to check if somebody already has the email ${req.body.email}`);
mw.throwErr(err,req); // Email reset link
res.redirect('/signup'); mail.send({
}); from: mail.noReply,
to: mail.to(user),
}); subject: 'Reset your Tracman password',
text: mail.text(`Hi, \n\nDid you request to reset your Tracman password? If so, follow this link to do so:\n${env.url}/settings/password/${token}\n\nIf you didn't initiate this request, just ignore this email. `),
// Forgot password html: mail.html(`<p>Hi, </p><p>Did you request to reset your Tracman password? If so, follow this link to do so:<br><a href="${env.url}/settings/password/${token}">${env.url}/settings/password/${token}</a></p><p>If you didn't initiate this request, just ignore this email. </p>`)
app.route('/login/forgot') }).then(() => {
req.flash('success', `If an account exists with the email <u>${req.body.email}</u>, an email has been sent there with a password reset link. `)
// Check if user is already logged in res.redirect('/login')
.all( (req,res,next)=>{ }).catch((err) => {
if (req.isAuthenticated()){ loginCallback(req,res); } debug(`Failed to send reset link to ${user.email}`)
else { next(); } mw.throwErr(err, req)
} ) res.redirect('/login')
})
// Show forgot password page })
.get( (req,res,next)=>{ }
res.render('forgot', {email:req.query.email}); }).catch((err) => {
} ) debug(`Failed to check for if somebody has that email (in reset request)!`)
mw.throwErr(err, req)
// Submitted forgot password form res.redirect('/login/forgot')
.post( (req,res,next)=>{ })
})
// Validate email
req.checkBody('email', 'Please enter a valid email address.').isEmail(); // Android
app.post('/login/app', passport.authenticate('local'), appLoginCallback)
// Check if somebody has that email
User.findOne({'email':req.body.email}) // Token-based (android social)
.then( (user)=>{ app.get(['/login/app/google', '/auth/google/idtoken'], passport.authenticate('google-token'), appLoginCallback)
// app.get('/login/app/facebook', passport.authenticate('facebook-token'), appLoginCallback);
// No user with that email // app.get('/login/app/twitter', passport.authenticate('twitter-token'), appLoginCallback);
if (!user) {
// Don't let on that no such user exists, to prevent dictionary attacks // Social
req.flash('success', `If an account exists with the email <u>${req.body.email}</u>, an email has been sent there with a password reset link. `); app.get('/login/:service', (req, res, next) => {
res.redirect('/login'); let service = req.params.service
} let sendParams = (service === 'google') ? {scope: ['https://www.googleapis.com/auth/userinfo.profile']} : null
// User with that email does exist // Social login
else { if (!req.user) {
debug(`Attempting to login with ${service} with params: ${JSON.stringify(sendParams)}...`)
// Create reset token passport.authenticate(service, sendParams)(req, res, next)
user.createPassToken( (err,token)=>{
if (err){ next(err); } // Connect social account
} else if (!req.user.auth[service]) {
// Email reset link debug(`Attempting to connect ${service} account...`)
mail.send({ passport.authorize(service, sendParams)(req, res, next)
from: mail.noReply,
to: mail.to(user), // Disconnect social account
subject: 'Reset your Tracman password', } else {
text: mail.text(`Hi, \n\nDid you request to reset your Tracman password? If so, follow this link to do so:\n${env.url}/settings/password/${token}\n\nIf you didn't initiate this request, just ignore this email. `), debug(`Attempting to disconnect ${service} account...`)
html: mail.html(`<p>Hi, </p><p>Did you request to reset your Tracman password? If so, follow this link to do so:<br><a href="${env.url}/settings/password/${token}">${env.url}/settings/password/${token}</a></p><p>If you didn't initiate this request, just ignore this email. </p>`)
}).then(()=>{ // Make sure the user has a password before they disconnect their google login account
req.flash('success', `If an account exists with the email <u>${req.body.email}</u>, an email has been sent there with a password reset link. `); // This is because login used to only be through google, and some people might not have
res.redirect('/login'); // set passwords yet...
}).catch((err)=>{ if (!req.user.auth.password && service === 'google') {
debug(`Failed to send reset link to ${user.email}`); req.flash('warning', `Hey, you need to <a href="/settings/password">set a password</a> before you can disconnect your google account. Otherwise, you won't be able to log in! `)
mw.throwErr(err,req); res.redirect('/settings')
res.redirect('/login'); } else {
}); req.user.auth[service] = undefined
req.user.save()
}); .then(() => {
req.flash('success', `${mw.capitalize(service)} account disconnected. `)
} res.redirect('/settings')
})
}).catch( (err)=>{ .catch((err) => {
debug(`Failed to check for if somebody has that email (in reset request)!`); debug(`Failed to save user after disconnecting ${service} account!`)
mw.throwErr(err,req); mw.throwErr(err, req)
res.redirect('/login/forgot'); res.redirect('/settings')
}); })
}
} ); }
})
// Android app.get('/login/google/cb', passport.authenticate('google', loginOutcome), loginCallback)
app.post('/login/app', passport.authenticate('local'), appLoginCallback); app.get('/login/facebook/cb', passport.authenticate('facebook', loginOutcome), loginCallback)
app.get('/login/twitter/cb', passport.authenticate('twitter', loginOutcome), loginCallback)
// Token-based (android social) }
app.get(['/login/app/google','/auth/google/idtoken'], passport.authenticate('google-token'), appLoginCallback);
// app.get('/login/app/facebook', passport.authenticate('facebook-token'), appLoginCallback);
// app.get('/login/app/twitter', passport.authenticate('twitter-token'), appLoginCallback);
// Social
app.get('/login/:service', (req,res,next)=>{
let service = req.params.service,
sendParams = (service==='google')?{scope:['https://www.googleapis.com/auth/userinfo.profile']}:null;
// Social login
if (!req.user) {
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]) {
debug(`Attempting to connect ${service} account...`);
passport.authorize(service, sendParams)(req,res,next);
}
// Disconnect social account
else {
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
// set passwords yet...
if (!req.user.auth.password && service==='google') {
req.flash('warning',`Hey, you need to <a href="/settings/password">set a password</a> before you can disconnect your google account. Otherwise, you won't be able to log in! `);
res.redirect('/settings');
}
else {
req.user.auth[service] = undefined;
req.user.save()
.then(()=>{
req.flash('success', `${mw.capitalize(service)} account disconnected. `);
res.redirect('/settings');
})
.catch((err)=>{
debug(`Failed to save user after disconnecting ${service} account!`);
mw.throwErr(err,req);
res.redirect('/settings');
});
}
}
});
app.get('/login/google/cb', passport.authenticate('google',loginOutcome), loginCallback );
app.get('/login/facebook/cb', passport.authenticate('facebook',loginOutcome), loginCallback );
app.get('/login/twitter/cb', passport.authenticate('twitter',loginOutcome), loginCallback );
};

View File

@ -1,92 +1,78 @@
'use strict'; 'use strict'
const env = require('../env/env.js'), const env = require('../env/env.js')
request = require('request'), const request = require('request')
mw = require('../middleware.js'), const mw = require('../middleware.js')
mail = require('../mail.js'), const mail = require('../mail.js')
router = require('express').Router(); const router = require('express').Router()
module.exports = router module.exports = router
// Display contact form // Display contact form
.get('/', (req,res)=>{ .get('/', (req, res) => {
res.render('contact', {active:'contact', res.render('contact', {active: 'contact',
sitekey: env.recaptchaSitekey sitekey: env.recaptchaSitekey
}); })
}) })
.post('/', (req,res,next)=>{ .post('/', (req, res, next) => {
// Check email
// Check email if (req.body.email === '') {
if (req.body.email==='') { req.flash('warning', `You need to enter an email address. `)
req.flash('warning', `You need to enter an email address. `); res.redirect('/contact')
res.redirect('/contact'); } else if (!mw.validateEmail(req.body.email)) {
} req.flash('warning', `<u>${req.body.email}</u> is not a valid email address. `)
else if (!mw.validateEmail(req.body.email)) { res.redirect('/contact')
req.flash('warning', `<u>${req.body.email}</u> is not a valid email address. `);
res.redirect('/contact'); // Check for message
} } else if (req.body.message === '') {
req.flash('warning', `You need to enter a message. `)
// Check for message res.redirect('/contact')
else if (req.body.message==='') {
req.flash('warning', `You need to enter a message. `); // Passed validations
res.redirect('/contact'); } else {
} // Confirm captcha
request.post('https://www.google.com/recaptcha/api/siteverify', {form: {
secret: env.recaptchaSecret,
// Passed validations response: req.body['g-recaptcha-response'],
else { remoteip: req.ip
}}, (err, response, body) => {
// Confirm captcha // Check for errors
request.post( 'https://www.google.com/recaptcha/api/siteverify', {form:{ if (err) {
secret: env.recaptchaSecret, mw.throwErr(err, req)
response: req.body['g-recaptcha-response'], res.redirect('/contact')
remoteip: req.ip }
}}, (err, response, body)=>{ if (response.statusCode !== 200) {
let err = new Error('Bad response from reCaptcha service')
// Check for errors mw.throwErr(err, req)
if (err){ res.redirect('/contact')
mw.throwErr(err,req);
res.redirect('/contact'); // No errors
} } else {
if (response.statusCode!==200) { // Captcha failed
let err = new Error('Bad response from reCaptcha service'); if (!JSON.parse(body).success) {
mw.throwErr(err,req); let err = new Error('Failed reCaptcha')
res.redirect('/contact'); mw.throwErr(err, req)
} res.redirect('/contact')
// No errors // Captcha succeeded
else { } else {
mail.send({
// Captcha failed from: `${req.body.name} <${req.body.email}>`,
if (!JSON.parse(body).success){ to: `Tracman Contact <contact@tracman.org>`,
let err = new Error('Failed reCaptcha'); subject: req.body.subject || 'A message',
mw.throwErr(err,req); text: req.body.message
res.redirect('/contact'); })
} .then(() => {
req.flash('success', `Your message has been sent. `)
// Captcha succeeded res.redirect(req.session.next || '/')
else { })
mail.send({ .catch((err) => {
from: `${req.body.name} <${req.body.email}>`, mw.throwErr(err, req)
to: `Tracman Contact <contact@tracman.org>`, res.redirect('/contact')
subject: req.body.subject||'A message', })
text: req.body.message }
}) }
.then(()=>{ })
req.flash('success', `Your message has been sent. `); }
res.redirect(req.session.next || '/'); })
})
.catch((err)=>{
mw.throwErr(err,req);
res.redirect('/contact');
});
}
}
});
}
});

View File

@ -1,106 +1,96 @@
'use strict'; 'use strict'
const router = require('express').Router(), const router = require('express').Router()
slug = require('slug'), const slug = require('slug')
xss = require('xss'), const xss = require('xss')
User = require('../models.js').user; const User = require('../models.js').user
module.exports = router module.exports = router
// Index
.get('/', (req,res,next)=>{
res.render('index', {active:'home'});
})
// Demo redirect
.get('/demo', (req,res,next)=>{
res.redirect('/map/demo');
})
// Help
.get('/help', (req,res)=>{
res.render('help', {active:'help'});
})
// Terms of Service and Privacy Policy
.get('/terms', (req,res)=>{
res.render('terms', {active:'terms'});
})
.get('/privacy', (req,res)=>{
res.render('privacy', {active:'privacy'});
})
// robots.txt
.get('/robots.txt', (req,res)=>{
res.type('text/plain');
res.send("User-agent: *\n"+
"Disallow: /map/*\n"
);
})
// favicon.ico
//TODO: Just serve it
.get('/favicon.ico', (req,res)=>{
res.redirect('/static/img/icon/by/16-32-48.ico');
})
// Endpoint to validate forms
.get('/validate', (req,res,next)=>{
// Validate unique slug
if (req.query.slug) {
User.findOne({ slug: slug(req.query.slug) })
.then( (existingUser)=>{
if (existingUser && existingUser.id!==req.user.id) {
res.sendStatus(400);
}
else { res.sendStatus(200); }
})
.catch( (err)=>{
console.error(err);
res.sendStatus(500);
});
}
// Validate unique email
else if (req.query.email) {
User.findOne({ email: req.query.email })
.then( (existingUser)=>{
if (existingUser && existingUser.id!==req.user.id) {
res.sendStatus(400);
}
else { res.sendStatus(200); }
})
.catch( (err)=>{
console.error(err);
res.sendStatus(500);
});
}
// Create slug
else if (req.query.slugify) {
res.send(slug(xss(req.query.slugify)));
}
// Sanitize for XSS
else if (req.query.xss) {
res.send(xss(req.query.xss));
}
// 404
else { next(); }
})
// Link to androidapp in play store
.get('/android', (req,res)=>{
res.redirect('https://play.google.com/store/apps/details?id=us.keithirwin.tracman');
})
// Link to iphone app in the apple store
// ... maybe someday
.get('/ios', (req,res)=>{
res.redirect('/help#why-is-there-no-ios-app');
})
; // Index
.get('/', (req, res, next) => {
res.render('index', {active: 'home'})
})
// Demo redirect
.get('/demo', (req, res, next) => {
res.redirect('/map/demo')
})
// Help
.get('/help', (req, res) => {
res.render('help', {active: 'help'})
})
// Terms of Service and Privacy Policy
.get('/terms', (req, res) => {
res.render('terms', {active: 'terms'})
})
.get('/privacy', (req, res) => {
res.render('privacy', {active: 'privacy'})
})
// robots.txt
.get('/robots.txt', (req, res) => {
res.type('text/plain')
res.send('User-agent: *\n' +
'Disallow: /map/*\n'
)
})
// favicon.ico
// TODO: Just serve it
.get('/favicon.ico', (req, res) => {
res.redirect('/static/img/icon/by/16-32-48.ico')
})
// Endpoint to validate forms
.get('/validate', (req, res, next) => {
// Validate unique slug
if (req.query.slug) {
User.findOne({ slug: slug(req.query.slug) })
.then((existingUser) => {
if (existingUser && existingUser.id !== req.user.id) {
res.sendStatus(400)
} else { res.sendStatus(200) }
})
.catch((err) => {
console.error(err)
res.sendStatus(500)
})
// Validate unique email
} else if (req.query.email) {
User.findOne({ email: req.query.email })
.then((existingUser) => {
if (existingUser && existingUser.id !== req.user.id) {
res.sendStatus(400)
} else { res.sendStatus(200) }
})
.catch((err) => {
console.error(err)
res.sendStatus(500)
})
// Create slug
} else if (req.query.slugify) {
res.send(slug(xss(req.query.slugify)))
// Sanitize for XSS
} else if (req.query.xss) {
res.send(xss(req.query.xss))
// 404
} else { next() }
})
// Link to androidapp in play store
.get('/android', (req, res) => {
res.redirect('https://play.google.com/store/apps/details?id=us.keithirwin.tracman')
})
// Link to iphone app in the apple store
// ... maybe someday
.get('/ios', (req, res) => {
res.redirect('/help#why-is-there-no-ios-app')
})

View File

@ -1,79 +1,76 @@
'use strict'; 'use strict'
const router = require('express').Router(), const router = require('express').Router()
mw = require('../middleware.js'), const mw = require('../middleware.js')
env = require('../env/env.js'), const env = require('../env/env.js')
User = require('../models.js').user; const User = require('../models.js').user
// Redirect to real slug // Redirect to real slug
router.get('/', mw.ensureAuth, (req,res)=>{ router.get('/', mw.ensureAuth, (req, res) => {
if (req.query.new){ if (req.query.new) {
res.redirect(`/map/${req.user.slug}?new=1`); res.redirect(`/map/${req.user.slug}?new=1`)
} } else {
else { res.redirect(`/map/${req.user.slug}`)
res.redirect(`/map/${req.user.slug}`); }
} })
});
// Demo // Demo
router.get('/demo', (req,res,next)=>{ router.get('/demo', (req, res, next) => {
res.render('map', { res.render('map', {
active: 'demo', active: 'demo',
mapuser: { mapuser: {
_id: 'demo', _id: 'demo',
name: 'Demo', name: 'Demo',
last: { last: {
lat: 40.1165853, lat: 40.1165853,
lon: -87.5417312, lon: -87.5417312,
dir: 249.0, dir: 249.0,
spd: 19.015747 spd: 19.015747
}, },
settings: { settings: {
marker: 'marker-red', marker: 'marker-red',
showAlt: false, showAlt: false,
showTemp: false, showTemp: false,
showSpeed: false, showSpeed: false,
showScale: false, showScale: false,
showStreetview: true, showStreetview: true,
defaultZoom: 13, defaultZoom: 13,
defaultMap: 'road', defaultMap: 'road',
units: 'standard' units: 'standard'
}, }
}, },
mapApi: env.googleMapsAPI, mapApi: env.googleMapsAPI,
user: req.user, user: req.user,
noFooter: '1', noFooter: '1',
noHeader: (req.query.noheader)?req.query.noheader.match(/\d/)[0]:0, noHeader: (req.query.noheader) ? req.query.noheader.match(/\d/)[0] : 0,
disp: (req.query.disp)?req.query.disp.match(/\d/)[0]:2, // 0=map, 1=streetview, 2=both disp: (req.query.disp) ? req.query.disp.match(/\d/)[0] : 2, // 0=map, 1=streetview, 2=both
newuserurl: (req.query.new)? env.url+'/map/'+req.params.slug : '' newuserurl: (req.query.new) ? env.url + '/map/' + req.params.slug : ''
}); })
}); })
// Show map // Show map
router.get('/:slug?', (req,res,next)=>{ router.get('/:slug?', (req, res, next) => {
User.findOne({slug: req.params.slug})
User.findOne({slug:req.params.slug}) .then((mapuser) => {
.then( (mapuser)=>{ if (!mapuser) {
if (!mapuser){ next(); } //404 next() // 404
else { } else {
var active = ''; // For header nav var active = '' // For header nav
if (req.user && req.user.id===mapuser.id){ active='map'; } if (req.user && req.user.id === mapuser.id) { active = 'map' }
res.render('map', { res.render('map', {
active: active, active: active,
mapuser: mapuser, mapuser: mapuser,
mapApi: env.googleMapsAPI, mapApi: env.googleMapsAPI,
user: req.user, user: req.user,
noFooter: '1', noFooter: '1',
noHeader: (req.query.noheader)?req.query.noheader.match(/\d/)[0]:0, noHeader: (req.query.noheader) ? req.query.noheader.match(/\d/)[0] : 0,
disp: (req.query.disp)?req.query.disp.match(/\d/)[0]:2, // 0=map, 1=streetview, 2=both disp: (req.query.disp) ? req.query.disp.match(/\d/)[0] : 2, // 0=map, 1=streetview, 2=both
newuserurl: (req.query.new)? env.url+'/map/'+req.params.slug : '' newuserurl: (req.query.new) ? env.url + '/map/' + req.params.slug : ''
}); })
} }
}).catch( (err)=>{ }).catch((err) => {
mw.throwErr(err,req); mw.throwErr(err, req)
}); })
})
});
module.exports = router; module.exports = router

View File

@ -1,359 +1,315 @@
'use strict'; 'use strict'
const slug = require('slug'),
xss = require('xss'),
zxcvbn = require('zxcvbn'),
moment = require('moment'),
mw = require('../middleware.js'),
User = require('../models.js').user,
mail = require('../mail.js'),
env = require('../env/env.js'),
debug = require('debug')('tracman-settings'),
router = require('express').Router();
const slug = require('slug')
const xss = require('xss')
const zxcvbn = require('zxcvbn')
const moment = require('moment')
const mw = require('../middleware.js')
const User = require('../models.js').user
const mail = require('../mail.js')
const env = require('../env/env.js')
const debug = require('debug')('tracman-settings')
const router = require('express').Router()
// Settings form // Settings form
router.route('/') router.route('/')
.all( mw.ensureAuth, (req,res,next)=>{ .all(mw.ensureAuth, (req, res, next) => {
next(); next()
} ) })
// Get settings form // Get settings form
.get( (req,res)=>{ .get((req, res) => {
res.render('settings', {active:'settings'}); res.render('settings', {active: 'settings'})
} ) })
// Set new settings // Set new settings
.post( (req,res,next)=>{ .post((req, res, next) => {
// Validate email
// Validate email const checkEmail = new Promise((resolve, reject) => {
const checkEmail = new Promise( (resolve,reject)=>{ // Check validity
if (!mw.validateEmail(req.body.email)) {
// Check validity req.flash('warning', `<u>${req.body.email}</u> is not a valid email address. `)
if (!mw.validateEmail(req.body.email)) { resolve()
req.flash('warning', `<u>${req.body.email}</u> is not a valid email address. `);
resolve(); // Check if unchanged
} } else if (req.user.email === req.body.email) {
resolve()
// Check if unchanged
else if (req.user.email===req.body.email) { // Check uniqueness
resolve(); } else {
} User.findOne({ email: req.body.email })
.then((existingUser) => {
// Check uniqueness // Not unique!
else { if (existingUser && existingUser.id !== req.user.id) {
User.findOne({ email: req.body.email }) debug('Email not unique!')
.then( (existingUser)=>{ req.flash('warning', `That email, <u>${req.body.email}</u>, is already in use by another user! `)
resolve()
// Not unique!
if (existingUser && existingUser.id!==req.user.id) { // It's unique
debug("Email not unique!"); } else {
req.flash('warning', `That email, <u>${req.body.email}</u>, is already in use by another user! `); debug('Email is unique')
resolve(); req.user.newEmail = req.body.email
}
// Create token
// It's unique debug(`Creating email token...`)
else { req.user.createEmailToken((err, token) => {
debug("Email is unique"); if (err) { reject(err) }
req.user.newEmail = req.body.email;
// Send token to user by email
// Create token debug(`Mailing new email token to ${req.body.email}...`)
debug(`Creating email token...`); mail.send({
req.user.createEmailToken((err,token)=>{ to: `"${req.user.name}" <${req.body.email}>`,
if (err){ reject(err); } from: mail.noReply,
subject: 'Confirm your new email address for Tracman',
// Send token to user by email text: mail.text(`A request has been made to change your Tracman email address. If you did not initiate this request, please disregard it. \n\nTo confirm your email, follow this link:\n${env.url}/settings/email/${token}. `),
debug(`Mailing new email token to ${req.body.email}...`); html: mail.html(`<p>A request has been made to change your Tracman email address. If you did not initiate this request, please disregard it. </p><p>To confirm your email, follow this link:<br><a href="${env.url}/settings/email/${token}">${env.url}/settings/email/${token}</a>. </p>`)
mail.send({ })
to: `"${req.user.name}" <${req.body.email}>`, .then(() => {
from: mail.noReply, req.flash('warning', `An email has been sent to <u>${req.body.email}</u>. Check your inbox to confirm your new email address. `)
subject: 'Confirm your new email address for Tracman', resolve()
text: mail.text(`A request has been made to change your Tracman email address. If you did not initiate this request, please disregard it. \n\nTo confirm your email, follow this link:\n${env.url}/settings/email/${token}. `), })
html: mail.html(`<p>A request has been made to change your Tracman email address. If you did not initiate this request, please disregard it. </p><p>To confirm your email, follow this link:<br><a href="${env.url}/settings/email/${token}">${env.url}/settings/email/${token}</a>. </p>`) .catch(reject)
}) })
.then( ()=>{ }
req.flash('warning',`An email has been sent to <u>${req.body.email}</u>. Check your inbox to confirm your new email address. `); })
resolve(); .catch(reject)
}) }
.catch(reject); })
}); // Validate slug
const checkSlug = new Promise((resolve, reject) => {
} // Check existence
if (req.body.slug === '') {
}) req.flash('warning', `You must supply a slug. `)
.catch(reject); resolve()
}
// Check if unchanged
}); } else if (req.user.slug === slug(xss(req.body.slug))) {
resolve()
// Validate slug
const checkSlug = new Promise( (resolve,reject)=>{ // Check uniqueness
} else {
// Check existence User.findOne({ slug: req.body.slug })
if (req.body.slug==='') { .then((existingUser) => {
req.flash('warning', `You must supply a slug. `); // Not unique!
resolve(); if (existingUser && existingUser.id !== req.user.id) {
} req.flash('warning', `That slug, <u>${req.body.slug}</u>, is already in use by another user! `)
// Check if unchanged // It's unique
else if (req.user.slug===slug(xss(req.body.slug))) { } else {
resolve(); req.user.slug = slug(xss(req.body.slug))
} }
})
// Check uniqueness .then(resolve)
else { .catch(reject)
}
User.findOne({ slug: req.body.slug }) })
.then( (existingUser)=>{
// Set settings when done
// Not unique! Promise.all([checkEmail, checkSlug])
if (existingUser && existingUser.id!==req.user.id) { .then(() => {
req.flash('warning', `That slug, <u>${req.body.slug}</u>, is already in use by another user! `); debug('Setting settings... ')
}
// Set values
// It's unique req.user.name = xss(req.body.name)
else { req.user.settings = {
req.user.slug = slug(xss(req.body.slug)); units: req.body.units,
} defaultMap: req.body.map,
defaultZoom: req.body.zoom,
}) showScale: !!(req.body.showScale),
.then(resolve) showSpeed: !!(req.body.showSpeed),
.catch(reject); showAlt: !!(req.body.showAlt),
showStreetview: !!(req.body.showStreet),
} marker: req.body.marker
}
});
// Save user and send response
// Set settings when done debug(`Saving new settings for user ${req.user.name}...`)
Promise.all([checkEmail, checkSlug]) req.user.save()
.then( ()=>{ .then(() => {
debug('Setting settings... '); debug(`DONE! Redirecting user...`)
req.flash('success', 'Settings updated. ')
// Set values res.redirect('/settings')
req.user.name = xss(req.body.name); })
req.user.settings = { .catch((err) => {
units: req.body.units, mw.throwErr(err, req)
defaultMap: req.body.map, res.redirect('/settings')
defaultZoom: req.body.zoom, })
showScale: (req.body.showScale)?true:false, })
showSpeed: (req.body.showSpeed)?true:false, .catch((err) => {
showAlt: (req.body.showAlt)?true:false, mw.throwErr(err, req)
showStreetview: (req.body.showStreet)?true:false, res.redirect('/settings')
marker: req.body.marker })
}; })
// Save user and send response
debug(`Saving new settings for user ${req.user.name}...`);
req.user.save()
.then( ()=>{
debug(`DONE! Redirecting user...`);
req.flash('success', 'Settings updated. ');
res.redirect('/settings');
})
.catch( (err)=>{
mw.throwErr(err,req);
res.redirect('/settings');
});
})
.catch( (err)=>{
mw.throwErr(err,req);
res.redirect('/settings');
});
} );
// Delete account // Delete account
router.get('/delete', (req,res)=>{ router.get('/delete', (req, res) => {
User.findByIdAndRemove(req.user) User.findByIdAndRemove(req.user)
.then( ()=>{ .then(() => {
req.flash('success', 'Your account has been deleted. '); req.flash('success', 'Your account has been deleted. ')
res.redirect('/'); res.redirect('/')
}) })
.catch( (err)=>{ .catch((err) => {
mw.throwErr(err,req); mw.throwErr(err, req)
res.redirect('/settings'); res.redirect('/settings')
}); })
}); })
// Confirm email address // Confirm email address
router.get('/email/:token', mw.ensureAuth, (req,res,next)=>{ router.get('/email/:token', mw.ensureAuth, (req, res, next) => {
// Check token
// Check token if (req.user.emailToken === req.params.token) {
if ( req.user.emailToken===req.params.token) { // Set new email
req.user.email = req.user.newEmail
// Set new email req.user.save()
req.user.email = req.user.newEmail;
req.user.save() // Delete token and newEmail
.then(() => {
// Delete token and newEmail req.user.emailToken = undefined
.then( ()=>{ req.user.newEmail = undefined
req.user.emailToken = undefined; req.user.save()
req.user.newEmail = undefined; })
req.user.save();
}) // Report success
.then(() => {
// Report success req.flash('success', `Your email has been set to <u>${req.user.email}</u>. `)
.then( ()=>{ res.redirect('/settings')
req.flash('success',`Your email has been set to <u>${req.user.email}</u>. `); })
res.redirect('/settings');
}) .catch((err) => {
mw.throwErr(err, req)
.catch( (err)=>{ res.redirect(req.session.next || '/settings')
mw.throwErr(err,req); })
res.redirect(req.session.next||'/settings');
}); // Invalid token
} else {
} req.flash('danger', 'Email confirmation token is invalid. ')
res.redirect('/settings')
// Invalid token }
else { })
req.flash('danger', 'Email confirmation token is invalid. ');
res.redirect('/settings');
}
} );
// Set password // Set password
router.route('/password') router.route('/password')
.all( mw.ensureAuth, (req,res,next)=>{ .all(mw.ensureAuth, (req, res, next) => {
next(); next()
} ) })
// Email user a token, proceed at /password/:token // Email user a token, proceed at /password/:token
.get( (req,res,next)=>{ .get((req, res, next) => {
// Create token for password change
req.user.createPassToken((err, token, expires) => {
if (err) {
mw.throwErr(err, req)
res.redirect((req.user) ? '/settings' : '/login')
} else {
// Figure out expiration time
let expirationTimeString = (req.query.tz)
? moment(expires).utcOffset(req.query.tz).toDate().toLocaleTimeString(req.acceptsLanguages[0])
: moment(expires).toDate().toLocaleTimeString(req.acceptsLanguages[0]) + ' UTC'
// Create token for password change // Confirm password change request by email.
req.user.createPassToken( (err,token,expires)=>{ mail.send({
if (err){ to: mail.to(req.user),
mw.throwErr(err,req); from: mail.noReply,
res.redirect((req.user)?'/settings':'/login'); subject: 'Request to change your Tracman password',
} text: mail.text(`A request has been made to change your tracman password. If you did not initiate this request, please contact support at keith@tracman.org. \n\nTo change your password, follow this link:\n${env.url}/settings/password/${token}. \n\nThis request will expire at ${expirationTimeString}. `),
else { html: mail.html(`<p>A request has been made to change your tracman password. If you did not initiate this request, please contact support at <a href="mailto:keith@tracman.org">keith@tracman.org</a>. </p><p>To change your password, follow this link:<br><a href="${env.url}/settings/password/${token}">${env.url}/settings/password/${token}</a>. </p><p>This request will expire at ${expirationTimeString}. </p>`)
})
// Figure out expiration time .then(() => {
let expirationTimeString = (req.query.tz)? // Alert user to check email.
moment(expires).utcOffset(req.query.tz).toDate().toLocaleTimeString(req.acceptsLanguages[0]): req.flash('success', `An link has been sent to <u>${req.user.email}</u>. Click on the link to complete your password change. This link will expire in one hour (${expirationTimeString}). `)
moment(expires).toDate().toLocaleTimeString(req.acceptsLanguages[0])+" UTC"; res.redirect((req.user) ? '/settings' : '/login')
})
// Confirm password change request by email. .catch((err) => {
mail.send({ mw.throwErr(err, req)
to: mail.to(req.user), res.redirect((req.user) ? '/settings' : '/login')
from: mail.noReply, })
subject: 'Request to change your Tracman password', }
text: mail.text(`A request has been made to change your tracman password. If you did not initiate this request, please contact support at keith@tracman.org. \n\nTo change your password, follow this link:\n${env.url}/settings/password/${token}. \n\nThis request will expire at ${expirationTimeString}. `), })
html: mail.html(`<p>A request has been made to change your tracman password. If you did not initiate this request, please contact support at <a href="mailto:keith@tracman.org">keith@tracman.org</a>. </p><p>To change your password, follow this link:<br><a href="${env.url}/settings/password/${token}">${env.url}/settings/password/${token}</a>. </p><p>This request will expire at ${expirationTimeString}. </p>`) })
})
.then( ()=>{
// Alert user to check email.
req.flash('success',`An link has been sent to <u>${req.user.email}</u>. Click on the link to complete your password change. This link will expire in one hour (${expirationTimeString}). `);
res.redirect((req.user)?'/settings':'/login');
})
.catch( (err)=>{
mw.throwErr(err,req);
res.redirect((req.user)?'/settings':'/login');
});
}
});
} );
router.route('/password/:token') router.route('/password/:token')
// Check token // Check token
.all( (req,res,next)=>{ .all((req, res, next) => {
debug('/settings/password/:token .all() called'); debug('/settings/password/:token .all() called')
User User
.findOne({'auth.passToken': req.params.token}) .findOne({'auth.passToken': req.params.token})
.where('auth.passTokenExpires').gt(Date.now()) .where('auth.passTokenExpires').gt(Date.now())
.then((user) => { .then((user) => {
if (!user) { if (!user) {
debug('Bad token'); debug('Bad token')
req.flash('danger', 'Password reset token is invalid or has expired. '); req.flash('danger', 'Password reset token is invalid or has expired. ')
res.redirect( (req.isAuthenticated)?'/settings':'/login' ); res.redirect((req.isAuthenticated) ? '/settings' : '/login')
} } else {
else { debug('setting passwordUser')
debug('setting passwordUser'); res.locals.passwordUser = user
res.locals.passwordUser = user; next()
next(); }
} })
}) .catch((err) => {
.catch((err)=>{ mw.throwErr(err, req)
mw.throwErr(err,req); res.redirect('/password')
res.redirect('/password'); })
}); })
} )
// Show password change form // Show password change form
.get( (req,res)=>{ .get((req, res) => {
debug('/settings/password/:token .get() called'); debug('/settings/password/:token .get() called')
res.render('password'); res.render('password')
} ) })
// Set new password
.post( (req,res,next)=>{
// Validate password
let zxcvbnResult = zxcvbn(req.body.password);
if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second < 864000) { // Less than ten days
mw.throwErr(new Error(`That password could be cracked in ${zxcvbnResult.crack_times_display.online_no_throttling_10_per_second}! Come up with a more complex password that would take at least 10 days to crack. `));
res.redirect(`/settings/password/${req.params.token}`);
}
else {
// Create hashed password and save to db
res.locals.passwordUser.generateHashedPassword( req.body.password, (err)=>{
if (err){
mw.throwErr(err,req);
res.redirect(`/password/${req.params.token}`);
}
// User changed password
else if (req.user) {
req.flash('success', 'Your password has been changed. ');
res.redirect('/settings');
}
// New user created password
else {
req.flash('success', 'Password set. You can use it to log in now. ');
res.redirect('/login?next=/map?new=1');
}
} );
}
} );
// Set new password
.post((req, res, next) => {
// Validate password
let zxcvbnResult = zxcvbn(req.body.password)
if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second < 864000) { // Less than ten days
mw.throwErr(new Error(`That password could be cracked in ${zxcvbnResult.crack_times_display.online_no_throttling_10_per_second}! Come up with a more complex password that would take at least 10 days to crack. `))
res.redirect(`/settings/password/${req.params.token}`)
} else {
// Create hashed password and save to db
res.locals.passwordUser.generateHashedPassword(req.body.password, (err) => {
if (err) {
mw.throwErr(err, req)
res.redirect(`/password/${req.params.token}`)
// User changed password
} else if (req.user) {
req.flash('success', 'Your password has been changed. ')
res.redirect('/settings')
// New user created password
} else {
req.flash('success', 'Password set. You can use it to log in now. ')
res.redirect('/login?next=/map?new=1')
}
})
}
})
// Tracman pro // Tracman pro
router.route('/pro') router.route('/pro')
.all( mw.ensureAuth, (req,res,next)=>{ .all(mw.ensureAuth, (req, res, next) => {
next(); next()
} ) })
// Get info about pro // Get info about pro
.get( (req,res,next)=>{ .get((req, res, next) => {
res.render('pro'); res.render('pro')
} ) })
// Join Tracman pro // Join Tracman pro
.post( (req,res)=>{ .post((req, res) => {
User.findByIdAndUpdate(req.user.id, User.findByIdAndUpdate(req.user.id,
{$set:{ isPro:true }}) {$set: { isPro: true }})
.then( (user)=>{ .then((user) => {
req.flash('success','You have been signed up for pro. '); req.flash('success', 'You have been signed up for pro. ')
res.redirect('/settings'); res.redirect('/settings')
}) })
.catch( (err)=>{ .catch((err) => {
mw.throwErr(err,req); mw.throwErr(err, req)
res.redirect('/settings/pro'); res.redirect('/settings/pro')
}); })
} ); })
module.exports = router; module.exports = router

View File

@ -1,52 +1,51 @@
'use strict'; 'use strict'
const router = require('express').Router(), const router = require('express').Router(),
zxcvbn = require('zxcvbn'), zxcvbn = require('zxcvbn'),
mw = require('../middleware.js'), mw = require('../middleware.js'),
mail = require('../mail.js'); mail = require('../mail.js')
router router
.get('/mail', (req,res,next)=>{ .get('/mail', (req, res, next) => {
mail.send({ mail.send({
to: `"Keith Irwin" <hypergeek14@gmail.com>`, to: `"Keith Irwin" <hypergeek14@gmail.com>`,
from: mail.noReply, from: mail.noReply,
subject: 'Test email', subject: 'Test email',
text: mail.text("Looks like everything's working! "), text: mail.text("Looks like everything's working! "),
html: mail.html("<p>Looks like everything's working! </p>") html: mail.html("<p>Looks like everything's working! </p>")
}) })
.then(()=>{ .then(() => {
console.log("Test email should have sent..."); console.log('Test email should have sent...')
res.sendStatus(200); res.sendStatus(200)
}) })
.catch((err)=>{ .catch((err) => {
mw.throwErr(err,req); mw.throwErr(err, req)
res.sendStatus(500); res.sendStatus(500)
}); })
}) })
.get('/password', (req,res)=>{ .get('/password', (req, res) => {
res.render('password'); res.render('password')
}) })
.post('/password', (req,res,next)=>{ .post('/password', (req, res, next) => {
let zxcvbnResult = zxcvbn(req.body.password); let zxcvbnResult = zxcvbn(req.body.password)
if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second < 864000) { // Less than ten days if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second < 864000) { // Less than ten days
let err = new Error(`That password could be cracked in ${zxcvbnResult.crack_times_display.online_no_throttling_10_per_second}! Come up with a more complex password that would take at least 10 days to crack. `); let err = new Error(`That password could be cracked in ${zxcvbnResult.crack_times_display.online_no_throttling_10_per_second}! Come up with a more complex password that would take at least 10 days to crack. `)
mw.throwErr(err,req); mw.throwErr(err, req)
next(err); next(err)
} } else {
else { res.sendStatus(200)
res.sendStatus(200); }
} })
})
.get('/settings', (req, res) => {
.get('/settings', (req,res)=>{ res.render('settings')
res.render('settings'); })
}) .post('/settings', (req, res) => {
.post('/settings', (req,res)=>{
// TODO: Test validation here?
//TODO: Test validation here?
})
});
module.exports = router
module.exports = router;

View File

@ -1,124 +1,114 @@
'use strict'; 'use strict'
// Imports // Imports
const debug = require('debug')('tracman-sockets'), const debug = require('debug')('tracman-sockets')
User = require('./models.js').user; const User = require('./models.js').user
// Check for tracking clients // Check for tracking clients
function checkForUsers(io, user) { function checkForUsers (io, user) {
debug(`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 // Checks if any sockets are getting updates for this user
if (Object.values(io.sockets.connected).some( (socket)=>{ if (Object.values(io.sockets.connected).some((socket) => {
return socket.gets===user; return socket.gets === user
})) { })) {
debug(`Activating updates for ${user}.`); debug(`Activating updates for ${user}.`)
io.to(user).emit('activate','true'); io.to(user).emit('activate', 'true')
} else { } else {
debug(`Deactivating updates for ${user}.`); debug(`Deactivating updates for ${user}.`)
io.to(user).emit('activate', 'false'); io.to(user).emit('activate', 'false')
} }
} }
module.exports = { module.exports = {
checkForUsers: checkForUsers,
init: (io)=>{
io.on('connection', (socket)=>{
debug(`${socket.id} connected.`);
// Set a few variables
//socket.ip = socket.client.request.headers['x-real-ip'];
//socket.ua = socket.client.request.headers['user-agent'];
// Log and errors
socket.on('log', (text)=>{
debug(`LOG: ${text}`);
});
socket.on('error', (err)=>{ console.error('❌', err.stack); });
// This socket can set location (app)
socket.on('can-set', (userId)=>{
debug(`${socket.id} can set updates for ${userId}.`);
socket.join(userId, ()=>{
debug(`${socket.id} joined ${userId}`);
});
checkForUsers( io, userId );
});
// This socket can receive location (map)
socket.on('can-get', (userId)=>{
socket.gets = userId;
debug(`${socket.id} can get updates for ${userId}.`);
socket.join(userId, ()=>{
debug(`${socket.id} joined ${userId}`);
socket.to(userId).emit('activate', 'true');
});
});
// Set location
socket.on('set', (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); }
else { loc.tim = Date.now(); }
// Check for user and sk32 token checkForUsers: checkForUsers,
if (!loc.usr){
console.error("❌", new Error(`Recieved an update from ${socket.ip} without a usr!`).message);
}
else if (!loc.tok){
console.error("❌", new Error(`Recieved an update from ${socket.ip} for usr ${loc.usr} without an sk32!`).message);
}
else {
// Get loc.usr
User.findById(loc.usr)
.where('sk32').equals(loc.tok)
.then( (user)=>{
if (!user){
console.error("❌", new Error(`Recieved an update from ${socket.ip} for ${loc.usr} with tok of ${loc.tok}, but no such user was found in the db!`).message);
}
else {
// Broadcast location
io.to(loc.usr).emit('get', loc);
debug(`Broadcasting ${loc.lat}, ${loc.lon} to ${loc.usr}`);
// Save in db as last seen
user.last = {
lat: parseFloat(loc.lat),
lon: parseFloat(loc.lon),
dir: parseFloat(loc.dir||0),
spd: parseFloat(loc.spd||0),
time: loc.tim
};
user.save()
.catch( (err)=>{ console.error("❌", err.stack); });
} init: (io) => {
}) io.on('connection', (socket) => {
.catch( (err)=>{ console.error("❌", err.stack); }); debug(`${socket.id} connected.`)
} // Set a few variables
}); // socket.ip = socket.client.request.headers['x-real-ip'];
// socket.ua = socket.client.request.headers['user-agent'];
// Shutdown (check for remaining clients)
socket.on('disconnect', (reason)=>{ // Log and errors
debug(`${socket.id} disconnected because of a ${reason}.`); socket.on('log', (text) => {
debug(`LOG: ${text}`)
// Check if client was receiving updates })
if (socket.gets){ socket.on('error', (err) => { console.error('❌', err.stack) })
debug(`${socket.id} left ${socket.gets}`);
checkForUsers( io, socket.gets ); // This socket can set location (app)
} socket.on('can-set', (userId) => {
debug(`${socket.id} can set updates for ${userId}.`)
}); socket.join(userId, () => {
debug(`${socket.id} joined ${userId}`)
}); })
} checkForUsers(io, userId)
})
};
// This socket can receive location (map)
socket.on('can-get', (userId) => {
socket.gets = userId
debug(`${socket.id} can get updates for ${userId}.`)
socket.join(userId, () => {
debug(`${socket.id} joined ${userId}`)
socket.to(userId).emit('activate', 'true')
})
})
// Set location
socket.on('set', (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) } else { loc.tim = Date.now() }
// Check for user and sk32 token
if (!loc.usr) {
console.error('❌', new Error(`Recieved an update from ${socket.ip} without a usr!`).message)
} else if (!loc.tok) {
console.error('❌', new Error(`Recieved an update from ${socket.ip} for usr ${loc.usr} without an sk32!`).message)
} else {
// Get loc.usr
User.findById(loc.usr)
.where('sk32').equals(loc.tok)
.then((user) => {
if (!user) {
console.error('❌', new Error(`Recieved an update from ${socket.ip} for ${loc.usr} with tok of ${loc.tok}, but no such user was found in the db!`).message)
} else {
// Broadcast location
io.to(loc.usr).emit('get', loc)
debug(`Broadcasting ${loc.lat}, ${loc.lon} to ${loc.usr}`)
// Save in db as last seen
user.last = {
lat: parseFloat(loc.lat),
lon: parseFloat(loc.lon),
dir: parseFloat(loc.dir || 0),
spd: parseFloat(loc.spd || 0),
time: loc.tim
}
user.save()
.catch((err) => { console.error('❌', err.stack) })
}
})
.catch((err) => { console.error('❌', err.stack) })
}
})
// Shutdown (check for remaining clients)
socket.on('disconnect', (reason) => {
debug(`${socket.id} disconnected because of a ${reason}.`)
// Check if client was receiving updates
if (socket.gets) {
debug(`${socket.id} left ${socket.gets}`)
checkForUsers(io, socket.gets)
}
})
})
}
}

View File

@ -52,7 +52,7 @@
"nodemon": "nodemon --ignore 'static/**/*.min.*' server.js", "nodemon": "nodemon --ignore 'static/**/*.min.*' server.js",
"update": "sudo npm update && sudo npm prune", "update": "sudo npm update && sudo npm prune",
"minify": "minify --template .{{filename}}.min.{{ext}} --clean static/css*", "minify": "minify --template .{{filename}}.min.{{ext}} --clean static/css*",
"build": "standard && ./node_modules/.bin/webpack --config webpack.config.js", "build": "./node_modules/.bin/webpack --config webpack.config.js",
"subuild": "sudo ./node_modules/.bin/webpack --config webpack.config.js" "subuild": "sudo ./node_modules/.bin/webpack --config webpack.config.js"
}, },
"repository": "Tracman-org/Server", "repository": "Tracman-org/Server",

364
server.js
View File

@ -1,199 +1,181 @@
'use strict'; 'use strict'
/* IMPORTS */ /* IMPORTS */
const const express = require('express')
express = require('express'), const bodyParser = require('body-parser')
bodyParser = require('body-parser'), const expressValidator = require('express-validator')
expressValidator = require('express-validator'), const cookieParser = require('cookie-parser')
cookieParser = require('cookie-parser'), const cookieSession = require('cookie-session')
cookieSession = require('cookie-session'), const debug = require('debug')('tracman-server')
debug = require('debug')('tracman-server'), const mongoose = require('mongoose')
mongoose = require('mongoose'), const nunjucks = require('nunjucks')
nunjucks = require('nunjucks'), const passport = require('passport')
passport = require('passport'), const flash = require('connect-flash-plus')
flash = require('connect-flash-plus'), const env = require('./config/env/env.js')
env = require('./config/env/env.js'), const User = require('./config/models.js').user
User = require('./config/models.js').user, const mail = require('./config/mail.js')
mail = require('./config/mail.js'), const demo = require('./config/demo.js')
demo = require('./config/demo.js'), const app = express()
app = express(), const http = require('http').Server(app)
http = require('http').Server(app), const io = require('socket.io')(http)
io = require('socket.io')(http), const sockets = require('./config/sockets.js')
sockets = require('./config/sockets.js');
/* SETUP */
/* Database */ {
// Setup with native ES6 promises
mongoose.Promise = global.Promise
/* SETUP */ { // Connect to database
mongoose.connect(env.mongoSetup, {
/* Database */ { server: {socketOptions: {
keepAlive: 1, connectTimeoutMS: 30000 }},
// Setup with native ES6 promises replset: {socketOptions: {
mongoose.Promise = global.Promise; keepAlive: 1, connectTimeoutMS: 30000 }}
})
// Connect to database .then(() => { console.log(`💿 Mongoose connected to mongoDB`) })
mongoose.connect(env.mongoSetup, { .catch((err) => { console.error(`${err.stack}`) })
server:{socketOptions:{
keepAlive:1, connectTimeoutMS:30000 }},
replset:{socketOptions:{
keepAlive:1, connectTimeoutMS:30000 }}
})
.then( ()=>{ console.log(`💿 Mongoose connected to mongoDB`); })
.catch( (err)=>{ console.error(`${err.stack}`); });
}
/* Templates */ {
nunjucks.configure(__dirname+'/views', {
autoescape: true,
express: app
});
app.set('view engine','html');
}
/* Session */ {
app.use(cookieParser(env.cookie));
app.use(cookieSession({
cookie: {maxAge:60000},
secret: env.session,
saveUninitialized: true,
resave: true
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(expressValidator());
app.use(flash());
}
/* Auth */ {
require('./config/passport.js')(passport);
app.use(passport.initialize());
app.use(passport.session());
}
/* Routes */ {
// Static files (keep this before default locals)
app.use('/static', express.static( __dirname+'/static', {dotfiles:'allow'} ));
// Default locals available to all views (keep this after static files)
app.get( '*', (req,res,next)=>{
// Path for redirects
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)!=='signup' && nextPath.substring(0,7)!=='/logout' && nextPath.substring(0,7)!=='/static' && nextPath.substring(0,6)!=='/admin' ){
req.session.next = nextPath+'#';
debug(`Set redirect path to ${nextPath}#`);
}
// User account
res.locals.user = req.user;
// Flash messages
res.locals.successes = req.flash('success');
res.locals.dangers = req.flash('danger');
res.locals.warnings = req.flash('warning');
next();
} );
// Auth routes
require('./config/routes/auth.js')(app, passport);
// Main routes
app.use( '/', require('./config/routes/index.js') );
// Contact form
app.use( '/contact', require('./config/routes/contact.js') );
// Settings
app.use( '/settings', require('./config/routes/settings.js') );
// Map
app.use( ['/map','/trac'], require('./config/routes/map.js') );
// Site administration
app.use( '/admin', require('./config/routes/admin.js') );
// Testing
if (env.mode == 'development') {
app.use( '/test', require('./config/routes/test.js' ) );
}
}
/* Errors */ {
// Catch-all for 404s
app.use( (req,res,next)=>{
if (!res.headersSent) {
var err = new Error(`Not found: ${req.url}`);
err.status = 404;
next(err);
}
} );
// Production handlers
if (env.mode!=='development') {
app.use( (err,req,res,next)=>{
if (err.status!==404&&err.status!==401){ console.error(`${err.stack}`); }
if (res.headersSent) { return next(err); }
res.status(err.status||500);
res.render('error', {
code: err.status||500,
message: (err.status<=499)?err.message:"Server error"
});
} );
}
// Development handlers
else {
app.use( (err,req,res,next)=>{
if (err.status!==404) { console.error(`${err.stack}`); }
if (res.headersSent) { return next(err); }
res.status(err.status||500);
res.render('error', {
code: err.status||500,
message: err.message,
stack: err.stack
});
} );
}
}
/* Sockets */ {
sockets.init(io);
}
} }
/* RUNTIME */ { /* Templates */ {
console.log('🖥 Starting Tracman server...'); nunjucks.configure(__dirname + '/views', {
autoescape: true,
// Test SMTP server express: app
mail.verify(); })
app.set('view engine', 'html')
// Listen
http.listen( env.port, ()=>{
console.log(`🌐 Listening in ${env.mode} mode on port ${env.port}... `);
// Check for clients for each user
User.find({})
.then( (users)=>{
users.forEach( (user)=>{
sockets.checkForUsers( io, user.id );
});
})
.catch( (err)=>{
console.error(`${err.stack}`);
});
// Start transmitting demo
demo(io);
});
} }
module.exports = app; /* Session */ {
app.use(cookieParser(env.cookie))
app.use(cookieSession({
cookie: {maxAge: 60000},
secret: env.session,
saveUninitialized: true,
resave: true
}))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(expressValidator())
app.use(flash())
}
/* Auth */ {
require('./config/passport.js')(passport)
app.use(passport.initialize())
app.use(passport.session())
}
/* Routes */ {
// Static files (keep this before default locals)
app.use('/static', express.static(__dirname + '/static', {dotfiles: 'allow'}))
// Default locals available to all views (keep this after static files)
app.get('*', (req, res, next) => {
// Path for redirects
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) !== 'signup' && nextPath.substring(0, 7) !== '/logout' && nextPath.substring(0, 7) !== '/static' && nextPath.substring(0, 6) !== '/admin') {
req.session.next = nextPath + '#'
debug(`Set redirect path to ${nextPath}#`)
}
// User account
res.locals.user = req.user
// Flash messages
res.locals.successes = req.flash('success')
res.locals.dangers = req.flash('danger')
res.locals.warnings = req.flash('warning')
next()
})
// Auth routes
require('./config/routes/auth.js')(app, passport)
// Main routes
app.use('/', require('./config/routes/index.js'))
// Contact form
app.use('/contact', require('./config/routes/contact.js'))
// Settings
app.use('/settings', require('./config/routes/settings.js'))
// Map
app.use(['/map', '/trac'], require('./config/routes/map.js'))
// Site administration
app.use('/admin', require('./config/routes/admin.js'))
// Testing
if (env.mode == 'development') {
app.use('/test', require('./config/routes/test.js'))
}
} {
// Catch-all for 404s
app.use((req, res, next) => {
if (!res.headersSent) {
var err = new Error(`Not found: ${req.url}`)
err.status = 404
next(err)
}
})
// Production handlers
if (env.mode !== 'development') {
app.use((err, req, res, next) => {
if (err.status !== 404 && err.status !== 401) { console.error(`${err.stack}`) }
if (res.headersSent) { return next(err) }
res.status(err.status || 500)
res.render('error', {
code: err.status || 500,
message: (err.status <= 499) ? err.message : 'Server error'
})
})
// Development handlers
} else {
app.use((err, req, res, next) => {
if (err.status !== 404) { console.error(`${err.stack}`) }
if (res.headersSent) { return next(err) }
res.status(err.status || 500)
res.render('error', {
code: err.status || 500,
message: err.message,
stack: err.stack
})
})
}
}
/* Sockets */ {
sockets.init(io)
}
/* RUNTIME */
console.log('🖥 Starting Tracman server...')
// Test SMTP server
mail.verify()
// Listen
http.listen(env.port, () => {
console.log(`🌐 Listening in ${env.mode} mode on port ${env.port}... `)
// Check for clients for each user
User.find({})
.then((users) => {
users.forEach((user) => {
sockets.checkForUsers(io, user.id)
})
})
.catch((err) => {
console.error(`${err.stack}`)
})
// Start transmitting demo
demo(io)
})
module.exports = app

View File

@ -2,16 +2,18 @@
/* global ga CoinHive */ /* global ga CoinHive */
// Google analytics // Google analytics
(function(t,r,a,c,m,o,n){t['GoogleAnalyticsObject']=m;t[m]=t[m]||function(){ (function (t, r, a, c, m, o, n) {
(t[m].q=t[m].q||[]).push(arguments);},t[m].l=1*new Date();o=r.createElement(a), t['GoogleAnalyticsObject'] = m; t[m] = t[m] || function () {
n=r.getElementsByTagName(a)[0];o.async=1;o.src=c;n.parentNode.insertBefore(o,n); (t[m].q = t[m].q || []).push(arguments)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga'); }, t[m].l = 1 * new Date(); o = r.createElement(a),
ga('create','UA-44266909-3','auto'); n = r.getElementsByTagName(a)[0]; o.async = 1; o.src = c; n.parentNode.insertBefore(o, n)
ga('require','linkid'); })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga')
ga('send','pageview'); ga('create', 'UA-44266909-3', 'auto')
ga('require', 'linkid')
ga('send', 'pageview')
// Coinhive // Coinhive
new CoinHive.Anonymous('7FZrGIbIO4kqxbTLa82QpffB9ShUGmWE',{ new CoinHive.Anonymous('7FZrGIbIO4kqxbTLa82QpffB9ShUGmWE', {
autoThreads: true, autoThreads: true,
throttle: .5 throttle: 0.5
}).start(CoinHive.FORCE_EXCLUSIVE_TAB); }).start(CoinHive.FORCE_EXCLUSIVE_TAB)

View File

@ -1,82 +1,72 @@
'use strict'; 'use strict'
/* global $ */ /* global $ */
var validEmail, validMessage; var validEmail, validMessage
// Validate email addresses // Validate email addresses
function validateEmail(email) { function validateEmail (email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email); return re.test(email)
} }
// Validate form // Validate form
function validateForm(input) { function validateForm (input) {
// Check if email is valid
// Check if email is valid if (input === 'email') {
if (input==='email') { if (!validateEmail($('#email-input').val())) {
if (!validateEmail($('#email-input').val())) { validEmail = false
validEmail = false; $('#email-help').show()
$('#email-help').show(); $('#submit-button').prop('disabled', true).prop('title', 'You need to enter a valid email address. ')
$('#submit-button').prop('disabled',true).prop('title',"You need to enter a valid email address. "); } else {
} validEmail = true
else { $('#email-help').hide()
validEmail = true; validateForm()
$('#email-help').hide(); }
validateForm(); }
}
} // Ensure message has been entered
if (input === 'message') {
// Ensure message has been entered if ($('#message-input').val() === '') {
if (input==='message') { validMessage = false
if ($('#message-input').val()==='') { $('#message-help').show()
validMessage = false; $('#submit-button').prop('disabled', true).prop('title', 'You need to enter a message. ')
$('#message-help').show(); } else {
$('#submit-button').prop('disabled',true).prop('title',"You need to enter a message. "); validMessage = true
} $('#message-help').hide()
else { validateForm()
validMessage = true; }
$('#message-help').hide();
validateForm(); // Recheck whole form
} } else {
} if (validEmail && validMessage) {
$('#submit-button').prop('disabled', false).prop('title', 'Click here to send your message. ')
// Recheck whole form return true
else { } else {
if (validEmail && validMessage) { $('#submit-button').prop('disabled', true).prop('title', 'Edit the form before clicking send. ')
$('#submit-button').prop('disabled',false).prop('title',"Click here to send your message. "); return false
return true; }
} }
else {
$('#submit-button').prop('disabled',true).prop('title',"Edit the form before clicking send. ");
return false;
}
}
} }
// Initial check // Initial check
$(function() { $(function () {
if (validateEmail($('#email-input').val())) { validEmail = true } else { validEmail = false }
if ( validateEmail($('#email-input').val()) ) { validEmail = true; }
else { validEmail = false; } if (!$('#message-input').val() === '') { validMessage = true } else { validMessage = false }
if ( !$('#message-input').val()==='' ) { validMessage = true; } // Use a one-second timout because reCaptcha re-enables the button by default
else { validMessage = false; } setTimeout(validateForm, 1000)
})
// Use a one-second timout because reCaptcha re-enables the button by default
setTimeout(validateForm,1000);
});
// Submit form (reCaptcha callback) // Submit form (reCaptcha callback)
window.onSubmit = function() { window.onSubmit = function () {
if (validateForm()) { $('#contact-form').submit(); } if (validateForm()) { $('#contact-form').submit() }
}; }
// Form change listener // Form change listener
$('#email-input').change(function(){ $('#email-input').change(function () {
validateForm('email'); validateForm('email')
}); })
$('#message-input').change(function(){ $('#message-input').change(function () {
validateForm('message'); validateForm('message')
}); })

View File

@ -1,17 +1,17 @@
'use strict'; 'use strict'
/* global $ */ /* global $ */
// Push footer to bottom on pages with little content // Push footer to bottom on pages with little content
function setFooter(){ function setFooter () {
var windowHeight = $(window).height(), var windowHeight = $(window).height()
footerBottom = $("footer").offset().top + $("footer").height(); var footerBottom = $('footer').offset().top + $('footer').height()
if (windowHeight > footerBottom){ if (windowHeight > footerBottom) {
$("footer").css( "margin-top", windowHeight-footerBottom ); $('footer').css('margin-top', windowHeight - footerBottom)
} }
} }
// Execute on page load // Execute on page load
$(function(){ setFooter(); }); $(function () { setFooter() })
// Execute on window resize // Execute on window resize
$(window).resize(function(){ setFooter(); }); $(window).resize(function () { setFooter() })

View File

@ -1,29 +1,27 @@
/* global $ */ /* global $ */
'use strict'; 'use strict'
$(document).ready(function(){ $(document).ready(function () {
// Open drawer with hamburger
// Open drawer with hamburger $('.hamburger').click(function () {
$('.hamburger').click(function(){ $('.hamburger').toggleClass('is-active')
$('.hamburger').toggleClass('is-active'); $('nav').toggleClass('visible')
$('nav').toggleClass('visible'); })
});
// Close drawer after tapping on nav
// Close drawer after tapping on nav $('nav').click(function () {
$('nav').click(function(){ $('.hamburger').removeClass('is-active')
$('.hamburger').removeClass('is-active'); $('nav').removeClass('visible')
$('nav').removeClass('visible'); })
});
// Close drawer by tapping outside it
// Close drawer by tapping outside it $('.wrap, section').click(function () {
$('.wrap, section').click(function(){ $('.hamburger').removeClass('is-active')
$('.hamburger').removeClass('is-active'); $('nav').removeClass('visible')
$('nav').removeClass('visible'); })
});
// Close alerts
// Close alerts $('.alert-dismissible .close').click(function () {
$('.alert-dismissible .close').click(function() { $(this).parent().slideUp(500)
$(this).parent().slideUp(500); })
}); })
});

View File

@ -1,8 +1,32 @@
/* /*
HTML5 Shiv v3.6.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed HTML5 Shiv v3.6.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/ */
(function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag(); (function (l, f) {
a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}</style>"; function m () { var a = e.elements; return typeof a === 'string' ? a.split(' ') : a } function i (a) { var b = n[a[o]]; b || (b = {}, h++, a[o] = h, n[h] = b); return b } function p (a, b, c) { b || (b = f); if (g) return b.createElement(a); c || (c = i(b)); b = c.cache[a] ? c.cache[a].cloneNode() : r.test(a) ? (c.cache[a] = c.createElem(a)).cloneNode() : c.createElem(a); return b.canHaveChildren && !s.test(a) ? c.frag.appendChild(b) : b } function t (a, b) {
c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode|| if (!b.cache)b.cache = {}, b.createElem = a.createElement, b.createFrag = a.createDocumentFragment, b.frag = b.createFrag()
"undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video",version:"3.6.2",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment(); a.createElement = function (c) { return !e.shivMethods ? b.createElem(c) : p(c, a, b) }; a.createDocumentFragment = Function('h,f', 'return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&(' + m().join().replace(/\w+/g, function (a) { b.createElem(a); b.frag.createElement(a); return 'c("' + a + '")' }) + ');return n}')(e, b.frag)
for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document); } function q (a) {
a || (a = f); var b = i(a); if (e.shivCSS && !j && !b.hasCSS) {
var c, d = a; c = d.createElement('p'); d = d.getElementsByTagName('head')[0] || d.documentElement; c.innerHTML = 'x<style>article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}</style>'
c = d.insertBefore(c.lastChild, d.firstChild); b.hasCSS = !!c
}g || t(a, b); return a
} var k = l.html5 || {}, s = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i, r = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i, j, o = '_html5shiv', h = 0, n = {}, g; (function () {
try {
var a = f.createElement('a'); a.innerHTML = '<xyz></xyz>'; j = 'hidden' in a; var b; if (!(b = a.childNodes.length == 1)) {
f.createElement('a'); var c = f.createDocumentFragment(); b = typeof c.cloneNode === 'undefined' ||
typeof c.createDocumentFragment === 'undefined' || typeof c.createElement === 'undefined'
}g = b
} catch (d) { g = j = !0 }
})(); var e = {elements: k.elements || 'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video',
version: '3.6.2',
shivCSS: !1 !== k.shivCSS,
supportsUnknownElements: g,
shivMethods: !1 !== k.shivMethods,
type: 'default',
shivDocument: q,
createElement: p,
createDocumentFragment: function (a, b) {
a || (a = f); if (g) return a.createDocumentFragment()
for (var b = b || i(a), c = b.frag.cloneNode(), d = 0, e = m(), h = e.length; d < h; d++)c.createElement(e[d]); return c
}}; l.html5 = e; q(f)
})(this, document)

View File

@ -1,15 +1,13 @@
'use strict'; 'use strict'
/* global $ */ /* global $ */
$(function(){ $(function () {
// On clocking 'show'
// On clocking 'show' $('#show').click(function () {
$('#show').click(function(){ if ($('#password').attr('type') === 'password') {
if ($('#password').attr('type')==="password") { $('#password').attr('type', 'text')
$('#password').attr('type','text'); } else {
} else { $('#password').attr('type', 'password')
$('#password').attr('type','password'); }
} })
}); })
});

View File

@ -1,464 +1,439 @@
'use strict'; 'use strict'
/* global mapuser userid disp noHeader mapKey navigator $ token */ /* global alert mapuser userid disp noHeader mapKey navigator token */
import io from 'socket.io-client'; import io from 'socket.io-client'
import $ from 'jquery'; import $ from 'jquery'
import loadGoogleMapsAPI from 'load-google-maps-api'; import loadGoogleMapsAPI from 'load-google-maps-api'
// Variables // Variables
var map, marker, elevator, newLoc; var map, marker, elevator, newLoc
const mapElem = document.getElementById('map'), const mapElem = document.getElementById('map')
socket = io('//'+window.location.hostname); const socket = io('//' + window.location.hostname)
// Convert to feet if needed // Convert to feet if needed
function metersToFeet(meters){ function metersToFeet (meters) {
//console.log('metersToFeet('+meters+')') // console.log('metersToFeet('+meters+')')
return (mapuser.settings.units=='standard')? (meters*3.28084).toFixed(): meters.toFixed() return (mapuser.settings.units === 'standard') ? (meters * 3.28084).toFixed() : meters.toFixed()
} }
// socket.io stuff // socket.io stuff
socket socket
.on('connect', function(){ .on('connect', function () {
console.log("Connected!"); console.log('Connected!')
// Can get location
socket.emit('can-get', mapuser._id );
// Can set location too // Can get location
if (mapuser._id===userid) { socket.emit('can-get', mapuser._id)
socket.emit('can-set', userid );
} // Can set location too
if (mapuser._id === userid) {
}) socket.emit('can-set', userid)
.on('disconnect', function(){ }
console.log("Disconnected!"); }).on('disconnect', function () {
}) console.log('Disconnected!')
.on('error', function (err){ }).on('error', function (err) {
console.error('❌️',err.message); console.error('❌️', err.message)
}); })
// Show/hide map if location is set/unset // Show/hide map if location is set/unset
function toggleMaps(loc) { function toggleMaps (loc) {
if (loc.lat===0&&loc.lon===0) { if (loc.lat === 0 && loc.lon === 0) {
$('#map').hide(); $('#map').hide()
$('#view').hide(); $('#view').hide()
$('#notset').show(); $('#notset').show()
} } else {
else { $('#map').show()
$('#map').show(); $('#view').show()
$('#view').show(); $('#notset').hide()
$('#notset').hide(); }
}
} }
// Toggle maps on page load
$(function() { // On page load
toggleMaps(mapuser.last); $(function () {
toggleMaps(mapuser.last)
// Controls
var wpid, newloc; // Controls
var wpid, newloc
// Set location
$('#set-loc').click(function(){ // Set location
if (!userid===mapuser._id){ alert('You are not logged in! '); } $('#set-loc').click(function () {
else { if (!navigator.geolocation){ alert('Geolocation not enabled. '); } if (!userid === mapuser._id) { alert('You are not logged in! ') } else {
if (!navigator.geolocation) { alert('Geolocation not enabled. ') } else {
else { navigator.geolocation.getCurrentPosition( navigator.geolocation.getCurrentPosition(
// Success callback // Success callback
function(pos){ function (pos) {
var newloc = { var newloc = {
ts: Date.now(), ts: Date.now(),
tok: token, tok: token,
usr: userid, usr: userid,
alt: pos.coords.altitude, alt: pos.coords.altitude,
lat: pos.coords.latitude, lat: pos.coords.latitude,
lon: pos.coords.longitude, lon: pos.coords.longitude,
spd: (pos.coords.speed||0) spd: (pos.coords.speed || 0)
}; }
socket.emit('set', newloc); socket.emit('set', newloc)
toggleMaps(newloc); toggleMaps(newloc)
console.log('Set location:',newloc.lat+", "+newloc.lon); console.log('Set location:', newloc.lat + ', ' + newloc.lon)
}, },
// Error callback // Error callback
function(err) { function (err) {
alert("Unable to set location."); alert('Unable to set location.')
console.error('❌️',err.message); console.error('❌️', err.message)
}, },
// Options // Options
{ enableHighAccuracy:true } { enableHighAccuracy: true }
); } } )
}
}); }
})
// Track location
$('#track-loc').click(function(){ // Track location
if (!userid===mapuser._id) { alert('You are not logged in! '); } $('#track-loc').click(function () {
else { if (!userid === mapuser._id) { alert('You are not logged in! ') } else {
// Start tracking
// Start tracking if (!wpid) {
if (!wpid) { if (!navigator.geolocation) {
if (!navigator.geolocation) { alert('Unable to track location. '); } alert('Unable to track location. ')
else { } else {
$('#track-loc').html('<i class="fa fa-crosshairs fa-spin"></i>Stop').prop('title',"Click here to stop tracking your location. "); $('#track-loc').html('<i class="fa fa-crosshairs fa-spin"></i>Stop').prop('title', 'Click here to stop tracking your location. ')
wpid = navigator.geolocation.watchPosition( wpid = navigator.geolocation.watchPosition(
// Success callback // Success callback
function(pos) { function (pos) {
newloc = { newloc = {
ts: Date.now(), ts: Date.now(),
tok: token, tok: token,
usr: userid, usr: userid,
lat: pos.coords.latitude, lat: pos.coords.latitude,
lon: pos.coords.longitude, lon: pos.coords.longitude,
alt: pos.coords.altitude, alt: pos.coords.altitude,
spd: (pos.coords.speed||0) spd: (pos.coords.speed || 0)
} }
socket.emit('set',newloc) socket.emit('set', newloc)
toggleMaps(newloc) toggleMaps(newloc)
console.log('Set location:',newloc.lat+", "+newloc.lon) console.log('Set location:', newloc.lat + ', ' + newloc.lon)
}, },
// Error callback // Error callback
function(err){ function (err) {
alert("Unable to track location."); alert('Unable to track location.')
console.error(err.message); console.error(err.message)
}, },
// Options // Options
{ enableHighAccuracy:true } { enableHighAccuracy: true }
); )
} }
} // Stop tracking
} else {
// Stop tracking $('#track-loc').html('<i class="fa fa-crosshairs"></i>Track').prop('title', 'Click here to track your location. ')
else { navigator.geolocation.clearWatch(wpid)
$('#track-loc').html('<i class="fa fa-crosshairs"></i>Track').prop('title',"Click here to track your location. "); wpid = undefined
navigator.geolocation.clearWatch(wpid); }
wpid = undefined; }
} })
} // Clear location
}); $('#clear-loc').click(function () {
if (!userid === mapuser._id) { alert('You are not logged in! ') } else {
// Clear location // Stop tracking
$('#clear-loc').click(function(){ if (wpid) {
if (!userid===mapuser._id) { alert('You are not logged in! '); } $('#track-loc').html('<i class="fa fa-crosshairs"></i>Track')
else { navigator.geolocation.clearWatch(wpid)
// Stop tracking wpid = undefined
if (wpid) { }
$('#track-loc').html('<i class="fa fa-crosshairs"></i>Track');
navigator.geolocation.clearWatch(wpid); // Clear location
wpid = undefined; newloc = {
} ts: Date.now(),
tok: token,
// Clear location usr: userid,
newloc = { lat: 0,
ts: Date.now(), lon: 0,
tok: token, spd: 0
usr: userid, }; socket.emit('set', newloc)
lat:0, lon:0, spd:0
}; socket.emit('set',newloc); // Turn off map
toggleMaps(newloc)
// Turn off map console.log('Cleared location')
toggleMaps(newloc); }
console.log('Cleared location'); })
} })
});
});
// Load google maps API // Load google maps API
loadGoogleMapsAPI({ key:mapKey }) loadGoogleMapsAPI({ key: mapKey })
.then( function(googlemaps) { .then(function (googlemaps) {
// Create map
if (disp !== '1') {
// Create map and marker elements
map = new googlemaps.Map(mapElem, {
center: {
lat: mapuser.last.lat,
lng: mapuser.last.lon
},
panControl: false,
scrollwheel: true,
scaleControl: !!(mapuser.settings.showScale),
draggable: false,
zoom: mapuser.settings.defaultZoom,
streetViewControl: false,
zoomControlOptions: {position: googlemaps.ControlPosition.LEFT_TOP},
mapTypeId: (mapuser.settings.defaultMap === 'road') ? googlemaps.MapTypeId.ROADMAP : googlemaps.MapTypeId.HYBRID
})
marker = new googlemaps.Marker({
position: { lat: mapuser.last.lat, lng: mapuser.last.lon },
title: mapuser.name,
icon: (mapuser.settings.marker) ? '/static/img/marker/' + mapuser.settings.marker + '.png' : '/static/img/marker/red.png',
map: map,
draggable: false
})
map.addListener('zoom_changed', function () {
map.setCenter(marker.getPosition())
})
// Create map // Create iFrame logo
if (disp!=='1') { if (noHeader !== '0' && mapuser._id !== 'demo') {
const logoDiv = document.createElement('div')
// Create map and marker elements logoDiv.id = 'map-logo'
map = new googlemaps.Map( mapElem, { logoDiv.innerHTML = '<a href="https://tracman.org/">' +
center: { '<img src="https://tracman.org/static/img/style/logo-28.png" alt="[]">' +
lat: mapuser.last.lat, "<span class='text'>Tracman</span></a>"
lng: mapuser.last.lon map.controls[googlemaps.ControlPosition.BOTTOM_LEFT].push(logoDiv)
}, }
panControl: false,
scrollwheel: true, // Create update time block
scaleControl: (mapuser.settings.showScale)?true:false, const timeDiv = document.createElement('div')
draggable: false, timeDiv.id = 'timestamp'
zoom: mapuser.settings.defaultZoom, if (mapuser.last.time) {
streetViewControl: false, timeDiv.innerHTML = 'location updated ' + new Date(mapuser.last.time).toLocaleString()
zoomControlOptions: {position: googlemaps.ControlPosition.LEFT_TOP}, }
mapTypeId: (mapuser.settings.defaultMap=='road')?googlemaps.MapTypeId.ROADMAP:googlemaps.MapTypeId.HYBRID map.controls[googlemaps.ControlPosition.RIGHT_BOTTOM].push(timeDiv)
});
marker = new googlemaps.Marker({ // Create speed block
position: { lat:mapuser.last.lat, lng:mapuser.last.lon }, if (mapuser.settings.showSpeed) {
title: mapuser.name, const speedSign = document.createElement('div')
icon: (mapuser.settings.marker)?'/static/img/marker/'+mapuser.settings.marker+'.png':'/static/img/marker/red.png', const speedLabel = document.createElement('div')
map: map, const speedText = document.createElement('div')
draggable: false const speedUnit = document.createElement('div')
}); speedLabel.id = 'spd-label'
map.addListener('zoom_changed',function(){ speedLabel.innerHTML = 'SPEED'
map.setCenter(marker.getPosition()); speedText.id = 'spd'
}); speedText.innerHTML = (mapuser.settings.units === 'standard') ? (parseFloat(mapuser.last.spd) * 2.23694).toFixed() : mapuser.last.spd.toFixed()
speedUnit.id = 'spd-unit'
// Create iFrame logo speedUnit.innerHTML = (mapuser.settings.units === 'standard') ? 'm.p.h.' : 'k.p.h.'
if (noHeader!=='0' && mapuser._id!=='demo') { speedSign.id = 'spd-sign'
const logoDiv = document.createElement('div'); speedSign.appendChild(speedLabel)
logoDiv.id = 'map-logo'; speedSign.appendChild(speedText)
logoDiv.innerHTML = '<a href="https://tracman.org/">'+ speedSign.appendChild(speedUnit)
'<img src="https://tracman.org/static/img/style/logo-28.png" alt="[]">'+ map.controls[googlemaps.ControlPosition.TOP_RIGHT].push(speedSign)
"<span class='text'>Tracman</span></a>"; }
map.controls[googlemaps.ControlPosition.BOTTOM_LEFT].push(logoDiv);
} // Create altitude block
if (mapuser.settings.showAlt) {
// Create update time block elevator = new googlemaps.ElevationService()
const timeDiv = document.createElement('div'); const altitudeSign = document.createElement('div')
timeDiv.id = 'timestamp'; const altitudeLabel = document.createElement('div')
if (mapuser.last.time) { const altitudeText = document.createElement('div')
timeDiv.innerHTML = 'location updated '+new Date(mapuser.last.time).toLocaleString(); const altitudeUnit = document.createElement('div')
} altitudeLabel.id = 'alt-label'
map.controls[googlemaps.ControlPosition.RIGHT_BOTTOM].push(timeDiv); altitudeText.id = 'alt'
altitudeUnit.id = 'alt-unit'
// Create speed block altitudeSign.id = 'alt-sign'
if (mapuser.settings.showSpeed) { altitudeText.innerHTML = ''
const speedSign = document.createElement('div'), altitudeLabel.innerHTML = 'ALTITUDE'
speedLabel = document.createElement('div'), parseAlt(mapuser.last).then(function (alt) {
speedText = document.createElement('div'), altitudeText.innerHTML = metersToFeet(alt)
speedUnit = document.createElement('div'); }).catch(function (err) {
speedLabel.id = 'spd-label'; console.error('Could not load altitude from last known location: ', err)
speedLabel.innerHTML = 'SPEED'; })
speedText.id = 'spd'; altitudeUnit.innerHTML = (mapuser.settings.units === 'standard') ? 'feet' : 'meters'
speedText.innerHTML = (mapuser.settings.units=='standard')?(parseFloat(mapuser.last.spd)*2.23694).toFixed():mapuser.last.spd.toFixed(); altitudeSign.appendChild(altitudeLabel)
speedUnit.id = 'spd-unit'; altitudeSign.appendChild(altitudeText)
speedUnit.innerHTML = (mapuser.settings.units=='standard')?'m.p.h.':'k.p.h.'; altitudeSign.appendChild(altitudeUnit)
speedSign.id = 'spd-sign'; map.controls[googlemaps.ControlPosition.TOP_RIGHT].push(altitudeSign)
speedSign.appendChild(speedLabel); }
speedSign.appendChild(speedText); }
speedSign.appendChild(speedUnit);
map.controls[googlemaps.ControlPosition.TOP_RIGHT].push(speedSign); // Create streetview
} if (disp !== '0' && mapuser.settings.showStreetview) {
updateStreetView(parseLoc(mapuser.last), 10)
// Create altitude block }
if (mapuser.settings.showAlt) {
elevator = new googlemaps.ElevationService; // Get altitude from Google API
const altitudeSign = document.createElement('div'), function getAlt (loc) {
altitudeLabel = document.createElement('div'), return new Promise(function (resolve, reject) {
altitudeText = document.createElement('div'), // Get elevator service
altitudeUnit = document.createElement('div'); elevator = elevator || new googlemaps.ElevationService()
altitudeLabel.id = 'alt-label'; return elevator.getElevationForLocations({
altitudeText.id = 'alt';
altitudeUnit.id = 'alt-unit'; // Query API
altitudeSign.id = 'alt-sign'; 'locations': [{ lat: loc.lat, lng: loc.lon }]
altitudeText.innerHTML = ''; }, function (results, status, errorMessage) {
altitudeLabel.innerHTML = 'ALTITUDE'; // Success; return altitude
parseAlt(mapuser.last).then( function(alt){ if (status === googlemaps.ElevationStatus.OK && results[0]) {
altitudeText.innerHTML = metersToFeet(alt) console.log('Altitude was retrieved from Google Elevations API as', results[0].elevation, 'm')
}).catch( function(err){ resolve(results[0].elevation)
console.error("Could not load altitude from last known location: ",err)
}); // Unable to get any altitude
altitudeUnit.innerHTML = (mapuser.settings.units=='standard')?'feet':'meters'; } else {
altitudeSign.appendChild(altitudeLabel); reject(Error(errorMessage))
altitudeSign.appendChild(altitudeText); }
altitudeSign.appendChild(altitudeUnit); })
map.controls[googlemaps.ControlPosition.TOP_RIGHT].push(altitudeSign); })
} }
} // Parse altitude
function parseAlt (loc) {
// Create streetview // console.log('parseAlt('+loc+'})')
if (disp!=='0' && mapuser.settings.showStreetview) {
updateStreetView(parseLoc(mapuser.last),10); return new Promise(function (resolve, reject) {
} // Check if altitude was provided
if (typeof loc.alt === 'number') {
// Get altitude from Google API console.log('Altitude was provided in loc as ', loc.alt, 'm')
function getAlt(loc){ resolve(loc.alt)
return new Promise( function(resolve,reject){
// No altitude provided
// Get elevator service } else {
elevator = elevator || new googlemaps.ElevationService; console.log('No altitude was provided in loc')
return elevator.getElevationForLocations({
// Query google altitude API
// Query API getAlt(loc).then(function (alt) {
'locations': [{ lat:loc.lat, lng:loc.lon }] resolve(alt)
}, function(results, status, error_message) { }).catch(function (err) {
reject(err)
// Success; return altitude })
if (status === googlemaps.ElevationStatus.OK && results[0]) { }
console.log("Altitude was retrieved from Google Elevations API as",results[0].elevation,'m') })
resolve( results[0].elevation ) }
}
// Parse location
// Unable to get any altitude function parseLoc (loc) {
else { loc.spd = (mapuser.settings.units === 'standard') ? parseFloat(loc.spd) * 2.23694 : parseFloat(loc.spd)
reject(Error(error_message)) loc.dir = parseFloat(loc.dir)
} loc.lat = parseFloat(loc.lat)
loc.lon = parseFloat(loc.lon)
}); // loc.alt = parseAlt(loc);
}) loc.tim = new Date(loc.tim).toLocaleString()
} return loc
}
// Parse altitude
function parseAlt(loc){ // Got location
//console.log('parseAlt('+loc+'})') socket.on('get', function (loc) {
console.log('Got location:', loc.lat + ', ' + loc.lon)
return new Promise( function(resolve,reject){
// Parse location
// Check if altitude was provided newLoc = parseLoc(loc)
if (typeof loc.alt=='number'){
console.log('Altitude was provided in loc as ',loc.alt,'m') // Update map
resolve(loc.alt) if (disp !== '1') {
} // console.log('Updating map...')
// No altitude provided // Update time
else { $('#timestamp').text('location updated ' + newLoc.tim)
console.log('No altitude was provided in loc')
// Update marker and map center
// Query google altitude API googlemaps.event.trigger(map, 'resize')
getAlt(loc).then( function(alt){ map.setCenter({ lat: newLoc.lat, lng: newLoc.lon })
resolve(alt) marker.setPosition({ lat: newLoc.lat, lng: newLoc.lon })
}).catch( function (err) {
reject(err) // Update speed
}) if (mapuser.settings.showSpeed) {
$('#spd').text(newLoc.spd.toFixed())
} }
}) // Update altitude
if (mapuser.settings.showAlt) {
} // console.log('updating altitude...');
parseAlt(loc).then(function (alt) {
// Parse location $('#alt').text(metersToFeet(alt))
function parseLoc(loc) { }).catch(function (err) {
loc.spd = (mapuser.settings.units=='standard')?parseFloat(loc.spd)*2.23694:parseFloat(loc.spd); $('#alt').text('????')
loc.dir = parseFloat(loc.dir); console.error(err)
loc.lat = parseFloat(loc.lat); })
loc.lon = parseFloat(loc.lon); }
//loc.alt = parseAlt(loc); }
loc.tim = new Date(loc.tim).toLocaleString();
return loc; // Update street view
} if (disp !== '0' && mapuser.settings.showStreetview) {
updateStreetView(newLoc, 10)
// Got location }
socket.on('get', function(loc) { })
console.log("Got location:",loc.lat+", "+loc.lon);
// Get street view imagery
// Parse location function getStreetViewData (loc, rad, cb) {
newLoc = parseLoc(loc); // Ensure that the location hasn't changed (or this is the initial setting)
if (newLoc == null || loc.tim === newLoc.tim) {
// Update map if (!sv) { var sv = new googlemaps.StreetViewService() }
if (disp!=='1') { sv.getPanorama({
//console.log('Updating map...') location: {
lat: loc.lat,
// Update time lng: loc.lon
$('#timestamp').text('location updated '+newLoc.tim); },
radius: rad
// Update marker and map center }, function (data, status) {
googlemaps.event.trigger(map,'resize'); switch (status) {
map.setCenter({ lat:newLoc.lat, lng:newLoc.lon }); // Success
marker.setPosition({ lat:newLoc.lat, lng:newLoc.lon }); case googlemaps.StreetViewStatus.OK:
cb(data)
// Update speed break
if (mapuser.settings.showSpeed) { // No results in that radius
$('#spd').text( newLoc.spd.toFixed() ); case googlemaps.StreetViewStatus.ZERO_RESULTS:
} // Try again with a bigger radius
getStreetViewData(loc, rad * 2, cb)
// Update altitude break
if (mapuser.settings.showAlt) { // Error
//console.log('updating altitude...'); default:
parseAlt(loc).then(function(alt){ console.error(new Error('❌️ Street view not available: ' + status).message)
$('#alt').text( metersToFeet(alt) ) }
}).catch(function(err){ })
$('#alt').text( '????' ) }
console.error(err); }
})
} // Update streetview
function updateStreetView (loc) {
} // Calculate bearing between user and position of streetview image
// https://stackoverflow.com/a/26609687/3006854
// Update street view function getBearing (userLoc, imageLoc) {
if (disp!=='0' && mapuser.settings.showStreetview) { return 90 - (
updateStreetView(newLoc,10); Math.atan2(userLoc.lat - imageLoc.latLng.lat(), userLoc.lon - imageLoc.latLng.lng()) *
} (180 / Math.PI)) % 360
}
});
// Get dimensions for sv request (images proportional to element up to 640x640)
// Get street view imagery function getDimensions (element) {
function getStreetViewData(loc,rad,cb) { // Window is smaller than max
// Ensure that the location hasn't changed (or this is the initial setting) if (element.width() < 640 && element.height() < 640) {
if ( newLoc == null || loc.tim===newLoc.tim ) { return element.width().toFixed() + 'x' + element.height().toFixed()
if (!sv) { var sv=new googlemaps.StreetViewService(); }
sv.getPanorama({ // Width must be made proportional to 640
location: { } else if (element.width() > element.height()) {
lat: loc.lat, return '640x' + (element.height() * 640 / element.width()).toFixed()
lng: loc.lon
}, // Height must be made proportional to 640
radius: rad } else {
}, function(data,status){ switch (status){ return (element.width() * 640 / element.height()).toFixed() + 'x640'
// Success }
case googlemaps.StreetViewStatus.OK: }
cb(data);
break; // Set image
// No results in that radius getStreetViewData(loc, 2, function (data) {
case googlemaps.StreetViewStatus.ZERO_RESULTS: $('#viewImg').attr('src', 'https://maps.googleapis.com/maps/api/streetview?' +
// Try again with a bigger radius 'size=' + getDimensions($('#view')) +
getStreetViewData(loc,rad*2,cb); '&location=' + data.location.latLng.lat() + ',' + data.location.latLng.lng() +
break; '&fov=90' + // Inclination
// Error // Show direction if moving, point to user if stationary
default: '&heading=' + ((loc.spd > 2) ? loc.dir : getBearing(loc, data.location)).toString() +
console.error(new Error('❌️ Street view not available: '+status).message); '&key=' + mapKey
} }); )
} })
} }
// Update streetview
function updateStreetView(loc) {
// Calculate bearing between user and position of streetview image
// https://stackoverflow.com/a/26609687/3006854
function getBearing(userLoc, imageLoc) {
return 90-(
Math.atan2( userLoc.lat-imageLoc.latLng.lat(), userLoc.lon-imageLoc.latLng.lng() )
* (180/Math.PI) ) % 360;
}
// Get dimensions for sv request (images proportional to element up to 640x640)
function getDimensions(element) {
// Window is smaller than max
if ( element.width()<640 && element.height()<640 ){
return element.width().toFixed()+'x'+element.height().toFixed();
}
// Width must be made proportional to 640
else if (element.width()>element.height()) {
return '640x'+(element.height()*640/element.width()).toFixed();
}
// Height must be made proportional to 640
else {
return (element.width()*640/element.height()).toFixed()+'x640';
}
}
// Set image
getStreetViewData(loc, 2, function(data){
$('#viewImg').attr('src','https://maps.googleapis.com/maps/api/streetview?'+
'size='+ getDimensions($('#view')) +
'&location='+ data.location.latLng.lat() +','+ data.location.latLng.lng() +
'&fov=90' + // Inclination
// Show direction if moving, point to user if stationary
'&heading='+ ( (loc.spd>2)? loc.dir: getBearing(loc,data.location) ).toString() +
'&key='+ mapKey
);
});
}
// Error loading gmaps API // Error loading gmaps API
}).catch( function(err) { }).catch(function (err) {
console.error(err); console.error(err)
}); })

View File

@ -1,87 +1,74 @@
'use strict'; 'use strict'
/* global $ */ /* global $ */
const zxcvbn = require('zxcvbn'); const zxcvbn = require('zxcvbn')
function checkMatch(){ function checkMatch () {
$('#submit').prop('title',"You need to type your password again before you can save it. "); $('#submit').prop('title', 'You need to type your password again before you can save it. ')
// They match // They match
if ( $('#p1').val() === $('#p2').val() ) { if ($('#p1').val() === $('#p2').val()) {
$('#submit').prop('disabled',false).prop('title',"Click here to save your password. "); $('#submit').prop('disabled', false).prop('title', 'Click here to save your password. ')
}
// User has retyped, but they don't match yet
// User has retyped, but they don't match yet } else if ($('#p2').val() !== '') {
else if ($('#p2').val()!=='') { $('#password-help').text("Those passwords don't match... ").css({'color': '#fb6e3d'})
$('#password-help').text("Those passwords don't match... ").css({'color':'#fb6e3d'}); $('#submit').prop('disabled', true).prop('title', 'You need to type the same password twice before you can save it. ')
$('#submit').prop('disabled',true).prop('title',"You need to type the same password twice before you can save it. "); }
}
} }
// On page load // On page load
$(function(){ $(function () {
// On typing password
// On typing password $('.password').keyup(function () {
$('.password').keyup(function(){ // Nothing entered
if ($('#p1').val() === '' && $('#p2').val() === '') {
// Nothing entered $('#password-help').hide()
if ( $('#p1').val()==='' && $('#p2').val()==='' ){ $('#submit').prop('disabled', true).prop('title', 'You need to enter a password first. ')
$('#password-help').hide();
$('#submit').prop('disabled',true).prop('title',"You need to enter a password first. "); // Only second password entered
} } else if ($('#p1').val() === '') {
$('#password-help').show().text("Those passwords don't match... ")
// Only second password entered $('#submit').prop('disabled', true).prop('title', 'You need to type the same password twice correctly before you can save it. ')
else if ($('#p1').val()==='') {
$('#password-help').show().text("Those passwords don't match... "); // At least first password entered
$('#submit').prop('disabled',true).prop('title',"You need to type the same password twice correctly before you can save it. "); } else {
} $('#password-help').show()
// At least first password entered // Check first password
else { var zxcvbnResult = zxcvbn($('#p1').val())
$('#password-help').show();
// Not good enough
// Check first password if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second < 3600) { // Less than an hour
var zxcvbnResult = zxcvbn($('#p1').val()); $('#password-help').text('That password is way too common or simple. You may not use it for Tracman and should not use it anywhere. ').css({'color': '#fb6e3d'})
$('#submit').prop('disabled', true).prop('title', 'You need to come up with a better password. ')
// Not good enough } else if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second < 86400) { // Less than a day
if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second < 3600) { // Less than an hour $('#password-help').text('That password is pretty bad. It could be cracked in ' + zxcvbnResult.crack_times_display.online_no_throttling_10_per_second + '. Try adding more words, numbers, or symbols. ').css({'color': '#fb6e3d'})
$('#password-help').text("That password is way too common or simple. You may not use it for Tracman and should not use it anywhere. ").css({'color':'#fb6e3d'}); $('#submit').prop('disabled', true).prop('title', 'You need to come up with a better password. ')
$('#submit').prop('disabled',true).prop('title',"You need to come up with a better password. "); } else if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second < 864000) { // Less than ten days
} $('#password-help').text("That password isn't good enough. It could be cracked in " + zxcvbnResult.crack_times_display.online_no_throttling_10_per_second + '. Try adding another word, number, or symbol. ').css({'color': '#fb6e3d'})
else if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second < 86400) { // Less than a day $('#submit').prop('disabled', true).prop('title', 'You need to come up with a better password. ')
$('#password-help').text("That password is pretty bad. It could be cracked in "+zxcvbnResult.crack_times_display.online_no_throttling_10_per_second+". Try adding more words, numbers, or symbols. ").css({'color':'#fb6e3d'});
$('#submit').prop('disabled',true).prop('title',"You need to come up with a better password. "); // Good enough
} } else if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second <= 2592000) { // Less than thirty days
else if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second < 864000) { // Less than ten days $('#password-help').text('That password is good enough, but it could still be cracked in ' + zxcvbnResult.crack_times_display.online_no_throttling_10_per_second + '. ').css({'color': '#eee'})
$('#password-help').text("That password isn't good enough. It could be cracked in "+zxcvbnResult.crack_times_display.online_no_throttling_10_per_second+". Try adding another word, number, or symbol. ").css({'color':'#fb6e3d'}); checkMatch()
$('#submit').prop('disabled',true).prop('title',"You need to come up with a better password. "); } else if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second <= 1314000) { // Less than a year
} $('#password-help').text('That password is good. It would take ' + zxcvbnResult.crack_times_display.online_no_throttling_10_per_second + ' to crack. ').css({'color': '#8ae137'})
checkMatch()
// Good enough } else { // Long ass time
else if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second <= 2592000) { // Less than thirty days $('#password-help').text('That password is great! It could take ' + zxcvbnResult.crack_times_display.online_no_throttling_10_per_second + ' to crack!').css({'color': '#8ae137'})
$('#password-help').text("That password is good enough, but it could still be cracked in "+zxcvbnResult.crack_times_display.online_no_throttling_10_per_second+". ").css({'color':'#eee'}); checkMatch()
checkMatch(); }
} }
else if (zxcvbnResult.crack_times_seconds.online_no_throttling_10_per_second <= 1314000) { // Less than a year })
$('#password-help').text("That password is good. It would take "+zxcvbnResult.crack_times_display.online_no_throttling_10_per_second+" to crack. ").css({'color':'#8ae137'});
checkMatch(); // On checking 'show'
} $('#show').click(function () {
else { // Long ass time if ($(this).is(':checked')) {
$('#password-help').text("That password is great! It could take "+zxcvbnResult.crack_times_display.online_no_throttling_10_per_second+" to crack!").css({'color':'#8ae137'}); $('.password').attr('type', 'text')
checkMatch(); } else {
} $('.password').attr('type', 'password')
} }
})
}); })
// On checking 'show'
$('#show').click(function(){
if ($(this).is(':checked')) {
$('.password').attr('type','text');
} else {
$('.password').attr('type','password');
}
});
});

View File

@ -1,155 +1,136 @@
'use strict'; 'use strict'
/* global location $ */ /* global $ confirm */
// Validate email addresses // Validate email addresses
function validateEmail(email) { function validateEmail (email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email); return re.test(email)
} }
// Replace inputed value with response // Replace inputed value with response
function replaceFromEndpoint(type, selector, cb) { function replaceFromEndpoint (type, selector, cb) {
$.get('/validate?'+type+'='+$(selector).val()) $.get('/validate?' + type + '=' + $(selector).val())
.done(function(data){ .done(function (data) {
$(selector).val(data); $(selector).val(data)
cb(); cb()
}); })
} }
// On page load // On page load
$(function(){ $(function () {
var slugNotUnique, emailNotUnique; var slugNotUnique, emailNotUnique
// Set timezone in password change link // Set timezone in password change link
$('#password').attr('href',"/settings/password?tz="+new Date().getTimezoneOffset()); $('#password').attr('href', '/settings/password?tz=' + new Date().getTimezoneOffset())
// Delete account // Delete account
$('#delete').click(function(){ $('#delete').click(function () {
if (confirm("Are you sure you want to delete your account? This CANNOT be undone! ")) { if (confirm('Are you sure you want to delete your account? This CANNOT be undone! ')) {
window.location.href = "/settings/delete"; window.location.href = '/settings/delete'
} }
}); })
function validateForm(input) { function validateForm (input) {
// Perform basic check, then validate uniqueness
// Perform basic check, then validate uniqueness basicCheck(function () { validateUniqueness(input) })
basicCheck(function(){ validateUniqueness(input); });
function basicCheck (cb) {
function basicCheck(cb){ var checkedCount = 0
var checkedCount = 0;
// Check slug
// Check slug if (!$('#slug-input').val()) {
if (!$('#slug-input').val()){ $('#slug-help').show().text('A slug is required. ')
$('#slug-help').show().text("A slug is required. "); $('#submit-group .main').prop('disabled', true).prop('title', 'You need to enter a slug. ')
$('#submit-group .main').prop('disabled',true).prop('title',"You need to enter a slug. "); if (checkedCount > 0) { cb() } else { checkedCount++ }
if (checkedCount>0) {cb();} else {checkedCount++;} } else {
} if (!slugNotUnique) { $('#slug-help').hide() }
else { if (checkedCount > 0) { cb() } else { checkedCount++ }
if (!slugNotUnique){ $('#slug-help').hide(); } }
if (checkedCount>0) {cb();} else {checkedCount++;}
} // Check email
if (!$('#email-input').val()) {
// Check email $('#email-help').show().text('An email is required. ')
if (!$('#email-input').val()){ $('#submit-group .main').prop('disabled', true).prop('title', 'You need to enter an email address. ')
$('#email-help').show().text("An email is required. "); if (checkedCount > 0) { cb() } else { checkedCount++ }
$('#submit-group .main').prop('disabled',true).prop('title',"You need to enter an email address. "); } else if (!validateEmail($('#email-input').val())) {
if (checkedCount>0) {cb();} else {checkedCount++;} $('#email-help').show().text('You must enter a valid email address. ')
} $('#submit-group .main').prop('disabled', true).prop('title', 'You need to enter a valid email address. ')
else if (!validateEmail($('#email-input').val())) { if (checkedCount > 0) { cb() } else { checkedCount++ }
$('#email-help').show().text("You must enter a valid email address. "); } else {
$('#submit-group .main').prop('disabled',true).prop('title',"You need to enter a valid email address. "); if (!emailNotUnique) { $('#email-help').hide() }
if (checkedCount>0) {cb();} else {checkedCount++;} if (checkedCount > 0) { cb() } else { checkedCount++ }
} }
else { }
if (!emailNotUnique){ $('#email-help').hide(); }
if (checkedCount>0) {cb();} else {checkedCount++;} function validateUniqueness (input) {
} function recheckBasic () {
} if ($('#email-help').is(':visible') && $('#email-help').text().substring(0, 25) !== 'Unable to confirm unique ') {
$('#submit-group .main').prop('disabled', true).prop('title', 'You need to supply a different email address. ')
function validateUniqueness(input){ } else if ($('#slug-help').is(':visible') && $('#slug-help').text().substring(0, 25) !== 'Unable to confirm unique ') {
$('#submit-group .main').prop('disabled', true).prop('title', 'You need to supply a different slug. ')
function recheckBasic(){ } else if ($('#slug-help').text().substring(0, 25) === 'Unable to confirm unique ') {
if ($('#email-help').is(":visible") && $('#email-help').text().substring(0,25)!=="Unable to confirm unique ") { $('#submit-group .main').prop('title', 'Unable to confirm unique slug with the server. This might not work... ')
$('#submit-group .main').prop('disabled',true).prop('title',"You need to supply a different email address. "); } else if ($('#email-help').text().substring(0, 25) === 'Unable to confirm unique ') {
} $('#submit-group .main').prop('title', 'Unable to confirm unique email with the server. This might not work... ')
else if ($('#slug-help').is(":visible") && $('#slug-help').text().substring(0,25)!=="Unable to confirm unique ") { } else {
$('#submit-group .main').prop('disabled',true).prop('title',"You need to supply a different slug. "); $('#submit-group .main').prop('disabled', false).prop('title', 'Click here to save your changes. ')
} }
else if ( $('#slug-help').text().substring(0,25)==="Unable to confirm unique " ) { }
$('#submit-group .main').prop('title',"Unable to confirm unique slug with the server. This might not work... ");
} // Should server be queried for unique values?
else if ( $('#email-help').text().substring(0,25)==="Unable to confirm unique " ) { if (input && $('#' + input + '-input').val()) {
$('#submit-group .main').prop('title',"Unable to confirm unique email with the server. This might not work... "); if (!input === 'email' || validateEmail($('#email-input').val())) {
} // Query server for unique values
else { $.ajax({
$('#submit-group .main').prop('disabled',false).prop('title',"Click here to save your changes. "); url: '/validate?' + input + '=' + $('#' + input + '-input').val(),
} type: 'GET',
} statusCode: {
// Should server be queried for unique values? // Is unique
if (input && $('#'+input+'-input').val()) { 200: function () {
if (input==='email' && !validateEmail($('#email-input').val())) {} $('#' + input + '-help').hide()
if (input === 'slug') { slugNotUnique = false } else if (input === 'email') { emailNotUnique = false }
// Query server for unique values recheckBasic()
else { },
$.ajax({
url: '/validate?'+input+'='+$('#'+input+'-input').val(), // Isn't unique
type: 'GET', 400: function () {
statusCode: { if (input === 'slug') { slugNotUnique = true } else if (input === 'email') { emailNotUnique = true }
$('#' + input + '-help').show().text('That ' + input + ' is already in use by another user. ')
// Is unique $('#submit-group .main').prop('disabled', true).prop('title', 'You need to supply a different ' + input + '. ')
200: function(){ }
$('#'+input+'-help').hide();
if (input==='slug'){ slugNotUnique=false; } } })
else if (input==='email'){ emailNotUnique=false; }
recheckBasic(); // Server error
}, .error(function () {
if (input === 'slug') { slugNotUnique = undefined } else if (input === 'email') { emailNotUnique = undefined }
// Isn't unique $('#' + input + '-help').show().text('Unable to confirm unique ' + input + '. This might not work... ')
400: function(){ recheckBasic()
if (input==='slug'){ slugNotUnique=true; } })
else if (input==='email'){ emailNotUnique=true; } }
$('#'+input+'-help').show().text("That "+input+" is already in use by another user. ");
$('#submit-group .main').prop('disabled',true).prop('title',"You need to supply a different "+input+". "); // Nothing changed. Recheck basic validations
} } else { recheckBasic() }
}
} }) }
// Server error // Input change listeners
.error( function(){ $('#slug-input').change(function () {
if (input==='slug'){ slugNotUnique=undefined; } if (!$('#slug-input').val()) {
else if (input==='email'){ emailNotUnique=undefined; } $('#slug-help').show().text('A slug is required. ')
$('#'+input+'-help').show().text("Unable to confirm unique "+input+". This might not work... "); $('#submit-group .main').prop('disabled', true).prop('title', 'You need to enter a slug. ')
recheckBasic(); } else {
}); $('#slug-help').hide()
replaceFromEndpoint('slugify', '#slug-input', function () {
} } validateForm('slug')
})
// Nothing changed. Recheck basic validations }
else { recheckBasic(); } })
$('#email-input').change(function () {
} validateForm('email')
})
} $('#name-input').change(function () {
replaceFromEndpoint('xss', '#name-input', validateForm)
// Input change listeners })
$('#slug-input').change(function(){ })
if (!$('#slug-input').val()){
$('#slug-help').show().text("A slug is required. ");
$('#submit-group .main').prop('disabled',true).prop('title',"You need to enter a slug. ");
}
else {
$('#slug-help').hide();
replaceFromEndpoint('slugify','#slug-input',function(){
validateForm('slug');
});
}
});
$('#email-input').change(function(){
validateForm('email');
});
$('#name-input').change(function(){
replaceFromEndpoint('xss','#name-input',validateForm);
});
});

291
test.js
View File

@ -1,151 +1,146 @@
const chai = require('chai'), const chai = require('chai')
chaiHttp = require('chai-http'), const chaiHttp = require('chai-http')
request = require('supertest'), const request = require('supertest')
server = require('./server'); const server = require('./server')
chai.use(chaiHttp); chai.use(chaiHttp)
describe('Public', function () {
it('Displays homepage', function (done) {
request(server).get('/')
.expect(200)
.end(function (err, res) { done() })
})
describe('Public', function() { it('Displays help page', function (done) {
request(server).get('/help')
it('Displays homepage', function(done){ .expect(200)
request(server).get('/') .end(function (err, res) { done() })
.expect(200) })
.end(function(err,res){ done(); });
});
it('Displays help page', function(done){
request(server).get('/help')
.expect(200)
.end(function(err,res){ done(); });
});
it('Displays terms of service', function(done){
request(server).get('/terms')
.expect(200)
.end(function(err,res){ done(); });
});
it('Displays privacy policy', function(done){
request(server).get('/privacy')
.expect(200)
.end(function(err,res){ done(); });
});
it('Displays robots.txt', function(done){
request(server).get('/robots.txt')
.expect(200)
.expect('Content-Type', /text/)
.end(function(err,res){ done(); });
});
it('Displays demo map', function(done){
request(server).get('/map/keith')
.expect(200)
.end(function(err,res){ done(); });
});
});
describe('User', function() { it('Displays terms of service', function (done) {
request(server).get('/terms')
it('Creates an account', function(done){ .expect(200)
request(server).post('/signup',{"email":"test@tracman.org"}) .end(function (err, res) { done() })
.expect(200) })
.end(function(err,res){ done(); });
}); it('Displays privacy policy', function (done) {
request(server).get('/privacy')
//TODO: it('Creates a password', function(done){ .expect(200)
.end(function (err, res) { done() })
// }); })
//TODO: it('Logs in', function(done){ it('Displays robots.txt', function (done) {
request(server).get('/robots.txt')
// }); .expect(200)
.expect('Content-Type', /text/)
//TODO: it('Logs out', function(done){ .end(function (err, res) { done() })
})
// });
it('Displays demo map', function (done) {
//TODO: it('Forgets password', function(done){ request(server).get('/map/keith')
.expect(200)
// }); .end(function (err, res) { done() })
})
//TODO: it('Changes forgotten password', function(done){ })
// }); describe('User', function () {
it('Creates an account', function (done) {
//TODO: it('Logs back in', function(done){ request(server).post('/signup', {'email': 'test@tracman.org'})
.expect(200)
// }); .end(function (err, res) { done() })
})
//TODO: it('Changes email address', function(done){
// TODO: it('Creates a password', function(done){
// });
// })
//TODO: it('Changes password', function(done){
// TODO: it('Logs in', function(done){
// });
// })
//TODO: it('Changes settings', function(done){
// TODO: it('Logs out', function(done){
// });
// })
//TODO: it('Connects a Google account', function(done){
// TODO: it('Forgets password', function(done){
// });
// })
//TODO: it('Connects a Facebook account', function(done){
// TODO: it('Changes forgotten password', function(done){
// });
// })
//TODO: it('Connects a Twitter account', function(done){
// TODO: it('Logs back in', function(done){
// });
// })
//TODO: it('Logs in with Google', function(done){
// TODO: it('Changes email address', function(done){
// });
// })
//TODO: it('Logs in with Facebook', function(done){
// TODO: it('Changes password', function(done){
// });
// })
//TODO: it('Logs in with Twitter', function(done){
// TODO: it('Changes settings', function(done){
// });
// })
//TODO: it('Disconnects a Google account', function(done){
// TODO: it('Connects a Google account', function(done){
// });
// })
//TODO: it('Disconnects a Facebook account', function(done){
// TODO: it('Connects a Facebook account', function(done){
// });
// })
//TODO: it('Disconnects a Twitter account', function(done){
// TODO: it('Connects a Twitter account', function(done){
// });
// })
//TODO: it('Shows own map', function(done){
// request(server).get('/map') // TODO: it('Logs in with Google', function(done){
// .expect(200)
// .end(function(err,res){ done(); }); // })
// });
// TODO: it('Logs in with Facebook', function(done){
//TODO: it('Sets own location', function(done){
// })
// });
// TODO: it('Logs in with Twitter', function(done){
//TODO: it('Tracks own location', function(done){
// })
// });
// TODO: it('Disconnects a Google account', function(done){
//TODO: it('Clears own location', function(done){
// })
// });
// TODO: it('Disconnects a Facebook account', function(done){
//TODO: it('Deletes account', function(done){
// })
// });
// TODO: it('Disconnects a Twitter account', function(done){
});
// })
// TODO: it('Shows own map', function(done){
// request(server).get('/map')
// .expect(200)
// .end(function(err,res){ done(); })
// })
// TODO: it('Sets own location', function(done){
// })
// TODO: it('Tracks own location', function(done){
// })
// TODO: it('Clears own location', function(done){
// })
// TODO: it('Deletes account', function(done){
// })
})

View File

@ -1,34 +1,34 @@
const path = require('path'), const path = require('path')
env = require('./config/env/env.js'), const env = require('./config/env/env.js')
uglifyJsPlugin = require('uglifyjs-webpack-plugin'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = { module.exports = {
// Javascript files to be bundled // Javascript files to be bundled
entry: { entry: {
base: './static/js/base.js', base: './static/js/base.js',
header: './static/js/header.js', header: './static/js/header.js',
footer: './static/js/footer.js', footer: './static/js/footer.js',
contact: './static/js/contact.js', contact: './static/js/contact.js',
login: './static/js/login.js', login: './static/js/login.js',
map: './static/js/map.js', map: './static/js/map.js',
// controls: './static/js/controls.js', // controls: './static/js/controls.js',
settings: './static/js/settings.js', settings: './static/js/settings.js',
password: './static/js/password.js' password: './static/js/password.js'
}, },
// Sourcemaps // Sourcemaps
devtool: (env.mode=='development')?'inline-source-map':false, devtool: (env.mode === 'development') ? 'inline-source-map' : false,
// Output format // Output format
output: { output: {
filename: '.[name].bun.js', filename: '.[name].bun.js',
path: path.resolve(__dirname, 'static/js') path: path.resolve(__dirname, 'static/js')
}, },
plugins: [ plugins: [
// Minimize JS // Minimize JS
new uglifyJsPlugin() new UglifyJsPlugin()
] ]
}; }